MCP 速查表
本页面汇总了 MCP 开发中最常用的 API 和配置。
核心概念
参与者
| 角色 | 说明 |
|---|---|
| Host | AI 应用程序(Claude Desktop、VS Code) |
| Client | 维护与服务器的连接 |
| Server | 提供 Tools、Resources、Prompts |
原语
| 原语 | 说明 | 方法 |
|---|---|---|
| Tools | 可执行函数 | tools/list, tools/call |
| Resources | 数据源 | resources/list, resources/read |
| Prompts | 提示模板 | prompts/list, prompts/get |
传输方式
| 传输 | 说明 | 使用场景 |
|---|---|---|
| Stdio | 标准输入输出 | 本地服务器 |
| HTTP | HTTP + SSE | 远程服务器 |
JSON-RPC 方法
生命周期
// 初始化请求
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": { "name": "client", "version": "1.0.0" }
}
}
// 初始化响应
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": { "tools": {}, "resources": {} },
"serverInfo": { "name": "server", "version": "1.0.0" }
}
}
// 初始化完成通知
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
工具操作
// 列出工具
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}
// 调用工具
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "tool_name",
"arguments": { "arg1": "value1" }
}
}
资源操作
// 列出资源
{
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list"
}
// 读取资源
{
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": { "uri": "file:///path/to/file" }
}
// 订阅资源
{
"jsonrpc": "2.0",
"id": 3,
"method": "resources/subscribe",
"params": { "uri": "file:///path/to/file" }
}
提示操作
// 列出提示
{
"jsonrpc": "2.0",
"id": 1,
"method": "prompts/list"
}
// 获取提示
{
"jsonrpc": "2.0",
"id": 2,
"method": "prompts/get",
"params": {
"name": "prompt_name",
"arguments": { "arg1": "value1" }
}
}
### 客户端特有能力 (Client Capabilities)
```json
// 服务器请求采样 (Sampling)
{
"jsonrpc": "2.0",
"method": "sampling/createMessage",
"params": {
"messages": [{ "role": "user", "content": { "type": "text", "text": "..." } }],
"maxTokens": 100
}
}
// 服务器请求互动启发 (Elicitation)
{
"jsonrpc": "2.0",
"method": "elicitation/requestInput",
"params": {
"message": "请确认操作",
"schema": { "type": "object", "properties": { "confirm": { "type": "boolean" } } }
}
}
// 客户端提交工作区根目录 (Roots)
{
"jsonrpc": "2.0",
"id": 1,
"method": "roots/list"
}
## 工具定义
```json
{
"name": "tool_name",
"title": "Tool Display Name",
"description": "工具功能描述",
"inputSchema": {
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "参数说明"
}
},
"required": ["param1"]
},
"outputSchema": {
"type": "object",
"properties": {
"result": { "type": "string" }
}
}
}
资源定义
{
"uri": "scheme://path/to/resource",
"name": "Resource Name",
"description": "资源描述",
"mimeType": "text/plain"
}
提示定义
{
"name": "prompt_name",
"title": "Prompt Title",
"description": "提示描述",
"arguments": [
{
"name": "arg1",
"description": "参数说明",
"required": true
}
]
}
内容类型
文本
{ "type": "text", "text": "文本内容" }
图像
{
"type": "image",
"data": "base64-encoded-data",
"mimeType": "image/png"
}
音频
{
"type": "audio",
"data": "base64-encoded-data",
"mimeType": "audio/wav"
}
资源链接
{
"type": "resource_link",
"uri": "file:///path/to/file",
"name": "filename",
"mimeType": "text/plain"
}
嵌入资源
{
"type": "resource",
"resource": {
"uri": "file:///path/to/file",
"mimeType": "text/plain",
"text": "文件内容"
}
}
通知类型
// 工具列表变化
{
"jsonrpc": "2.0",
"method": "notifications/tools/list_changed"
}
// 资源列表变化
{
"jsonrpc": "2.0",
"method": "notifications/resources/list_changed"
}
// 资源更新
{
"jsonrpc": "2.0",
"method": "notifications/resources/updated",
"params": { "uri": "file:///path/to/file" }
}
// 提示列表变化
{
"jsonrpc": "2.0",
"method": "notifications/prompts/list_changed"
}
// 日志消息
{
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "info",
"data": "日志消息"
}
}
TypeScript SDK
创建服务器
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const server = new Server(
{ name: 'my-server', version: '1.0.0' },
{ capabilities: { tools: {}, resources: {}, prompts: {} } }
);
const transport = new StdioServerTransport();
await server.connect(transport);
注册处理器
import {
ListToolsRequestSchema,
CallToolRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema
} from '@modelcontextprotocol/sdk/types.js';
// 工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{ name: 'hello', description: '打招呼', inputSchema: { type: 'object', properties: {} } }]
}));
// 工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
return { content: [{ type: 'text', text: 'Hello!' }] };
});
// 资源列表
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: []
}));
// 资源读取
server.setRequestHandler(ReadResourceRequestSchema, async (request) => ({
contents: []
}));
创建客户端
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
const transport = new StdioClientTransport({ command: "node", args: ["index.js"] });
const client = new Client({ name: "my-client", version: "1.0.0" }, { capabilities: {} });
await client.connect(transport);
const toolsResponse = await client.listTools();
Python SDK
创建服务器
from mcp.server import Server
from mcp.server.stdio import stdio_server
server = Server("my-server")
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream, server.create_initialization_options())
注册处理器
from mcp.types import Tool, Resource
@server.list_tools()
async def list_tools():
return [
Tool(
name="hello",
description="打招呼",
inputSchema={"type": "object", "properties": {}}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
return [{"type": "text", "text": "Hello!"}]
@server.list_resources()
async def list_resources():
return []
@server.read_resource()
async def read_resource(uri: str):
return []
创建客户端
import asyncio
from mcp import ClientSession
from mcp.client.stdio import stdio_client, StdioServerParameters
async def main():
server_params = StdioServerParameters(command="node", args=["index.js"])
async with stdio_client(server_params) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
tools = await session.list_tools()
Claude Desktop 配置
配置文件位置
| 平台 | 路径 |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
本地服务器配置
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Documents"
]
},
"my-server": {
"command": "node",
"args": ["/path/to/server/dist/index.js"]
}
}
}
远程服务器配置
{
"mcpServers": {
"remote-api": {
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_TOKEN"
}
}
}
}
常见错误码
| 代码 | 说明 |
|---|---|
| -32700 | 解析错误 |
| -32600 | 无效请求 |
| -32601 | 方法不存在 |
| -32602 | 无效参数 |
| -32603 | 内部错误 |
调试命令
# 使用 Inspector 调试
npx @modelcontextprotocol/inspector node dist/index.js
# 直接运行服务器
node dist/index.js
# 查看 Claude Desktop 日志
# macOS
tail -f ~/Library/Logs/Claude/mcp.log
# Windows
type %APPDATA%\Claude\logs\mcp.log