内容
# MCP Python Client
[](https://opensource.org/licenses/MIT) [](https://badge.fury.io/py/mcpwire) [](https://pypi.org/project/mcpwire/) [](https://github.com/anukchat/mcpwire/actions/workflows/test.yml)
[](https://github.com/anukchat/mcpwire/actions/workflows/publish.yml)
[](https://codecov.io/gh/anukchat/mcpwire)
[](https://github.com/psf/black)
[](https://github.com/anukchat/mcpwire/stargazers)
[](https://pypi.org/project/mcpwire/)
[](https://mcpwire.readthedocs.io/en/latest/?badge=latest)
一个用于与实现[模型上下文协议(Model Context Protocol, MCP)](https://modelcontextprotocol.io/)的服务器进行交互的Python客户端库。该库简化了与暴露MCP接口的AI模型和代理的通信。
**版本:** 0.5.1
## 特性
* **官方MCP实现:** 该库使用官方MCP库和langchain-mcp-adapters。
* **资源支持:** 完全支持MCP资源API,用于暴露和访问数据。
* **发送提示:** 轻松发送对话历史,以从MCP服务器获取响应。
* **工具支持:** 访问MCP服务器提供的工具,并将其转换为LangChain工具。
* **MultiServerMCPClient:** 连接多个MCP服务器并访问它们的工具和资源。
* **配置文件:** 从`mcp.json`文件加载服务器连接详情和资源配置。
* **强大的错误处理:** 区分连接错误、超时、API错误和数据验证错误。
* **身份验证:** 通过`Authorization: Bearer`头支持API密钥身份验证。
* **上下文管理器:** 支持作为异步上下文管理器使用。
## 安装
```bash
```
# 从 PyPI(发布后)
pip install mcpwire
# 开发依赖
pip install mcpwire[dev]
# 或直接从 GitHub
pip install git+https://github.com/anukchat/mcpwire.git
# 或者用于开发
```bash
git clone https://github.com/anukchat/mcpwire.git
cd mcpwire
pip install -e .
```
## 配置 (mcp.json)
客户端可以通过 mcp.json 文件进行配置。这允许您定义多个服务器环境,并通过 `MCPClient.from_config()` 轻松切换它们。
客户端按以下顺序搜索 mcp.json:
1. 显式提供给 `MCPClient.from_config(config_path=...)` 的路径。
2. 当前工作目录中的 mcp.json。
3. 您的主目录中的 `.mcp.json` (`~/.mcp.json`)。
4. 您的主目录中的 `.config/mcp/mcp.json` (`~/.config/mcp/mcp.json`)。
示例 mcp.json:
```json
{
"default_server": "local",
"servers": {
"local": {
"base_url": "http://localhost:8000",
"api_key": null,
"timeout": 60,
"transport": "sse",
"description": "本地开发服务器(例如,fast-agent)",
"resources": {
"enabled": true,
"auto_subscribe": ["file:///workspace/shared/*"],
"default_templates": [
{
"uri_template": "file:///workspace/{path}",
"name": "工作区文件",
"description": "访问工作区目录中的文件"
},
{
"uri_template": "db://customers/{customer_id}",
"name": "客户记录",
"description": "访问数据库中的客户数据",
"mime_type": "application/json"
}
]
}
},
"stdio_server": {
"transport": "stdio",
"command": "python",
"args": ["-m", "mcp.server.cli"],
"timeout": 60,
"description": "本地 stdio 服务器",
"resources": {
"enabled": false
}
},
"remote_dev": {
"base_url": "https://dev-mcp.example.com",
"api_key": "dev-secret-key-abc",
"timeout": 90,
"transport": "sse",
"description": "远程开发/测试服务器",
"resources": {
"enabled": true,
"auto_subscribe": ["screen://capture/*"],
"default_templates": [
{
"uri_template": "screen://capture/{timestamp}",
"name": "屏幕截图",
"description": "访问浏览过程中捕获的屏幕截图",
"mime_type": "image/png"
}
]
}
},
"production": {
"base_url": "https://mcp.example.com",
"api_key": "env:MCP_PROD_API_KEY",
"timeout": 120,
"transport": "sse",
"description": "生产环境 MCP 服务器"
}
}
}
```
- `default_server`: (可选)如果在 from_config() 中省略 server_name,则使用的服务器的键。
- `servers`: 命名服务器配置的字典。
- `base_url`: (http/sse 必需)服务器 URL。
- `api_key`: (可选)API 密钥字符串、null 或 "env:YOUR_ENV_VAR"。
- `timeout`: (可选)请求超时时间(以秒为单位,默认为 60)。
- `transport`: (必需)要使用的传输协议("sse" 或 "stdio")。
- `command`: (stdio 必需)要执行的命令。
- `args`: (stdio 必需)命令的参数。
- `description`: (可选)描述。
- `resources`: (可选)MCP 资源的配置。
- `enabled`: (必需)此服务器是否启用资源。
- `auto_subscribe`: (可选)要自动订阅的资源 URI 模式列表。
- `default_templates`: (可选)定义动态资源的资源模板列表。
- `uri_template`: (必需)遵循 RFC 6570 的 URI 模板。
- `name`: (必需)此资源类型的人类可读名称。
- `description`: (可选)此资源类型的描述。
- `mime_type`: (可选)所有匹配资源的 MIME 类型。
## 快速入门 (异步)
```python
import asyncio
import logging
from mcpwire import (
MCPClient,
MultiServerMCPClient,
StdioConnection,
SSEConnection,
MCPAPIError,
MCPConnectionError,
MCPDataError
)
logging.basicConfig(level=logging.INFO)
async def main():
# --- 选项 1:直接初始化 ---
# 注意:官方的 MCP 库支持 "sse" 传输,而不是 "http"
client = MCPClient(base_url="http://localhost:8000", transport="sse")
try:
# 初始化并使用客户端
async with client as mcp:
# 获取服务器元数据
metadata = await mcp.get_server_metadata()
logging.info(f"连接到 MCP 服务器:{metadata.name} v{metadata.version}")
# 列出可用工具
tools = await mcp.list_tools()
for tool in tools:
logging.info(f"可用工具:{tool.name}")
# 获取提示
prompt_messages = await mcp.get_prompt("hello_world", {})
for msg in prompt_messages:
logging.info(f"[{msg.type}] {msg.content}")
# 调用工具
tool_result = await mcp.call_tool("search", {"query": "MCP protocol"})
logging.info(f"工具结果:{tool_result}")
# 处理资源
# 列出可用资源
resources_result = await mcp.list_resources()
logging.info(f"找到 {len(resources_result.resources)} 个资源和 {len(resources_result.templates)} 个模板")
# 显示可用资源
for resource in resources_result.resources:
logging.info(f"资源:{resource.name} (URI: {resource.uri})")
# 读取资源内容(如果有可用资源)
if resources_result.resources:
resource_uri = resources_result.resources[0].uri
content = await mcp.read_resource(resource_uri)
logging.info(f"读取资源内容,URI: {resource_uri}")
# 订阅资源更新
await mcp.subscribe_to_resource(resource_uri)
logging.info(f"已订阅资源:{resource_uri}")
# 稍后在不再需要时取消订阅
await mcp.unsubscribe_from_resource(resource_uri)
logging.info(f"已取消订阅资源:{resource_uri}")
except (MCPAPIError, MCPConnectionError, MCPDataError) as e:
logging.error(f"MCP 错误:{e}")
except Exception as e:
logging.error(f"发生意外错误:{e}", exc_info=True)
# --- 选项 2:从 mcp.json 初始化 ---
try:
# 从 mcp.json 加载 'local' 配置
client_from_config = MCPClient.from_config(server_name="local")
async with client_from_config as mcp:
logging.info(f"使用配置为 'local' 的服务器")
tools = await mcp.list_tools()
logging.info(f"找到 {len(tools)} 个工具")
except (FileNotFoundError, ValueError, KeyError, MCPDataError) as e:
logging.error(f"配置错误:{e}")
except Exception as e:
logging.error(f"发生意外错误:{e}", exc_info=True)
# --- 选项 3:使用 MultiServerMCPClient ---
try:
# 连接到多个服务器
connections = {
"math": {
"transport": "stdio",
"command": "python",
"args": ["-m", "mcp.server.cli"],
},
"web": {
"transport": "sse",
"url": "http://localhost:8000/sse",
}
}
async with MultiServerMCPClient(connections) as multi_client:
# 从所有服务器获取工具
all_tools = multi_client.get_tools()
logging.info(f"所有服务器的工具总数:{len(all_tools)}")
# 从特定服务器获取提示
messages = await multi_client.get_prompt("math", "calculate", {"expression": "2+2"})
for msg in messages:
logging.info(f"消息:{msg.content}")
# 处理来自多个服务器的资源
# 列出特定服务器的资源
math_resources = await multi_client.list_resources("math")
logging.info(f"数学服务器有 {len(math_resources.resources)} 个资源")
# 从特定服务器读取资源(如果有可用)
if math_resources.resources:
math_resource_uri = math_resources.resources[0].uri
math_content = await multi_client.read_resource("math", math_resource_uri)
logging.info(f"读取数学资源:{math_resource_uri}")
# 订阅和取消订阅资源更新
await multi_client.subscribe_to_resource("math", math_resource_uri)
await multi_client.unsubscribe_from_resource("math", math_resource_uri)
except Exception as e:
logging.error(f"MultiServerMCPClient 错误:{e}", exc_info=True)
```
# 运行异步主函数
if __name__ == "__main__":
asyncio.run(main())
```
## 从 v0.4.1 迁移到 v0.5.0
版本 0.5.0 增加了对 MCP Resources 的全面支持:
1. **Resource API**: 新增用于处理资源的方法(`list_resources()`、`read_resource()` 等)
2. **Configuration**: 在 mcp.json 中添加了资源配置选项
3. **Resource Templates**: 支持 URI 模板以访问动态资源
4. **Resource Subscriptions**: 使用 `subscribe_to_resource()` 订阅资源更新
5. **MultiServer Resources**: 通过 MultiServerMCPClient 访问来自多个服务器的资源
## 开发
- 克隆: `git clone https://github.com/anukchat/mcpwire.git`
- 设置环境: 创建并激活一个虚拟环境
- 安装开发依赖: `pip install -e ".[dev]"`
## 贡献
欢迎贡献!以下是您可以为项目贡献的方式:
1. **分叉仓库**:创建您自己的项目分叉
2. **创建分支**:为您的更改创建一个分支
3. **进行更改**:实施您的更改,遵循编码风格
4. **运行测试**:通过运行 `pytest` 确保测试通过
5. **提交拉取请求**:打开一个 PR,并清楚描述您的更改
### 测试
使用 pytest 运行测试:
```bash
# 安装测试依赖
pip install -e ".[dev]"
# 运行测试
pytest
```
### 持续集成
该项目使用 GitHub Actions 进行持续集成:
- **测试**:在每次推送和对主分支(main/master)的拉取请求时自动运行
- **构建**:打包并验证,以确保其能够正确安装
- **发布**:当新的版本标签被推送时(例如,v0.4.1),该包会自动发布到 PyPI
### 创建发布版本
要发布新版本:
1. 更新 `pyproject.toml` 和 `mcpwire/__init__.py` 中的版本号
2. 更新 CHANGELOG.md 文件以记录更改
3. 提交更改并推送到 GitHub
4. 创建并推送一个与版本匹配的新标签:
```bash
git tag -a v0.5.0 -m "Release v0.5.0"
git push origin v0.5.0
```
GitHub Actions 工作流将自动构建并发布该包到 PyPI。
## 许可证
本项目采用 MIT 许可证 - 详细信息请参见 LICENSE 文件。
## 故障排除资源
在使用 MCP 资源时,可能会出现以下问题:
### 资源错误
1. **服务器未找到**:使用 `MultiServerMCPClient` 时,确保在访问资源之前服务器名称存在。
```python
# 如果 "math_server" 未连接,将引发 ValueError
resources = await multi_client.list_resources("math_server")
```
2. **资源未找到**:确保资源 URI 是有效且可访问的。
```python
try:
resource = await client.read_resource("file:///nonexistent/file.txt")
except MCPAPIError as e:
print(f"资源错误: {e}")
```
3. **二进制资源处理**:处理二进制资源(图像、PDF 等)时:
```python
import base64
# 读取二进制资源
response = await client.read_resource("image:///logo.png")
if response.contents[0].blob:
# 解码 base64 数据
binary_data = base64.b64decode(response.contents[0].blob)
with open("logo.png", "wb") as f:
f.write(binary_data)
```
4. **模板参数**:使用模板时,确保提供所有必需的参数:
```python
# 对于像 "file:///workspace/{path}" 的模板
file_uri = "file:///workspace/documents/report.pdf" # 提供完整的 URI
```
5. **订阅泄漏**:在不再需要资源时,始终取消订阅:
```python
try:
await client.subscribe_to_resource("screen://capture/latest")
# 对资源进行操作...
finally:
# 确保即使发生错误也能取消订阅
await client.unsubscribe_from_resource("screen://capture/latest")
```
### 常见配置问题
1. **缺少资源配置**:确保服务器已启用资源:
```json
"resources": {
"enabled": true
}
```
2. **无效的模板格式**:资源模板必须遵循 RFC 6570 URI 模板格式:
```json
"uri_template": "file:///workspace/{path}", // 正确
"uri_template": "file:///workspace/<path>", // 错误
```
3. **不正确的 MIME 类型**:使用标准 MIME 类型以确保正确处理资源:
```json
"mime_type": "application/json" // 用于 JSON 数据
"mime_type": "text/plain" // 用于文本文件
"mime_type": "image/png" // 用于 PNG 图像
"mime_type": "application/pdf" // 用于 PDF 文档
```
连接信息
猜你喜欢
暂无推荐服务器