MSMuhammad Shahid

מאמרים הנדסיים

בניית מערכות מרובות סוכנים עם TypeScript ו-Model Context Protocol

מאת Muhammad Shahid · · 22 דקות קריאה

תשובה קצרה

כדי לבנות מערכת מרובת סוכנים עם TypeScript ו-Model Context Protocol, חשפו כל יכולת כשרת MCP (כאן שרת מסמכים ושרת קריאות, שנבנו עם ה-SDK של TypeScript בגרסה 2 ומוגשים ב-Streamable HTTP), תנו לכל סוכן מומחה לקוח MCP רק לשרתים שהוא צריך, ותנו לסוכן מתזמר לקרוא למומחים ככלים. המירו את רשימות הכלים של MCP לכלים של המודל, נתבו כל קריאה בחזרה לשרת שלה, והוסיפו מעקות בטיחות: ארגז כלים נפרד לכל סוכן, הרשאות טוקן שמסתירות כלי כתיבה, אישור אנושי לכתיבה, בדיקת סכמות והגבלת סבבים.

עובדות עיקריות
סטאקTypeScript, ‏MCP TypeScript SDK v2‏ (@modelcontextprotocol/server, client, node), ‏Claude Sonnet 5.5 ו-Haiku 5.5
סוכניםמתזמר ושני מומחים; כל מומחה רואה שרת MCP אחד בלבד
תעבורהStreamable HTTP על Node.js עם בדיקות Host ו-Origin וטוקני Bearer
מעקותרשימות כלים לפי הרשאה, אישור אנושי לכתיבה, בדיקת zod בשרת, הגבלת סבבים, מעקב
נבדקשרתי MCP אמיתיים ב-HTTP עם לקוח Claude מתוסרט; כל מעקה נבדק

סוכן AI יחיד עם עשרים כלים מתבלבל, וסוכן יחיד עם הרשאת כתיבה לכל דבר הוא סיכון. חלוקת העבודה בין כמה סוכנים קטנים, שלכל אחד רק הכלים שהוא צריך, פותרת את שתי הבעיות, ו-Model Context Protocol הוא הדרך הנקייה לחלק את הכלים האלה. המדריך הזה בונה מערכת מרובת סוכנים עם TypeScript ו-MCP: שני שרתי MCP שנכתבו עם ה-SDK של TypeScript בגרסה 2, מוגשים ב-Streamable HTTP עם טוקנים והרשאות, סוכן מתזמר שמאציל במקביל לחוקר ולמסווג, ומעקות הבטיחות שעוצרים מודל מבולבל מלגרום נזק. כל הקוד מלא ועבר בדיקת טיפוסים. הבדיקה מריצה את שרתי ה-MCP האמיתיים ב-HTTP עם לקוח Claude מתוסרט, כך שכל קריאת כלי, הרשאה ומעקה רצים באמת, בזמן שההחלטות של המודל קבועות בתסריט.

מה זה Model Context Protocol?

Model Context Protocol‏ (MCP) הוא פרוטוקול פתוח שמאפשר לאפליקציית AI לגלות ולהפעיל כלים, לקרוא משאבים ולהשתמש בפרומפטים שמספקים שרתים נפרדים. שרת MCP אומר "אלה הכלים שלי והסכמות שלהם ב-JSON"; לקוח MCP מקבל את הרשימה, מעביר אותה למודל ושולח את קריאות הכלים של המודל בחזרה לשרת. כיוון שהפרוטוקול זהה בכל מקום, שרת אחד עובד עם כל לקוח MCP: הסוכנים שלכם, Claude Desktop, סביבות פיתוח ומארחים אחרים. גרסה 2 של ה-SDK הרשמי ל-TypeScript, הקו היציב, מממשת את המפרט מ-2026-07-28 ומפצלת את החבילה הישנה ל-@modelcontextprotocol/server, ל-@modelcontextprotocol/client ולמתאמים כמו @modelcontextprotocol/node.

למה כמה סוכנים, ומתי לא

השתמשו ביותר מסוכן אחד כשחלקי העבודה צריכים כלים, הרשאות או מודלים שונים: חוקר שיכול רק לקרוא מסמכים לא יכול לפתוח קריאות בטעות, ומודל זול ומהיר יכול לבצע משימות צרות בזמן שמודל חזק מתכנן. אל תפצלו עבודה רק כי זה נשמע מתקדם: כל מעבר בין סוכנים עולה קריאה למודל, מוסיף השהיה והוא עוד מקום לאבד הקשר. אם סוכן אחד עם חמישה כלים מתוארים היטב עושה את העבודה, השאירו סוכן אחד. המדריך לסוכני AI בפרודקשן מכסה את המקרה של סוכן יחיד, והמדריך ל-function calling מראה קריאה לכלים בלי 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 מקבל factory שבונה שרת חדש לכל בקשה, מה ששומר את השרת בלי מצב וקל להרחבה.

