MCP服务器模板

一个用于在Node.js中构建模型上下文协议(MCP)服务器的简单样板,提供HTTP MCP传输、自动JSON模式生成、工具注册和API密钥认证等功能。

  • by Helmi97
  • JavaScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Helmi97/MCP-JS-Server

使用说明

MCP JS服务器模板

一个用于在Node.js中构建模型上下文协议(MCP)服务器的简单样板:

  • HTTP MCP传输
  • 从Zod自动生成JSON模式
  • 通过单个配置文件轻松注册工具
  • 可选的API密钥身份验证
  • 集中记录和错误处理

快速开始

克隆存储库:

git clone https://github.com/Helmi97/MCP-JS-Server.git
cd mcp-js-server
npm install
npm start

您应该看到服务器信息,包括MCP和工具端点。

项目结构

mcp-js-server/
  package.json
  src/
    server.js         # Main entry point
    toolRegistry.js   # Tool loader, zod→JSON schema generator
    tools.config.js   # The ONLY file developers edit to add tools
    logger.js         # Logging middleware
    auth.js           # Optional API key middleware

添加工具

编辑:

src/tools.config.js

添加新块:

defineTool({
  name: "echo",
  title: "Echo Tool",
  description: "Returns the input message",
  inputShape: {
    message: z.string()
  },
  async handler({ message }) {
    const result = `Echo: ${message}`;
    return {
      content: [{ type: "text", text: result }],
      structuredContent: { result }
    };
  }
});

重新启动:

npm start

现在访问:

http://localhost:3000/tools

您的工具将会出现。

端点

GET/工具

列出工具和模式。

POST/mcp

MCP JSON-RPC接口。

要求:

Accept: application/json, text/event-stream

例子:

curl -i http://localhost:3000/mcp   -H "Content-Type: application/json"   -H "Accept: application/json, text/event-stream"   -d '{
    "jsonrpc": "2.0",
    "id": "1",
    "method": "tools/call",
    "params": {
      "name": "get_weather",
      "arguments": { "city": "Dortmund", "unit": "c" }
    }
  }'

身份验证(可选)

启用API密钥:

export MCP_API_KEY=secret

客户端必须发送:

x-api-key: secret

调试日志记录

启用:

DEBUG=1 npm start