使用说明
MCP客户端
一个用于与MCP服务器交互的Python客户端,以天气工具服务器为例。客户端使用Anthropic的Claude API进行自然语言查询,并可以连接到任何兼容的MCP服务器脚本。
特性
- MCP服务器的交互式聊天客户端
- 天气服务器示例(
server/weather.py)与:- 美国各州天气警报
- 基于位置的天气预报(通过NWS API)
- 可扩展:连接到任何兼容MCP的服务器脚本
- 使用Anthropic Claude API进行自然语言理解
需求
安装
-
克隆存储库:
git clone <your-repo-url> cd mcp-client -
安装依赖项:
uv pip install -r requirements.txt或者,如果你使用
uv和pyproject.toml:uv pip install -
设置您的Anthropic API密钥:
- 创建一个
.env项目根目录中的文件:ANTHROPIC_API_KEY=your-anthropic-api-key-here - 这
.env文件在.gitignore并将自动加载。
- 创建一个
用法
启动天气服务器
示例天气服务器位于 server/weather.py它提供了两个工具: get_alerts 和 get_forecast.
运行客户端
您可以使用以下方式将客户端连接到天气服务器:
uv run client.py ./server/weather.py
或者,如果你更喜欢纯Python:
python client.py ./server/weather.py
您应该看到如下输出:
Connected to server with tools: ['get_alerts', 'get_forecast']
MCP Client Started!
Type your queries or 'quit' to exit.
查询示例
What is the weather in New York?Are there any weather alerts for CA?Give me the forecast for latitude 40.7, longitude -74.0
退出
类型 quit 退出聊天循环。
项目结构
.
├── client.py # Main MCP client
├── server/
│ └── weather.py # Example weather MCP server
├── pyproject.toml # Project metadata and dependencies
├── .env # (Not committed) Your API keys
├── .gitignore
└── README.md
发展
- 客户端从以下位置加载环境变量
.env使用python-dotenv. - 天气服务器使用美国国家气象局API,需要互联网接入。
故障排除
- 人类API错误:
请确保您的API密钥有效并且有足够的信用。 - Python版本:
该项目需要Python 3.12或更高版本。 - 网络问题:
天气服务器需要连接https://api.weather.gov.