python3有什么库可以帮助我快速实现一个MCP服务吗?
- User
python3有什么库可以帮助我快速实现一个MCP服务吗?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
python3有什么库可以帮助我快速实现一个MCP服务吗?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
是的,Python 有一些专门的库可以帮助你快速实现 MCP (Model Context Protocol) 服务。MCP 是 Anthropic 开发的一个协议,用于让 AI 助手与外部工具和数据源进行交互。
这是 Anthropic 提供的官方 Python MCP 实现库:
pip install mcp
基本使用示例:
import asyncio
from mcp.server import Server
from mcp.server.models import InitializationOptions
from mcp.server.stdio import stdio_server
from mcp.types import Resource, Tool, TextContent
# 创建服务器实例
server = Server("my-mcp-server")
@server.list_resources()
async def handle_list_resources() -> list[Resource]:
"""返回可用资源列表"""
return [
Resource(
uri="file://example.txt",
name="示例文件",
description="一个示例文本文件",
mimeType="text/plain"
)
]
@server.read_resource()
async def handle_read_resource(uri: str) -> str:
"""读取指定资源"""
if uri == "file://example.txt":
return "这是示例文件的内容"
else:
raise ValueError(f"未知资源: {uri}")
@server.list_tools()
async def handle_list_tools() -> list[Tool]:
"""返回可用工具列表"""
return [
Tool(
name="echo",
description="回显输入的文本",
inputSchema={
"type": "object",
"properties": {
"text": {"type": "string", "description": "要回显的文本"}
},
"required": ["text"]
}
)
]
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[TextContent]:
"""执行工具调用"""
if name == "echo":
text = arguments.get("text", "")
return [TextContent(type="text", text=f"回显: {text}")]
else:
raise ValueError(f"未知工具: {name}")
async def main():
# 使用 stdio 传输运行服务器
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="my-mcp-server",
server_version="1.0.0"
)
)
if __name__ == "__main__":
asyncio.run(main())
这是另一个流行的 MCP 服务器实现:
pip install mcp-server-python
你也可以使用 FastAPI 来构建符合 MCP 协议的 HTTP 服务:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Dict, Any
app = FastAPI(title="MCP Server")
class Resource(BaseModel):
uri: str
name: str
description: str
mimeType: str
class Tool(BaseModel):
name: str
description: str
inputSchema: Dict[str, Any]
@app.get("/resources")
async def list_resources() -> List[Resource]:
return [
Resource(
uri="file://data.json",
name="数据文件",
description="包含示例数据的JSON文件",
mimeType="application/json"
)
]
@app.get("/resources/{uri:path}")
async def read_resource(uri: str):
# 根据 URI 返回资源内容
if uri == "file://data.json":
return {"message": "这是数据文件的内容"}
return {"error": "资源未找到"}
@app.get("/tools")
async def list_tools() -> List[Tool]:
return [
Tool(
name="calculator",
description="执行基本数学计算",
inputSchema={
"type": "object",
"properties": {
"expression": {"type": "string", "description": "数学表达式"}
},
"required": ["expression"]
}
)
]
@app.post("/tools/{tool_name}")
async def call_tool(tool_name: str, arguments: Dict[str, Any]):
if tool_name == "calculator":
expression = arguments.get("expression", "")
try:
result = eval(expression) # 注意:生产环境中不要使用 eval
return {"result": str(result)}
except Exception as e:
return {"error": str(e)}
return {"error": "未知工具"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
对于快速开始,我推荐使用官方的 mcp 库,因为它:
你可以根据具体需求选择合适的实现方式。如果需要更多定制化功能,FastAPI 方案会给你更大的灵活性。