代理MCP服务器

使用Microsoft Agent Framework将代理作为MCP服务器暴露,支持通过STDIO传输与客户端进行JSON-RPC通信。

  • by chanirban
  • Python
  • 本地部署
  • 13 星标
  • 更新于
在 GitHub 查看 chanirban/agent-as-mcp-server-MAF

使用说明

代理作为MCP服务器(Microsoft代理框架)

此repo演示了如何 将代理暴露为MCP服务器 使用 微软代理框架(MAF),以及如何从以下位置连接到它:

  • 一 测试ping客户端 (mcp-ping.py),以及
  • 一 ChatAgent编排客户端 (client-local-mcp.py)它使用本地MCP服务器作为工具。

它使用 STDIO传输 对于MCP,这意味着客户端将服务器作为子进程启动,双方通过以下方式交换JSON-RPC消息 stdin/stdout.

文件

  • agent-as-mcp-svr.py --MCP 服务器 通过以下方式暴露代理 agent.as_mcp_server() 和 stdio_server().
  • mcp-ping.py --最小 客户端 启动服务器 stdio_client(),列出工具,并调用代理工具。
  • client-local-mcp.py — 聊天代理 编排示例使用 MCPStdioTool 连接到本地服务器。

先决条件

  • Python 3.10+
  • 推荐:虚拟环境
  • 包装:
    pip install --pre agent-framework mcp anyio azure-identity python-dotenv
    

环境配置

如果你使用 Azure OpenAI (推荐):

export AZURE_OPENAI_ENDPOINT="https://<your-endpoint>.cognitiveservices.azure.com/"
export AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME="gpt-4o"     # responses / agent usage
export AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o"          # optional for chat client
export AZURE_OPENAI_API_VERSION="2025-03-01-preview"       # or 'preview'
# One of:
export AZURE_OPENAI_API_KEY="<your-key>"                   # simplest
# OR AAD-based:
# (unset REQUESTS_CA_BUNDLE SSL_CERT_FILE; az login)
# export AZURE_USE_CLI=1

企业CA捆绑用户:确保 REQUESTS_CA_BUNDLE (以及可选 SSL_CERT_FILE)指向a 有效的 PEM路径。对于 az login,您可能需要暂时取消设置这些变量。

如何跑步

1) 快速本地ping(STDIO客户端/服务器)

这将服务器作为子进程启动,并调用代理工具:

python mcp-ping.py

预期产出(节略):

TOOLS: ['RestaurantAgent']
== RestaurantAgent input schema ==
{ ... JSON schema ... }

== Health Check (JSON) ==
{ "status": "ok", "endpoint": "...", ... }

2) 使用MCP服务器编排ChatAgent

这允许ChatAgent使用本地MCP服务器作为工具:

python client-local-mcp.py

它将运行一系列提示(健康检查、菜单列表、饮食过滤器、定价、欢乐时光)。

故障排除

  • JSON/EOF无效 当单独运行服务器时,您在没有客户端的情况下启动了服务器。使用 mcp-ping.py (他们启动服务器并使用MCP)。
  • 令牌/凭证错误 --提供 AZURE_OPENAI_API_KEY 或 AZURE_USE_CLI=1 随着 az login对于AAD链, DefaultAzureCredential 必须能够找到身份。
  • 工具参数不匹配 --代理作为工具通常需要一个 task 弦。确保客户端发送 {"task":"your prompt"}.

工作原理(STDIO)

  • 服务器: stdio_server() 公开异步stdin/stdout流; server.run() 处理JSON-RPC(初始化/list_tools/call_tool)。
  • 客户端: stdio_client() 启动服务器进程并返回流; ClientSession 驱动JSON-RPC调用。