MCP服务器模板

一个基于TypeScript的Model Context Protocol服务器模板,提供身份验证、错误处理、速率限制、输入验证、测试设置和Docker部署等功能。

  • by sairam3824
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 sairam3824/mcp-server-template

使用说明

MCP服务器模板

生产就绪的建筑模板 模型上下文协议(MCP) TypeScript中的服务器。包括身份验证、错误处理、速率限制、输入验证、测试设置和Docker部署。

特性

  • ✅ 具有严格类型的完全TypeScript支持
  • ✅ 使用Zod模式进行输入验证
  • ✅ 使用令牌桶算法进行速率限制
  • ✅ 使用Pino进行结构化日志记录
  • ✅ 全面的错误处理
  • ✅ Docker支持多阶段构建
  • ✅ 通过示例进行Jest测试设置
  • ✅ GitHub操作CI/CD
  • ✅ 示例工具、资源和提示
  • ✅ 交互式设置脚本

快速开始

# Clone the template
git clone https://github.com/your-username/mcp-server-template.git my-mcp-server
cd my-mcp-server

# Run interactive setup
npm run setup

# Start development
npm run dev

注: 在运行之前,您可能会在测试文件中看到TypeScript错误 npm install这是正常的-一旦安装了Jest类型,错误就会消失。

建筑

graph TD
    A[Claude Desktop] -->|stdio| B[MCP Server]
    B --> C[Request Handler]
    C --> D[Rate Limiter]
    D --> E[Validator]
    E --> F[Tool Executor]
    F --> G[Logger]
    F --> H[Error Handler]
    
    style B fill:#f9f,stroke:#333,stroke-width:2px
    style F fill:#bbf,stroke:#333,stroke-width:2px

项目结构

mcp-server-template/
├── src/
│   ├── index.ts              # Server entry point
│   ├── tools/                # Tool implementations
│   │   ├── hello-world.ts    # Example: Simple tool
│   │   ├── fetch-data.ts     # Example: HTTP requests
│   │   └── database-query.ts # Example: Database queries
│   ├── resources/            # MCP resources
│   ├── prompts/              # Prompt templates
│   ├── middleware/
│   │   ├── rate-limiter.ts   # Token bucket rate limiting
│   │   ├── validator.ts      # Zod validation
│   │   ├── logger.ts         # Pino logging
│   │   └── error-handler.ts  # Error handling
│   ├── utils/
│   │   └── config.ts         # Environment config
│   └── types/                # TypeScript types
├── tests/                    # Jest tests
├── scripts/
│   └── setup.sh             # Interactive setup
└── Dockerfile               # Production Docker image

添加新工具

1.创建工具文件

创建 src/tools/my-tool.ts:

import { z } from 'zod';
import { validate } from '../middleware/validator.js';
import { logger } from '../middleware/logger.js';

const MyToolSchema = z.object({
  input: z.string().min(1)
});

export const myTool = {
  name: 'my_tool',
  description: 'Description of what my tool does',
  inputSchema: {
    type: 'object',
    properties: {
      input: {
        type: 'string',
        description: 'Input parameter description'
      }
    },
    required: ['input']
  },
  
  async execute(args: unknown) {
    const input = validate(MyToolSchema, args);
    logger.info({ input }, 'Executing my_tool');
    
    // Your tool logic here
    const result = `Processed: ${input.input}`;
    
    return {
      content: [{ type: 'text', text: result }]
    };
  }
};

2.注册工具

添加 src/index.ts:

import { myTool } from './tools/my-tool.js';

const tools = [helloWorldTool, fetchDataTool, databaseQueryTool, myTool];

3.添加测试

创建 tests/my-tool.test.ts:

import { myTool } from '../src/tools/my-tool.js';

describe('My Tool', () => {
  it('should process input correctly', async () => {
    const result = await myTool.execute({ input: 'test' });
    expect(result.content[0].text).toContain('test');
  });
});

配置

复制 .env.example 到 .env 并配置:

NODE_ENV=development
LOG_LEVEL=info
RATE_LIMIT_TOKENS=100
RATE_LIMIT_REFILL_RATE=10
DATABASE_URL=postgresql://user:password@localhost:5432/dbname

测试

# Run all tests
npm test

# Watch mode
npm run test:watch

# With coverage
npm test -- --coverage

部署

码头工人

# Build image
docker build -t my-mcp-server .

# Run container
docker-compose up

Claude桌面配置

添加到您的Claude桌面配置(~/Library/Application Support/Claude/claude_desktop_config.json 在macOS上):

{
  "mcpServers": {
    "my-mcp-server": {
      "command": "node",
      "args": ["/absolute/path/to/my-mcp-server/dist/index.js"]
    }
  }
}

或用于开发:

{
  "mcpServers": {
    "my-mcp-server": {
      "command": "npm",
      "args": ["run", "dev"],
      "cwd": "/absolute/path/to/my-mcp-server"
    }
  }
}

发展

# Install dependencies
npm install

# Start development server
npm run dev

# Run server with MCP Inspector (Interactive Web UI for testing)
npx @modelcontextprotocol/inspector node dist/index.js
# Or using tsx directly:
npx @modelcontextprotocol/inspector npm run dev

# Lint code
npm run lint

# Format code
npm run format

# Build for production
npm run build

示例工具

你好_世界

演示基本输入/输出的简单问候工具。

fetch_data

HTTP客户端工具,用于通过可配置的方法和标头从URL中获取数据。

数据库查询

数据库查询工具(占位符实现-添加您的数据库客户端)。

资源

贡献

欢迎投稿!请随时提交拉取请求。

许可证

MIT许可证-请参阅 许可证 了解详情。

支持

  • 为bug或功能请求打开问题
  • 在创建新问题之前检查现有问题
  • 提供错误的详细复制步骤