4.2 用 WorkBuddy 生成 TypeScript MCP 服务器与调试

什么时候选 TypeScript

场景 建议
团队主力是前端 / Node TypeScript
要复用已有的 npm 包或 Node SDK TypeScript
要和现有 Node 服务同进程思路对齐 TypeScript
数据处理、脚本类工具、快速原型 Python 更省事
需要 npx -y xxx 一键分发 TypeScript(npm 生态分发最顺)

两者的协议能力完全一致,选型只看团队与分发方式。

第一步:环境

mkdir kb-server-ts && cd kb-server-ts
npm init -y
npm install @modelcontextprotocol/server zod
npm install -D @types/node typescript
mkdir src

package.json 里加两行:

{
  "type": "module",
  "scripts": { "build": "tsc", "start": "node dist/index.js" }
}

tsconfig.json(最小可用):

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

第二步:让 WorkBuddy 生成代码

提示词模板:

请用 TypeScript 写一个 MCP 服务器(stdio 传输),实现内部 Markdown 知识库的只读检索。

约束:
1) 依赖固定为 @modelcontextprotocol/server 与 zod;从
   "@modelcontextprotocol/server" 导入 McpServer,
   从 "@modelcontextprotocol/server/stdio" 导入 StdioServerTransport;
2) 所有日志用 console.error,严禁 console.log(会污染 stdout);
3) 笔记根目录取环境变量 KB_ROOT,默认 ./notes;路径必须做前缀校验防止 ../ 逃逸;
4) 工具:search_notes(query, limit=5, scope?)、read_note(path);
5) 用 zod 定义参数 schema,每个字段都要 .describe(),描述里给示例值;
6) 工具描述必须包含「何时用 / 何时不要用」;
7) 返回 { content: [{type:"text", text}], structuredContent } 形式;
8) 找不到文件时返回 isError: true 并给出可用路径示例;
9) 写完给出 tsconfig 与运行方式。

第三步:完整代码

import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { readFile, readdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";

const KB_ROOT = path.resolve(process.env.KB_ROOT ?? "./notes");

const server = new McpServer({ name: "kb-server", version: "1.0.0" });

/** 解析并校验相对路径,越界抛错 */
function safePath(rel: string): string {
  const abs = path.resolve(KB_ROOT, rel);
  if (abs !== KB_ROOT && !abs.startsWith(KB_ROOT + path.sep)) {
    throw new Error(`路径越界:${rel} 不在知识库目录内`);
  }
  if (!existsSync(abs)) throw new Error(`文件不存在:${rel}`);
  return abs;
}

/** 递归列出所有 .md 文件(相对路径) */
async function listNotes(dir = KB_ROOT, prefix = ""): Promise<string[]> {
  const out: string[] = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isDirectory()) out.push(...(await listNotes(path.join(dir, entry.name), rel)));
    else if (entry.name.endsWith(".md")) out.push(rel);
  }
  return out;
}

server.registerTool(
  "search_notes",
  {
    title: "检索笔记",
    description:
      "在本地 Markdown 知识库中按关键词检索笔记。需要回忆“我们以前怎么处理过 X”、" +
      "查找会议纪要或设计文档时使用;已知具体路径要读全文请改用 read_note。",
    inputSchema: {
      query: z.string().describe("检索关键词或自然语言问题,例如“季度复盘”"),
      limit: z.number().int().min(1).max(20).default(5).describe("返回条数,默认 5"),
      scope: z.string().optional().describe("限定子目录,例如 meeting、design、ops"),
    },
  },
  async ({ query, limit, scope }) => {
    const terms = query.split(/\s+/).filter(Boolean);
    const matches: { path: string; score: number; snippet: string }[] = [];

    for (const rel of await listNotes()) {
      if (scope && !rel.startsWith(scope.replace(/\/+$/, "") + "/")) continue;
      const text = await readFile(path.join(KB_ROOT, rel), "utf8").catch(() => "");
      const lower = text.toLowerCase();
      const score = terms.reduce((n, t) => n + lower.split(t.toLowerCase()).length - 1, 0);
      if (!score) continue;
      const pos = Math.max(0, lower.indexOf(terms[0].toLowerCase()));
      matches.push({
        path: rel,
        score,
        snippet: text.slice(Math.max(0, pos - 60), pos + 200).replace(/\s+/g, " ").trim(),
      });
    }

    matches.sort((a, b) => b.score - a.score);
    const top = matches.slice(0, limit);
    const text = top.length
      ? top.map((m) => `- ${m.path}(命中 ${m.score} 次):${m.snippet}`).join("\n")
      : "未找到匹配笔记。建议换用更短的关键词。";

    return { content: [{ type: "text", text }], structuredContent: { matches: top } };
  },
);