שלב 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 });
  };
}

ה-factory מקבל את ה-authInfo של הבקשה, כך שרשימת הכלים יכולה להיות תלויה במי ששואל: create_ticket נרשם רק כשלטוקן יש tickets:write. זו הרשאה מינימלית ברמת הפרוטוקול: לקוח לקריאה בלבד לא יכול לקרוא לכלי שהוא לא רואה, ואי אפשר לשכנע מודל להשתמש בו. 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 מתאים את ה-handler הסטנדרטי לשרת http של Node. בדיקות ה-Host וה-Origin חוסמות התקפות DNS rebinding, שבהן דף אינטרנט גורם לדפדפן לקרוא לשרת על המחשב שלכם; ה-handler של 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: ה-inputSchema של MCP כבר 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, שעולה 0.10$ למיליון טוקני קלט מול 2$ ל-Sonnet, כי המשימות שלהם צרות. פרומפט המערכת של כל מומחה מגדיר את התפקיד והכללים שלו ("הצג קריאות פתוחות לפני שאתה יוצר אחת"). הפרומפט של המתזמר אומר לו להריץ משימות בלתי תלויות במקביל: כשהוא שואל את שני הסוכנים באותו סבב, לולאת הסוכן מריצה את שתי הקריאות בו זמנית.

בדיקה

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 של המסווג רצו זה לצד זה, והמתזמר ענה רק אחרי ששני הדיווחים הגיעו. בפרודקשן, שלחו את המעקב הזה ללוגים עם מזהה בקשה; כשתשובה שגויה, הוא מראה איזה סוכן טעה ובאיזו תוצאת כלי.

מעקות הבטיחות

שישה כרטיסי מעקות: ארגז כלים לכל סוכן עצר create_ticket מהסוכן הלא נכון; הרשאות הסתירו את create_ticket מטוקן קריאה; אישור אנושי עצר קריאה שנדחתה; סכמות בשרת דחו עדיפות P0 וכותרת של אות אחת; הגבלת סבבים עצרה לולאה אינסופית אחרי 3 סבבים; בדיקות Host, ‏Origin וטוקן החזירו 401 ו-403
כל מעקה עצר משהו מוגדר בבדיקה.

אף אחד מהם לא תלוי בכך שהמודל יתנהג יפה, וזו בדיוק הנקודה: אפשר לבלבל מודל או להטעות אותו בטקסט שבמסמך, כפי שהמדריך לאבטחת APIs של AI מסביר. ההרשאות יושבות בשרתים ובמארח הסוכנים, במקום שהמודל לא יכול לשנות.

עלות והשהיה

כל האצלה היא לפחות שתי קריאות למודל: של המומחה ושל הסבב של המתזמר שקורא את הדיווח שלו. הבקשה בבדיקה ביצעה תשע קריאות למודל בסך הכל. שמרו על פרומפט קצר למתזמר, תנו למומחים את המודל הזול ביותר שעושה את המשימה שלהם היטב, הגבילו את max_tokens, והריצו משימות בלתי תלויות במקביל, כמו כאן, כך שהזמן הכולל קרוב למומחה האיטי ביותר ולא לסכום. מדדו עם המעקב: טוקנים ומילישניות נרשמים לכל צעד.

טעויות נפוצות ואיך לתקן אותן

טעותמה קורהתיקון
כל סוכן מתחבר לכל שרתכל סוכן יכול לקרוא לכל כליארגז כלים לכל סוכן עם השרתים שלו בלבד
כלי כתיבה גלויים ללקוחות לקריאה בלבדמודל שהוטעה קורא להםרשמו כלי כתיבה רק לטוקנים עם הרשאת כתיבה
אמון ב-readOnlyHint משרת לא מוכרשרת שמשקר מדלג על שלב האישור שלכםהתייחסו לרמזים משרתים חיצוניים כעצה; אשרו לפי רשימה משלכם
אין הגבלת סבביםלולאת קריאות לכלים מנפחת חשבוןmaxTurns לכל סוכן
שרת MCP על 0.0.0.0 בלי בדיקות Hostדפי אינטרנט יכולים להגיע אליו דרך DNS rebindingהאזינו ל-127.0.0.1 ובדקו Host ו-Origin
שמות כלים כפולים בין שרתיםקריאות מגיעות לשרת הלא נכוןהכשילו כפילויות, או הוסיפו קידומת לפי שרת
ייבוא של v1 עם SDK v2הייבוא נכשל (@modelcontextprotocol/sdk, ‏server.tool)השתמשו בחבילות המפוצלות וב-registerTool; ל-SDK יש codemod מ-v1 ל-v2

