MCPServerAdapter
amazon_get_product_detail
walmart_get_item
tiktok_shop_search_products
mode="summary" · -81.3% Avg Tokens
import os
from crewai import Agent, Crew, Process, Task
from crewai_tools import MCPServerAdapter
EDGEDATA_API_KEY = os.getenv("EDGEDATA_API_KEY", "YOUR_EDGEDATA_API_KEY")
MCP_SERVER_PARAMS = {
"url": "https://mcp.upp3.com/mcp", # Same-origin alias https://upp3.com/mcp also valid
"transport": "streamable-http",
"headers": {
"Authorization": f"Bearer {EDGEDATA_API_KEY}",
},
}
COMMERCE_TOOL_NAMES = {
"amazon_get_product_detail",
"amazon_search_products",
"walmart_get_item",
"tiktok_shop_search_products",
}
def run_ecommerce_crew() -> str:
with MCPServerAdapter(MCP_SERVER_PARAMS) as all_mcp_tools:
commerce_tools = [t for t in all_mcp_tools if t.name in COMMERCE_TOOL_NAMES]
researcher = Agent(
role="Cross-Platform Commerce Researcher",
goal="Collect compact live SKU telemetry from Amazon, Walmart, and TikTok Shop.",
backstory=(
"You gather structured product pricing, ratings, and sold velocity using EdgeData MCP. "
"Always pass mode='summary' on every tool call (-81.3% avg token reduction)."
),
tools=commerce_tools,
llm="gpt-4.1-mini",
verbose=True,
)
analyst = Agent(
role="Pricing & Margin Analyst",
goal="Compare cross-channel prices, rating spreads, and social demand velocity.",
backstory=(
"You synthesize compact JSON observations into exact numerical price spreads "
"without hallucinating unavailable fields."
),
llm="gpt-4.1-mini",
verbose=True,
)
strategist = Agent(
role="Merchandising Strategist",
goal="Produce an actionable 3-bullet channel positioning and bundle plan.",
backstory=(
"You turn verified competitive pricing tables into concise executive decisions."
),
llm="gpt-4.1-mini",
verbose=True,
)
research_task = Task(
description=(
"Using mode='summary' on every call, collect:\n"
"1) amazon_get_product_detail(asin='B0BSHF7WHW', country='US', mode='summary')\n"
"2) walmart_get_item(item_id='5043652254', mode='summary')\n"
"3) tiktok_shop_search_products(query='portable espresso maker', region='US', mode='summary')"
),
expected_output="Structured bullet summary of live prices, ratings, and availability across all 3 channels.",
agent=researcher,
)
analysis_task = Task(
description="Build a Markdown pricing & rating comparison table from the researcher's telemetry.",
expected_output="Compact Markdown table showing channel price spread and top rating strengths/risks.",
agent=analyst,
context=[research_task],
)
strategy_task = Task(
description="Recommend target retail price, differentiation angle, and promotional channel priority.",
expected_output="Concise 3-bullet executive merchandising recommendation.",
agent=strategist,
context=[analysis_task],
)
crew = Crew(
agents=[researcher, analyst, strategist],
tasks=[research_task, analysis_task, strategy_task],
process=Process.sequential,
verbose=True,
)
result = crew.kickoff()
return str(result)
if __name__ == "__main__":
print(run_ecommerce_crew())
MCPServerStreamableHTTP
output_type=BaseModel
redfin_search_properties
rightmove_search_properties
tradingview_get_quotes
GDPR 0-PII · strip_real_estate_pii
import asyncio
import os
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP
EDGEDATA_API_KEY = os.getenv("EDGEDATA_API_KEY", "YOUR_EDGEDATA_API_KEY")
MCP_URL = "https://mcp.upp3.com/mcp" # Same-origin alias https://upp3.com/mcp also valid
@dataclass
class ResearchDeps:
default_mode: str = "summary"
max_retry_attempts: int = 3
class MarketSnapshot(BaseModel):
market_label: str = Field(description="e.g. Austin, TX (Redfin US) or London (Rightmove UK)")
sample_count: int = Field(ge=0, description="Number of listings inspected")
median_asking_price: float = Field(ge=0, description="Approximate median asking price in local currency")
currency: str = Field(description="USD or GBP")
pii_scrubbed: bool = Field(default=True, description="Confirmed 0-PII via strip_real_estate_pii")
class QuoteSnapshot(BaseModel):
symbol: str
last_price: float
change_percent: float
class CrossAssetBrief(BaseModel):
us_housing: MarketSnapshot
uk_housing: MarketSnapshot
macro_quotes: list[QuoteSnapshot]
key_takeaways: list[str] = Field(min_length=2, max_length=4)
disclaimer: str = Field(default="Informational telemetry only; not investment advice.")
edgedata_mcp = MCPServerStreamableHTTP(
url=MCP_URL,
headers={"Authorization": f"Bearer {EDGEDATA_API_KEY}"},
timeout=30.0,
)
proptech_finance_agent: Agent[ResearchDeps, CrossAssetBrief] = Agent(
model="openai:gpt-4.1-mini",
deps_type=ResearchDeps,
output_type=CrossAssetBrief,
retries=2,
toolsets=[edgedata_mcp],
instructions=(
"You analyze US Redfin, UK Rightmove, and TradingView live telemetry via EdgeData Hosted MCP. "
"Always pass mode='summary' (-81.3% avg tokens: Redfin -82.4%, Rightmove -81.0%, TradingView -83.8%). "
"All real estate payloads are pre-scrubbed server-side by strip_real_estate_pii (GDPR 0-PII). "
"Upstream HTTP 504/429 errors incur strictly 0 credits. Informational telemetry only."
),
)
async def run_typed_research() -> CrossAssetBrief:
deps = ResearchDeps(default_mode="summary", max_retry_attempts=3)
prompt = (
"Using mode='summary' on every call, execute:\n"
"1) redfin_search_properties(query='Austin, TX', status='active', min_price=400000, max_price=850000, mode='summary')\n"
"2) rightmove_search_properties(query='London', channel='BUY', min_price=350000, max_price=750000, mode='summary')\n"
"3) tradingview_get_quotes(symbols='NASDAQ:AAPL,NASDAQ:NVDA,BINANCE:BTCUSDT', mode='summary')\n"
"Populate the CrossAssetBrief schema with observed metrics."
)
async with proptech_finance_agent:
for attempt in range(deps.max_retry_attempts):
try:
result = await proptech_finance_agent.run(prompt, deps=deps)
return result.output
except Exception as exc:
err_msg = str(exc)
if ("504" in err_msg or "429" in err_msg) and attempt < deps.max_retry_attempts - 1:
# EdgeData strictly charges 0 credits on upstream HTTP 504/429
await asyncio.sleep(1.5 * (2 ** attempt))
continue
raise
raise RuntimeError("PydanticAI retry budget exhausted")
if __name__ == "__main__":
brief = asyncio.run(run_typed_research())
print(brief.model_dump_json(indent=2))
crewai.tools.BaseTool
POST /v1/amazon/products/detail
GET /v1/real-estate/redfin/properties/search
GET /v1/finance/tradingview/quotes
504/429 = $0 + Token Budget Cap
import json
import os
import time
from typing import Any, Type
import httpx
from crewai import Agent, Crew, Process, Task
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
API_BASE = "https://api.upp3.com"
EDGEDATA_API_KEY = os.getenv("EDGEDATA_API_KEY", "YOUR_EDGEDATA_API_KEY")
MAX_TOOL_CHARS = 8000 # ~2,000 tokens hard guardrail per tool response
def edgedata_rest_call(method: str, path: str, **kwargs: Any) -> dict[str, Any]:
"""Deterministic REST call with 0-credit exponential backoff on HTTP 504/429."""
headers = {
"X-API-Key": EDGEDATA_API_KEY,
"Content-Type": "application/json",
}
with httpx.Client(base_url=API_BASE, headers=headers, timeout=30.0) as client:
for attempt in range(3):
resp = client.request(method, path, **kwargs)
# EdgeData strictly charges 0 credits on upstream HTTP 504 or 429
if resp.status_code in (429, 504) and attempt < 2:
retry_after = float(resp.headers.get("Retry-After", 1.5 * (2 ** attempt)))
time.sleep(min(retry_after, 8.0))
continue
resp.raise_for_status()
return resp.json()
raise RuntimeError(f"EdgeData retry budget exhausted for {path}")
def compact_budget_json(payload: dict[str, Any], limit_chars: int = MAX_TOOL_CHARS) -> str:
serialized = json.dumps(payload.get("data", payload), separators=(",", ":"))
if len(serialized) > limit_chars:
return serialized[:limit_chars] + "...[truncated_by_token_guard]"
return serialized
class AmazonDetailInput(BaseModel):
asin: str = Field(..., description="10-character Amazon ASIN, e.g. B0BSHF7WHW")
country: str = Field(default="US", description="Marketplace country code")
class EdgeDataAmazonDetailTool(BaseTool):
name: str = "edgedata_amazon_detail_rest"
description: str = "Fetch compact Amazon product detail via EdgeData REST mode='summary'."
args_schema: Type[BaseModel] = AmazonDetailInput
def _run(self, asin: str, country: str = "US") -> str:
res = edgedata_rest_call(
"POST",
"/v1/amazon/products/detail",
json={"asin": asin, "country": country, "mode": "summary"},
)
return compact_budget_json(res)
class TradingViewQuotesInput(BaseModel):
symbols: str = Field(..., description="Comma-separated symbols, e.g. NASDAQ:AAPL,BINANCE:BTCUSDT")
class EdgeDataTradingViewQuotesTool(BaseTool):
name: str = "edgedata_tradingview_quotes_rest"
description: str = "Fetch live TradingView quotes via EdgeData REST mode='summary' (2 credits/call)."
args_schema: Type[BaseModel] = TradingViewQuotesInput
def _run(self, symbols: str) -> str:
res = edgedata_rest_call(
"GET",
"/v1/finance/tradingview/quotes",
params={"symbols": symbols, "mode": "summary"},
)
return compact_budget_json(res)
class RedfinSearchInput(BaseModel):
query: str = Field(..., description="US city or ZIP, e.g. Seattle, WA")
max_price: int = Field(default=950000, description="Maximum asking price USD")
class EdgeDataRedfinSearchTool(BaseTool):
name: str = "edgedata_redfin_search_rest"
description: str = "Search GDPR 0-PII US residential listings on Redfin via mode='summary'."
args_schema: Type[BaseModel] = RedfinSearchInput
def _run(self, query: str, max_price: int = 950000) -> str:
res = edgedata_rest_call(
"GET",
"/v1/real-estate/redfin/properties/search",
params={
"query": query,
"status": "active",
"max_price": max_price,
"mode": "summary",
},
)
return compact_budget_json(res)
def run_resilient_rest_crew() -> str:
agent = Agent(
role="Resilient Multi-Vertical Data Analyst",
goal="Fetch compact cross-vertical telemetry with deterministic 504/429 backoff and token caps.",
backstory="You rely on EdgeData REST tools with strict mode='summary' and GDPR 0-PII compliance.",
tools=[
EdgeDataAmazonDetailTool(),
EdgeDataRedfinSearchTool(),
EdgeDataTradingViewQuotesTool(),
],
llm="gpt-4.1-mini",
verbose=True,
)
task = Task(
description=(
"1) Inspect Amazon ASIN B0BSHF7WHW in US; "
"2) Pull active Redfin 0-PII listings in Seattle, WA under $950,000; "
"3) Fetch quotes for NASDAQ:AAPL,NASDAQ:NVDA,BINANCE:BTCUSDT. "
"Return a concise executive telemetry summary (informational only)."
),
expected_output="Compact Markdown summary covering commerce, housing, and macro quotes.",
agent=agent,
)
crew = Crew(agents=[agent], tasks=[task], process=Process.sequential, verbose=True)
return str(crew.kickoff())
if __name__ == "__main__":
print(run_resilient_rest_crew())