MSMuhammad Shahid

工程笔记

用 TypeScript 和 Model Context Protocol 构建多智能体系统

作者 Muhammad Shahid · · 阅读约 16 分钟

快速解答

要用 TypeScript 和模型上下文协议构建多智能体系统,把每项能力做成一个 MCP 服务器(本文是用 v2 TypeScript SDK 构建、通过 Streamable HTTP 提供的文档服务器和工单服务器),让每个专家智能体只拥有它所需服务器的 MCP 客户端,再让编排智能体把专家当作工具调用。把 MCP 工具列表转换成模型工具,把每次工具调用路由回所属服务器,并加上防护:每个智能体独立的工具箱、隐藏写入工具的令牌权限范围、写入前的人工审批、模式校验和轮次限制。

关键信息
技术栈TypeScript、MCP TypeScript SDK v2(@modelcontextprotocol/server、client、node)、Claude Sonnet 5.5 和 Haiku 5.5
智能体一个编排者加两个专家;每个专家只能看到一个 MCP 服务器
传输Node.js 上的 Streamable HTTP,带 Host 和 Origin 检查及 Bearer 令牌
防护按权限的工具列表、写入人工审批、服务器端 zod 校验、轮次限制、追踪
测试真实的 MCP 服务器通过 HTTP 运行,配合脚本化的 Claude 客户端;每项防护都经过验证

一个拥有二十个工具的 AI 智能体容易混乱,一个对所有东西都有写权限的智能体则是风险。把工作分给几个小智能体,每个只拿到所需的工具,可以同时解决这两个问题,而模型上下文协议(Model Context Protocol)就是分发这些工具的干净方式。本教程用 TypeScript 和 MCP 构建一个多智能体系统:两个用 v2 TypeScript SDK 编写、通过 Streamable HTTP 提供并带令牌和权限范围的 MCP 服务器,一个并行委派给研究员和分诊员的编排智能体,以及防止困惑的模型造成损害的防护措施。所有代码完整并通过类型检查。测试通过 HTTP 运行真实的 MCP 服务器,配合脚本化的 Claude 客户端,所以每次工具调用、每项权限和防护都真实运行,而模型的决策固定在脚本中。

什么是模型上下文协议?

模型上下文协议(MCP)是一种开放协议,让 AI 应用发现并调用由独立服务器提供的工具、读取资源和使用提示词。MCP 服务器声明"这是我的工具及其 JSON 模式";MCP 客户端获取列表,交给模型,再把模型的工具调用发回服务器。由于协议处处相同,一个服务器可以配合任何 MCP 客户端使用:你自己的智能体、Claude Desktop、IDE 和其他宿主。官方 TypeScript SDK 的第 2 版是稳定版本,实现了 2026-07-28 规范,把原来的单一包拆分为 @modelcontextprotocol/server、@modelcontextprotocol/client 以及 @modelcontextprotocol/node 等框架适配器。

为什么用多个智能体,什么时候不该用

当工作的不同部分需要不同的工具、权限或模型时,就用多个智能体:只能读文档的研究员不会误开工单,便宜快速的模型可以做窄任务,强模型负责规划。不要只因为听起来高级就拆分:智能体之间的每次传递都要多一次模型调用、增加延迟,也多一个丢失上下文的地方。如果一个带五个描述清楚的工具的智能体就能完成,就保持一个智能体。生产环境 AI 智能体指南介绍了单智能体的情况,函数调用教程展示了不使用 MCP 的工具调用。

架构

架构:用户向编排智能体提问,它运行在 Claude Sonnet 5.5 上,只有 ask_researcher 和 ask_triager 两个工具;研究员智能体运行在 Claude Haiku 5.5 上,是文档服务器的 MCP 客户端,只有只读的 search_docs 和 get_doc;分诊智能体运行在 Haiku 5.5 上,是工单服务器的 MCP 客户端,拥有 list_tickets 和需要写入权限及人工审批的 create_ticket
智能体之间通过工具互相调用,每个专家只能访问自己的 MCP 服务器。

编排者从不直接访问服务器;它唯一的工具是"问研究员"和"问分诊员"。每个专家连接一个 MCP 服务器。工单服务器检查 Bearer 令牌,并根据令牌的权限范围构建工具列表,所以没有 tickets:write 的客户端根本看不到写入工具。写入操作还要经过智能体宿主中的人工审批回调。

需要准备什么?

工具使用版本用途
Node.js20 或更高运行时
@modelcontextprotocol/server2.4McpServer、registerTool、createMcpHandler
@modelcontextprotocol/client2.4Client 和 StreamableHTTPClientTransport
@modelcontextprotocol/node2.1toNodeHandler、Host 和 Origin 检查
zod4(以 zod/v4 导入)工具输入和输出模式
@anthropic-ai/sdk1.8智能体的模型调用

步骤 1:创建项目

mkdir mcp-team && cd mcp-team && npm init -y && npm pkg set type=module
npm install @modelcontextprotocol/server @modelcontextprotocol/client @modelcontextprotocol/node @anthropic-ai/sdk zod
npm install -D typescript tsx @types/node

步骤 2:只读 MCP 服务器

// MCP server 1: read-only search over internal docs. Any agent may use it.
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";

const DOCS = [
  { id: "deploy", title: "Deploying the API", text: "Deploys run from main through GitHub Actions. A failed health check rolls back automatically within 5 minutes." },
  { id: "oncall", title: "On-call rota", text: "The on-call engineer answers P1 tickets within 15 minutes and P2 tickets within 4 hours." },
  { id: "payments", title: "Payments service", text: "Payment webhooks retry for 24 hours. Duplicate webhooks are ignored using the event id." },
  { id: "login", title: "Login and sessions", text: "Sessions last 7 days. A spike in 401 errors after a deploy usually means the signing key changed." },
];

export function createDocsHandler() {
  return createMcpHandler(() => {
    const server = new McpServer({ name: "docs", version: "1.0.0" });
    server.registerTool(
      "search_docs",
      {
        title: "Search internal docs",
        description: "Search the engineering docs. Returns matching document ids and titles.",
        inputSchema: z.object({ query: z.string().min(2).describe("Words to look for") }),
        annotations: { readOnlyHint: true },
      },
      async ({ query }) => {
        const words = query.toLowerCase().split(/\W+/).filter((w) => w.length > 2);
        const hits = DOCS.filter((d) => words.some((w) => (d.title + " " + d.text).toLowerCase().includes(w)));
        return { content: [{ type: "text", text: hits.map((d) => d.id + ": " + d.title).join("\n") || "No matches" }] };
      },
    );
    server.registerTool(
      "get_doc",
      {
        title: "Read one doc",
        description: "Read the full text of one document by id.",
        inputSchema: z.object({ id: z.string() }),
        outputSchema: z.object({ id: z.string(), title: z.string(), text: z.string() }),
        annotations: { readOnlyHint: true },
      },
      async ({ id }) => {
        const doc = DOCS.find((d) => d.id === id);
        if (!doc) return { content: [{ type: "text", text: "No document " + id }], isError: true };
        return { content: [{ type: "text", text: doc.title + "\n" + doc.text }], structuredContent: doc };
      },
    );
    return server;
  });
}

registerTool 接收名称、配置和处理函数。inputSchema 是一个 zod 对象:SDK 会把它转换成客户端看到的 JSON Schema,并在你的处理函数运行前拒绝错误参数。outputSchema 加上 structuredContent 让客户端在文本之外获得类型化结果。readOnlyHint: true 告诉客户端这个工具不会改变任何东西,本教程的智能体宿主据此决定哪些调用需要审批。createMcpHandler 接收一个为每个请求构建新服务器的工厂函数,让服务器保持无状态、易于扩展。

步骤 3:带权限范围的工单服务器

// MCP server 2: the ticket system. Reading needs "tickets:read"; the write tool exists only for "tickets:write".
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";

export interface Ticket { id: number; title: string; priority: "P1" | "P2" | "P3"; status: "open" | "closed" }
export interface AuthInfo { token: string; clientId: string; scopes: string[]; expiresAt?: number }

export function createTicketsHandler(store: Ticket[]) {
  return createMcpHandler(({ authInfo }) => {
    const server = new McpServer({ name: "tickets", version: "1.0.0" });
    const scopes = authInfo?.scopes ?? [];

    server.registerTool(
      "list_tickets",
      {
        description: "List tickets, newest first, optionally by status.",
        inputSchema: z.object({ status: z.enum(["open", "closed"]).optional() }),
        annotations: { readOnlyHint: true },
      },
      async ({ status }) => {
        const rows = store.filter((t) => !status || t.status === status).slice(-20).reverse();
        return { content: [{ type: "text", text: rows.map((t) => "#" + t.id + " [" + t.priority + "] " + t.title).join("\n") || "No tickets" }] };
      },
    );

    // Least privilege: a client without the write scope never even sees this tool.
    if (scopes.includes("tickets:write")) {
      server.registerTool(
        "create_ticket",
        {
          description: "Open a new ticket. Use only when no open ticket already covers the problem.",
          inputSchema: z.object({
            title: z.string().min(5).max(120),
            priority: z.enum(["P1", "P2", "P3"]),
          }),
          annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
        },
        async ({ title, priority }) => {
          const ticket: Ticket = { id: store.length + 1, title, priority, status: "open" };
          store.push(ticket);
          console.error(JSON.stringify({ audit: "create_ticket", by: authInfo?.clientId, ticket: ticket.id }));
          return { content: [{ type: "text", text: "Created #" + ticket.id }] };
        },
      );
    }
    return server;
  });
}

