Claude 的“USB 接口“来了!一文读懂 MCP 协议,让你的 AI 秒变超级助手

张开发
2026/5/27 21:49:13 15 分钟阅读
Claude 的“USB 接口“来了!一文读懂 MCP 协议,让你的 AI 秒变超级助手
MCP 架构┌─────────────────────────────────────────┐ │ Host (宿主应用) │ │ (Claude Desktop / IDE / 你的应用) │ ├─────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ │ │ │ Client 1 │ │ Client 2 │ │ │ │ (连接Server)│ │ (连接Server)│ │ │ └──────┬──────┘ └──────┬──────┘ │ └─────────┼──────────────────┼────────────┘ │ │ ┌─────┴─────┐ ┌─────┴─────┐ │ MCP Server│ │ MCP Server│ │ (工具/数据)│ │ (工具/数据)│ └───────────┘ └───────────┘核心角色Host承载 LLM 的应用如 Claude DesktopClientHost 内的 MCP 客户端维护与 Server 的连接Server提供资源、工具、Prompts 的独立进程 MCP 三大核心概念1. Resources资源类似 REST API 的 GET提供只读数据文件内容数据库查询结果API 响应数据{ uri: file:///project/src/main.py, mimeType: text/x-python, text: def hello(): ... }2. Tools工具LLM 可调用的函数可以产生副作用执行命令修改文件调用外部 API{ name: execute_command, description: 执行 shell 命令, inputSchema: { type: object, properties: { command: { type: string } }, required: [command] } }3. Prompts提示词模板预定义的提示词可参数化{ name: review_code, description: 代码审查模板, arguments: [ { name: code, required: true } ] } 传输层stdio vs SSEMCP 支持两种传输方式方式适用场景特点stdio本地 Server通过 stdin/stdout 通信最简单SSE远程 ServerHTTP Server-Sent Events支持网络部署 从零实现一个 MCP Server下面是一个完整的stdio 模式MCP Server 示例Python1. 基础 Server 结构# weather_server.py from mcp.server import Server from mcp.server.stdio import stdio_server from mcp.types import Resource, Tool, TextContent import asyncio # 创建 Server 实例 app Server(weather-server) app.list_resources() async def list_resources() - list[Resource]: 列出可用资源 return [ Resource( uriweather://beijing/current, name北京当前天气, mimeTypeapplication/json, description北京市实时天气数据 ) ] app.read_resource() async def read_resource(uri: str) - str: 读取资源内容 if uri weather://beijing/current: return {temp: 25, condition: sunny} raise ValueError(fUnknown resource: {uri}) app.list_tools() async def list_tools() - list[Tool]: 列出可用工具 return [ Tool( nameget_weather, description获取指定城市的天气, inputSchema{ type: object, properties: { city: {type: string, description: 城市名称}, unit: {type: string, enum: [C, F], default: C} }, required: [city] } ) ] app.call_tool() async def call_tool(name: str, arguments: dict) - list[TextContent]: 执行工具调用 if name get_weather: city arguments[city] unit arguments.get(unit, C) # 实际这里调用天气 API result f{city} 当前温度: 25°{unit}, 晴朗 return [TextContent(typetext, textresult)] raise ValueError(fUnknown tool: {name}) async def main(): async with stdio_server() as (read_stream, write_stream): await app.run( read_stream, write_stream, app.create_initialization_options() ) if __name__ __main__: asyncio.run(main())2. 配置 Claude Desktop 使用编辑~/Library/Application Support/Claude/claude_desktop_config.jsonmacOS{ mcpServers: { weather: { command: python, args: [/path/to/weather_server.py], env: { API_KEY: your-api-key } }, filesystem: { command: npx, args: [-y, modelcontextprotocol/server-filesystem, /Users/xxx/Desktop] } } }3. 测试流程重启 Claude Desktop看到工具图标出现即连接成功对话中可以直接使用查一下北京天气 → 调用get_weather工具读取 weather://beijing/current → 读取资源 进阶SSE 模式部署适合远程服务或需要 HTTP 接口的场景from mcp.server.sse import SseServerTransport from starlette.applications import Starlette from starlette.routing import Route sse SseServerTransport(/messages/) async def handle_sse(request): async with sse.connect_sse( request.scope, request.receive, request.send ) as (read_stream, write_stream): await app.run(read_stream, write_stream, app.create_initialization_options()) async def handle_messages(request): await sse.handle_post_message(request.scope, request.receive, request.send) starlette_app Starlette( routes[ Route(/sse, endpointhandle_sse), Route(/messages/, endpointhandle_messages, methods[POST]), ] ) 设计建议粒度控制Tools 应该原子化一个 Tool 做一件事描述清晰Tool 的 description 直接影响 LLM 调用决策错误处理返回明确的错误信息LLM 会据此调整策略安全边界Tools 应该有权限控制避免危险操作 生态现状官方 SDKsPythonmodelcontextprotocol/sdk, TypeScriptmodelcontextprotocol/sdk官方 Servers文件系统、Git、PostgreSQL、Brave 搜索等社区 ServersSlack、Notion、Figma、Spotify 等集成

更多文章