MCP服务器模板

一个基于TypeScript的MCP服务器模板,支持stdio和HTTP传输,提供可扩展的工具架构和生产就绪的最佳实践。

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

使用说明

MCP服务器模板

用于使用TypeScript构建模型上下文协议(MCP)服务器的生产就绪模板。此模板为支持stdio和HTTP传输、可扩展的工具架构和最佳实践提供了坚实的基础。

特性

  • ✅ 双重运输支持:stdio(默认)和HTTP传输
  • ✅ 类型安全:完全支持TypeScript,启用严格模式
  • ✅ 可扩展架构:便于创建工具的基类
  • ✅ 生产准备就绪:日志记录、错误处理和配置管理
  • ✅ CI/CD:用于自动化测试和npm发布的GitHub操作
  • ✅ 自动依赖关系更新:具有自动合并功能的Dependabot配置
  • ✅ 开发者友好:热装、ESLint和综合工具
  • ✅ 示例工具:以Echo和Ping工具为例

先决条件

  • Node.js>=22.10.0
  • pnpm>=10.19.0

快速开始

1.使用此模板

在GitHub上单击“使用此模板”或克隆此存储库:

git clone https://github.com/yourusername/mcp-server-template.git
cd mcp-server-template

2.安装依赖项

pnpm install

3.以开发模式运行

# stdio transport (default)
pnpm run dev

# HTTP transport (with hot reload)
pnpm run dev:http

4.为生产而建造

pnpm run build

5.试生产

# stdio transport
pnpm run start:stdio

# HTTP transport
pnpm run start:http

项目结构

mcp-server-template/
├── src/
│   ├── server/
│   │   ├── mcp-server.ts       # Main MCP server implementation
│   │   └── tool-registry.ts    # Tool registration and management
│   ├── tools/
│   │   ├── base/
│   │   │   ├── base-tool.ts    # Base class for all tools
│   │   │   └── raw-tool.ts     # Base class for tools with raw option
│   │   ├── implementations/
│   │   │   ├── echo-tool.ts    # Example: Echo tool
│   │   │   └── ping-tool.ts    # Example: Ping tool
│   │   └── base-tool.ts        # Tool utilities
│   ├── types/
│   │   └── index.ts            # Type definitions
│   ├── config/
│   │   └── index.ts            # Configuration management
│   ├── utils/
│   │   └── logger.ts           # Logging utilities
│   └── index.ts                # Entry point
├── dist/                       # Compiled output (generated)
├── logs/                       # Log files (generated)
├── package.json
├── tsconfig.json
├── tsup.config.ts
└── README.md

创建自己的工具

基本工具示例

在中创建新文件 src/tools/implementations/:

import { z } from "zod";
import { BaseTool } from "../base/base-tool.js";
import type { MCPToolResponse } from "../../types/index.js";

type MyToolArgs = {
  input: string;
};

export class MyTool extends BaseTool<MyToolArgs> {
  readonly name = "my_tool";
  readonly description = "Description of what my tool does";

  getInputSchema() {
    return z.object({
      input: z.string().describe("Input parameter description"),
    });
  }

  async execute(args: MyToolArgs): Promise<MCPToolResponse<YourDataType>> {
    // Your tool logic here
    const result = await someOperation(args.input);

    return {
      success: true,
      message: "Operation completed successfully",
      data: result,
    };
  }
}

注册你的工具

将您的工具添加到 src/server/tool-registry.ts:

import { MyTool } from "../tools/implementations/my-tool.js";

// Add to Tool type
type Tool = EchoTool | PingTool | MyTool;

// Add to tools array in initialize()
const tools: Tool[] = [
  new EchoTool(context),
  new PingTool(context),
  new MyTool(context), // Add your tool
];

可用脚本

# Development
pnpm run dev          # Start with stdio transport (hot reload)
pnpm run dev:http     # Start with HTTP transport (hot reload)

# Production
pnpm run build        # Build for production
pnpm run start:stdio  # Run built server with stdio
pnpm run start:http   # Run built server with HTTP

