MCP客户端示例☀️
这个项目演示了一个使用模型上下文协议(MCP)的简单客户端-服务器实现,MCP是一种将大型语言模型与工具和数据连接起来的标准化方法。
概述
此示例显示了如何:
- 使用自定义工具创建MCP服务器
- 使用MCP客户端连接到服务器
- 调用工具并从服务器获取响应
教程视频

单击上图观看MCP实现教程。
项目结构
.
├── pyproject.toml
├── README.md
├── src
│ ├── client
│ │ └── mcp_client.py # MCP client implementation
│ └── server
│ └── example_server.py # MCP server with tools
└── uv.lock服务器实现
服务器公开了两个工具:
calculate_bmi-一个计算体重指数的简单计算器fetch_weather-从外部API检索天气数据的异步工具
客户端实施
客户端通过stdio连接到服务器,初始化会话,并调用服务器的工具。
入门指南
先决条件
- Python 3.9+
- uv(Python包管理器)
安装
# Install dependencies
uv install -e .运行示例
- 启动客户端(这将自动启动服务器):
uv run src/client/mcp_client.py用法
客户将:
- 连接到服务器
- 列出可用工具
- 使用样本数据调用BMI计算器
- 使用示例坐标调用天气工具
示例响应
Available tools: meta=None nextCursor=None tools=[...]
BMI calculation result: 22.857142857142858
Weather data: {"current_weather":{"temperature":14.2,"windspeed":12.6, ...}}使用MCP检查员进行测试
(运行下面的命令,然后访问http://localhost:5173 )
❯ mcp dev src/server/example_server.py
Starting MCP inspector...
Proxy server listening on port 3000
🔍 MCP Inspector is up and running at http://localhost:5173 🚀
New SSE connection
Query parameters: {
transportType: 'stdio',
command: 'uv',
args: 'run --with mcp mcp run src/server/example_server.py',资源
本项目使用:
许可证
此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。
