使用Python实现带有MCP(模型上下文协议)工具和MCP服务器/客户端架构的AI代理。
创建并运行一个带有自定义工具的MCP服务器,然后实现一个使用该服务器中工具的MCP客户端AI代理。此任务展示了从服务器实现到客户端集成的完整MCP工作流程。
通过完成本项目,您将学习:
├── agent/ # MCP客户端实现
│ ├── clients/
│ │ ├── custom_mcp_client.py 🚧 待办事项:纯Python MCP客户端
│ │ ├── mcp_client.py ✅ 完成:基于框架的客户端
│ │ └── openai_client.py ✅ 完成:AI模型集成
│ ├── models/
│ │ └── message.py ✅ 完成:消息结构
│ └── app.py 🚧 待办事项:使用MCPClient和CustomMCPClient测试
└── mcp_server/ # MCP服务器实现
├── models/
│ ├── request.py ✅ 完成:请求模型
│ └── response.py ✅ 完成:响应模型
├── services/
│ └── mcp_server.py 🚧 待办事项:实现核心服务器逻辑
├── tools/
│ ├── base.py ✅ 完成:抽象工具接口
│ ├── create_user_tool.py 🚧 待办事项:实现网络搜索工具
│ ├── delete_user_tool.py 🚧 待办事项:实现网络搜索工具
│ ├── update_user_tool.py 🚧 待办事项:实现网络搜索工具
│ ├── get_user_by_id_tool.py 🚧 待办事项:实现网络搜索工具
│ └── search_users.py 🚧 待办事项:实现网络搜索工具
└── server.py 🚧 待办事项:实现FastAPI服务器
requirements.txt中python -m venv .venv
pip install -r requirements.txt
with-detailed-description分支TODO部分描述的内容TODO部分描述的实现init -> init-notification -> tools/list -> tools/call)TODO部分描述的实现检查Arkadiy Dobkin是否作为用户存在,如果不存在,则在网络上搜索他的信息并添加他
请求格式:
{
"jsonrpc": "2.0",
"id": "唯一请求ID",
"method": "方法名称",
"params": {
"参数": "值"
}
}
响应格式:
{
"jsonrpc": "2.0",
"id": "匹配请求ID",
"result": {
"数据": "响应数据"
}
}
initialize请求notifications/initializedtools/list以获取可用工具tools/call,指定特定工具及其参数DELETE, {主机}, Mcp-Session-Id: {Mcp-Session-Id},关闭不在本练习范围内,但它是简单的REST请求Content-Type:application/jsonAccept:application/json, text/event-streamMcp-Session-Id:会话标识符(初始化后)data:开头的行,忽略[DONE]error字段result.content[0].text