使用TypeScript构建一个最简单的MCP服务器

发布于:2025-06-05 ⋅ 阅读:(28) ⋅ 点赞:(0)

什么是MCP?

Model Context Protocol(模型上下文协议)是一个开放标准,它允许AI助手与外部工具和数据源进行标准化通信。简单来说,MCP就像是AI和各种工具之间的"翻译官",让AI能够调用你编写的自定义功能。

项目准备

1. 初始化项目

首先,让我们创建一个新的TypeScript项目:

mkdir mcp-calculator-server
cd mcp-calculator-server
npm init -y

2. 安装核心依赖

# 核心MCP SDK
npm install @modelcontextprotocol/sdk

# 输入验证库
npm install zod

# TypeScript相关依赖
npm install -D typescript @types/node

# 创建TypeScript配置
npx tsc --init

3. 项目结构设计

mcp-calculator-server/
├── package.json          # 项目配置
├── tsconfig.json         # TypeScript配置
├── src/
│   └── server/
│       └── index.ts      # 主服务器文件
├── build/                # 编译输出
└── .vscode/
    └── mcp.json          # VS Code MCP配置

核心代码实现

1. 服务器基础框架

让我们从最基本的服务器结构开始:

#!/usr/bin/env node

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

/**
 * MCP Calculator Server
 * 一个功能完整的计算器MCP服务器
 */

// 创建服务器实例
const server = new McpServer({
  name: "mcp-calculator-server",
  version: "1.0.0",
  description: "提供基本四则运算功能的MCP计算器服务器",
  capabilities: {
    resources: {},  // 资源能力
    tools: {},      // 工具能力
  },
});

2. 输入验证Schema定义

使用Zod进行严格的输入验证:

// 数字参数验证
const NumberSchema = z.number().describe("数值参数,支持整数和浮点数");

// 可以扩展更复杂的验证规则
const PositiveNumberSchema = z.number().positive().describe("正数");
const IntegerSchema = z.number().int().describe("整数");

3. 工具实现:加法运算

server.tool(
  "add",
  "执行两个数字的加法运算,返回它们的和。支持整数和浮点数。",
  {
    a: NumberSchema,
    b: NumberSchema,
  },
  async ({ a, b }) => {
    const result = a + b;
    
    // 记录操作日志(用于调试)
    console.error(`计算: ${a} + ${b} = ${result}`);
    
    return {
      content: [
        {
          type: "text",
          text: `${a} + ${b} = ${result}`,
        },
      ],
    };
  }
);

4. 错误处理:除法运算

在实际项目中,错误处理至关重要:

server.tool(
  "divide",
  "执行两个数字的除法运算,包含除零错误检查。",
  {
    dividend: NumberSchema.describe("被除数"),
    divisor: NumberSchema.describe("除数"),
  },
  async ({ dividend, divisor }) => {
    // 除零检查
    if (divisor === 0) {
      console.error(`错误: 除数不能为零`);
      return {
        content: [
          {
            type: "text",
            text: "错误:除数不能为零,请检查输入参数。",
          },
        ],
      };
    }
    
    const result = dividend / divisor;
    console.error(`计算: ${dividend} ÷ ${divisor} = ${result}`);
    
    return {
      content: [
        {
          type: "text",
          text: `${dividend} ÷ ${divisor} = ${result}`,
        },
      ],
    };
  }
);

5. 服务器启动逻辑

async function main() {
  try {
    // 使用标准输入输出传输
    const transport = new StdioServerTransport();
    await server.connect(transport);
    
    console.error("MCP计算器服务器已启动,使用stdio传输");
  } catch (error) {
    console.error("服务器启动失败:", error);
    process.exit(1);
  }
}

// 启动服务器并处理异常
main().catch((error) => {
  console.error("主函数执行失败:", error);
  process.exit(1);
});

完整的服务器代码

将所有部分组合起来,我们得到了一个完整的MCP计算器服务器。这个服务器包含四个基本运算工具:

  • add: 加法运算
  • subtract: 减法运算
  • multiply: 乘法运算
  • divide: 除法运算(含错误处理)

每个工具都有详细的描述和严格的输入验证,确保服务器的稳定性和易用性。

#!/usr/bin/env node

/**
 * 新手版 MCP 计算器服务器
 * 
 * 这是一个简化的MCP服务器示例,适合初学者学习
 * 提供基本的加减乘除运算功能
 * 
 * 安装依赖:
 * npm install @modelcontextprotocol/sdk zod
 * 
 * 编译运行:
 * npx tsc
 * node build/server/index.js
 */

// 导入需要的模块
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

// 创建服务器
const server = new McpServer({
  name: "simple-calculator",
  version: "1.0.0",
  capabilities: {
    resources: {},
    tools: {},
  },
});

