Token导航 LogoToken导航TokenDH.com
MCP Agent Kit logo
AI代理stdio官方级别未说明来源级核验

MCP Agent Kit

MCP Server

ts-node

一个简化创建MCP服务器、AI代理和聊天机器人的TypeScript工具包,支持多种LLM提供商,适用于智能路由和多LLM编排场景。

工具数

2

提示词数

0

GitHub Stars

1

资源数

0
AI代理TypeScriptClaude聊天机器人Claude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

dominiquekossi

提供方

dominiquekossi

最后核验

2026/5/17 20:20

运行时

Node.js

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

npx ts-node examples/basic-agent.ts

详细介绍

mcp试剂盒

使用任何LLM创建MCP服务器、AI代理和聊天机器人的最简单方法

](https://www.npmjs.com/package/mcp-agent-kit) ![License: MIT](https://opensource.org/licenses/MIT) ![TypeScript](https://www.typescriptlang.org/)

mcp试剂盒 是一个TypeScript包,简化了以下内容的创建:

  • 🔌 MCP服务器 (模型上下文协议)
  • 🤖 AI代理 与多家LLM提供商合作
  • 🧠 智能路由器 用于多LLM编排
  • 💬 聊天机器人 有对话记忆
  • 🌐 API帮助人员 带有重试和超时

特性

  • 零配置:使用智能默认值即可开箱即用
  • 多供应商:OpenAI、Anthropic、Gemini、Olama支持
  • 类型安全:完全支持TypeScript,具有自动补全功能
  • 生产就绪:内置重试、超时和错误处理
  • 开发者友好:复杂功能的单行设置
  • 可扩展:易于添加自定义提供程序和中间件

安装

npm install mcp-agent-kit

快速开始

创建AI代理(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 = 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代理

创建与多个LLM提供商协同工作的智能代理。

基本用法

import { createAgent } from "mcp-agent-kit";

const agent = createAgent({
  provider: "openai",
  model: "gpt-4-turbo-preview",
  temperature: 0.7,
  maxTokens: 2000,
});

const response = await agent.chat("Explain TypeScript");
console.log(response.content);

支持的提供商

提供程序型号需要API密钥
开放人工智能GPT-4、GPT-3.5✅ 是的
Anthropic克劳德3.5,克劳德3✅ 是的
双子座双子座2.0+✅ 是的
奥拉玛本地模型❌ 没有

使用工具(函数调用)

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",
});

配置选项

选项类型默认值描述
forceToolUsebooleanfalse强制模型在可用时使用工具
maxRetriesnumber3工具故障时的最大重试次数
onToolNotCalledstring“重试”未调用工具时的操作:“重试”、“错误”、“警告”、“允许”
toolTimeoutnumber30000工具执行超时(毫秒)
cacheResults.enabledbooleantrue启用结果缓存
cacheResults.ttlnumber300000缓存生存时间(ms)
cacheResults.maxSizenumber100最大缓存结果
debugbooleanfalse启用调试日志记录

完整示例

const agent = createAgent({
  provider: "openai",
  model: "gpt-4-turbo-preview",
  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" };
      },
    },
  ],
});

// Use in chat - tools are automatically called
const response = await agent.chat("What's the weather in NYC?");

// Or execute directly with retry and caching
const result = await agent.executeTool("get_weather", {
  location: "New York, NY",
});

______________________________________________________________________

MCP服务器

创建模型上下文协议服务器以公开工具和资源。

基本MCP服务器

import { createMCPServer } from "mcp-agent-kit";

const server = createMCPServer({
  name: "my-mcp-server",
  port: 7777,
  logLevel: "info",
});

await server.start(); // Starts on stdio by default

使用工具

const server = 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 = 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" });
      },
    },
  ],
});

WebSocket传输

const server = createMCPServer({
  name: "ws-server",
  port: 8080,
});

await server.start("websocket"); // Use WebSocket instead of stdio

______________________________________________________________________

LLM路由器

根据智能规则将请求路由到不同的LLM。

基本路由器

import { createLLMRouter } from "mcp-agent-kit";

const router = createLLMRouter({
  rules: [
    {
      when: (input) => input.length  input.includes("code"),
      use: { provider: "anthropic", model: "claude-3-5-sonnet-20241022" },
    },
    {
      default: true,
      use: { provider: "openai", model: "gpt-4-turbo-preview" },
    },
  ],
});

const response = await router.route("Write a function to sort an array");

使用回退和重试