# Code Quality
pnpm run type-check   # Run TypeScript type checking
pnpm run lint         # Run ESLint
pnpm run lint:fix     # Fix ESLint errors automatically

# Testing
pnpm run test         # Run tests once
pnpm run test:watch   # Run tests in watch mode
pnpm run test:coverage # Run tests with coverage

# Maintenance
pnpm run clean        # Remove dist directory
pnpm run knip         # Detect unused files/dependencies
pnpm run knip:fix     # Auto-fix knip issues

配置

配置通过环境变量进行管理,可以在 src/config/index.ts:

export type ServerConfig = {
  server: {
    name: string;
    version: string;
  };
  mcp: {
    maxResponseSize: number;
    defaultPageSize: number;
  };
  logging: {
    level: string;
    enableDebugConsole: boolean;
  };
}

环境变量

  • LOG_LEVEL:日志记录级别(错误|警告|信息|调试,默认值:信息)
  • DEBUG:启用调试控制台输出(true|false,默认值:false)
  • PORT:HTTP服务器端口(默认值:3000)

运输方式

stdio传输(默认)

用于与Claude Desktop等MCP客户端直接集成:

pnpm run dev          # Development
pnpm run start:stdio  # Production

HTTP传输

用于基于HTTP的客户端或调试:

pnpm run dev:http     # Development (port 3000)
pnpm run start:http   # Production (port 3000)

终点:

  • GET /health -健康检查端点
  • POST /mcp -MCP可流式HTTP端点

建筑

工具系统

模板使用 模板方法模式 对于工具:

  1. BaseTool 的:所有工具的抽象基类

    • 处理错误捕获和响应格式化
    • 提供一致的工具定义界面
  2. Rawn工具:工具的扩展底座 raw 选项

    • 支持最小响应模式与完全响应模式
    • 自动处理 raw 参数提取

错误处理

所有工具自动:

  • 捕获和记录错误
  • 返回用户友好的错误消息
  • 集 isError: true 错误响应标志
  • 切勿泄露敏感信息

示例工具

回声工具

返回输入消息的简单工具:

# Test with HTTP transport
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "echo",
      "arguments": {
        "message": "Hello, MCP!"
      }
    }
  }'

Ping工具

返回服务器状态的健康检查工具:

curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "ping",
      "arguments": {}
    }
  }'

日志记录

日志将写入:

  • logs/mcp-server-{timestamp}.log (总是)
  • 控制台输出(仅限HTTP传输)

日志级别: error, warn, info, debug

最佳实践

  1. 工具命名:使用snake_case作为工具名称
  2. 描述:撰写清晰、简洁的工具描述
  3. 输入验证:始终使用Zod模式进行输入验证
  4. 错误消息:返回用户友好的错误消息
  5. 响应格式:使用 MCPToolResponse<T> 用于一致的响应
  6. 上下文:将共享资源添加到 ToolContext 类型

扩展模板

添加API客户端

  1. 在中创建客户端 src/clients/
  2. 增添 ToolContext 输入 src/tools/base-tool.ts
  3. 在中初始化 src/server/tool-registry.ts
  4. 通过以下方式在工具中使用 this.context

添加响应格式化程序

  1. 在中创建格式化程序 src/formatters/
  2. 添加到上下文或直接在工具中导入
  3. 将RawTool基类用于需要优化的工具

发布到npm

此模板包括用于自动发布到npm的GitHub Actions工作流。

设置

  1. 创建npm帐户并获取访问令牌:

    • 首选https://www.npmjs.com/
    • 创建帐户或登录
    • 生成访问令牌:设置→ 访问令牌→ 生成新令牌(自动化)
  2. 将npm令牌添加到GitHub secrets:

    • 转到您的GitHub存储库→ 设置→ 秘密和变量→ 行动
    • 点击“新建存储库密钥”
    • 姓名: NPM_TOKEN
    • 值:您的npm访问令牌
  3. 更新package.json:

    {
      "name": "your-package-name",
      "version": "0.1.0",
      "author": "Your Name",
      "repository": {
        "type": "git",
        "url": "https://github.com/yourusername/your-repo.git"
      }
    }
    

