锅炉板MCP服务器
在TypeScript中开发自定义模型上下文协议(MCP)服务器的基础。提供完整的分层架构模式、工作示例工具和开发人员基础设施,将AI助手与外部API和数据源连接起来。
](https://www.npmjs.com/package/@aashari/boilerplate-mcp-server)   
为什么要使用这个锅炉板?
- 生产就绪架构:遵循已发布的MCP服务器中使用的相同模式,CLI、工具、控制器和服务之间保持了清晰的分离
- 类型安全:使用TypeScript构建,以改善开发人员体验、代码质量和可维护性
- 工作示例:包括完全实现的工具,演示从CLI到API集成的完整模式
- 测试框架:用于单元和CLI集成测试的即用型测试基础架构,具有覆盖率报告功能
- 完整的开发人员工具:预配置的ESLint、Prettier、TypeScript和CI/CD工作流
什么是MCP?
模型上下文协议(MCP)是一个开放标准,用于将人工智能系统安全地连接到外部工具和数据源。该样板文件采用一种干净、分层的体系结构来实现MCP规范,该体系结构可以扩展为为任何API或数据源构建自定义MCP服务器。
先决条件
- Node.js (>=18.x): 下载
- Git:用于版本控制
快速开始
# Clone the repository
git clone https://github.com/aashari/boilerplate-mcp-server.git
cd boilerplate-mcp-server
# Install dependencies
npm install
# Start development server
npm run dev:server
# Try the example tool
npm run dev:cli -- get-ip-details 8.8.8.8架构概述
Project Structure (Click to expand)
src/
├── cli/ # Command-line interfaces
│ ├── index.ts # CLI entry point
│ └── *.cli.ts # Feature-specific CLI modules
├── controllers/ # Business logic
│ └── *.controller.ts # Feature controllers
├── services/ # External API interactions
│ └── *.service.ts # Service modules
├── tools/ # MCP tool definitions
│ ├── *.tool.ts # Tool implementations
│ └── *.types.ts # Tool argument schemas
├── types/ # Type definitions
│ └── common.types.ts # Shared type definitions
├── utils/ # Shared utilities
│ ├── logger.util.ts # Structured logging
│ ├── error.util.ts # Error handling
│ └── ... # Other utility modules
└── index.ts # Server entry point分层架构
样板遵循一个干净、分层的架构,促进了可维护性和明确的关注点分离:
1.CLI层(src/cli/*.cli.ts)
- 目的:解析参数和调用控制器的命令行接口
- 模式:使用
commander对于参数解析,调用控制器,使用以下命令处理错误handleCliError - 命名:
.cli.ts
2.工具层(src/tools/*.tool.ts)
- 目的:向AI助手公开MCP工具定义
- 模式:使用
zod用于模式验证、呼叫控制器、MCP的格式响应 - 命名:
.tool.ts类型在.types.ts
3.控制器层(src/controllers/*.controller.ts)
- 目的:业务逻辑编排、错误处理、响应格式
- 模式:返回标准化
ControllerResponse对象,根据上下文抛出错误 - 命名:
.controller.ts可选.formatter.ts
4.服务层(src/services/*.service.ts)
- 目的:外部API交互和数据处理
- 模式:具有最小逻辑的纯API调用,返回原始数据
- 命名:
.service.ts或vendor...service.ts
5. 工具层(src/utils/*.util.ts)
- 目的:跨应用程序共享功能
- 关键实用程序:日志记录、错误处理、格式化、配置
开发者指南
开发脚本
# Start server in dev mode with hot-reload & inspector
npm run dev:server
# Run CLI commands in development
npm run dev:cli -- [command] [args]
# Build the project
npm run build
# Production server
npm start
npm run start:server
# Production CLI
npm run start:cli -- [command] [args]
# Testing
npm test # Run all tests
npm test -- src/path/to/test.ts # Run specific tests
npm run test:coverage # Generate coverage report
# Code Quality
npm run lint # Run ESLint
npm run format # Format with Prettier
npm run typecheck # Check TypeScript types调试工具
- MCP检查员:用于测试MCP工具的可视化工具
- 使用以下命令运行服务器 npm run dev:server - 打开http://localhost:5173在您的浏览器中
- 服务器日志:启用
DEBUG=true npm run dev:server或在配置中
Configuration (Click to expand)
创建 ~/.mcp/configs.json:
{
"boilerplate": {
"environments": {
"DEBUG": "true",
"ANY_OTHER_CONFIG": "value"
}
}
}构建自定义工具
Step-by-Step Tool Implementation Guide (Click to expand)
1.定义服务层
在中创建新服务 src/services/ 与外部API交互:
// src/services/example.service.ts
import { Logger } from '../utils/logger.util.js';
const logger = Logger.forContext('services/example.service.ts');
export async function getData(param: string): Promise {
logger.debug('Getting data', { param });
// API interaction code here
return { result: 'example data' };
}2.创建控制器
在中添加控制器 src/controllers/ 处理业务逻辑:
// src/controllers/example.controller.ts
import { Logger } from '../utils/logger.util.js';
import * as exampleService from '../services/example.service.js';
import { formatMarkdown } from '../utils/formatter.util.js';
import { handleControllerError } from '../utils/error-handler.util.js';
import { ControllerResponse } from '../types/common.types.js';
const logger = Logger.forContext('controllers/example.controller.ts');
export interface GetDataOptions {
param?: string;
}
export async function getData(
options: GetDataOptions = {},
): Promise {
try {
logger.debug('Getting data with options', options);
const data = await exampleService.getData(options.param || 'default');
const content = formatMarkdown(data);
return { content };
} catch (error) {
throw handleControllerError(error, {
entityType: 'ExampleData',
operation: 'getData',
source: 'controllers/example.controller.ts',
});
}
}3.实施MCP工具
在中创建工具定义 src/tools/:
// src/tools/example.tool.ts
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { Logger } from '../utils/logger.util.js';
import { formatErrorForMcpTool } from '../utils/error.util.js';
import * as exampleController from '../controllers/example.controller.js';
const logger = Logger.forContext('tools/example.tool.ts');
const GetDataArgs = z.object({
param: z.string().optional().describe('Optional parameter'),
});
type GetDataArgsType = z.infer;
async function handleGetData(args: GetDataArgsType) {
try {
logger.debug('Tool get_data called', args);
const result = await exampleController.getData({
param: args.param,
});
return {
content: [{ type: 'text' as const, text: result.content }],
};
} catch (error) {
logger.error('Tool get_data failed', error);
return formatErrorForMcpTool(error);
}
}
export function register(server: McpServer) {
server.tool(
'get_data',
`Gets data from the example API, optionally using \`param\`.
Use this to fetch example data. Returns formatted data as Markdown.`,
GetDataArgs.shape,
handleGetData,
);
}4.添加CLI支持
在中创建CLI命令 src/cli/:
// src/cli/example.cli.ts
import { program } from 'commander';
import { Logger } from '../utils/logger.util.js';
import * as exampleController from '../controllers/example.controller.js';
import { handleCliError } from '../utils/error-handler.util.js';
const logger = Logger.forContext('cli/example.cli.ts');
program
.command('get-data')
.description('Get example data')
.option('--param ', 'Optional parameter')
.action(async (options) => {
try {
logger.debug('CLI get-data called', options);
const result = await exampleController.getData({
param: options.param,
});
console.log(result.content);
} catch (error) {
handleCliError(error);
}
});5.注册组件
更新入口点以注册新组件:
// In src/cli/index.ts
import '../cli/example.cli.js';
// In src/index.ts (for the tool)
import exampleTool from './tools/example.tool.js';
// Then in registerTools function:
exampleTool.register(server);发布您的MCP服务器
- 用您的详细信息更新package.json:
{
"name": "your-mcp-server-name",
"version": "1.0.0",
"description": "Your custom MCP server",
"author": "Your Name",
// Other fields...
}- 使用您的工具文档更新README.md
- 构建:
npm run build
- 测试:
npm run start:server
- 发布:
npm publish
测试最佳实践
- 单元测试:单独测试实用程序和纯函数
- 控制器测试:使用模拟服务调用测试业务逻辑
- 集成测试:使用真实依赖关系测试CLI
- 覆盖目标:目标测试覆盖率>80%