const router = createLLMRouter({
  rules: [...],
  fallback: {
    provider: 'openai',
    model: 'gpt-4-turbo-preview'
  },
  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-4-turbo-preview', 'anthropic:claude-3-5-sonnet-20241022']

______________________________________________________________________

聊天机器人

通过自动内存管理创建会话式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);

发布请求

const response = await api.post(
  "https://api.example.com/users",
  { name: "John", email: "john@example.com" },
  {
    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

包裹会自动加载 .env 文件使用 dotenv.

______________________________________________________________________

示例

看看 /examples 完整工作示例目录:

  • basic-agent.ts -简单的代理使用
  • smart-tool-calling.ts -具有重试和缓存功能的智能工具调用
  • mcp-server.ts -配备工具和资源的MCP服务器
  • mcp-server-websocket.ts -带WebSocket的MCP服务器
  • llm-router.ts -LLM之间的智能路由
  • 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 参考

代理API

createAgent(config: AgentConfig)

创建新的AI代理实例。

参数:

  • provider (必填):法学硕士提供者-“openai”、“anthropic”、“gemini”或“ollama”
  • model (可选):模型名称(默认为提供程序的默认值)
  • temperature (可选):采样温度0-2(默认值:0.7)
  • maxTokens (可选):响应中的最大令牌数(默认值:2000)
  • apiKey (可选):API密钥(如果未提供,则从env读取)
  • tools (可选):工具定义数组
  • system (可选):系统提示
  • toolConfig (可选):智能工具调用配置

退货: 代理实例

方法:

  • chat(message: string): Promise -发送消息并获得响应
  • executeTool(name: string, params: any): Promise -直接执行工具

AgentResponse

来自agent.chat()的响应对象:

{
  content: string;           // Response text
  toolCalls?: Array;
  usage?: {                  // Token usage
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
}

MCP服务器API

createMCPServer(config: MCPServerConfig)

创建新的MCP服务器实例。

参数:

  • name (可选):服务器名称(默认:来自env或“mcp-Server”)
  • port (可选):端口号(默认值:7777)
  • logLevel (可选):日志级别-“调试”、“信息”、“警告”、“错误”
  • tools (可选):工具定义数组
  • resources (可选):资源定义数组

退货: MCP服务器实例

方法:

  • start(transport?: "stdio" | "websocket"): Promise -启动服务器

路由器API

createLLMRouter(config: LLMRouterConfig)

创建新的LLM路由器实例。

参数:

  • rules (必填):路由规则数组
  • fallback (可选):后备提供者配置
  • retryAttempts (可选):重试次数(默认值:3)
  • logLevel (可选):日志级别

退货: 路由器实例

方法:

  • route(input: string): Promise -将输入路由到适当的LLM
  • getStats(): object -获取路由器统计信息
  • listAgents(): string[] -列出所有已配置的代理

聊天机器人API

createChatbot(config: ChatbotConfig)

创建一个具有对话记忆的新聊天机器人实例。

参数:

  • agentrouter (必填):代理或路由器实例
  • system (可选):系统提示
  • maxHistory (可选):要保留的最大消息数(默认值:10)

退货: 聊天机器人实例

方法:

  • chat(message: string): Promise -发送带有上下文的消息
  • getHistory(): ChatMessage[] -获取对话历史记录
  • getStats(): object -获取对话统计信息
  • reset(): void -清除对话历史记录
  • setSystemPrompt(prompt: string): void -更新系统提示

API请求帮助程序

api.request(config: APIRequestConfig)

发出带有重试和超时的HTTP请求。

参数:

  • name (可选):日志记录请求名称
  • url (必填):请求URL
  • method (可选):HTTP方法(默认:“GET”)
  • headers (可选):请求标头
  • query (可选):查询参数
  • body (可选):请求正文
  • timeout (可选):超时(毫秒)(默认值:30000)
  • retries (可选):重试尝试(默认值:3)

退货: Promise

便利方法:

  • 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?) -删除请求

______________________________________________________________________

高级用法

自定义提供者

// Coming soon: Plugin system for custom providers

中间件

// Coming soon: Middleware support for request/response processing

流媒体响应

// Coming soon: Streaming support for real-time responses

______________________________________________________________________

贡献

欢迎投稿!请随时提交拉取请求。

  1. 分叉存储库
  2. 创建功能分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add amazing feature')
  4. 推到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

______________________________________________________________________

许可证

MIT© 多米尼克·科西

______________________________________________________________________

致谢

  • 内置于 TypeScript
  • 用途 MCP-SDK
  • 由OpenAI、Anthropic、谷歌和Ollama提供技术支持

______________________________________________________________________

支持

  • 电子邮件:houessoudominique@gmail.com
  • 问题:
  • 讨论:

______________________________________________________________________

由开发者打造,为开发者服务

目录标签

目录标签

AI代理TypeScriptClaude聊天机器人本地部署多LLM支持智能路由TypeScript工具包

支持客户端

Claude

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

token

运行时(runtime,运行环境)

Node.js

来源包(packageName,安装包名)

ts-node

工具数量(toolCount,工具数)

2

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdiotoken部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP