#!/usr/bin/env python3 """本地测试 MCP server 的工具调用。用法: test_client.py [json_args]""" import json import sys import anyio from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client # mcp 2.x URL = "http://127.0.0.1:8765/mcp" async def main(): tool = sys.argv[1] if len(sys.argv) > 1 else "status" args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {} async with streamable_http_client(URL) as (read, write): async with ClientSession(read, write) as session: await session.initialize() if tool == "list": tools = await session.list_tools() for t in tools.tools: print(f"- {t.name}: {t.description.splitlines()[0]}") return res = await session.call_tool(tool, arguments=args) for c in res.content: if hasattr(c, "text"): try: print(json.dumps(json.loads(c.text), ensure_ascii=False, indent=2)) except Exception: print(c.text) if res.is_error: print("[ERROR]") anyio.run(main) # 用 anyio 事件循环,避免和 MCP 客户端的 TaskGroup 清理冲突