关于 Mcp Agent Kit
mcp-agent-kit 是用于在应用内构建 MCP 服务和 Agent 的 TypeScript SDK,集成多服务编排、工具执行与检查 CLI,并支持多个 LLM 提供方。
主要功能
- 01连接并聚合多个 MCP 服务
- 02筛选工具并按服务命名
- 03创建包含工具和资源的 MCP 服务
- 04基于四个 LLM 提供方构建 Agent
- 05检查并验证服务架构
适用场景
- 01让 Agent 连接多个 MCP 服务
- 02通过 MCP 发布工具和资源
- 03在 CI 中检查服务架构与连接
MCP 相关
它可通过 stdio 或 Streamable HTTP 连接多个 MCP 服务,将其工具整合供 Agent 使用,也可创建暴露工具和资源的 MCP 服务。inspect CLI 可检查服务工具、架构及响应耗时。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
mcp-agent-kit
在 TypeScript 中编排 MCP 服务并构建 AI Agent——在你的应用中,而非基础设施中
只需三行代码,即可将你的 Agent 连接到多个 MCP 服务——无需网关、代理或容器:
const mcp = await connectMCP({
servers: {
files: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "./"] },
github: { url: "https://mcp.example.com/mcp" },
},
});
const agent = createAgent({ provider: "openai" });
agent.use(mcp);
const answer = await agent.chat("Summarise the open issues into notes.md");
mcp-agent-kit 是一个 TypeScript 包,可让你在应用中使用 MCP:
- 🎛️ MCP 编排器 — 连接多个 MCP 服务,并聚合、筛选其工具
- 🔍
inspectCLI — 无需编写代码,即可验证任意 MCP 服务的工具 - 🔌 MCP 服务 — 通过 stdio 或 Streamable HTTP 发布你自己的工具
- 🤖 AI Agent,支持在四种大模型提供方之间自动执行工具
- 🧠 智能路由器,用于多大模型路由
- 💬 聊天机器人,具备对话记忆
- 🌐 API 辅助工具,支持重试和超时
功能特性
- 进程内运行:只需执行
npm install,无需部署其他服务 - 内置工具循环:执行工具,并将结果反馈给模型
- 工具筛选:通过允许/拒绝 glob 模式,避免 60 个工具使提示词变得臃肿
- 故障隔离:某个服务宕机时,只会减少可用工具,不会影响 Agent
- 多提供方支持:OpenAI、Anthropic、Gemini、Ollama
- 类型安全:全面支持 TypeScript 和自动补全
- 文档经过验证:本页中的每个示例都会在 CI 中编译
安装
npm install mcp-agent-kit
快速开始
创建 AI Agent(只需 1 行代码!)
import { createAgent } from "mcp-agent-kit";
const agent = createAgent({ provider: "openai" });
const response = await agent.chat("Hello!");
console.log(response.content);
创建 MCP 服务(只需 1 个函数!)
import { createMCPServer } from "mcp-agent-kit";
const server = await createMCPServer({
name: "my-server",
tools: [
{
name: "get_weather",
description: "Get weather for a location",
inputSchema: {
type: "object",
properties: {
location: { type: "string" },
},
},
handler: async ({ location }) => {
return `Weather in ${location}: Sunny, 72°F`;
},
},
],
});
await server.start();
创建带记忆功能的聊天机器人
import { createChatbot, createAgent } from "mcp-agent-kit";
const bot = createChatbot({
agent: createAgent({ provider: "openai" }),
system: "You are a helpful assistant",
maxHistory: 10,
});
await bot.chat("Hi, my name is John");
await bot.chat("What is my name?"); // Remembers context!
文档
目录
AI Agent
创建可与多个大模型提供方协作的智能 Agent。
基本用法
import { createAgent } from "mcp-agent-kit";
const agent = createAgent({
provider: "openai",
model: "gpt-4o",
temperature: 0.7,
maxTokens: 2000,
});
const response = await agent.chat("Explain TypeScript");
console.log(response.content);
支持的提供方
| 提供方 | 模型 | 需要 API 密钥 |
|---|---|---|
| OpenAI | GPT-4o、GPT-4、o-series | ✅ 是 |
| Anthropic | Claude Opus 5、Sonnet 5 | ✅ 是 |
| Gemini | Gemini 2.0+ | ✅ 是 |
| Ollama | 本地模型 | ❌ 否 |
使用工具(函数调用)
const agent = createAgent({
provider: "openai",
tools: [
{
name: "calculate",
description: "Perform calculations",
parameters: {
type: "object",
properties: {
operation: { type: "string", enum: ["add", "subtract"] },
a: { type: "number" },
b: { type: "number" },
},
required: ["operation", "a", "b"],
},
handler: async ({ operation, a, b }) => {
return operation === "add" ? a + b : a - b;
},
},
],
});
const response = await agent.chat("What is 15 + 27?");
使用系统提示词
const agent = createAgent({
provider: "anthropic",
system: "You are an expert Python developer. Always provide code examples.",
});
智能工具调用
智能工具调用通过自动重试、超时和缓存,提升工具执行的可靠性和性能。
基本配置
const agent = createAgent({
provider: "openai",
toolConfig: {
forceToolUse: true, // Force model to use tools
maxRetries: 3, // Retry up to 3 times on failure
toolTimeout: 30000, // 30 second timeout
onToolNotCalled: "retry", // Action when tool not called
},
tools: [...],
});
使用缓存
const agent = createAgent({
provider: "openai",
toolConfig: {
cacheResults: {
enabled: true,
ttl: 300000, // Cache for 5 minutes
maxSize: 100, // Store up to 100 results
},
},
tools: [...],
});
直接执行工具
// Execute a tool directly with retry and caching
const result = await agent.executeTool("get_weather", {
location: "San Francisco, CA",
});
配置选项
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
forceToolUse | boolean | false | 有可用工具时,强制模型使用工具 |
maxRetries | number | 3 | 工具调用失败时的最大重试次数 |
onToolNotCalled | string | "retry" | 未调用工具时的操作:"retry"、"error"、"warn"、"allow" |
toolTimeout | number | 30000 | 工具执行超时时间(ms) |
cacheResults.enabled | boolean | true | 启用结果缓存 |
cacheResults.ttl | number | 300000 | 缓存生存时间(ms) |
cacheResults.maxSize | number | 100 | 最大缓存结果数 |
debug | boolean | false | 启用调试日志 |
autoExecuteTools | boolean | true | 运行请求的工具,并将结果反馈给模型 |
maxIterations | number | 5 | 单次 chat() 调用中模型往返交互的最大次数 |
完整示例
const agent = createAgent({
provider: "openai",
model: "gpt-4o",
toolConfig: {
forceToolUse: true,
maxRetries: 3,
onToolNotCalled: "retry",
toolTimeout: 30000,
cacheResults: {
enabled: true,
ttl: 300000,
maxSize: 100,
},
debug: true,
},
tools: [
{
name: "get_weather",
description: "Get current weather for a location",
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
handler: async ({ location }) => {
// Your weather API logic
return { location, temp: 72, condition: "Sunny" };
},
},
],
});
// Tools are executed automatically and their results are sent back to the
// model, so `content` is the final answer — not an empty string with a
// pending tool call.
const response = await agent.chat("What's the weather in NYC?");
console.log(response.content); // "It's 72°F and sunny in New York."
console.log(response.toolResults); // [{ name: 'get_weather', result: {...} }]
console.log(response.iterations); // 2 (one call for the tool, one for the answer)
// Or execute directly with retry and caching
const result = await agent.executeTool("get_weather", {
location: "New York, NY",
});
MCP 服务
创建 Model Context Protocol 服务以公开工具和资源。
基本 MCP 服务
import { createMCPServer } from "mcp-agent-kit";
const server = await createMCPServer({
name: "my-mcp-server",
port: 7777,
logLevel: "info",
});
await server.start(); // Starts on stdio by default
包含工具
const server = await createMCPServer({
name: "weather-server",
tools: [
{
name: "get_weather",
description: "Get current weather",
inputSchema: {
type: "object",
properties: {
location: { type: "string" },
units: { type: "string", enum: ["celsius", "fahrenheit"] },
},
required: ["location"],
},
handler: async ({ location, units = "celsius" }) => {
// Your weather API logic here
return { location, temp: 22, units, condition: "Sunny" };
},
},
],
});
包含资源
const server = await createMCPServer({
name: "data-server",
resources: [
{
uri: "config://app-settings",
name: "Application Settings",
description: "Current app configuration",
mimeType: "application/json",
handler: async () => {
return JSON.stringify({ version: "1.0.0", env: "production" });
},
},
],
});
Streamable HTTP 传输
const server = await createMCPServer({
name: "http-server",
port: 8080,
path: "/mcp", // default
});
await server.start("http"); // Serves MCP at http://localhost:8080/mcp
websocket传输已在 v1.2.0 中移除。它虽然接受连接, 但从未接入 MCP 服务,因此不会响应任何请求,却会报告自身运行正常。 请改用"http"(Streamable HTTP)——这是当前 MCP 客户端使用的 传输方式。
MCP 编排器
createMCPServer 用于发布工具。connectMCP 则负责另一半工作:连接到 MCP 服务,
将它们的工具聚合到一个命名空间下,并交给 Agent 使用——无需网关、代理或容器。
连接多个服务
import { connectMCP, createAgent } from "mcp-agent-kit";
const mcp = await connectMCP({
servers: {
// stdio: started as a child process
files: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "./"],
},
// Streamable HTTP: a remote server
github: {
url: "https://mcp.example.com/mcp",
headers: { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` },
},
},
});
const agent = createAgent({ provider: "openai" });
agent.use(mcp); // every MCP tool is now callable by the agent
const answer = await agent.chat("Summarise the open issues into notes.md");
await mcp.close();
工具按服务命名空间区分,因此两个服务可以同时公开名为 read 的工具而不发生
冲突:files__read、github__read。
筛选工具范围
六个服务很容易累积到 60 个工具,这会使提示词臃肿,并降低模型选择的质量。 只公开任务所需的工具:
const mcp = await connectMCP({
servers: {
files: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "./"] },
},
// Globs match the namespaced name
allowTools: ["files__read_*", "files__list_*"],
denyTools: ["*__delete_*"],
});
也可以针对每个服务,按不带命名空间的工具名称设置筛选条件:
const mcp = await connectMCP({
servers: {
files: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "./"],
denyTools: ["write_file", "move_file"],
},
},
});
服务宕机不会连带影响 Agent
默认情况下,某个服务故障会使工具集有所缩减,但其余服务仍可正常工作:
const mcp = await connectMCP({
servers: {
good: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "./"] },
flaky: { url: "https://might-be-down.example.com/mcp" },
},
});
console.log(mcp.listServers());
// [{ name: 'good', state: 'connected', tools: 12, toolsAvailable: 12 },
// { name: 'flaky', state: 'failed', error: 'fetch failed', tools: 0 }]
传入 strict: true 可让整个连接失败。
可观测性
console.log(mcp.getStats());
// { servers: 2, connected: 1, failed: 1, tools: 12,
// calls: 4, failedCalls: 0, avgDurationMs: 37 }
console.log(mcp.getCallLog());
// [{ server: 'good', tool: 'read_file', durationMs: 12, ok: true }, ...]
编排器选项
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
servers | object | — | 要连接的服务,按命名空间作为键 |
allowTools | string[] | — | 允许列表中的命名空间名称(支持 glob) |
denyTools | string[] | — | 拒绝列表中的命名空间名称(支持 glob) |
connectTimeout | number | 30000 | 等待服务连接的时长(毫秒) |
toolTimeout | number | 60000 | 单次工具调用允许的时长(毫秒) |
namespaceSeparator | string | __ | 服务名称与工具名称之间的分隔符 |
strict | boolean | false | 任一服务连接失败时,连接整体失败 |
autoReconnect | boolean | true | 连接断开时重新连接并重试一次 |
方法: getTools()、getServerTools(name)、getRawTools(name)、
listResources(name)、callTool(name, params)、listServers()、getStats()、
getCallLog()、getServerLogs(name)、reconnect(name)、close()。
CLI:检查 MCP 服务
inspect 会连接任意 MCP 服务,列出其提供的内容,验证其工具架构并测量往返时间。无需配置,也无需编写代码——只需指定一个服务并查看报告。
npx mcp-agent-kit inspect npx -y @modelcontextprotocol/server-filesystem ./
Target npx -y @modelcontextprotocol/server-filesystem ./
Transport stdio
✓ connected in 2453ms
✓ 14 tool(s), 0 resource(s) listed in 2ms
TOOLS
⚠ read_file { path: string, tail?: number, head?: number }
✓ read_multiple_files { paths: array }
⚠ write_file { path: string, content: string }
...
ISSUES
⚠ read_file: property "path" has no description
Summary 14 tool(s) · 0 resource(s) · 0 errors · 18 warning(s)
验证内容
错误是实际客户端会拒绝的内容;警告则是会导致模型做出较差选择的内容:
| 级别 | 检查项 |
|---|---|
| 错误 | 工具名称不符合 [a-zA-Z0-9_-]{1,64} — OpenAI 和 Anthropic 会拒绝它 |
| 错误 | required 列出的键未由 properties 声明 |
| 错误 | 缺少 inputSchema,或 type 不是 object |
| 错误 | 工具名称重复 |
| 警告 | 工具或属性没有描述 |
| 警告 | 属性没有声明类型 |
调用工具
npx mcp-agent-kit inspect --call read_file --args '{"path":"README.md"}' \
npx -y @modelcontextprotocol/server-filesystem ./
远程服务
npx mcp-agent-kit inspect https://mcp.example.com/mcp -H "Authorization: Bearer $TOKEN"
在 CI 中
--json 会生成机器可读的输出,退出代码也有实际意义:
0 表示无问题,1 表示架构错误,2 表示无法连接。
npx mcp-agent-kit inspect --json node ./my-server.js | jq '.issues'
选项
| 选项 | 描述 |
|---|---|
--json | 机器可读的输出 |
--quiet、-q | 仅显示摘要和问题 |
--timeout <ms> | 连接和调用超时时间(默认值为 30000) |
--header、-H | HTTP 标头,可重复("Name: value") |
--env、-e | stdio 服务的环境变量,可重复 |
--call <tool> | 检查后调用工具 |
--args <json> | --call 的参数 |
选项必须放在目标之前;目标之后的所有内容都属于服务自身的 命令行。
LLM 路由器
根据智能规则将请求路由到不同的 LLM。
基础路由器
import { createLLMRouter } from "mcp-agent-kit";
const router = createLLMRouter({
rules: [
{
when: (input) => input.length < 200,
use: { provider: "openai", model: "gpt-4o" },
},
{
when: (input) => input.includes("code"),
use: { provider: "anthropic", model: "claude-opus-5" },
},
{
default: true,
use: { provider: "openai", model: "gpt-4o" },
},
],
});
const response = await router.route("Write a function to sort an array");
带回退和重试
const router = createLLMRouter({
rules: [...],
fallback: {
provider: 'openai',
model: 'gpt-4o'
},
retryAttempts: 3,
logLevel: 'debug'
});
路由器统计信息
const stats = router.getStats();
console.log(stats);
// { totalRules: 3, totalAgents: 2, hasFallback: true }
const agents = router.listAgents();
console.log(agents);
// ['openai:gpt-4o', 'anthropic:claude-opus-5']
聊天机器人
创建具备自动记忆管理功能的对话式 AI。
基础聊天机器人
import { createChatbot, createAgent } from "mcp-agent-kit";
const bot = createChatbot({
agent: createAgent({ provider: "openai" }),
system: "You are a helpful assistant",
maxHistory: 10,
});
await bot.chat("Hi, I am learning TypeScript");
await bot.chat("Can you help me with interfaces?");
await bot.chat("Thanks!");
使用路由器
const bot = createChatbot({
router: createLLMRouter({ rules: [...] }),
maxHistory: 20
});
记忆管理
// Get conversation history
const history = bot.getHistory();
// Get statistics
const stats = bot.getStats();
console.log(stats);
// {
// messageCount: 6,
// userMessages: 3,
// assistantMessages: 3,
// oldestMessage: Date,
// newestMessage: Date
// }
// Reset conversation
bot.reset();
// Update system prompt
bot.setSystemPrompt("You are now a Python expert");
API 请求
简化的 HTTP 请求,支持自动重试和超时。
基础请求
import { api } from "mcp-agent-kit";
const response = await api.get("https://api.example.com/data");
console.log(response.data);
POST 请求
const response = await api.post(
"https://api.example.com/users",
{ name: "John", email: "[email protected]" },
{
name: "create-user",
headers: { "Content-Type": "application/json" },
}
);
配置重试和超时
const response = await api.request({
name: "important-request",
url: "https://api.example.com/data",
method: "GET",
timeout: 10000, // 10 seconds
retries: 5, // 5 attempts
query: { page: 1, limit: 10 },
});
所有 HTTP 方法
await api.get(url, config);
await api.post(url, body, config);
await api.put(url, body, config);
await api.patch(url, body, config);
await api.delete(url, config);
配置
环境变量
所有配置都是可选的。设置这些环境变量或在代码中传入:
# MCP Server
MCP_SERVER_NAME=my-server
MCP_PORT=7777
# Logging
LOG_LEVEL=info # debug | info | warn | error
# LLM API Keys
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
OLLAMA_HOST=http://localhost:11434
使用 .env 文件
# .env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
LOG_LEVEL=debug
该软件包会使用 dotenv 自动加载 .env 文件。
示例
查看 /examples 目录,了解完整的可运行示例:
basic-agent.ts- 简单的 Agent 用法smart-tool-calling.ts- 支持重试和缓存的智能工具调用mcp-server.ts- 提供工具和资源的 MCP 服务mcp-server-http.ts- 通过 Streamable HTTP 提供服务的 MCP 服务mcp-orchestrator.ts- 连接多个 MCP 服务并将其交给 Agentllm-router.ts- 在多个大模型之间进行智能路由chatbot-basic.ts- 带对话记忆的聊天机器人chatbot-with-router.ts- 使用路由器的聊天机器人api-requests.ts- 带重试机制的 HTTP 请求
运行示例
# Install dependencies
npm install
# Run an example
npx ts-node examples/basic-agent.ts
API 参考
Agent API
createAgent(config: AgentConfig)
创建一个新的 AI Agent 实例。
参数:
provider(必需):大模型提供商——"openai"、"anthropic"、"gemini" 或 "ollama"model(可选):模型名称(默认为提供商的默认模型)temperature(可选):采样温度,范围为 0-2(默认值:0.7)maxTokens(可选):回复中的最大令牌数(默认值:2000)apiKey(可选):API 密钥(若未提供,则从环境变量读取)tools(可选):工具定义数组system(可选):系统提示词toolConfig(可选):智能工具调用配置
返回值: Agent 实例
方法:
chat(message: string | AgentMessage[]): Promise<AgentResponse>- 发送消息并获取最终答案,同时运行模型请求的任何工具executeTool(name: string, params: any): Promise<any>- 直接执行工具registerTools(tools: AgentTool[]): Agent- 为运行中的 Agent 添加工具listTools(): AgentTool[]- 获取当前对模型可见的工具cleanup(): void- 清理缓存计时器
AgentResponse
agent.chat() 返回的响应对象:
{
content: string; // Final response text
toolCalls?: Array<{ // Tools still pending (empty once the loop finishes)
id?: string;
name: string;
arguments: any;
}>;
toolResults?: Array<{ // Tools executed while producing this response
toolCallId: string;
name: string;
result: any;
isError?: boolean;
}>;
iterations?: number; // Model round-trips taken (1 when no tool ran)
usage?: { // Token usage, summed across every round-trip
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
}
MCP 服务 API
createMCPServer(config: MCPServerConfig)
创建一个新的 MCP 服务实例。
参数:
name(可选):服务名称(默认值:从环境变量读取或使用 "mcp-server")port(可选):端口号(默认值:7777)logLevel(可选):日志级别——"debug"、"info"、"warn"、"error"tools(可选):工具定义数组resources(可选):资源定义数组
返回值: Promise<MCPServer> — 此函数为异步函数(会先加载 MCP SDK),因此始终使用 await
方法:
start(transport?: "stdio" | "websocket"): Promise<void>- 启动服务
路由器 API
createLLMRouter(config: LLMRouterConfig)
创建一个新的大模型路由器实例。
参数:
rules(必需):路由规则数组fallback(可选):回退提供商配置retryAttempts(可选):重试次数(默认值:3)logLevel(可选):日志级别
返回值: 路由器实例
方法:
route(input: string): Promise<AgentResponse>- 将输入路由至合适的大模型getStats(): object- 获取路由器统计信息listAgents(): string[]- 列出所有已配置的 Agent
聊天机器人 API
createChatbot(config: ChatbotConfig)
创建一个带对话记忆的新聊天机器人实例。
参数:
agent或router(必需):Agent 或路由器实例system(可选):系统提示词maxHistory(可选):保留的最大消息数(默认值:10)
返回值: 聊天机器人实例
方法:
chat(message: string): Promise<string>- 在上下文中发送消息,并返回回复文本getHistory(): ChatMessage[]- 获取对话历史getStats(): object- 获取对话统计信息reset(): void- 清除对话历史setSystemPrompt(prompt: string): void- 更新系统提示词
API 请求辅助函数
api.request(config: APIRequestConfig)
发送带重试和超时的 HTTP 请求。
参数:
name(可选):用于日志记录的请求名称url(必填):请求 URLmethod(可选):HTTP 方法(默认值:"GET")headers(可选):请求标头query(可选):查询参数body(可选):请求正文timeout(可选):超时时间,单位为毫秒(默认值:30000)retries(可选):重试次数(默认值:3)
返回: Promise<APIResponse>
便捷方法:
api.get(url, config?)- GET 请求api.post(url, body, config?)- POST 请求api.put(url, body, config?)- PUT 请求api.patch(url, body, config?)- PATCH 请求api.delete(url, config?)- DELETE 请求
高级用法
自定义提供程序
// Coming soon: Plugin system for custom providers
中间件
// Coming soon: Middleware support for request/response processing
流式响应
// Coming soon: Streaming support for real-time responses
参与贡献
欢迎贡献!欢迎随时提交 Pull Request。
- Fork 仓库
- 创建功能分支(
git checkout -b feature/amazing-feature) - 提交更改(
git commit -m 'Add amazing feature') - 推送到分支(
git push origin feature/amazing-feature) - 创建 Pull Request
许可证
MIT © Dominique Kossi
致谢
- 使用 TypeScript 构建
- 使用 MCP SDK
- 由 OpenAI、Anthropic、Google 和 Ollama 提供支持
支持
- 电子邮件:[email protected]
- 问题:GitHub Issues
- 讨论:GitHub Discussions
由开发者打造,为开发者服务
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。