// 定义数字验证规则
const NumberSchema = z.number().describe("数字");

// 加法工具
server.tool(
  "add",
  "计算两个数字相加",
  {
    a: NumberSchema,
    b: NumberSchema,
  },
  async ({ a, b }) => {
    const result = a + b;
    
    return {
      content: [
        {
          type: "text",
          text: `${a} + ${b} = ${result}`,
        },
      ],
    };
  }
);

// 减法工具
server.tool(
  "subtract",
  "计算两个数字相减",
  {
    a: NumberSchema,
    b: NumberSchema,
  },
  async ({ a, b }) => {
    const result = a - b;
    
    return {
      content: [
        {
          type: "text",
          text: `${a} - ${b} = ${result}`,
        },
      ],
    };
  }
);

// 乘法工具
server.tool(
  "multiply",
  "计算两个数字相乘",
  {
    a: NumberSchema,
    b: NumberSchema,
  },
  async ({ a, b }) => {
    const result = a * b;
    
    return {
      content: [
        {
          type: "text",
          text: `${a} × ${b} = ${result}`,
        },
      ],
    };
  }
);

// 除法工具
server.tool(
  "divide",
  "计算两个数字相除",
  {
    a: NumberSchema,
    b: NumberSchema,
  },
  async ({ a, b }) => {
    // 检查除数是否为零
    if (b === 0) {
      return {
        content: [
          {
            type: "text",
            text: "错误:不能除以零",
          },
        ],
      };
    }
    
    const result = a / b;
    
    return {
      content: [
        {
          type: "text",
          text: `${a} ÷ ${b} = ${result}`,
        },
      ],
    };
  }
);

// 启动服务器
async function main() {
  try {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("计算器服务器已启动");
  } catch (error) {
    console.error("启动失败:", error);
    process.exit(1);
  }
}

main().catch((error) => {
  console.error("运行出错:", error);
  process.exit(1);
});

/*
使用方法:

1. 安装依赖包
   npm install @modelcontextprotocol/sdk zod

2. 编译 TypeScript
   npx tsc

3. 在 VS Code 中配置 .vscode/mcp.json:
   {
     "servers": {
       "calculator": {
         "type": "stdio",
         "command": "node",
         "args": ["你的绝对路径/server/index.js"]
       }
     }
   }

4. 重启 VS Code,然后就可以使用计算功能了

代码说明:

- McpServer: 创建 MCP 服务器
- server.tool(): 定义可用的工具/功能
- NumberSchema: 验证输入必须是数字
- async/await: 处理异步操作
- StdioServerTransport: 使用标准输入输出通信

每个工具包含:
- 名称 (如 "add")
- 描述 (如 "计算两个数字相加")
- 参数定义 (如 {a: NumberSchema, b: NumberSchema})
- 实现函数 (执行具体的计算逻辑)
*/

VS Code集成配置

1. 创建MCP配置文件

在项目根目录的.vscode/mcp.json中配置:

{
  "servers": {
    "mcp-calculator": {
      "type": "stdio",
      "command": "node",
      "args": ["你的绝对路径/server/index.js"]
    }
  }
}
MCP配置参数详解
参数 作用 示例值 说明
servers 服务器配置容器 {...} 包含所有MCP服务器的配置信息
"mcp-calculator" 服务器标识名称 任意字符串 VS Code中显示的服务器名称,可自定义
type 通信协议类型 "stdio" 支持stdio(标准输入输出)模式
command 执行命令 "node" 用于启动MCP服务器的可执行文件
args 命令参数数组 ["你的绝对路径/server/index.js"] 传递给command的参数列表
配置示例解析
{
  "servers": {
    "calculator": {              // 服务器名称(自定义)
      "type": "stdio",           // 使用标准输入输出通信
      "command": "node",         // 使用Node.js执行
      "args": [                  // 传递给node的参数
        "你的绝对路径/server/index.js" // 编译后的服务器文件路径
      ]
    },
    "file-manager": {            // 可以配置多个服务器
      "type": "stdio",
      "command": "python",
      "args": ["-m", "my_mcp_server"]
    }
  }
}

⚠️ 重要提示

  • 路径必须指向编译后的.js文件,不是.ts源文件
  • 确保编译后的文件存在且有执行权限

2. 编译和构建

# 使用tsc编译,在目录下生成js文件
npx tsc

3. 测试服务器

# 1. 首先确保TypeScript已编译
npx tsc

# 2. 直接运行服务器测试
node build/server/index.js

# 3. 如果正常,您应该看到类似输出:
# "计算器服务器已启动"

# 4. 使用 Ctrl+C 停止服务器

参考资源