MCP协议服务器

基于Express.js和TypeScript的模块化Model Context Protocol (MCP)服务器实现,支持HTTP流式传输、会话管理和工具集成。

  • by hencydsouza24
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 hencydsouza24/mcp_demo

使用说明

快速MCP服务器

使用Express.js和TypeScript的模型上下文协议(MCP)的干净、模块化实现。

快速开始

# Install dependencies
npm install

# Development (with file watching)
npm run dev

# Production
npm run build
npm start

# Type checking
npm run type-check

服务器在上运行 http://localhost:3001

端点

  • 健康: GET /mcp/health -服务器运行状况
  • 信息: GET /mcp/info -服务器信息和功能
  • MCP协议: POST/GET/DELETE /mcp -支持流媒体的主要MCP端点

项目结构

src/
├── index.ts              Entry point - starts the server
├── app.ts                Express app factory
├── server/
│   └── mcp.ts            Core MCP server logic
├── routes/
│   └── mcp.ts            HTTP route handlers
└── tools/
    └── index.ts          Tool definitions

总计:201行清晰易读的代码

建筑

单一责任原则

每个模块都有一个明确的目的:

  • index.ts (10行)-服务器启动
  • app.ts (20行)-快速设置
  • server/mcp.ts (60行)-MCP协议处理
  • routes/mcp.ts (69行)-HTTP路由
  • tools/index.ts (42行)-工具目录

特性

✓ 官方MCP SDK集成(StreamableHTTPServerTransport) ✓ HTTP流(分块编码+服务器发送事件) ✓ 具有自动UUID生成功能的会话管理 ✓ 工具输入的Zod模式验证 ✓ 全面的错误处理 ✓ 健康检查和信息端点 ✓ TypeScript严格模式

工具

包括三个示例工具:

  1. 添加(a,b) -加两个数字
  2. 乘(x,y) -将两个数字相乘
  3. 回声(消息) -回一条消息

添加新工具

编辑 src/tools/index.ts 并添加到数组中:

{
  name: "my-tool",
  description: "What this tool does",
  inputSchema: {
    param1: z.string().describe("Parameter description"),
    param2: z.number().describe("Another parameter"),
  },
  handler: async (args) => {
    const p1 = args.param1 as string;
    const p2 = args.param2 as number;
    // Tool logic here
    return `Result: ${p1} ${p2}`;
  },
}

然后重建:

npm run build
npm start

测试

# Health check
curl http://localhost:3001/mcp/health

# Server info
curl http://localhost:3001/mcp/info

# MCP protocol request (with proper headers)
curl -X POST http://localhost:3001/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

发展

# Watch mode (recompiles on file changes)
npm run dev

# Type checking only
npm run type-check

# Build production bundle
npm run build

环境变量

  • PORT (默认值:3001)-服务器端口
PORT=4000 npm start

堆栈

  • Express.js -Web框架
  • TypeScript -类型安全
  • 萨德 -架构验证
  • MCP-SDK -协议实施
  • Node.js 18+ -运行时间

标准

  • MCP协议版本:2024-11-05
  • HTTP流媒体:分块编码+SSE
  • 模式验证:Zod
  • 代码格式:带严格模式的TypeScript
  • 代码样式:制表符,格式一致

文档

许可证

麻省理工学院