HTTP流MCP模板
用于构建具有HTTP流功能的MCP(模型上下文协议)服务器的基础结构。
概述
此模板使用Streamable HTTP传输协议提供了一个完整的、生产就绪的MCP服务器实现。它包括Hello world功能、全面的测试覆盖率和清晰的文档,可作为开发人员构建自己的MCP服务器的起点。
该模板实现了MCP协议版本2025-06-18,并遵循所有安全最佳实践,使其适用于开发和生产使用。
特性
- ✅ MCP协议2025-06-18合规性 -全面实施最新的MCP规范
- ✅ HTTP流式传输 -POST/GET支持,可选服务器发送事件(SSE)
- ✅ Hello world工具实现 -带有参数处理的完整示例工具
- ✅ 全面的测试覆盖率 -通过单元和集成测试,线路覆盖率达到95%以上
- ✅ 具有严格模式的TypeScript -完全类型安全和现代JavaScript功能
- ✅ 安全最佳实践 -源验证、本地主机绑定、输入净化
- ✅ 可扩展架构 -易于添加新工具和自定义行为
- ✅ 生产就绪 -错误处理、日志记录、正常关机和配置
快速开始
先决条件
- Node.js 18+(推荐:Node.js 20 LTS)
- npm 9+或纱1.22+
安装
- 克隆或下载模板:
git clone my-mcp-server
cd my-mcp-server- 安装依赖项:
npm install- 启动开发服务器:
npm run dev服务器将于启动 http://127.0.0.1:3000 默认情况下。
验证安装
用一个简单的HTTP请求测试服务器:
# Test server health
curl http://127.0.0.1:3000/mcp
# Test MCP initialization (requires proper MCP client)
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "test-client", "version": "1.0.0"}
}
}'配置
环境变量
可以使用环境变量配置服务器:
# Server configuration
export MCP_PORT=3000 # Server port (default: 3000)
export MCP_HOST=127.0.0.1 # Server host (default: 127.0.0.1)
# Start server with custom configuration
npm start程序化配置
import { MCPServer, createDefaultConfig } from './src/index.js';
const config = {
...createDefaultConfig(),
port: 8080,
host: '0.0.0.0', // WARNING: Only use in secure environments
allowedOrigins: ['localhost', '127.0.0.1', 'myapp.com'],
serverInfo: {
name: 'my-custom-mcp-server',
version: '2.0.0'
}
};
const server = new MCPServer(config);
await server.start();配置选项
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
port | number | 3000 | HTTP服务器端口 |
host | string | '127.0.0.1' | 服务器绑定地址 |
allowedOrigins | string\[\] | \['localhost','127.0.0.1'\] | 允许的Origin标头 |
protocolVersion | string | '2025-06-18' | MCP协议版本 |
serverInfo.name | string | “http流mcp模板” | 服务器名称 |
serverInfo.version | string | “1.0.0” | 服务器版本 |
用法
使用Hello工具
该模板包括一个Hello工具,用于演示基本的MCP功能:
# List available tools
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}'
# Call Hello tool without parameters
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "hello",
"arguments": {}
}
}'
# Call Hello tool with name parameter
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "hello",
"arguments": {"name": "Alice"}
}
}'添加自定义工具
- 创建新的工具类:
// src/tools/my-tool.ts
import { ToolImplementation, ToolResult } from '../types/index.js';
export class MyTool implements ToolImplementation {
name = 'my-tool';
description = 'My custom tool';
inputSchema = {
type: 'object',
properties: {
input: { type: 'string' }
}
};
async execute(args: any): Promise {
return {
content: [{ type: 'text', text: `Processed: ${args.input}` }],
isError: false
};
}
}- 注册工具:
// In your server setup
import { MyTool } from './tools/my-tool.js';
const server = new MCPServer(config);
server.registerTool(new MyTool());
await server.start();发展
可用脚本
| 脚本 | 描述 |
|---|---|
npm run dev | 使用热重新加载启动开发服务器 |
npm run build | 将TypeScript构建为JavaScript |
npm start | 启动生产服务器 |
npm test | 运行所有测试 |
npm run test:watch | 在监视模式下运行测试 |
npm run test:coverage | 使用覆盖率报告运行测试 |
npm run lint | 检查代码样式 |
npm run lint:fix | 修复代码风格问题 |
npm run format | 使用Prettier格式化代码 |
项目结构
├── src/
│ ├── types/ # TypeScript type definitions
│ │ ├── index.ts # Main type exports
│ │ ├── mcp.ts # MCP protocol types
│ │ └── server.ts # Server configuration types
│ ├── protocol/ # MCP protocol implementation
│ │ ├── errors.ts # Error handling and standard error codes
│ │ ├── initialization.ts # MCP initialization handshake
│ │ └── jsonrpc.ts # JSON-RPC message handling
│ ├── transport/ # HTTP transport layer
│ │ ├── http-server.ts # Main HTTP server implementation
│ │ ├── content-negotiation.ts # Accept header handling
│ │ └── security-middleware.ts # Origin validation & security
│ ├── server/ # MCP server orchestration
│ │ ├── mcp-server.ts # Main server class
│ │ └── tools-handler.ts # Tool request routing
│ ├── tools/ # Tool implementations
│ │ ├── hello-tool.ts # Hello world tool example
│ │ ├── registry.ts # Tool registration and management
│ │ └── index.ts # Tool exports
│ └── index.ts # Main entry point and exports
├── tests/
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── examples/ # Usage examples
├── dist/ # Compiled JavaScript (generated)
└── coverage/ # Test coverage reports (generated)测试
该模板包括全面的测试覆盖率:
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode during development
npm run test:watch
# Run specific test file
npx vitest run tests/unit/tools/hello-tool.test.ts代码质量
该项目使用ESLint和Prettier来提高代码质量:
# Check for linting issues
npm run lint
# Automatically fix linting issues
npm run lint:fix
# Format code
npm run format生产部署
生产大楼
# Build the project
npm run build
# Start production server
npm startDocker部署
创建一个 Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
EXPOSE 3000
CMD ["npm", "start"]构建并运行:
docker build -t my-mcp-server .
docker run -p 3000:3000 my-mcp-server流程管理
对于生产部署,使用PM2这样的流程管理器:
# Install PM2
npm install -g pm2
# Start with PM2
pm2 start dist/index.js --name mcp-server
# Monitor
pm2 status
pm2 logs mcp-server安全考虑
默认安全功能
- 本地主机绑定:默认情况下,服务器绑定到127.0.0.1
- 原产地验证:验证Origin标头以防止DNS重新绑定攻击
- 输入净化:所有工具输入都经过验证和消毒
- 错误处理:防止通过错误消息泄露信息
生产安全
对于生产部署:
- 使用HTTPS:在生产环境中始终使用TLS
- 防火墙:限制对MCP端口的访问
- 认证:添加身份验证中间件(参见示例)
- 速率限制:对工具调用实施速率限制
- 监控:添加日志记录和监控
添加身份验证
// Example authentication middleware
import { MCPServer } from './src/index.js';
const server = new MCPServer(config);
// Add authentication hook (implement based on your needs)
server.addAuthenticationHook(async (request) => {
const token = request.headers.authorization;
if (!isValidToken(token)) {
throw new Error('Unauthorized');
}
});故障排除
常见问题
服务器无法启动
问题: Error: listen EADDRINUSE :::3000 解决方案:端口3000已在使用中。要么:
- 使用端口3000停止进程:
lsof -ti:3000 | xargs kill - 使用其他端口:
MCP_PORT=3001 npm start
问题: Error: listen EACCES :::80 解决方案:1024以下的端口需要root权限。使用端口3000+或使用sudo运行(不推荐)。
连接被拒绝
问题: curl: (7) Failed to connect to 127.0.0.1 port 3000: Connection refused 解决方案:
- 确保服务器正在运行:
npm run dev - 检查服务器日志中的启动错误
- 验证端口配置
原产地验证错误
问题: Error: Invalid Origin header 解决方案:将您的域名添加到 allowedOrigins 在配置中:
const config = {
...createDefaultConfig(),
allowedOrigins: ['localhost', '127.0.0.1', 'yourdomain.com']
};未找到工具
问题: Method not found: tools/call 解决方案:
- 在调用工具之前,确保服务器已初始化
- 检查工具是否正确登记
- 验证请求中的工具名称
JSON-RPC错误
问题: Parse error 或 Invalid Request 解决方案:
- 确保内容类型为
application/json - 验证JSON语法
- 包含必需的JSON-RPC字段(
jsonrpc,method,id)
调试模式
启用调试日志记录:
# Set debug environment variable
DEBUG=mcp:* npm run dev
# Or in code
process.env.DEBUG = 'mcp:*';健康检查
服务器提供健康检查端点:
# Basic health check
curl http://127.0.0.1:3000/mcp
# Server statistics
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"server/stats"}'性能问题
如果遇到性能问题:
- 检查测试覆盖率:
npm run test:coverage - 配置文件内存使用情况:使用Node.js
--inspect旗帜 - 监控工具执行时间:检查服务器日志
- 验证输入模式:确保有效验证
获取帮助
- 检查日志:服务器日志包含详细的错误信息
- 审查测试用例:测试证明了预期的行为
- 参考MCP规范: MCP协议文件
- 查看示例:参见
examples/使用模式目录
文档
贡献
- 分叉存储库
- 创建要素分支:
git checkout -b feature/my-feature - 进行更改并添加测试
- 确保测试通过:
npm test - 检查代码质量:
npm run lint - 提交更改:
git commit -am 'Add my feature' - 推送到分支:
git push origin feature/my-feature - 创建拉取请求
许可证
MIT许可证-有关详细信息,请参阅许可证文件。
