首页 MCP系列4:MCP与MCP Server啥区别,自己项目如何接入
文章
取消

MCP系列4:MCP与MCP Server啥区别,自己项目如何接入

MCP是协议,mcp Server则是实现这个协议的具体的服务程序


🔧 一、安装必备库

1
pip install mcp-client httpx  # 官方MCP客户端库 + HTTP库(用于SSE)

⚙️ 二、接入流程(根据对方服务协议类型选择)

场景1:对方MCP Server使用 SSE(HTTP)协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from mcp_client import MCPClient

# 步骤1:初始化客户端(替换为实际URL)
client = MCPClient(
    transport="sse",  # 使用SSE协议
    endpoint="https://api.other-mcp-server.com/mcp"  # 对方服务地址
)

# 步骤2:调用工具(以"get_weather"为例)
try:
    # 同步调用
    result = client.call_tool(
        tool_name="get_weather",  # 工具名称(需对方提供)
        params={"city": "Beijing"},  # 参数(格式需匹配对方定义)
        timeout=10  # 超时时间(秒)
    )
    print(f"天气查询结果: {result['temperature']}℃")
    
except Exception as e:
    print(f"调用失败: {str(e)}")

场景2:对方MCP Server使用 STDIO(本地进程)协议

1
2
3
4
5
6
7
8
9
10
11
from mcp_client import MCPClient

# 步骤1:初始化客户端(需知道对方可执行文件路径)
client = MCPClient(
    transport="stdio",
    command="/path/to/other_mcp_server",  # 对方服务的可执行文件
    args=["--config", "config.json"]     # 启动参数(如有)
)

# 步骤2:调用工具(与SSE方式相同)
result = client.call_tool("read_file", {"path": "/data/report.pdf"})

🔍 三、关键配置说明

| 参数 | SSE 模式 | STDIO 模式 | |—————–|————————————–|———————————–| | transport | "sse" | "stdio" | | endpoint | 服务URL (e.g. https://xxx/mcp) | ❌ 不需要 | | command | ❌ 不需要 | 可执行文件路径 (e.g. ./mcp-tools) | | args | ❌ 不需要 | 启动参数列表 (e.g. ["--port=8080"]) | | api_key | 如需认证,通过headers传递 | ❌ 通常不需要 |

▶️ 认证处理示例(SSE模式)

1
2
3
4
5
client = MCPClient(
    transport="sse",
    endpoint="https://api.secure-mcp.com/mcp",
    headers={"Authorization": "Bearer YOUR_API_KEY"}  # 添加认证头
)

🚀 四、高级用法:流式响应处理

若对方工具返回流式数据(如LLM逐字生成):

1
2
3
4
# 异步流式调用(需Python 3.7+)
async with MCPClient("sse", endpoint=url) as client:
    async for chunk in client.stream_tool("generate_text", {"prompt": "Hello"}):
        print(chunk["text"], end="", flush=True)  # 逐块打印文本

⚠️ 五、调试与错误排查

1. 获取可用工具列表

1
2
tools = client.list_tools()  # 获取对方服务暴露的所有工具
print("可用工具:", [t["name"] for t in tools])

2. 常见错误码

| 错误码 | 含义 | 解决方案 | |————————|————————–|———————————-| | TOOL_NOT_FOUND | 工具名不存在 | 检查list_tools()返回的正确名称 | | INVALID_PARAMS | 参数格式错误 | 对照对方API文档检查参数结构 | | TRANSPORT_ERROR | 网络/进程通信失败 | 检查服务地址或进程是否运行 | | PERMISSION_DENIED | 缺少认证或权限不足 | 提供有效API Key |

3. 日志记录

1
2
import logging
logging.basicConfig(level=logging.DEBUG)  # 查看详细通信日志

💡 六、完整调用示例(SSE模式 + 错误处理)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from mcp_client import MCPClient, MCPError

def fetch_user_data(user_id: str):
    client = MCPClient(
        transport="sse",
        endpoint="https://user-service.com/mcp",
        headers={"X-API-Key": "your_key_here"}
    )
    
    try:
        return client.call_tool(
            tool_name="get_user_profile",
            params={"user_id": user_id, "fields": ["name", "email"]}
        )
        
    except MCPError as e:
        if e.code == "TOOL_NOT_FOUND":
            print("工具不存在!请检查服务版本")
        elif e.code == "INVALID_PARAMS":
            print("参数错误:", e.message)
        else:
            print("未知错误:", str(e))
            
    finally:
        client.close()

# 使用示例
user_data = fetch_user_data("U123456")
print(user_data)

📌 关键总结

  1. 确认对方协议:SSE(远程HTTP)还是STDIO(本地进程)
  2. 初始化客户端:根据协议选择正确配置参数
  3. 调用工具:使用call_tool(tool_name, params)
  4. 处理异常:捕获MCPError并针对性处理

⚠️ 重要提醒

  • 向对方索要 工具清单参数规范文档(缺少时用client.list_tools()探测)
  • 生产环境务必配置 超时timeout参数)和 重试机制
  • 敏感操作要求对方启用 HTTPS+Token认证

按照此方案,你可像调用普通API一样集成第三方MCP Server到Python项目中,无需依赖任何特定IDE或桌面应用。

本文由作者按照 CC BY 4.0 进行授权

网络系列5:Fiddler Classic 抓包

AI系列25:Gemini 2.5 Pro (1/O edition)成编程模型新王