// Bearer tokens checked before MCP sees the request; the verified identity is passed through as authInfo.
export function withBearer(handler: { fetch: (r: Request, o?: { authInfo?: AuthInfo }) => Promise<Response> }, tokens: Map<string, AuthInfo>) {
  return async (request: Request) => {
    const token = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
    const auth = tokens.get(token);
    if (!auth || (auth.expiresAt && auth.expiresAt < Date.now() / 1000)) {
      return new Response(JSON.stringify({ error: "invalid_token" }), {
        status: 401,
        headers: { "content-type": "application/json", "www-authenticate": 'Bearer error="invalid_token"' },
      });
    }
    return handler.fetch(request, { authInfo: auth });
  };
}

工厂函数会收到请求的 authInfo,所以工具列表可以取决于调用者:只有当令牌拥有 tickets:write 时才注册 create_ticket。这是协议层面的最小权限:只读客户端无法调用它看不到的工具,模型也无法被说服去使用它。withBearer 在 MCP 运行前检查令牌,并通过 handler.fetch(request, { authInfo }) 传入已验证的身份;SDK 本身不检查令牌。生产环境中,应在这里验证真正的 OAuth 访问令牌而不是固定表,并检查其 audience。每次写入都会记录执行它的客户端。

步骤 4:通过 HTTP 提供服务

// Serve both MCP servers over Streamable HTTP on plain Node.js, bound to loopback.
// In production, put them behind your reverse proxy with TLS; tokens come from your secret store.
import { createServer } from "node:http";
import { localhostHostValidation, localhostOriginValidation, toNodeHandler } from "@modelcontextprotocol/node";
import { createDocsHandler } from "./servers/docs";
import { createTicketsHandler, withBearer, type AuthInfo, type Ticket } from "./servers/tickets";

export function serve(port: number, tokens: Map<string, AuthInfo>, store: Ticket[] = []) {
  const docs = toNodeHandler(createDocsHandler());
  const tickets = toNodeHandler({ fetch: withBearer(createTicketsHandler(store), tokens) });
  const validHost = localhostHostValidation();
  const validOrigin = localhostOriginValidation();
  return createServer((req, res) => {
    if (!validHost(req, res) || !validOrigin(req, res)) return; // blocks DNS-rebinding from web pages
    if (req.url?.startsWith("/docs/mcp")) return void docs(req, res);
    if (req.url?.startsWith("/tickets/mcp")) return void tickets(req, res);
    res.writeHead(404).end();
  }).listen(port, "127.0.0.1");
}

toNodeHandler 把 Web 标准处理器适配到 Node 的 http 服务器。Host 和 Origin 检查可以阻止 DNS 重绑定攻击,即网页诱使浏览器调用你本机上的服务器;MCP 的处理器不会替你做这些检查。这里两个服务器共用一个进程和端口、使用不同路径,但它们同样可以运行在不同团队的不同机器上。

步骤 5:把 MCP 工具变成 Claude 工具

// Turns MCP servers (and plain functions) into Claude tools, and routes each tool call back to its owner.
import type Anthropic from "@anthropic-ai/sdk";
import { Client, StreamableHTTPClientTransport, type FetchLike } from "@modelcontextprotocol/client";

export interface ToolResult { text: string; isError: boolean }
export interface Toolbox {
  tools: Anthropic.Tool[];
  call(name: string, input: unknown): Promise<ToolResult>;
  close(): Promise<void>;
}

export interface McpServerRef { url: string; token?: string; fetch?: FetchLike }

export async function mcpToolbox(
  servers: McpServerRef[],
  opts: { approve?: (tool: string, input: unknown) => Promise<boolean> } = {},
): Promise<Toolbox> {
  const owner = new Map<string, Client>();
  const writes = new Set<string>();
  const tools: Anthropic.Tool[] = [];
  const clients: Client[] = [];

  for (const s of servers) {
    const transport = new StreamableHTTPClientTransport(new URL(s.url), {
      fetch: s.fetch,
      requestInit: s.token ? { headers: { Authorization: "Bearer " + s.token } } : undefined,
    });
    const client = new Client({ name: "agent-host", version: "1.0.0" });
    await client.connect(transport);
    clients.push(client);
    for (const t of (await client.listTools()).tools) {
      if (owner.has(t.name)) throw new Error("Two servers expose a tool called " + t.name);
      owner.set(t.name, client);
      if (!t.annotations?.readOnlyHint) writes.add(t.name);
      tools.push({ name: t.name, description: t.description ?? t.name, input_schema: t.inputSchema as Anthropic.Tool.InputSchema });
    }
  }

  return {
    tools,
    async call(name, input) {
      const client = owner.get(name);
      if (!client) return { text: "This agent has no tool called " + name, isError: true };
      if (writes.has(name) && opts.approve && !(await opts.approve(name, input))) {
        return { text: "A person declined this action. Do not retry it; explain what you wanted to do instead.", isError: true };
      }
      const r = await client.callTool({ name, arguments: input as Record<string, unknown> });
      const text = (r.content as { type: string; text?: string }[]).map((c) => (c.type === "text" ? c.text : "[" + c.type + "]")).join("\n");
      return { text, isError: Boolean(r.isError) };
    },
    async close() {
      await Promise.all(clients.map((c) => c.close()));
    },
  };
}

// Local tools, used to let the orchestrator call other agents.
export function localToolbox(entries: { name: string; description: string; run: (task: string) => Promise<string> }[]): Toolbox {
  return {
    tools: entries.map((e) => ({
      name: e.name,
      description: e.description,
      input_schema: { type: "object", properties: { task: { type: "string", description: "A complete, self-contained task" } }, required: ["task"] },
    })),
    async call(name, input) {
      const entry = entries.find((e) => e.name === name);
      if (!entry) return { text: "No tool called " + name, isError: true };
      try {
        return { text: await entry.run(String((input as { task?: unknown }).task ?? "")), isError: false };
      } catch (err) {
        return { text: "The " + name + " agent failed: " + String(err), isError: true };
      }
    },
    async close() {},
  };
}

mcpToolbox 为每个服务器连接一个客户端,获取工具列表并把每个工具转换成 Claude 工具定义:MCP 的 inputSchema 本身就是 JSON Schema,可以直接传过去。一个映射表记录每个工具属于哪个服务器,不同服务器间的重名会报错,而不是悄悄覆盖。没有 readOnlyHint 的工具会先经过 approve。如果模型请求了这个智能体没有的工具,调用会返回错误结果,而不会到达任何服务器。localToolbox 用同样方式包装普通函数,编排者的"问某个智能体"工具就是这样来的。

步骤 6:智能体循环

// One agent = one model, one system prompt, one toolbox and a turn limit. Every step goes into a shared trace.
import type Anthropic from "@anthropic-ai/sdk";
import type { Toolbox } from "./toolbox";

export interface AgentSpec { name: string; model: string; system: string; toolbox: Toolbox; maxTurns: number }
export interface TraceEvent { agent: string; step: "tool" | "answer" | "turn-limit"; tool?: string; ms?: number; error?: boolean; tokens?: number }

export async function runAgent(claude: Anthropic, spec: AgentSpec, task: string, trace: TraceEvent[]): Promise<string> {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: task }];
  for (let turn = 0; turn < spec.maxTurns; turn++) {
    const res = await claude.messages.create({
      model: spec.model,
      max_tokens: 4000,
      system: spec.system,
      tools: spec.toolbox.tools,
      messages,
    });
    const tokens = res.usage.input_tokens + res.usage.output_tokens;
    if (res.stop_reason !== "tool_use") {
      trace.push({ agent: spec.name, step: "answer", tokens });
      return res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
    }
    messages.push({ role: "assistant", content: res.content }); // keep every block, thinking included
    const calls = res.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
    const results = await Promise.all(
      calls.map(async (call): Promise<Anthropic.ToolResultBlockParam> => {
        const t0 = performance.now();
        const r = await spec.toolbox.call(call.name, call.input);
        trace.push({ agent: spec.name, step: "tool", tool: call.name, ms: Math.round(performance.now() - t0), error: r.isError, tokens });
        return { type: "tool_result", tool_use_id: call.id, content: r.text, is_error: r.isError };
      }),
    );
    messages.push({ role: "user", content: results });
  }
  trace.push({ agent: spec.name, step: "turn-limit" });
  return spec.name + " stopped after " + spec.maxTurns + " turns without finishing.";
}

