计算器MCP服务

一个基于TypeScript和Zod构建的微型模型上下文协议(MCP)服务器,提供基本的计算器工具,易于扩展。

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

使用说明

计算器MCP服务器

一个小型的模型上下文协议(MCP)服务器,提供基本的计算器工具。使用TypeScript和Zod构建,易于扩展。

快速入门

npm install
npm run build && npm start

服务器通过标准输入输出运行并记录日志:

Calculator MCP server is running...

发展

npm run dev

检查员

使用MCP Inspector进行交互式测试:

npm run build
npm run inspector

这会在检查器(inspector)下启动服务器,以便您可以列出工具并调用它们。

工具

  • add: 加两个数
  • 减法:减去两个数
  • 乘法:将两个数相乘
  • 除法:对两个数进行除法运算(除以零时抛出异常)

工具需求清单(MCP):

{
  "method": "tools/list",
  "params": {}
}

调用示例:

{
  "method": "tools/call",
  "params": {
    "name": "add",
    "arguments": { "a": 3, "b": 5 }
  }
}

响应示例:

{
  "content": [{ "type": "text", "text": "3 + 5 = 8" }]
}

验证与模式(或架构)

  • 使用Zod直接进行输入验证 src/index.ts。
  • inputSchema 由……返回 tools/list 是一个MCP客户端可以使用的JSON Schema对象。

双数字输入模式(Zod):

const twoNumberInput = z.object({ a: z.number(), b: z.number() });

JSON Schema(针对MCP):

const twoNumberJsonSchema = {
  type: 'object',
  properties: {
    a: { type: 'number', description: 'First number' },
    b: { type: 'number', description: 'Second number' },
  },
  required: ['a', 'b'],
} as const;

项目结构

src/
  index.ts   # server setup, tool definitions, validation, and handlers
dist/
  index.js   # build output

扩展(添加新工具)

所有工具均在 src/index.ts 在……之下 tools 地图。要添加一个:

  1. 添加或重用一个Zod模式及其对应的JSON模式。
  2. 实施一个 execute 功能。
  3. 在(系统/平台)中注册该工具 tools 带有地图的 description, inputSchema, validate, execute,以及 format。

脚本

来自 package.json:

  • build将 TypeScript 编译为 dist/
  • start跑 node dist/index.js
  • dev: tsc && node dist/index.js
  • inspector: npx @modelcontextprotocol/inspector node dist/index.js

故障排除

  • “无法找到模块 …/x.js”:请确保 ESM 路径包含 .js 扩展(tsconfig 使用 NodeNext)。
  • “除以零错误!” divide 当……时抛出(异常) b === 0。
  • “无效的参数…”:Zod 验证失败;请确保为数字 a 和 b。

许可证

麻省理工学院(MIT)