מגבלות

הבדיקה קובעת את ההחלטות של המודל בתסריט, כך שהיא מוכיחה שהצנרת, ההרשאות ומעקות הבטיחות עובדים, לא שמודל אמיתי מתכנן טוב; העריכו את זה בהרצות אמיתיות על המשימות שלכם. טבלת ה-Bearer כאן מחליפה את OAuth: מפרט MCP מתאר שרתים כ-resource servers של OAuth, ופריסות פרודקשן צריכות לאמת טוקני גישה אמיתיים ואת ה-audience שלהם. מערכות מרובות סוכנים גם קשות יותר לדיבוג ויקרות יותר מסוכן יחיד, אז התחילו בסוכן אחד ופצלו רק היכן שהכלים, ההרשאות או המודלים באמת שונים.

להמשיך הלאה

אותם שרתים יכולים לרוץ ב-stdio לכלים מקומיים (serveStdio מ-@modelcontextprotocol/server/stdio), כך שאפליקציות דסקטופ וסביבות פיתוח יפעילו אותם כתהליכי בן. הוסיפו resources לנתונים לקריאה בלבד ו-prompts להוראות לשימוש חוזר, והשתמשו ב-MCP Inspector כדי לנסות שרת ידנית. אם אתם רוצים שרת MCP שנבנה ל-API של המוצר שלכם, זה אחד השירותים שאני מציע.

שאלות נפוצות

מה זה Model Context Protocol?

פרוטוקול פתוח שמאפשר לאפליקציות AI לגלות ולהפעיל כלים, לקרוא משאבים ולהשתמש בפרומפטים משרתים נפרדים, כך ששרת אחד עובד עם כל לקוח MCP.

באיזה SDK של MCP ל-TypeScript להשתמש?

בגרסה 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 }] } מהפונקציה.

איך מגישים שרת MCP ב-HTTP?

עוטפים factory של שרת ב-createMcpHandler, מתאימים אותו עם toNodeHandler מ-‏@modelcontextprotocol/node, ומחברים לשרת http של Node.js עם בדיקות Host ו-Origin לפניו.

איך סוכנים משתמשים בכלי MCP עם Claude?

מארח הסוכנים מקבל את רשימת הכלים של השרת, מעביר ל-Claude את השם, התיאור וה-JSON Schema של כל כלי כהגדרת כלי, ושולח כל בלוק tool_use בחזרה לשרת עם callTool.

איך מונעים מסוכן להשתמש בכלים שאסור לו?

נותנים לכל סוכן ארגז כלים רק עם השרתים שלו, רושמים כלי כתיבה רק לטוקנים עם הרשאת כתיבה, ודוחים כל שם כלי שלא נמצא בארגז הכלים של הסוכן.

איך סוכן אחד קורא לסוכן אחר?

עוטפים את הסוכן השני בכלי, כמו ask_researcher, שהפונקציה שלו מריצה את לולאת הסוכן עם המשימה ומחזירה את התשובה הסופית שלו.

האם מערכות מרובות סוכנים צריכות להריץ משימות במקביל?

כן, כשהמשימות בלתי תלויות. אם המתזמר שואל שני סוכנים באותו סבב, הריצו את שתי הקריאות בבת אחת כדי שהזמן הכולל יהיה קרוב לאיטית מביניהן.

איך מוסיפים אישור אנושי לקריאות כלים של MCP?

במארח הסוכנים, בודקים כל קריאה מול רשימת כלי הכתיבה ושואלים אדם לפני הקריאה לשרת; אם הוא מסרב, מחזירים למודל תוצאת שגיאה.

איך מאבטחים שרת MCP ב-HTTP?

מאמתים טוקני Bearer לפני ש-MCP רץ, מעבירים את הזהות כ-authInfo, מגבילים את רשימת הכלים לפי הרשאות, מאזינים ל-loopback או לרשת פרטית, ובודקים Host ו-Origin.

מה ההבדל בין MCP ל-function calling?

function calling הוא האופן שבו מודל מבקש להפעיל כלי. MCP הוא האופן שבו כלים מתוארים ומוגשים על ידי שרתים נפרדים, כך שאפליקציות רבות יכולות להשתמש בהם שוב.

איך עוברים מ-MCP SDK v1 ל-v2?

מריצים את ה-codemod הרשמי, עוברים לחבילות המפוצלות, ומחליפים את server.tool ב-registerTool ואת התעבורות הישנות ב-createMcpHandler או serveStdio.

מקורות

אפליקציות חינמיות מהכותב של המדריך