Engineering notes
Building Multi-Agent Systems with TypeScript and Model Context Protocol
By Muhammad Shahid · · 25 min read
Quick answer
To build a multi-agent system with TypeScript and the Model Context Protocol, expose each capability as an MCP server (here a docs server and a ticket server, built with the v2 TypeScript SDK and served over Streamable HTTP), give each specialist agent an MCP client for only the servers it needs, and let an orchestrator agent call the specialists as tools. Turn MCP tool listings into model tools, route each tool call back to its server, and add guardrails: per-agent toolboxes, token scopes that hide write tools, human approval for writes, schema validation and turn limits.
| Stack | TypeScript, MCP TypeScript SDK v2 (@modelcontextprotocol/server, client, node), Claude Sonnet 5.5 and Haiku 5.5 |
|---|---|
| Agents | Orchestrator plus two specialists; each specialist sees one MCP server only |
| Transport | Streamable HTTP on Node.js with Host and Origin checks and Bearer tokens |
| Guardrails | Scoped tool lists, human approval for writes, server-side zod validation, turn limits, a trace |
| Tested | Real MCP servers over HTTP with a scripted Claude client; every guardrail exercised |
A single AI agent with twenty tools gets confused, and a single agent with write access to everything is a risk. Splitting the work between a few small agents, each with only the tools it needs, fixes both, and the Model Context Protocol is the clean way to hand those tools out. This tutorial builds a multi-agent system with TypeScript and MCP: two MCP servers written with the v2 TypeScript SDK, served over Streamable HTTP with tokens and scopes, an orchestrator agent that delegates to a researcher and a triager in parallel, and the guardrails that stop a confused model from doing damage. All code is complete and type-checked. The test runs the real MCP servers over HTTP with a scripted Claude client, so every tool call, permission and guardrail runs for real, while the model's decisions are fixed in a script.
What is the Model Context Protocol?
The Model Context Protocol (MCP) is an open protocol that lets an AI application discover and call tools, read resources and use prompts provided by separate servers. An MCP server says "here are my tools and their JSON schemas"; an MCP client lists them, passes them to a model, and sends the model's tool calls back to the server. Because the protocol is the same everywhere, one server works with any MCP client: your own agents, Claude Desktop, IDEs and other hosts. Version 2 of the official TypeScript SDK, the stable line, implements the 2026-07-28 specification and splits the old single package into @modelcontextprotocol/server, @modelcontextprotocol/client and framework adapters such as @modelcontextprotocol/node.
Why several agents, and when not to
Use more than one agent when the parts of a job need different tools, different permissions or different models: a researcher that can only read docs cannot open tickets by mistake, and a cheap fast model can do the narrow tasks while a stronger one plans. Do not split work just because it sounds advanced: every hop between agents costs a model call, adds latency and is one more place to lose context. If one agent with five well-described tools does the job, keep one agent. The guide to AI agents in production covers that single-agent case, and the function calling tutorial shows tool calling without MCP.
The architecture
The orchestrator never touches a server directly; its only tools are "ask the researcher" and "ask the triager". Each specialist connects to one MCP server. The ticket server checks a Bearer token and builds its tool list from the token's scopes, so a client without tickets:write does not even see the write tool. Writes also go through a human approval callback in the agent host.
What do you need?
| Tool | Version used | Why |
|---|---|---|
| Node.js | 20 or later | Runtime |
| @modelcontextprotocol/server | 2.4 | McpServer, registerTool, createMcpHandler |
| @modelcontextprotocol/client | 2.4 | Client and StreamableHTTPClientTransport |
| @modelcontextprotocol/node | 2.1 | toNodeHandler, Host and Origin checks |
| zod | 4 (imported as zod/v4) | Tool input and output schemas |
| @anthropic-ai/sdk | 1.8 | The agents' model calls |
Step 1: Set up the project
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
Step 2: A read-only MCP server
// 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 takes a name, a config and a handler. The inputSchema is a zod object: the SDK turns it into the JSON Schema clients see, and rejects bad arguments before your handler runs. outputSchema plus structuredContent gives clients typed results alongside the text. readOnlyHint: true tells clients the tool changes nothing, and this tutorial's agent host uses that hint to decide which calls need approval. createMcpHandler takes a factory that builds a fresh server for each request, which keeps the server stateless and easy to scale.
Step 3: A ticket server with scopes
// 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 });
};
}
The factory receives the request's authInfo, so the tool list can depend on who is asking: create_ticket is registered only when the token has tickets:write. That is least privilege at the protocol level: a read-only client cannot call a tool it cannot see, and a model cannot be talked into using it. withBearer checks the token before MCP runs and passes the verified identity through handler.fetch(request, { authInfo }); the SDK itself does no token checking. In production, verify real OAuth access tokens here instead of a fixed table, and check their audience. Every write is logged with the client that made it.
Step 4: Serve them over 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 adapts the web-standard handler to Node's http server. The Host and Origin checks block DNS-rebinding attacks, where a web page tricks a browser into calling a server on your own machine; MCP's handler does not check them for you. Both servers here share one process and one port with different paths, but they could just as well run on different machines owned by different teams.
Step 5: Turn MCP tools into Claude tools
// 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 connects one client per server, lists the tools and converts each into a Claude tool definition: the MCP inputSchema is already JSON Schema, so it passes straight through. A map remembers which server owns which tool, and a duplicate name across servers is an error rather than a silent override. Tools without readOnlyHint go through approve first. If the model asks for a tool this agent does not have, the call returns an error result instead of reaching any server. localToolbox wraps plain functions the same way, which is how the orchestrator gets its "ask an agent" tools.
Step 6: The agent loop
// 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.";
}
This is the standard tool-use loop: call the model, run any tool calls, send the results back, repeat until the model answers. The whole assistant message, including any thinking blocks, goes back unchanged, as the API requires. Tool calls in one turn run in parallel. The loop stops after maxTurns, so a model that keeps calling tools cannot run up a bill, and every step is written to a shared trace with the agent's name, the tool, the time it took and whether it failed.
Step 7: The orchestrator and its team
// 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()]);
},
};
}
The orchestrator runs on Claude Sonnet 5.5 and plans; the specialists run on Claude Haiku 5.5, which costs $0.10 per million input tokens against $2 for Sonnet, because their tasks are narrow. Each specialist's system prompt states its job and its rules ("list open tickets before creating one"). The orchestrator's prompt tells it to run independent tasks in parallel: when it asks both agents in one turn, the agent loop runs both tool calls at the same time.
Testing it
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
Output:
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
The test starts both servers on a real port and checks the permissions first: no token gets a 401, a read token lists only list_tickets, a write token also lists create_ticket, and a request with a foreign Host header gets a 403. Server-side validation rejects a ticket with priority "P0". Then the whole team runs one request with a scripted model, and the guardrails are tested one by one: a docs-only agent asking for create_ticket, a person declining a write, and a model that never stops calling tools.
What happened in one request
The trace shows the parallel delegation working: the researcher's search_docs and the triager's list_tickets ran side by side, and the orchestrator answered only after both reports arrived. In production, send this trace to your logs with a request ID; when an answer is wrong, it shows which agent went wrong and with which tool result.
The guardrails
None of these depend on the model behaving well, which is the point: a model can be confused or tricked by text in a document, as the guide to securing AI APIs explains. Permissions live in the servers and the agent host, where the model cannot change them.
Cost and latency
Every delegation is at least two model calls: the specialist's and the orchestrator's turn that reads its report. The request in the test made nine model calls in total. Keep the orchestrator's prompt short, give specialists the cheapest model that does their task well, cap max_tokens, and run independent tasks in parallel, as here, so total time is close to the slowest specialist rather than the sum. Measure with the trace: tokens and milliseconds are recorded for every step.
Common mistakes and how to fix them
| Mistake | What happens | Fix |
|---|---|---|
| Every agent connects to every server | Any agent can call any tool | One toolbox per agent with only its servers |
| Write tools visible to read-only clients | A tricked model calls them | Register write tools only for tokens with the write scope |
| Trusting readOnlyHint from an unknown server | A server that lies skips your approval step | Treat hints from third-party servers as advice; approve by your own list |
| No turn limit | A loop of tool calls runs up a bill | maxTurns per agent |
| MCP server on 0.0.0.0 without Host checks | Web pages can reach it through DNS rebinding | Bind to 127.0.0.1 and check Host and Origin |
| Duplicate tool names across servers | Calls go to the wrong server | Fail on duplicates, or prefix names per server |
| Using v1 imports with SDK v2 | Imports fail (@modelcontextprotocol/sdk, server.tool) | Use the split packages and registerTool; the SDK has a v1-to-v2 codemod |
Limitations
The test fixes the model's decisions in a script, so it proves that the plumbing, permissions and guardrails work, not that a real model plans well; evaluate that with real runs on your own tasks. The Bearer table here stands in for OAuth: the MCP specification describes servers as OAuth resource servers, and production deployments should verify real access tokens and their audience. Multi-agent systems are also harder to debug and more expensive than single agents, so start with one agent and split only where tools, permissions or models genuinely differ.
Going further
The same servers can run over stdio for local tools (serveStdio from @modelcontextprotocol/server/stdio), so desktop apps and IDEs can launch them as child processes. Add resources for read-only data and prompts for reusable instructions, and use the MCP Inspector to try a server by hand. If you want an MCP server built for your product's API, that is one of the services I offer.
Frequently asked questions
What is the Model Context Protocol?
An open protocol that lets AI applications discover and call tools, read resources and use prompts from separate servers, so one server works with any MCP client.
Which MCP TypeScript SDK should I use?
Version 2, the stable line: @modelcontextprotocol/server for servers, @modelcontextprotocol/client for clients, plus adapters such as @modelcontextprotocol/node. It implements the 2026-07-28 specification.
How do I register a tool in the MCP TypeScript SDK v2?
Call server.registerTool(name, { description, inputSchema }, handler), with inputSchema as a zod object, and return { content: [{ type: "text", text }] } from the handler.
How do I serve an MCP server over HTTP?
Wrap a server factory with createMcpHandler, adapt it with toNodeHandler from @modelcontextprotocol/node, and mount it on a Node.js http server, with Host and Origin checks in front.
How do agents use MCP tools with Claude?
The agent host lists the server's tools, passes each tool's name, description and JSON Schema to Claude as a tool definition, and sends each tool_use block back to the server with callTool.
How do I stop an agent from using tools it should not?
Give each agent a toolbox with only its own servers, register write tools only for tokens with a write scope, and refuse any tool name that is not in the agent's toolbox.
How does one agent call another agent?
Wrap the second agent in a tool, such as ask_researcher, whose handler runs that agent's loop with the task and returns its final answer.
Should multi-agent systems run tasks in parallel?
Yes, when the tasks are independent. If the orchestrator asks two agents in one turn, run both tool calls at once so total time is close to the slowest one.
How do I add human approval to MCP tool calls?
In the agent host, check each call against the list of write tools and ask a person before calling the server; return an error result to the model if they decline.
How do I secure an MCP server over HTTP?
Verify Bearer access tokens before MCP runs, pass the identity as authInfo, scope the tool list by permissions, bind to loopback or a private network, and check Host and Origin.
What is the difference between MCP and function calling?
Function calling is how a model asks to run a tool. MCP is how tools are described and served by separate servers, so many applications can reuse them.
How do I migrate from MCP SDK v1 to v2?
Run the official codemod, switch to the split packages, and replace server.tool with registerTool and the old transports with createMcpHandler or serveStdio.