MCP后端服务器
概述
使用TypeScript构建的专业模型上下文协议(MCP)后端服务器,实现 SOLID原则 和 清洁建筑 模式。具有双重访问模式:用于开发的本地MCP协议和用于外部集成的HTTP REST API。
✨ 主要特点
- 🏗️ 固态架构:完全符合所有5项SOLID原则
- 🔧 清洁建筑:六边形(端口和适配器)模式实现
- 🚀 双重访问:MCP协议+HTTP REST API包装器
- 🔍 类型安全:具有严格模式的完整TypeScript实现
- ✅ 综合测试:100%覆盖率的单元测试
- 📝 领域驱动:具有验证功能的丰富域模型
- 💉 依赖注入:IoC容器用于松耦合
- 📊 结构化日志记录:不同级别的集中日志记录
- 🔒 输入验证:所有端点的Zod模式验证
🏛️ 架构概述
SOLID原则实施
✅ S单一责任原则(SRP)
- 控制器:仅处理HTTP请求/响应
- 服务:纯业务逻辑实现
- 仓库:数据访问抽象
- 验证器:仅输入验证
- 模型:域实体表示
✅ 英语字母表的第15个字母笔/闭合原理(OCP)
- 基于界面的设计允许无需修改即可扩展
- 新工具和资源的插件架构
- 不同实现的策略模式
✅ L伊斯科夫替代原理(LSP)
- 所有实现都正确地替换了它们的接口
- HttpClient可以用任何IHttpClient实现替换
- 记录器实现完全可互换
✅ 一、界面隔离原则
- 聚焦界面(
IHttpClient,ILogger,IResourceService) - 不强制依赖未使用的方法
- 客户特定界面设计
✅ D依赖性反转原理
- 高级模块不依赖于低级模块
- 两者都依赖于抽象(接口)
- ServiceContainer管理所有依赖关系
🏗️ 分层体系结构
┌─────────────────────────────────────────────────────────────┐
│ ADAPTERS LAYER │
│ ┌─────────────────┐ ┌─────────────────┐ ┌──────────────┐ │
│ │ HTTP REST API │ │ MCP Protocol │ │ Controllers │ │
│ │ (Express) │ │ (stdio) │ │ Routes │ │
│ └─────────────────┘ └─────────────────┘ └──────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ APPLICATION LAYER │
│ ┌─────────────────┐ ┌─────────────────┐ ┌──────────────┐ │
│ │ Services │ │ Use Cases │ │ Handlers │ │
│ │ (Business Logic)│ │ (Orchestration) │ │ (MCP Tools) │ │
│ └─────────────────┘ └─────────────────┘ └──────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ DOMAIN LAYER │
│ ┌─────────────────┐ ┌─────────────────┐ ┌──────────────┐ │
│ │ Entities │ │ Value Objects │ │ Interfaces │ │
│ │ (User, Post, │ │ (Validation) │ │ (Contracts) │ │
│ │ Comment) │ │ │ │ │ │
│ └─────────────────┘ └─────────────────┘ └──────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ INFRASTRUCTURE LAYER │
│ ┌─────────────────┐ ┌─────────────────┐ ┌──────────────┐ │
│ │ HTTP Client │ │ Logger │ │ External │ │
│ │ (node-fetch) │ │ (Console) │ │ APIs │ │
│ └─────────────────┘ └─────────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘📁 项目结构
src/
├── adapters/ # 🔌 External interfaces
│ ├── controllers/ # HTTP request handlers
│ │ ├── resourceController.ts
│ │ ├── toolController.ts
│ │ └── index.ts
│ ├── routes/ # Route definitions
│ │ └── httpRoutes.ts
│ ├── validators/ # Input validation schemas
│ │ └── httpValidators.ts
│ ├── httpAdapter.ts # Express server setup
│ ├── mcpAdapter.ts # MCP SDK wrapper
│ └── mcpServerAdapter.ts # MCP server configuration
├── application/ # 🎯 Business logic
│ ├── services/ # Core business services
│ │ ├── resourceService.ts # Resource operations
│ │ └── toolService.ts # Tool operations
│ ├── interfaces/ # Dependency contracts
│ │ └── index.ts # All interfaces
│ ├── container/ # Dependency injection
│ │ └── serviceContainer.ts
│ ├── resources/ # MCP resource handlers
│ │ └── resourceHandlers.ts
│ ├── tools/ # MCP tool handlers
│ │ └── toolHandlers.ts
│ └── index.ts # Layer exports
├── domain/ # 🎭 Business entities
│ ├── user.ts # User entity & validation
│ ├── post.ts # Post entity & validation
│ ├── comment.ts # Comment entity & validation
│ └── index.ts # Domain exports
├── infrastructure/ # 🔧 Technical implementations
│ ├── httpClient.ts # HTTP client implementation
│ ├── logger.ts # Logging implementation
│ ├── fetchUtil.ts # Legacy utility (deprecated)
│ └── index.ts # Infrastructure exports
├── server.ts # MCP server entry point
└── httpServer.ts # HTTP server entry point🚀 快速开始
先决条件
- Node.js≥18.0.0
- npm或纱线
安装
# Clone and install dependencies
git clone
cd mcp-example
npm install开发命令
# Build the project
npm run build
# Start MCP server (for MCP Inspector)
npm start
# Start HTTP REST API server
npm run start:http
# Run tests with coverage
npm test
# Lint and fix code
npm run lint
npm run format🔌 API终点
基本URL: http://localhost:3001
📊 资源
GET /api/users-获取所有用户GET /api/posts-获取所有帖子GET /api/comments?postId=-获取评论(可选过滤)
🔧 工具
POST /api/calculate-数学运算POST /api/temperature-温度转换
📖 文档
GET /health-健康检查GET /api/docs-完整的API文件
请求示例
计算
curl -X POST http://localhost:3001/api/calculate \
-H "Content-Type: application/json" \
-d '{"a": 10, "b": 5, "operation": "add"}'温度转换
curl -X POST http://localhost:3001/api/temperature \
-H "Content-Type: application/json" \
-d '{"value": 25, "fromUnit": "celsius", "toUnit": "fahrenheit"}'🧪 测试
测试覆盖率
- 单元测试:所有服务、控制器和公用设施
- 集成测试:完整的HTTP API工作流
- 域测试:实体验证和转换
- 基础设施测试:外部集成
# Run all tests
npm test
# Run tests in watch mode
npm test -- --watch
# Run specific test file
npm test -- --testPathPattern=resourceController🔧 配置
环境变量
# Copy example configuration
cp .env.example .env
# Available variables
NODE_ENV=development # Environment mode
PORT=3001 # HTTP server port
API_BASE_URL=https://... # External API URL
LOG_LEVEL=debug # Logging level🚀 部署
生产建设
npm run build
NODE_ENV=production node dist/httpServer.jsDocker支持
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
EXPOSE 3001
CMD ["node", "dist/httpServer.js"]🔧 扩展指南
添加新资源
- 创建域模型 (
src/domain/) - 实施服务 (
src/application/services/) - 添加控制器 (
src/adapters/controllers/) - 注册路线 (
src/adapters/routes/) - 添加验证 (
src/adapters/validators/) - 编写测试 (
tests/)
添加新工具
- 实施服务逻辑 (
src/application/services/) - 创建MCP处理程序 (
src/application/tools/) - 添加HTTP控制器 (
src/adapters/controllers/) - 定义验证模式 (
src/adapters/validators/) - 注册路由 (
src/adapters/routes/)
自定义实现
// Example: Custom HTTP Client
export class CustomHttpClient implements IHttpClient {
async fetch(url: string, options?: any): Promise {
// Your implementation
}
}
// Register in ServiceContainer
const customClient = new CustomHttpClient();
container.register('httpClient', customClient);📊 监控和记录
日志级别
- 调试:详细的执行信息
- 信息:一般操作信息
- 警告:警告条件
- 错误:错误条件
日志输出示例
[INFO] Successfully fetched 10 users
[DEBUG] Processing GET /api/users request
[WARN] Invalid query parameters for comments request
[ERROR] Failed to fetch posts: HTTP 500🤝 贡献
- 代码的风格:遵循现有的Types/ESLint配置
- 测试:保持100%的测试覆盖率
- 文档:更新README以获取新功能
- 建筑:遵循SOLID原则和清洁架构
- 承诺:使用常规提交消息
📋 开发检查表
- \[ \] 可靠的合规性:每个类都有单一的职责
- \[ \] 接口隔离:无脂肪界面
- \[ \] 依赖注入:使用服务容器
- \[ \] 类型安全:严格的TypeScript模式
- \[ \] 输入验证:所有输入的Zod模式
- \[ \] 错误处理:正确的错误传播
- \[ \] 日志记录:全程结构化日志记录
- \[ \] 测试:单元+集成测试
- \[ \] 文档:英文评论
📚 技术栈
核心
- TypeScript 5.9.2 -类型安全的JavaScript
- Node.js 18+ -运行时环境
- 佐德3.25.76 -架构验证
MCP集成
- @模型上下文协议/sdk 1.17.4 -MCP协议支持
HTTP服务器
- 快递5.1.0 -Web应用程序框架
- CORS 2.8.5 版本 -跨源资源共享
测试
- Jest 30.0.5 -测试框架
- 超级测试7.1.4 -HTTP集成测试
- 玩笑29.4.1 -对Jest的TypeScript支持
开发工具
- ESLint 9.34.0 版本 -代码linting
- 预处理3.6.2 -代码格式
- TypeScript ESLint -TypeScript特定的linting
👤 作者
Jaury Abreu\ 📧 abreuj03@thryv.com\ 🏢 Threv,股份有限公司。
📄 许可证
ISC许可证-有关详细信息,请参阅许可证文件。
🔄 版本历史记录
v1.0.0
- ✅ SOLID架构的初始版本
- ✅ 清洁架构实施
- ✅ 双MCP/HTTP访问模式
- ✅ 全面的测试覆盖率
- ✅ 完整的TypeScript实现
- ✅ 依赖注入容器
- ✅ 结构化测井系统