这是标准的工具使用循环:调用模型,执行工具调用,发回结果,重复直到模型给出答案。整个助手消息(包括思考块)按 API 要求原样发回。同一轮中的工具调用并行执行。循环在 maxTurns 后停止,所以不断调用工具的模型无法让账单失控;每一步都会写入共享追踪,记录智能体名、工具、耗时以及是否失败。

步骤 7:编排者和它的团队

// The team: an orchestrator that plans and delegates, a researcher that can only read docs,
// and a triager that can only touch tickets. Each specialist sees only its own MCP server.
import type Anthropic from "@anthropic-ai/sdk";
import { runAgent, type TraceEvent } from "./agent";
import { localToolbox, mcpToolbox, type McpServerRef } from "./toolbox";

export async function createTeam(
  claude: Anthropic,
  servers: { docs: McpServerRef; tickets: McpServerRef },
  approve: (tool: string, input: unknown) => Promise<boolean>,
) {
  const researcherTools = await mcpToolbox([servers.docs]);
  const triagerTools = await mcpToolbox([servers.tickets], { approve });

  return {
    async ask(question: string) {
      const trace: TraceEvent[] = [];
      const researcher = (task: string) => runAgent(claude, {
        name: "researcher", model: "claude-haiku-5-5", maxTurns: 6, toolbox: researcherTools,
        system: "You research questions in the engineering docs. Cite doc ids. Never guess: say what the docs do not cover.",
      }, task, trace);
      const triager = (task: string) => runAgent(claude, {
        name: "triager", model: "claude-haiku-5-5", maxTurns: 6, toolbox: triagerTools,
        system: "You manage tickets. List open tickets before creating one, and never create a duplicate.",
      }, task, trace);
      const orchestrator = localToolbox([
        { name: "ask_researcher", description: "Ask the researcher agent to find facts in the engineering docs.", run: researcher },
        { name: "ask_triager", description: "Ask the triager agent to check or open tickets.", run: triager },
      ]);
      const answer = await runAgent(claude, {
        name: "orchestrator", model: "claude-sonnet-5-5", maxTurns: 4, toolbox: orchestrator,
        system: "You lead an incident helper. Split the user's request into tasks for your agents, run independent tasks in parallel, then answer in under 120 words.",
      }, question, trace);
      return { answer, trace };
    },
    async close() {
      await Promise.all([researcherTools.close(), triagerTools.close()]);
    },
  };
}

编排者运行在 Claude Sonnet 5.5 上负责规划;专家运行在 Claude Haiku 5.5 上,输入每百万 token 0.10 美元,而 Sonnet 为 2 美元,因为它们的任务很窄。每个专家的系统提示说明它的职责和规则("创建前先列出未关闭的工单")。编排者的提示要求它并行运行相互独立的任务:当它在同一轮中询问两个智能体时,智能体循环会同时执行这两个工具调用。

测试

import assert from "node:assert/strict";
import type Anthropic from "@anthropic-ai/sdk";
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { createTeam } from "../src/team";
import { runAgent, type TraceEvent } from "../src/agent";
import { mcpToolbox } from "../src/toolbox";
import { serve } from "../src/serve";
import type { AuthInfo, Ticket } from "../src/servers/tickets";

const tokens = new Map<string, AuthInfo>([
  ["tok-read", { token: "tok-read", clientId: "dashboard", scopes: ["tickets:read"] }],
  ["tok-write", { token: "tok-write", clientId: "incident-bot", scopes: ["tickets:read", "tickets:write"] }],
]);
const store: Ticket[] = [{ id: 1, title: "Slow search on mobile", priority: "P3", status: "open" }];
const http = serve(4410, tokens, store);
const base = "http://127.0.0.1:4410";

