MCP服务器模板

用于构建自定义MCP(模型上下文协议)服务器的模板,提供示例工具、TypeScript设置、测试基础设施和最佳实践。

  • by Theycallmeholla
  • 本地部署
  • 更新于
在 GitHub 查看 theycallmeholla/template-mcp

使用说明

MCP服务器模板

用于构建自定义MCP(模型上下文协议)服务器的模板。该模板提供了一个坚实的基础,包括示例工具、正确的TypeScript设置、测试基础设施和最佳实践。

🚀 快速开始

1.克隆或复制此模板

# Copy the template to your new project
cp -r template-mcp my-new-mcp-server
cd my-new-mcp-server

2.自定义项目

  1. 更新 package.json:

    # Change the name, description, and other metadata
    vim package.json
    
  2. 重命名主客户端类:

    # Rename template-client.ts to something meaningful
    mv src/template-client.ts src/my-client.ts
    
  3. 更新导入 src/index.ts:

    // Change this line:
    import { TemplateClient } from './template-client.js';
    // To:
    import { MyClient } from './my-client.js';
    

3.安装和构建

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

📁 项目结构

my-mcp-server/
├── src/
│   ├── index.ts              # Main MCP server implementation
│   └── template-client.ts    # Business logic and external API calls
├── tests/
│   └── template-client.test.ts # Test suite
├── dist/                     # Compiled TypeScript output
├── package.json              # Project configuration
├── tsconfig.json             # TypeScript configuration
├── jest.config.js            # Testing configuration
├── .gitignore               # Git ignore rules
└── README.md                # This file

🛠️ 自定义您的MCP服务器

1.定义你的工具

编辑 src/index.ts 在中定义您的工具 ListToolsRequestSchema 处理程序:

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: 'my_custom_tool',
        description: 'Description of what this tool does',
        inputSchema: {
          type: 'object',
          properties: {
            // Define your tool's input parameters
            param1: {
              type: 'string',
              description: 'Description of param1',
            },
            param2: {
              type: 'number',
              description: 'Description of param2',
              default: 10,
            },
          },
          required: ['param1'],
        },
      },
      // Add more tools here...
    ],
  };
});

2.执行工具逻辑

在中添加相应案例 CallToolRequestSchema 处理程序:

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  try {
    switch (name) {
      case 'my_custom_tool': {
        const result = await myClient.myCustomMethod(
          args.param1 as string,
          args.param2 as number || 10
        );
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      }
      // Add more cases here...
    }
  } catch (error) {
    // Error handling...
  }
});

3.实现业务逻辑

编辑 src/template-client.ts (或您重命名的客户端)来实现您的实际业务逻辑:

export class MyClient {
  constructor(apiKey?: string, baseUrl?: string) {
    // Initialize your client with necessary configuration
  }

  async myCustomMethod(param1: string, param2: number): Promise<any> {
    // Implement your business logic here
    // Make API calls, process data, etc.
    return {
      result: 'Your processed result',
      input: { param1, param2 },
    };
  }
}

🔧 配置

环境变量

创建一个 .env 敏感配置文件:

API_KEY=your_api_key_here
BASE_URL=https://api.yourservice.com
DEBUG=true

在客户端中加载环境变量:

import dotenv from 'dotenv';
dotenv.config();

export class MyClient {
  constructor() {
    this.apiKey = process.env.API_KEY;
    this.baseUrl = process.env.BASE_URL || 'https://api.example.com';
  }
}

Claude桌面集成

将您的服务器添加到Claude Desktop的配置中:

  1. 打开 ~/Library/Application Support/Claude/claude_desktop_config.json
  2. 添加您的服务器:
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["/path/to/your/project/dist/index.js"],
      "env": {
        "API_KEY": "your_api_key_here"
      }
    }
  }
}
  1. 重新启动克劳德桌面

🧪 测试

运行测试

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run with coverage
npm run test:coverage

写作测试

在中为自定义方法添加测试 tests/:

import { MyClient } from '../src/my-client';

describe('MyClient', () => {
  let client: MyClient;

  beforeAll(() => {
    client = new MyClient();
  });

  test('should process data correctly', async () => {
    const result = await client.myCustomMethod('test', 42);
    expect(result).toBeDefined();
    expect(result.input.param1).toBe('test');
  });
});

📦 建筑和配电

为生产而建

# Clean previous build
npm run clean

# Build
npm run build

# The built files will be in dist/

发布到npm

  1. 更新版本 package.json
  2. 构建项目
  3. 发布:
npm publish

🔍 调试

启用调试日志记录

// In your client, add debug logging
console.error('Debug:', { param1, param2, result });

直接测试服务器

# Run the server directly to test
npm start

# Or run in development mode with auto-reload
npm run dev

📚 常见模式

1.API客户端模式

export class MyApiClient {
  private httpClient: AxiosInstance;

  constructor(apiKey: string, baseUrl: string) {
    this.httpClient = axios.create({
      baseURL: baseUrl,
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    });
  }

  async getData(id: string): Promise<any> {
    const response = await this.httpClient.get(`/data/${id}`);
    return response.data;
  }
}

2.数据处理模式

export class DataProcessor {
  static filterData<T>(data: T[], predicate: (item: T) => boolean): T[] {
    return data.filter(predicate);
  }

  static transformData<T, U>(data: T[], transformer: (item: T) => U): U[] {
    return data.map(transformer);
  }
}

3.错误处理模式

export class CustomError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode?: number
  ) {
    super(message);
    this.name = 'CustomError';
  }
}

// Usage in tools
try {
  const result = await myClient.riskyOperation();
  return result;
} catch (error) {
  if (error instanceof CustomError) {
    throw new McpError(ErrorCode.InternalError, `Custom error: ${error.message}`);
  }
  throw new McpError(ErrorCode.InternalError, `Unexpected error: ${error}`);
}

🤝 贡献

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/my-feature
  3. 进行更改
  4. 为您的更改添加测试
  5. 运行测试: npm test
  6. 提交您的更改: git commit -am 'Add some feature'
  7. 推到分支: git push origin feature/my-feature
  8. 提交拉取请求

📄 许可证

MIT许可证-有关详细信息,请参阅许可证文件。

🆘 获取帮助

  • 检查 MCP文件
  • 查看 SDK参考
  • 查看示例实现
  • 如果发现错误或需要功能,请打开问题

🚀 后续步骤

自定义此模板后:

  1. 替换所有占位符内容 与您的实际实施
  2. 添加适当的错误处理 针对您的特定用例
  3. 实施身份验证 如果您的服务需要它
  4. 添加输入验证 对于您的工具参数
  5. 编写全面的测试 为您的业务逻辑
  6. 更新文档 以反映您的实际工具和使用情况
  7. 配置CI/CD 用于自动化测试和部署

快乐建筑! 🎉