简体中文
MCP 协议集成
MCP(Model Context Protocol)是连接 LLM 与外部工具、数据源的标准协议。Blade Agent SDK 支持连接外部 MCP Server,也支持在进程内创建 MCP Server。
所有远程工具都以保留命名空间 mcp__<server>__<tool> 暴露。MCP Server 不能用 Read、Write、Bash 等名称覆盖内置或应用工具;规范化后的名称冲突会 在注册阶段直接失败。
连接外部 MCP Server
在 createSession 的 mcpServers 中配置:
ts
import { createServerSession as createSession } from '@blade-ai/agent-sdk/advanced';
const session = await createSession({
provider: { type: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY },
model: 'claude-sonnet-4-20250514',
mcpServers: {
filesystem: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'],
},
},
});三种传输模式
stdio — 本地子进程
最常见的模式,SDK 启动子进程并通过 stdin/stdout 通信:
ts
mcpServers: {
github: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN },
},
}SSE — Server-Sent Events
适用于远程 MCP 服务器:
ts
mcpServers: {
remote: {
type: 'sse',
url: 'https://mcp.example.com/sse',
headers: { Authorization: `Bearer ${token}` },
},
}HTTP — Streamable HTTP
适用于支持 HTTP 传输的 MCP 服务器:
ts
mcpServers: {
api: {
type: 'http',
url: 'https://mcp.example.com/mcp',
},
}McpServerConfig 完整参考
ts
interface McpServerConfig {
command?: string;
args?: string[];
env?: Record<string, string>;
disabled?: boolean;
alwaysAllow?: string[];
type?: 'stdio' | 'sse' | 'http';
url?: string;
headers?: Record<string, string>;
oauth?: {
provider: string;
clientId?: string;
enabled?: boolean;
};
healthCheck?: {
enabled?: boolean;
intervalMs?: number;
};
}OAuth 授权码流程只接受 http://localhost:7777/oauth/callback、 http://127.0.0.1:7777/oauth/callback 或等价的 IPv6 loopback URI。 state 具有 5 分钟 TTL 且只能消费一次;不支持把授权码重定向到远程主机。
| 字段 | 类型 | 说明 |
|---|---|---|
command | string | stdio 模式的启动命令 |
args | string[] | 命令参数 |
env | Record<string, string> | 子进程环境变量 |
disabled | boolean | 暂时禁用此服务器 |
alwaysAllow | string[] | 保留的 MCP 配置元数据;当前 Session 权限管道不会据此自动授权 |
type | 'stdio' | 'sse' | 'http' | 传输模式 |
url | string | SSE/HTTP 模式的服务器 URL |
headers | Record<string, string> | SSE/HTTP 的请求头 |
oauth | object | OAuth 认证配置 |
healthCheck | object | 健康检查配置 |
运行时管理
Session 提供了完整的 MCP 运行时管理 API:
查看服务器状态
ts
const statuses = await session.mcpServerStatus();
for (const s of statuses) {
console.log(`${s.name}: ${s.status} (${s.toolCount} tools)`);
}ts
interface McpServerStatus {
name: string;
status: 'connected' | 'disconnected' | 'connecting' | 'error';
toolCount: number;
tools?: string[];
connectedAt?: Date;
error?: string;
}连接/断开/重连
ts
await session.mcpConnect('github');
await session.mcpDisconnect('github');
await session.mcpReconnect('github');列出可用工具
ts
const tools = await session.mcpListTools();
for (const t of tools) {
console.log(`${t.serverName}/${t.name}: ${t.description}`);
}ts
interface McpToolInfo {
name: string;
description: string;
serverName: string;
}创建进程内 MCP Server
当你需要用 TypeScript 编写自定义工具时,可以用 tool() 和 createSdkMcpServer() 创建进程内 MCP Server,无需启动额外进程:
ts
import { createSdkMcpServer, tool } from '@blade-ai/agent-sdk/advanced';
import { createServerSession as createSession } from '@blade-ai/agent-sdk/advanced';
import Type from 'typebox';
// 定义工具(使用 TypeBox schema)
const getWeather = tool(
'get-weather',
'查询指定城市的当前天气',
Type.Object({
city: Type.String({ description: '城市名称' }),
}),
async ({ city }) => ({
content: [{ type: 'text', text: `${city}: 晴 25°C` }],
}),
);
const queryDB = tool(
'query-database',
'执行 SQL 查询',
Type.Object({
sql: Type.String({ description: 'SQL 语句' }),
database: Type.String({ default: 'main', description: '数据库名' }),
}),
async ({ sql, database }) => {
const result = await executeSQL(database, sql);
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
},
);
// 创建 MCP Server
const myServer = await createSdkMcpServer({
name: 'my-tools',
version: '1.0.0',
tools: [getWeather, queryDB],
});
// 在 Session 中使用
const session = await createSession({
provider: { type: 'openai', apiKey: process.env.OPENAI_API_KEY },
model: 'gpt-4o',
mcpServers: {
myTools: myServer, // SdkMcpServerHandle
},
});TIP
进程内 MCP Server 不会启动子进程,直接在当前进程中执行,性能更高、调试更方便。 其 handle 通过 type: 'in-process' 与外部 MCP 配置形成可判别联合。
tool() 函数签名
ts
function tool<TSchema extends Type.TObject>(
name: string,
description: string,
schema: TSchema,
handler: (params: Type.Static<TSchema>) => Promise<McpToolCallResponse>,
): SdkTool<TSchema>;McpToolCallResponse
ts
interface McpToolCallResponse {
content: Array<{
type: 'text' | 'image' | 'resource';
text?: string;
data?: string;
mimeType?: string;
}>;
isError?: boolean;
}MCP 工具授权
alwaysAllow 当前不会跳过 Agent 的权限检查。需要自动授权可信 MCP 工具时, 请在 advanced.permission 中显式实现策略:
ts
const agent = await createAgent({
// ...model, apiKey
advanced: {
mcpServers,
permission: async ({ toolName }) =>
['read_file', 'list_directory'].includes(toolName) ? 'allow' : 'ask',
},
});当不同 MCP Server 暴露同名工具时,SDK 可能将名称改写为 serverName__toolName。权限策略应同时考虑 mcpListTools() 返回的实际名称, 不要只匹配服务器声明的原始名称。
WARNING
权限授权不等价于沙箱隔离。MCP 工具在远端或子进程中的实际能力还取决于对应 MCP Server 的部署与安全边界。
OAuth 认证
远程 MCP 服务器可以使用 OAuth 进行认证:
ts
mcpServers: {
enterprise: {
type: 'http',
url: 'https://mcp.enterprise.com/api',
oauth: {
provider: 'github',
clientId: 'your-client-id',
enabled: true,
},
},
}健康检查
启用健康检查后,SDK 会定期检测 MCP 服务器状态,自动发现连接中断:
ts
mcpServers: {
critical: {
type: 'stdio',
command: 'my-mcp-server',
healthCheck: {
enabled: true,
intervalMs: 30000, // 每 30 秒检查一次
},
},
}健康检查支持以下状态:
| 状态 | 说明 |
|---|---|
healthy | 服务器响应正常 |
degraded | 服务器响应变慢或部分功能异常 |
unhealthy | 服务器无响应或连续失败 |
checking | 正在执行健康检查 |
disabled | 未启用健康检查 |
工具排序
MCP 服务器注册的工具在发送给 LLM 时排列在内置工具之后。每组内按名称字母序排列。这意味着内置工具在 LLM 上下文中具有更高的优先级。
实战示例
多服务器组合
ts
import { createSdkMcpServer, tool } from '@blade-ai/agent-sdk/advanced';
import { createServerSession as createSession } from '@blade-ai/agent-sdk/advanced';
import Type from 'typebox';
// 进程内工具
const analyzeCode = tool(
'analyze-code',
'分析代码质量',
Type.Object({ filePath: Type.String() }),
async ({ filePath }) => {
const result = await runLinter(filePath);
return { content: [{ type: 'text', text: result }] };
},
);
const codeAnalyzer = await createSdkMcpServer({
name: 'code-analyzer',
version: '1.0.0',
tools: [analyzeCode],
});
const session = await createSession({
provider: { type: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY },
model: 'claude-sonnet-4-20250514',
mcpServers: {
// 外部:文件系统
filesystem: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '.'],
},
// 外部:GitHub
github: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN },
},
// 进程内:自定义分析工具
analyzer: codeAnalyzer,
},
});动态连接管理
ts
const session = await createSession({
provider: { type: 'openai', apiKey: process.env.OPENAI_API_KEY },
model: 'gpt-4o',
mcpServers: {
github: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
disabled: true, // 先不连接
},
},
});
// 需要时手动连接
await session.mcpConnect('github');
// 查看状态
const status = await session.mcpServerStatus();
console.log(status);
// 列出所有可用 MCP 工具
const tools = await session.mcpListTools();
console.log(`共 ${tools.length} 个 MCP 工具`);
// 用完断开
await session.mcpDisconnect('github');