server.registerTool(
  "read_note",
  {
    title: "读取笔记",
    description:
      "按相对路径读取一篇笔记的完整内容。已知路径(如刚从 search_notes 得到)时使用;" +
      "只知道关键词时请先用 search_notes 定位。",
    inputSchema: {
      path: z.string().describe("相对知识库根目录的路径,例如 meeting/2026-10-weekly.md"),
    },
  },
  async ({ path: rel }) => {
    try {
      const content = await readFile(safePath(rel), "utf8");
      return {
        content: [{ type: "text", text: `已读取 ${rel}(${content.length} 字符)` }],
        structuredContent: { path: rel, content },
      };
    } catch (e) {
      const sample = (await listNotes()).slice(0, 5).join(", ") || "知识库为空";
      return {
        content: [{ type: "text", text: `${(e as Error).message}。可用路径示例:${sample}` }],
        isError: true,
      };
    }
  },
);

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("kb-server 已就绪(stdio)");   // 必须用 console.error
}

main().catch((error) => {
  console.error("启动失败:", error);
  process.exit(1);
});

第四步:构建与运行

npm run build
node dist/index.js        # stdio 服务器,静默运行属正常

第五步:用 Inspector CLI 做自动化回归

CLI 模式最适合写进 CI,把「工具在不在、参数对不对、调用成不成」变成可断言的结果:

# 1) 工具清单必须包含两个工具
npx @modelcontextprotocol/inspector --cli node dist/index.js --method tools/list \
  | jq -e '.result.tools | map(.name) | contains(["search_notes","read_note"])'

# 2) 检索能返回结果
npx @modelcontextprotocol/inspector --cli node dist/index.js \
  --method tools/call --tool-name search_notes --tool-arg query=周会 \
  --format json | jq -e '.result.structuredContent.matches | length > 0'

# 3) 读不存在的文件必须 isError=true(错误路径也要测)
npx @modelcontextprotocol/inspector --cli node dist/index.js \
  --method tools/call --tool-name read_note --tool-arg path=不存在.md \
  --format json | jq -e '.result.isError == true'

把这三条做成 npm run check,任何改动都会自动回归——这比手动点界面可靠得多。

Python 与 TypeScript 版对照

维度 Python(MCPServer) TypeScript(McpServer)
参数 schema 来源 类型注解 + docstring zod schema + .describe()
注册方式 @mcp.tool() 装饰器 server.registerTool(name, cfg, handler)
运行 mcp.run(transport="stdio") server.connect(new StdioServerTransport())
日志 logging(stderr) console.error
分发 PyPI / uvx npm / npx

相同的规范(描述五要素、错误两分法、路径校验、分页)两边完全一致——跨语言不变的是设计,不是语法。

小结

  • TypeScript 侧用 @modelcontextprotocol/server + zod,schema 由 zod 描述生成;
  • console.log 是 stdio 服务器的大忌,一律 console.error;
  • Inspector CLI + jq -e 可以把协议行为变成 CI 断言;
  • 两种语言能力等价,按团队与分发方式选。

下一节:进阶——接真实数据源、长任务与进度、多轮往返请求与性能优化。