MCP 知识速查表
本页面汇总了 MCP(Model Context Protocol)的核心知识点,方便快速查阅。
核心概念
| 概念 | 说明 |
|---|---|
| Host | LLM 应用程序,启动连接(如 Claude Desktop、Cursor) |
| Client | 主机内部的连接器,负责与 Server 通信 |
| Server | 提供上下文和能力的服务 |
| Tools | AI 模型可调用的函数(服务器原语) |
| Resources | 可共享的上下文和数据(服务器原语) |
| Prompts | 预定义的提示模板(服务器原语) |
| Sampling | 服务器请求 LLM 推理(客户端原语) |
| Elicitation | 服务器请求用户输入(客户端原语) |
| Logging | 服务器发送日志消息(客户端原语) |
| Completions | 参数自动补全建议(服务器原语) |
| Tasks | 异步任务执行(实验性功能) |
| Roots | 文件系统访问边界定义 |
分层架构
| 层次 | 说明 |
|---|---|
| 数据层 | JSON-RPC 2.0 协议、生命周期管理、原语定义 |
| 传输层 | STDIO 传输、Streamable HTTP 传输 |
协议版本
| 版本 | 发布日期 | 状态 |
|---|---|---|
| 2025-11-25 | 2025-11-25 | 最新稳定版 |
| 2025-06-18 | 2025-06-18 | 支持中 |
| 2024-11-05 | 2024-11-05 | 支持中 |
消息格式
// 请求
{
"jsonrpc": "2.0",
"id": "unique-id",
"method": "tools/list",
"params": {}
}
// 响应
{
"jsonrpc": "2.0",
"id": "unique-id",
"result": {}
}
// 错误
{
"jsonrpc": "2.0",
"id": "unique-id",
"error": {
"code": -32601,
"message": "Method not found"
}
}
// 通知(无 id,无需响应)
{
"jsonrpc": "2.0",
"method": "notifications/tools/list_changed"
}
核心方法
生命周期
initialize # 初始化连接
notifications/initialized # 初始化完成通知
shutdown # 关闭连接
notifications/exit # 退出通知
工具相关
tools/list # 列出可用工具
tools/call # 调用工具
notifications/tools/list_changed # 工具列表变更通知
资源相关
resources/list # 列出可用资源
resources/read # 读取资源内容
resources/subscribe # 订阅资源变更
resources/unsubscribe # 取消订阅
notifications/resources/updated # 资源更新通知
notifications/resources/list_changed # 资源列表变更通知
提示相关
prompts/list # 列出可用提示模板
prompts/get # 获取提示内容
notifications/prompts/list_changed # 提示列表变更通知
补全相关
completion/complete # 获取补全建议
任务相关(实验性)
tasks/get # 获取任务状态
tasks/result # 获取任务结果
tasks/list # 列出任务
tasks/cancel # 取消任务
notifications/tasks/status # 任务状态变更通知
客户端原语
sampling/createMessage # 服务器请求 LLM 采样
elicitation/create # 服务器请求用户输入
logging/setLevel # 设置日志级别
notifications/message # 日志消息通知
根目录相关
roots/list # 列出根目录
notifications/roots/list_changed # 根目录变更通知
Python SDK 常用代码
创建服务器
from mcp.server import Server
app = Server("my-server")
定义工具
from mcp.types import Tool, TextContent
@app.list_tools()
async def list_tools():
return [
Tool(
name="tool_name",
description="工具描述",
inputSchema={
"type": "object",
"properties": {
"param": {"type": "string", "description": "参数描述"}
},
"required": ["param"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict | None):
if name == "tool_name":
return [TextContent(type="text", text="result")]
raise ValueError(f"Unknown tool: {name}")
定义资源
from mcp.types import Resource
@app.list_resources()
async def list_resources():
return [Resource(
uri="resource://id",
name="资源名称",
mimeType="application/json"
)]
@app.read_resource()
async def read_resource(uri: str):
return [TextContent(type="text", text="content")]
定义提示
from mcp.types import Prompt, PromptArgument
@app.list_prompts()
async def list_prompts():
return [Prompt(
name="prompt_name",
description="提示描述",
arguments=[
PromptArgument(name="arg", description="参数", required=True)
]
)]
@app.get_prompt()
async def get_prompt(name: str, arguments: dict | None):
return [TextContent(type="text", text="prompt content")]
定义补全
@app.complete()
async def handle_completion(ref: dict, argument: dict, context: dict | None):
return {
"completion": {
"values": ["suggestion1", "suggestion2"],
"hasMore": False
}
}
处理任务
from mcp.types import Task, TaskStatus
@app.call_tool()
async def call_tool(name: str, arguments: dict | None, task: dict | None = None):
if task:
# 作为任务处理
task_id = create_task_id()
return {
"task": Task(
taskId=task_id,
status=TaskStatus.WORKING,
createdAt=datetime.utcnow().isoformat() + "Z"
).model_dump()
}
# 普通调用
return [TextContent(type="text", text="result")]
启动 STDIO 服务器
from mcp.server.stdio import stdio_server
import asyncio
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(
read_stream,
write_stream,
app.create_initialization_options()
)
asyncio.run(main())
FastMCP 快速开发
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field
mcp = FastMCP("my-server")
# 工具
@mcp.tool()
def calculate(expression: str) -> str:
"""计算数学表达式"""
return str(eval(expression))
# 资源
@mcp.resource("config://settings")
def get_settings() -> str:
"""获取配置"""
return json.dumps({"version": "1.0"})
# 提示
@mcp.prompt()
def review_code(language: str = "python") -> str:
"""代码审查模板"""
return f"请审查以下{language}代码..."
# 补全
@mcp.completion("ref/prompt", "review_code", "language")
def complete_language(argument: dict, context: dict | None):
return ["python", "javascript", "java", "go"]
# 运行
if __name__ == "__main__":
mcp.run()
TypeScript SDK 常用代码
创建服务器
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({
name: "my-server",
version: "1.0.0"
});
定义工具
server.tool(
"tool_name",
{ param: z.string().describe("参数描述") },
async ({ param }) => ({
content: [{ type: "text", text: "result" }]
})
);
启动 STDIO 服务器
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Server running on stdio"); // 使用 stderr
}
main().catch(console.error);
传输层配置
STDIO 配置
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["/absolute/path/to/server.py"]
}
}
}
HTTP 配置
{
"mcpServers": {
"my-server": {
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer your-token"
}
}
}
}
错误码
| 错误码 | 名称 | 说明 |
|---|---|---|
| -32700 | Parse error | JSON 解析错误 |
| -32600 | Invalid Request | 无效请求 |
| -32601 | Method not found | 方法不存在 |
| -32602 | Invalid params | 无效参数 |
| -32603 | Internal error | 内部错误 |
任务状态(实验性)
| 状态 | 说明 |
|---|---|
working | 任务正在执行 |
input_required | 需要额外输入 |
completed | 执行成功 |
failed | 执行失败 |
cancelled | 已取消 |
常用 MIME 类型
| 类型 | MIME |
|---|---|
| JSON | application/json |
| Markdown | text/markdown |
| 纯文本 | text/plain |
| HTML | text/html |
| application/pdf | |
| PNG | image/png |
| JPEG | image/jpeg |
工具设计模板
Tool(
name="function_name", # snake_case 命名
description="清晰的描述,说明工具用途、参数含义和返回内容",
inputSchema={
"type": "object",
"properties": {
"param_name": {
"type": "string",
"description": "参数描述,包括格式要求"
},
"optional_param": {
"type": "integer",
"description": "可选参数描述",
"default": 10
}
},
"required": ["param_name"]
},
execution={"taskSupport": "optional"} # 任务支持(可选)
)
资源 URI 模式
# 静态资源
Resource(uri="config://app", ...)
# 模板资源(动态)
ResourceTemplate(
uriTemplate="file:///project/{filename}",
...
)
能力声明模板
服务器能力
from mcp.types import ServerCapabilities
capabilities = ServerCapabilities(
tools={"listChanged": True},
resources={"subscribe": True, "listChanged": True},
prompts={"listChanged": True},
completions={},
tasks={
"list": {},
"cancel": {},
"requests": {"tools": {"call": {}}}
},
logging={}
)
客户端能力
capabilities = {
"roots": {"listChanged": True},
"sampling": {},
"elicitation": {},
"tasks": {
"list": {},
"cancel": {},
"requests": {
"sampling": {"createMessage": {}},
"elicitation": {"create": {}}
}
}
}
调试命令
# 使用 Inspector 调试
npx @modelcontextprotocol/inspector python server.py
# 直接运行服务器
python server.py
# 查看日志(macOS)
tail -f ~/Library/Logs/Claude/mcp*.log
# 查看日志(Windows)
type %APPDATA%\Claude\Logs\mcp*.log
安全检查清单
- 工具执行前验证所有输入参数
- 敏感操作需要用户确认(使用 Elicitation)
- 文件操作检查路径是否在允许的根目录内
- API 调用设置合理超时时间
- 日志输出到 stderr(STDIO 传输)
- 不在工具描述中暴露敏感信息
- 实现速率限制防止滥用
- 任务 ID 使用加密安全的随机值
- 验证资源 URI 防止路径遍历
官方资源
官方参考服务器
| 服务器 | 功能 | 安装命令 |
|---|---|---|
| filesystem | 文件系统访问 | npx @modelcontextprotocol/server-filesystem /path |
| github | GitHub API 集成 | npx @modelcontextprotocol/server-github |
| postgres | PostgreSQL 数据库 | npx @modelcontextprotocol/server-postgres |
| sqlite | SQLite 数据库 | npx @modelcontextprotocol/server-sqlite |
| brave-search | Brave 搜索 | npx @modelcontextprotocol/server-brave-search |
| puppeteer | 浏览器自动化 | npx @modelcontextprotocol/server-puppeteer |
| slack | Slack 集成 | npx @modelcontextprotocol/server-slack |