// 1) Real HTTP: discovery, auth and least privilege
const anon = await fetch(base + "/tickets/mcp", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
assert.equal(anon.status, 401);
const listNames = async (url: string, token?: string) => {
  const box = await mcpToolbox([{ url, token }]);
  const names = box.tools.map((t) => t.name).sort();
  await box.close();
  return names;
};
assert.deepEqual(await listNames(base + "/docs/mcp"), ["get_doc", "search_docs"]);
assert.deepEqual(await listNames(base + "/tickets/mcp", "tok-read"), ["list_tickets"]);
assert.deepEqual(await listNames(base + "/tickets/mcp", "tok-write"), ["create_ticket", "list_tickets"]);
// fetch() will not let you change Host, so send a raw request the way a DNS-rebinding page would arrive
const { request } = await import("node:http");
const evilStatus = await new Promise<number>((resolve) => {
  request({ host: "127.0.0.1", port: 4410, path: "/docs/mcp", method: "POST", headers: { host: "attacker.example", "content-type": "application/json" } },
    (res) => { res.resume(); resolve(res.statusCode ?? 0); }).end("{}");
});
assert.equal(evilStatus, 403);
console.log("http: tickets server 401 without a token; read token sees list_tickets only; write token also sees create_ticket; foreign Host header 403");

// Schema validation happens in the server, before the handler runs
const raw = new Client({ name: "raw", version: "1.0.0" });
await raw.connect(new StreamableHTTPClientTransport(new URL(base + "/tickets/mcp"), { requestInit: { headers: { Authorization: "Bearer tok-write" } } }));
const bad = await raw.callTool({ name: "create_ticket", arguments: { title: "x", priority: "P0" } });
assert.equal(bad.isError, true);
assert.equal(store.length, 1);
await raw.close();
console.log("validation: create_ticket with a 1-letter title and priority P0 -> isError, nothing written");

// 2) The whole team with a scripted model: the orchestrator delegates in parallel, specialists use MCP tools
type Params = { system: string; tools: Anthropic.Tool[]; messages: Anthropic.MessageParam[] };
const seenTools: Record<string, string[]> = {};
const lastResult = (p: Params) => {
  const last = p.messages[p.messages.length - 1];
  return Array.isArray(last.content) ? String((last.content[0] as { content?: unknown }).content ?? "") : "";
};
const turnOf = (p: Params) => p.messages.filter((m) => m.role === "assistant").length;
const say = (text: string) => ({ stop_reason: "end_turn", content: [{ type: "text", text }], usage: { input_tokens: 400, output_tokens: 80 } });
const use = (...calls: [string, object][]) => ({
  stop_reason: "tool_use",
  content: calls.map(([name, input], i) => ({ type: "tool_use", id: "tu_" + name + "_" + i + "_" + Math.random().toString(36).slice(2, 6), name, input })),
  usage: { input_tokens: 400, output_tokens: 60 },
});
const script = (p: Params) => {
  const who = p.system.startsWith("You lead") ? "orchestrator" : p.system.startsWith("You research") ? "researcher" : "triager";
  seenTools[who] = p.tools.map((t) => t.name);
  const turn = turnOf(p);
  if (who === "orchestrator") {
    if (turn === 0) return use(["ask_researcher", { task: "Why could users get 401 errors after today's deploy? Use the docs." }], ["ask_triager", { task: "Is there an open ticket for login 401 errors? If not, open a P1." }]);
    return say("Likely cause: the signing key changed in the deploy (doc: login). Ticket handled by the triager.");
  }
  if (who === "researcher") {
    if (turn === 0) return use(["search_docs", { query: "401 errors deploy" }]);
    if (turn === 1) return use(["get_doc", { id: "login" }]);
    return say("From doc login: " + lastResult(p).split("\n")[1]);
  }
  if (turn === 0) return use(["list_tickets", { status: "open" }]);
  if (turn === 1) return use(["create_ticket", { title: "Users get 401 errors after deploy", priority: "P1" }]);
  return say(lastResult(p));
};
const fakeClaude = { messages: { create: async (p: Params) => script(p) } } as unknown as Anthropic;

const approvals: string[] = [];
const team = await createTeam(
  fakeClaude,
  { docs: { url: base + "/docs/mcp" }, tickets: { url: base + "/tickets/mcp", token: "tok-write" } },
  async (tool, input) => { approvals.push(tool + " " + JSON.stringify(input)); return true; },
);
const { answer, trace } = await team.ask("Users can't log in since the deploy. What's going on, and is it tracked?");
assert.deepEqual(seenTools.researcher, ["search_docs", "get_doc"]);
assert.deepEqual(seenTools.triager.sort(), ["create_ticket", "list_tickets"]);
assert.deepEqual(seenTools.orchestrator, ["ask_researcher", "ask_triager"]);
assert.equal(store.length, 2);
assert.equal(approvals.length, 1);
console.log("team: " + trace.map((e) => e.agent + ":" + (e.tool ?? e.step)).join(" > "));
console.log("answer: " + answer);
console.log("approval asked once, for: " + approvals[0]);

// 3) Guardrails
// a) A specialist cannot use another specialist's tools, even if the model asks for them
const docsOnly = await mcpToolbox([{ url: base + "/docs/mcp" }]);
const r = await docsOnly.call("create_ticket", { title: "sneaky", priority: "P1" });
assert.equal(r.isError, true);
assert.equal(store.length, 2);
// b) A person can decline a write
const declined = await mcpToolbox([{ url: base + "/tickets/mcp", token: "tok-write" }], { approve: async () => false });
const d = await declined.call("create_ticket", { title: "Declined ticket here", priority: "P2" });
assert.equal(d.isError, true);
assert.equal(store.length, 2);
// c) A model that never stops is cut off by the turn limit
const loopTrace: TraceEvent[] = [];
const looping = { messages: { create: async () => use(["search_docs", { query: "again and again" }]) } } as unknown as Anthropic;
const out = await runAgent(looping, { name: "researcher", model: "claude-haiku-5-5", system: "x", toolbox: docsOnly, maxTurns: 3 }, "loop", loopTrace);
assert.equal(loopTrace.at(-1)?.step, "turn-limit");
console.log("guardrails: foreign tool refused, declined write not executed, endless loop stopped: " + JSON.stringify(out));

await Promise.all([team.close(), docsOnly.close(), declined.close()]);
http.close();
console.log("ALL MCP TEAM TESTS PASS");
process.exit(0);
npx tsx test/team.test.ts      # no API key: the Claude client is scripted, the MCP servers are real

输出:

http: tickets server 401 without a token; read token sees list_tickets only; write token also sees create_ticket; foreign Host header 403
validation: create_ticket with a 1-letter title and priority P0 -> isError, nothing written
{"audit":"create_ticket","by":"incident-bot","ticket":2}
team: researcher:search_docs > triager:list_tickets > researcher:get_doc > researcher:answer > orchestrator:ask_researcher > triager:create_ticket > triager:answer > orchestrator:ask_triager > orchestrator:answer
answer: Likely cause: the signing key changed in the deploy (doc: login). Ticket handled by the triager.
approval asked once, for: create_ticket {"title":"Users get 401 errors after deploy","priority":"P1"}
guardrails: foreign tool refused, declined write not executed, endless loop stopped: "researcher stopped after 3 turns without finishing."
ALL MCP TEAM TESTS PASS

测试在真实端口上启动两个服务器,先检查权限:没有令牌返回 401,只读令牌只能看到 list_tickets,写入令牌还能看到 create_ticket,带外部 Host 头的请求返回 403。服务器端校验拒绝了优先级为 "P0" 的工单。然后整个团队用脚本化模型处理一个请求,再逐一测试防护:只读文档的智能体请求 create_ticket、有人拒绝写入,以及一个不停调用工具的模型。

一个请求中发生了什么

测试追踪的泳道图:编排者委派两项任务;研究员调用 search_docs,分诊员调用 list_tickets,研究员调用 get_doc 并回答,分诊员在有人批准后调用 create_ticket 并回答,最后编排者给出最终答案
研究员和分诊员的步骤交错进行,因为编排者同时询问了两者。

追踪显示并行委派确实有效:研究员的 search_docs 和分诊员的 list_tickets 同时运行,编排者在两份报告都到达后才回答。生产环境中,把这份追踪连同请求 ID 发送到日志;当答案出错时,它能显示是哪个智能体、因哪个工具结果出了错。

防护措施

六张防护卡片:每个智能体一个工具箱,阻止了错误智能体调用 create_ticket;权限范围对只读令牌隐藏了 create_ticket;人工审批阻止了被拒绝的工单;服务器端模式拒绝了优先级 P0 和只有一个字母的标题;轮次限制在 3 轮后停止了无限循环;Host、Origin 和令牌检查返回了 401 和 403
每项防护在测试中都拦下了具体的问题。

这些防护都不依赖模型表现良好,这正是关键:模型可能被文档中的文字迷惑或欺骗,正如 AI API 安全指南所解释的。权限存在于服务器和智能体宿主中,模型无法更改。

成本和延迟

每次委派至少需要两次模型调用:专家的调用,以及编排者读取报告的那一轮。测试中的请求总共进行了九次模型调用。保持编排者的提示简短,给专家能胜任任务的最便宜模型,限制 max_tokens,并像这里一样并行运行独立任务,这样总时间接近最慢的那个专家,而不是所有时间之和。用追踪来测量:每一步都记录了 token 和毫秒数。

常见错误及修复方法

错误后果修复
每个智能体都连接所有服务器任何智能体都能调用任何工具每个智能体只连接自己服务器的工具箱
只读客户端能看到写入工具被误导的模型会调用它们只为拥有写入权限的令牌注册写入工具
信任未知服务器的 readOnlyHint撒谎的服务器会绕过你的审批步骤把第三方服务器的提示当作参考;按自己的列表审批
没有轮次限制循环调用工具让账单失控每个智能体设置 maxTurns
MCP 服务器监听 0.0.0.0 且不检查 Host网页可通过 DNS 重绑定访问它绑定 127.0.0.1 并检查 Host 和 Origin
不同服务器的工具重名调用被发往错误的服务器遇到重名直接报错,或按服务器加前缀
在 SDK v2 中使用 v1 的导入导入失败(@modelcontextprotocol/sdk、server.tool)使用拆分后的包和 registerTool;SDK 提供 v1 到 v2 的 codemod

局限

测试把模型的决策固定在脚本中,所以它证明了管道、权限和防护有效,而不是证明真实模型能规划得好;请在自己的任务上用真实运行来评估。这里的 Bearer 表代替了 OAuth:MCP 规范把服务器描述为 OAuth 资源服务器,生产部署应验证真实的访问令牌及其 audience。多智能体系统也比单智能体更难调试、更贵,所以从一个智能体开始,只在工具、权限或模型确实不同的地方拆分。

进一步扩展

同样的服务器也可以通过 stdio 运行,用于本地工具(@modelcontextprotocol/server/stdio 中的 serveStdio),这样桌面应用和 IDE 可以把它们作为子进程启动。为只读数据添加 resources,为可复用的指令添加 prompts,并用 MCP Inspector 手动试用服务器。如果你需要为自己产品的 API 构建 MCP 服务器,这正是我提供的服务之一。

常见问题

什么是模型上下文协议?

一种开放协议,让 AI 应用发现并调用独立服务器提供的工具、读取资源和使用提示词,因此一个服务器可以配合任何 MCP 客户端使用。

应该使用哪个 MCP TypeScript SDK?

第 2 版,即稳定版本:服务器用 @modelcontextprotocol/server,客户端用 @modelcontextprotocol/client,再加上 @modelcontextprotocol/node 等适配器。它实现了 2026-07-28 规范。

在 MCP TypeScript SDK v2 中如何注册工具?

调用 server.registerTool(name, { description, inputSchema }, handler),其中 inputSchema 是 zod 对象,处理函数返回 { content: [{ type: "text", text }] }。

如何通过 HTTP 提供 MCP 服务器?

用 createMcpHandler 包装服务器工厂函数,用 @modelcontextprotocol/node 的 toNodeHandler 适配,挂到 Node.js 的 http 服务器上,并在前面加 Host 和 Origin 检查。

智能体如何配合 Claude 使用 MCP 工具?

智能体宿主获取服务器的工具列表,把每个工具的名称、描述和 JSON Schema 作为工具定义交给 Claude,再用 callTool 把每个 tool_use 块发回服务器。

如何阻止智能体使用不该用的工具?

给每个智能体一个只包含自己服务器的工具箱,只为拥有写入权限的令牌注册写入工具,并拒绝不在该智能体工具箱中的工具名。

一个智能体如何调用另一个智能体?

把第二个智能体包装成一个工具,例如 ask_researcher,其处理函数用任务运行那个智能体的循环并返回它的最终答案。

多智能体系统应该并行运行任务吗?

应该,前提是任务相互独立。如果编排者在一轮中询问两个智能体,就同时执行两个工具调用,让总时间接近较慢的那个。

如何为 MCP 工具调用加入人工审批?

在智能体宿主中,把每次调用与写入工具列表比对,在调用服务器前询问人员;如果被拒绝,就向模型返回错误结果。

如何保护通过 HTTP 提供的 MCP 服务器?

在 MCP 运行前验证 Bearer 访问令牌,把身份作为 authInfo 传入,按权限限定工具列表,只绑定回环地址或私有网络,并检查 Host 和 Origin。

MCP 和函数调用有什么区别?

函数调用是模型请求运行工具的方式。MCP 是由独立服务器描述并提供工具的方式,让许多应用都能复用这些工具。

如何从 MCP SDK v1 迁移到 v2?

运行官方 codemod,换成拆分后的包,把 server.tool 换成 registerTool,把旧的传输方式换成 createMcpHandler 或 serveStdio。

来源

本指南作者的免费应用