"""AgentMall 购物 agent 参考实现(最小可运行)。 演示一个用户端 agent 如何通过 MCP 与 AgentMall 交互:检索 → 报价 → 下单 → 把支付链接给用户 → 轮询通知 → 查返佣。 真实产品里,「选哪个」「确认下单」「确认收货」这些步骤要问用户;这里用 input() 代替。 依赖:pip install "mcp>=2" 运行:AGENTMALL_URL=https://www.copyonline.cn AGENTMALL_KEY=ak_xxx python example_agent.py """ import asyncio import json import os import uuid import httpx2 from mcp import Client from mcp.client.streamable_http import streamable_http_client URL = os.environ.get("AGENTMALL_URL", "https://www.copyonline.cn").rstrip("/") + "/mcp/" KEY = os.environ.get("AGENTMALL_KEY", "") # 只在运行 main() 时需要;import 本文件复用 AgentMall 类不需要 class AgentMall: """把 MCP 调用包一层:成功返回 dict,失败抛 AgentMallError(带 category,方便按类别处理)。""" def __init__(self, url, key): self.url, self.key = url, key async def __aenter__(self): self._http = httpx2.AsyncClient(headers={"Authorization": f"Bearer {self.key}"}, timeout=30) self._c = Client(streamable_http_client(self.url, http_client=self._http)) await self._c.__aenter__() return self async def __aexit__(self, *a): await self._c.__aexit__(*a) await self._http.aclose() async def call(self, tool, **args): r = await self._c.call_tool(tool, {k: v for k, v in args.items() if v is not None}) text = "".join(getattr(c, "text", "") for c in r.content) if r.is_error: raw = text.split(": ", 1)[1] if text.startswith("Error executing") else text try: err = json.loads(raw) except ValueError: err = {"code": "UNKNOWN", "category": "REJECTED", "message": text} raise AgentMallError(err) sc = r.structured_content if isinstance(sc, dict): return sc.get("result", sc) if set(sc) == {"result"} else sc return json.loads(text) class AgentMallError(Exception): def __init__(self, err): super().__init__(err.get("message")) self.code, self.category, self.hint = err.get("code"), err.get("category"), err.get("hint") async def main(): if not KEY: raise SystemExit("请先设置环境变量 AGENTMALL_KEY(在开发者中心注册获取)") async with AgentMall(URL, KEY) as am: model = input("手机型号(如 iPhone 16 Pro):").strip() or "iPhone 16 Pro" try: res = await am.call("search_products", model=model, category="PHONE_CASE", max_price_yuan=60, sort="rating") except AgentMallError as e: if e.code == "UNKNOWN_MODEL": print("不支持这个机型,支持的有:", e.hint) return raise items = res["items"][:3] for i, it in enumerate(items, 1): s = it["seller"] print(f"{i}. ¥{it['price_yuan']} {it['title']}({it['color']}){'/'.join(s['badges'])} {s['region']}") pick = items[int(input("选哪个:") or 1) - 1] quote = await am.call("get_quote", offer_id=pick["offer_id"], qty=1, province="广东") if input(f"总价 ¥{quote['total_yuan']}(含运费 ¥{quote['shipping_yuan']}),确认下单?(y/n) ") != "y": return key = str(uuid.uuid4()) # 同一笔购买重试时复用这个 key order = await am.call("create_order", quote_id=quote["quote_id"], idempotency_key=key, buyer_ref="user-demo-1", receiver_name="测试", receiver_phone="13800000000", province="广东", city="深圳", district="南山区", address="科技园测试地址") print("请用户打开链接付款:", order["payment"]["pay_url"]) last = 0 for _ in range(10): # 真实产品用 webhook 或定时轮询 n = await am.call("list_notifications", after_id=last) for x in n["notifications"]: print(f"[{x['ts']}] {x['event']}: {x['data'].get('message', '')}") last = n["last_id"] await asyncio.sleep(5) acct = await am.call("get_my_account") print("返佣:", json.dumps(acct["rebates"], ensure_ascii=False)[:300]) if __name__ == "__main__": asyncio.run(main())