发布新版本

该模板包括两个GitHub Actions工作流:

1.CI工作流程(.github/workflows/ci.yml)

在每次推送和拉取请求时自动运行:

  • 门楣(ESLint)
  • 运行类型检查
  • 运行测试
  • 运行knip(未使用代码检测)
  • 构建项目

2.发布工作流(.github/workflows/publish.yml)

发布到npm的手动工作流程:

  1. 转到您的GitHub存储库→ 操作选项卡
  2. 选择“发布到npm”工作流
  3. 点击“运行工作流”
  4. 输入版本号(例如。, 1.0.1, 1.1.0, 2.0.0)
  5. 点击“运行工作流”

工作流程将:

  • ✅ 运行所有测试
  • ✅ 运行门楣
  • ✅ 运行类型检查
  • ✅ 更新package.json中的版本
  • ✅ 构建项目
  • ✅ 发布到npm
  • ✅ 创建git标签并提交
  • ✅ 将标签推送到GitHub

手动出版(替代)

您还可以手动发布:

# Login to npm
npm login

# Update version
npm version patch  # or minor, major

# Build
pnpm run build

# Publish
npm publish

# Push git tag
git push origin main --tags

版本指南

跟随 语义化版本:

  • 重大 (1.0.0 → 2.0.0):突破性变化
  • 次要的 (1.0.0 → 1.1.0):新功能(向后兼容)
  • 补丁 (1.0.0 → 1.0.1):Bug修复(向后兼容)

依赖管理

此模板包括使用Dependabot的自动依赖关系管理。

Dependabot配置

这 .github/dependabot.yml 配置:

  1. npm依赖关系 (每周一更新一次):

    • 所有更新都分组到一个PR中 (主要、次要、补丁)
    • 每周为npm依赖关系创建一个合并的PR
    • 减少PR噪音,同时保持相关性最新
  2. GitHub操作 (每周一更新一次):

    • 使工作流操作保持最新
    • 将所有操作更新分组在一起
  3. 自动合并 (可选):

    • CI通过后,次要更新和补丁更新可以自动合并
    • 重大更新需要手动审查(带警告注释)
    • 通过配置 .github/workflows/dependabot-auto-merge.yml

运作原理

  1. 自动PR:Dependabot每周一上午9:00创建PR(亚洲/东京)
    • 所有npm依赖项(主+次+补丁)的PR为1
    • GitHub Actions更新的1个PR
  2. CI验证:所有PR都通过CI工作流运行(lint、测试、构建)
  3. 自动合并 (可选):
    • CI通过后,次要/补丁更新会自动合并
    • 重大更新会得到警告注释,需要手动审查
  4. 审查变更:在合并主要更新之前,检查PR差异和测试结果

定制

编辑 .github/dependabot.yml 自定义:

更改更新计划:

schedule:
  interval: "weekly"  # Can be: daily, weekly, monthly
  day: "monday"       # Day of the week
  time: "09:00"       # Time of day
  timezone: "Asia/Tokyo"

更新审阅者/指定人员:

reviewers:
  - "your-github-username"
assignees:
  - "your-github-username"

单独的主要/次要/补丁更新(如果愿意):

如果您希望在单独的PR中进行重大更新,请修改 groups 章节:

groups:
  dependencies:
    patterns:
      - "*"
    update-types:
      - "minor"
      - "patch"
  # Add another package-ecosystem entry for major updates

禁用自动合并

如果您更喜欢手动合并,请删除 .github/workflows/dependabot-auto-merge.yml:

rm .github/workflows/dependabot-auto-merge.yml
git add .github/workflows/dependabot-auto-merge.yml
git commit -m "chore: disable dependabot auto-merge"
git push

贡献

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

许可证

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

资源

支持

对于问题和疑问:

  • GitHub问题:https://github.com/yourusername/mcp-server-template/issues
  • MCP故障:https://discord.gg/modelcontextprotocol

内置于❤️ 使用TypeScript和模型上下文协议