What is MCP? Build an MCP server in TypeScript

What is MCP and why does it let many AI apps share the same tools? Write an MCP server in TypeScript, call it from a chatbot and another assistant, with tests.

MCP (Model Context Protocol) is an open standard for connecting AI applications to outside tools and data. You write a tool once inside an MCP server, and every app that speaks MCP can use it. Does copying tools from one app to the next annoy you? Let's fix that.

Why not just copy the tools into a second app?

In the previous post, the chatbot of the Mộc café found policies by meaning. (Mộc is an illustrative café that I use as the running example in this series.) The chatbot already had three tools: look up an order by its ID, find an order by phone number, and add an item to an order that is still being prepared. All three live directly inside the chatbot code. Now the café wants a second assistant for the staff at the counter, who ask things like "where is order 1041?" or "add two bac xiu to this order". That assistant needs exactly the same three tools.

The fastest way is to copy the code over. The price shows up even with the smallest rule. The add_item tool allows between 1 and 5 portions at a time, and that rule lives in two places: in the description sent to the model, and in the validation code. With two apps, the rule lives in four places. One day the café raises the limit to 10 and you forget one place. The chatbot lets people add 10 while the counter assistant still stops at 5. Two copies of the same tool slowly drift apart, and the customer is the one who pays for it.

What I want is for the tools to live in one place, and for the chatbot and the counter assistant to just plug into it. That is exactly the job of MCP.

What is MCP?

The official documentation describes MCP as an open-source standard for connecting AI applications to external systems: data sources, tools and workflows. They compare it to a USB-C port for AI apps: one common plug instead of a different cable for every device.

There are three roles. A server is the program that offers tools, for example the Mộc server. A client is the part inside an AI application that talks to one server. A host is the AI application itself, such as the chatbot or the counter assistant, and it can run several clients to connect to several servers at once. A server can offer tools, readable resources and prompt templates. In this post I only build tools, since tools are what the Mộc chatbot already has.

For transport, a server running on the same machine usually talks through the stdin and stdout of a child process (called stdio), while a remote server uses HTTP. I use stdio to keep things simple. One important detail: with stdio, stdout is the channel reserved for the protocol, so every log line from the server must go to stderr, as the documentation's server guide says. In my tests, SDK version 1.32.2 silently ignored a few stray console.log lines that leaked into stdout. I still follow the advice, because I do not want my whole program to depend on how forgiving one particular client happens to be.

Building the MCP server for Mộc

I use the official SDK @modelcontextprotocol/sdk (version 1.32.2 was the newest I could see on npm on 12 November 2026) and Zod to declare the input. You need Node.js 22.18 or newer, because Node can run .ts files directly from that version on, and the client in this post starts the server with the same node command. Create a folder moc-mcp with this layout:

Folder layout
moc-mcp/
  package.json
  src/shop-info.ts
  src/orders.ts
  src/moc-server.ts
  src/mcp-client.ts
  src/try-client.ts
  src/try-chatbot.ts
  src/moc-server.test.ts
package.json
{
  "name": "moc-mcp",
  "private": true,
  "type": "module",
  "dependencies": {
    "@modelcontextprotocol/sdk": "1.32.2",
    "zod": "4.6.7"
  },
  "devDependencies": {
    "vitest": "5.1.0"
  }
}

The first two files are the café's data and logic, taken from the chatbot of the earlier posts (I dropped the parts of the menu we do not use here). This is where the tools really do their work: the menu, a list that already holds two orders, and a function that adds an item only while the order is still being prepared. The resetOrders function exists only so tests can put the data back as it was. Prices are in Vietnamese đồng, so 25000 is about one US dollar.

src/shop-info.ts
// Menu of the Mộc café (illustrative): item name and price in Vietnamese đồng.
export const MENU: Record<string, number> = {
  "black coffee": 25000,
  "milk coffee": 29000,
  "bac xiu": 32000,
  "salt coffee": 35000,
  "egg banh mi": 25000,
};
src/orders.ts
import { MENU } from "./shop-info.ts";

export type Order = {
  orderId: string;
  phone: string;
  items: string[];
  status: "preparing" | "out for delivery" | "delivered";
  placedAt: string;
};

const INITIAL_ORDERS: Order[] = [
  { orderId: "1041", phone: "0901000001", items: ["milk coffee", "egg banh mi"], status: "preparing", placedAt: "today 8:12" },
  { orderId: "1042", phone: "0901000002", items: ["bac xiu"], status: "out for delivery", placedAt: "today 9:40" },
];

let ORDERS: Order[] = structuredClone(INITIAL_ORDERS);

// Put the data back as it was, so test runs do not affect each other.
export function resetOrders(): void {
  ORDERS = structuredClone(INITIAL_ORDERS);
}

export function findOrderById(orderId: string): Order | undefined {
  return ORDERS.find((order) => order.orderId === orderId);
}

export function findOrderByPhone(phone: string): Order | undefined {
  return ORDERS.find((order) => order.phone === phone);
}

// Add items to an order. Only allowed while the order is still being prepared: an order that has left cannot change.
export function addItem(orderId: string, item: string, quantity: number): { ok: true; order: Order } | { ok: false; reason: string } {
  const order = findOrderById(orderId);
  if (!order) return { ok: false, reason: `There is no order ${orderId}.` };
  if (!(item in MENU)) return { ok: false, reason: `The café does not sell "${item}".` };
  if (order.status !== "preparing") return { ok: false, reason: `Order ${orderId} is ${order.status}, so items can no longer be added.` };
  for (let i = 0; i < quantity; i++) order.items.push(item);
  return { ok: true, order };
}

Now the main part. The three tools get registered on one MCP server. Look at three things in this file: the Zod schema that replaces the hand-written input_schema block, the annotations on each tool, and the way errors are reported.

src/moc-server.ts
// MCP server of the Mộc café: packages three tools (look up an order / find by phone / add an item) so every app can share them.
// Run directly (node src/moc-server.ts) it talks over stdin/stdout. Remember: stdout is reserved for the protocol, logs go to stderr.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

import { addItem, findOrderById, findOrderByPhone } from "./orders.ts";

const orderId = z.string().regex(/^\d{4}$/, "An order ID is exactly 4 digits, with no # sign").describe("Order ID: 4 digits, no # sign");

const result = (content: unknown) => ({ content: [{ type: "text" as const, text: JSON.stringify(content) }] });
const failure = (message: string) => ({ content: [{ type: "text" as const, text: message }], isError: true });

export function createServer(): McpServer {
  const server = new McpServer({ name: "moc-orders", version: "1.0.0" });

  server.registerTool(
    "view_order",
    {
      title: "View an order",
      description:
        "View the items and current status of an order by its order ID (4 digits, for example 1041). " +
        "Call this tool whenever a customer asks whether an order has been delivered, where it is, or when it will arrive.",
      inputSchema: { order_id: orderId },
      annotations: { readOnlyHint: true },
    },
    async ({ order_id }) => {
      const order = findOrderById(order_id);
      if (!order) return failure(`There is no order ${order_id}.`);
      return result({ order_id: order.orderId, items: order.items, status: order.status, placed_at: order.placedAt });
    },
  );

  server.registerTool(
    "find_order_by_phone",
    {
      title: "Find an order by phone number",
      description:
        "Find the most recent order ID of a customer by phone number (10 digits, starting with 0). " +
        "It only returns the order ID; to get the status, call view_order next.",
      inputSchema: { phone: z.string().regex(/^0\d{9}$/, "A phone number is 10 digits and starts with 0").describe("10-digit phone number") },
      annotations: { readOnlyHint: true },
    },
    async ({ phone }) => {
      const order = findOrderByPhone(phone);
      if (!order) return failure("No order found for this number.");
      return result({ order_id: order.orderId });
    },
  );

  server.registerTool(
    "add_item",
    {
      title: "Add an item to an order",
      description:
        "Add an item to an order that is still being prepared. Only call it when the customer says clearly which item and how many. " +
        "If the order is out for delivery or delivered, the tool returns an error.",
      inputSchema: {
        order_id: orderId,
        item: z.string().describe("Item name exactly as on the menu, for example: bac xiu"),
        quantity: z.number().int().min(1).max(5).describe("Number of portions, from 1 to 5"),
      },
      annotations: { readOnlyHint: false, destructiveHint: false },
    },
    async ({ order_id, item, quantity }) => {
      const outcome = addItem(order_id, item.trim().toLowerCase(), quantity);
      if (!outcome.ok) return failure(outcome.reason);
      return result({ order_id: outcome.order.orderId, items: outcome.order.items, status: outcome.order.status });
    },
  );

  return server;
}

if (import.meta.main) {
  await createServer().connect(new StdioServerTransport());
  console.error("Mộc MCP server is ready (stdio)"); // stderr, not stdout
}

About the schema: in the old chatbot, every tool had a hand-written input_schema block and a separate piece of code that checked order_id with a regular expression. Now there is one place, the Zod schema. The SDK uses it both to generate the JSON Schema sent to the model and to reject bad input before the code of the tool runs. I write the rule "an order ID is 4 digits" only once, so it can no longer disagree with itself.

About annotations: readOnlyHint: true says the tool only reads, while add_item writes. They are only hints that help an application decide whether to ask for confirmation, and the specification says clients must treat them as untrusted unless the server itself is trusted. Do not mistake them for a safety mechanism.

About errors: the MCP specification separates two kinds. Protocol errors (the tool does not exist, the input has the wrong type) and errors while running the tool, such as "the order does not exist" or "the order is out for delivery, so you cannot add items". The second kind comes back as an ordinary result with isError: true, so the model can read the reason and handle it, for instance by apologising to the customer and explaining. The two helpers result and failure at the top of the file do exactly that. You can read this in the specification about tools (the 2025-06-18 version, which I read on 12 November 2026; the site may have a newer version by now).

Calling the server from two apps

Now the client side. The file mcp-client.ts starts the server as a child process and connects to it. Both apps of the café use these two functions:

src/mcp-client.ts
// Connect to the Mộc MCP server by running it as a child process. Shared by every app of the café.
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

export async function connectToServer(path = "src/moc-server.ts"): Promise<Client> {
  const client = new Client({ name: "moc-app", version: "1.0.0" });
  await client.connect(new StdioClientTransport({ command: process.execPath, args: [path] }));
  return client;
}

// Call one tool and return the result text, plus an error flag.
export async function callTool(client: Client, name: string, input: Record<string, unknown>): Promise<{ text: string; isError: boolean }> {
  const response = await client.callTool({ name, arguments: input });
  const text = (response.content as { type: string; text?: string }[]).map((part) => part.text ?? "").join("");
  return { text, isError: response.isError === true };
}

The first app is the counter assistant. It does not need a language model, only direct tool calls. This script lists the tools and then calls them four times: a normal order lookup, adding an item to an order that is still being prepared, adding an item to an order that has already left (this must be refused), and a lookup with an order ID that has only three digits (this must be blocked):

src/try-client.ts
// App 1: an assistant for the staff at the counter, calling tools directly. Run: node src/try-client.ts
import { callTool, connectToServer } from "./mcp-client.ts";

const client = await connectToServer();
const { tools } = await client.listTools();
console.log(`The server has ${tools.length} tools: ${tools.map((t) => t.name).join(", ")}`);

for (const [name, input] of [
  ["view_order", { order_id: "1041" }],
  ["add_item", { order_id: "1041", item: "Bac xiu", quantity: 2 }],
  ["add_item", { order_id: "1042", item: "bac xiu", quantity: 1 }],
  ["view_order", { order_id: "104" }],
] as const) {
  const outcome = await callTool(client, name, input);
  console.log(`${name} ${JSON.stringify(input)} → ${outcome.isError ? "ERROR: " : ""}${outcome.text}`);
}
await client.close();
Run the counter assistant
npm install
node src/try-client.ts
Output (the first line is the server log, printed to stderr)
Mộc MCP server is ready (stdio)
The server has 3 tools: view_order, find_order_by_phone, add_item
view_order {"order_id":"1041"} → {"order_id":"1041","items":["milk coffee","egg banh mi"],"status":"preparing","placed_at":"today 8:12"}
add_item {"order_id":"1041","item":"Bac xiu","quantity":2} → {"order_id":"1041","items":["milk coffee","egg banh mi","bac xiu","bac xiu"],"status":"preparing"}
add_item {"order_id":"1042","item":"bac xiu","quantity":1} → ERROR: Order 1042 is out for delivery, so items can no longer be added.
view_order {"order_id":"104"} → ERROR: MCP error -32602: Input validation error: Invalid arguments for tool view_order: An order ID is exactly 4 digits, with no # sign at order_id

The last three lines are worth a look. In the add-item line, "Bac xiu" with a capital letter is lowercased inside the tool (item.trim().toLowerCase()), so the order receives two portions of "bac xiu". On the next line, the rule "an order that has left cannot be changed" lives in addItem, and the error comes back as a result the caller can read. On the last line, the ID 104 never reaches the code of view_order: the schema blocks it, and the message is the very sentence I wrote in Zod.

The second app is the chatbot, and this is where MCP saves the most work. In the post about tool calling, I wrote the tool list by hand to give to the model. Now the list comes from the server. MCP and the Anthropic API use almost the same shape for a tool definition, so I only rename inputSchema to input_schema and drop the $schema field (the line that declares the JSON Schema version) to keep it short. I do not have an API key to call a real model in this post, so the script below uses a tool_use block that I wrote by hand in place of the answer of the model, for a customer who asks "where is my order 1042?":

src/try-chatbot.ts
// App 2: the chatbot. Take the tool list from the MCP server, convert it to the shape the Anthropic API accepts, then run one tool call.
// No ANTHROPIC_API_KEY needed: the tool_use block below is written by hand in place of the answer of the model. Run: node src/try-chatbot.ts
import { callTool, connectToServer } from "./mcp-client.ts";

const client = await connectToServer();
const { tools } = await client.listTools();

// MCP and the Anthropic API use almost the same shape: rename inputSchema to input_schema, and drop the $schema field (the JSON Schema version line) to keep it short.
const toolsForModel = tools.map(({ name, description, inputSchema: { $schema, ...inputSchema } }) => ({ name, description, input_schema: inputSchema }));
console.log("Tool given to the model:", JSON.stringify(toolsForModel.find((t) => t.name === "view_order"), null, 2));

// Pretend the model answered with this tool_use block (the customer asked: "where is my order 1042?").
const toolUse = { type: "tool_use", id: "toolu_01", name: "view_order", input: { order_id: "1042" } };
const outcome = await callTool(client, toolUse.name, toolUse.input);
// This block is sent back to the model on the next turn, exactly as in the tool calling post.
console.log("Sent back to the model:", JSON.stringify({ type: "tool_result", tool_use_id: toolUse.id, content: outcome.text, is_error: outcome.isError }));
await client.close();
Run the chatbot
node src/try-chatbot.ts
Output
Mộc MCP server is ready (stdio)
Tool given to the model: {
  "name": "view_order",
  "description": "View the items and current status of an order by its order ID (4 digits, for example 1041). Call this tool whenever a customer asks whether an order has been delivered, where it is, or when it will arrive.",
  "input_schema": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "pattern": "^\\d{4}$",
        "description": "Order ID: 4 digits, no # sign"
      }
    },
    "required": [
      "order_id"
    ]
  }
}
Sent back to the model: {"type":"tool_result","tool_use_id":"toolu_01","content":"{\"order_id\":\"1042\",\"items\":[\"bac xiu\"],\"status\":\"out for delivery\",\"placed_at\":\"today 9:40\"}","is_error":false}

The part labelled "Tool given to the model" is what the chatbot attaches to every API call, in place of the hand-written block. The last line is the tool_result block that the chatbot sends back to the model on the next turn, just like the agent loop of the earlier posts. The only difference is that the step that runs the tool now goes through callTool instead of a function in the same file. Neither the chatbot nor the counter assistant contains a single line of business logic for the tools any more.

Writing tests for the server

Another benefit of keeping the tools separate is that you can test them without a model and without starting a child process. The SDK has an InMemoryTransport that links a client and a server inside one process:

src/moc-server.test.ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { beforeEach, expect, test } from "vitest";

import { resetOrders } from "./orders.ts";
import { createServer } from "./moc-server.ts";

// Connect client and server inside one process (no child process): fast and easy to check.
async function connect(): Promise<Client> {
  const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
  await createServer().connect(serverSide);
  const client = new Client({ name: "test", version: "1.0.0" });
  await client.connect(clientSide);
  return client;
}

const textOf = (response: Awaited<ReturnType<Client["callTool"]>>) => (response.content as { text: string }[])[0].text;

beforeEach(() => resetOrders());

test("lists all three tools, and the read-only ones carry readOnlyHint", async () => {
  const { tools } = await (await connect()).listTools();
  expect(tools.map((t) => t.name)).toEqual(["view_order", "find_order_by_phone", "add_item"]);
  expect(tools.find((t) => t.name === "view_order")?.annotations?.readOnlyHint).toBe(true);
  expect(tools.find((t) => t.name === "add_item")?.annotations?.readOnlyHint).toBe(false);
});

test("view_order returns the right order", async () => {
  const response = await (await connect()).callTool({ name: "view_order", arguments: { order_id: "1042" } });
  expect(JSON.parse(textOf(response))).toMatchObject({ order_id: "1042", status: "out for delivery" });
});

test("an unknown order gives isError instead of throwing", async () => {
  const response = await (await connect()).callTool({ name: "view_order", arguments: { order_id: "9999" } });
  expect(response.isError).toBe(true);
  expect(textOf(response)).toBe("There is no order 9999.");
});

test("badly formatted input is stopped by the schema before the tool code runs", async () => {
  const response = await (await connect()).callTool({ name: "view_order", arguments: { order_id: "104" } });
  expect(response.isError).toBe(true);
  expect(textOf(response)).toContain("An order ID is exactly 4 digits");
});

test("add_item only works on an order that is still being prepared", async () => {
  const client = await connect();
  const allowed = await client.callTool({ name: "add_item", arguments: { order_id: "1041", item: "Bac xiu", quantity: 2 } });
  expect(JSON.parse(textOf(allowed)).items).toEqual(["milk coffee", "egg banh mi", "bac xiu", "bac xiu"]);
  const refused = await client.callTool({ name: "add_item", arguments: { order_id: "1042", item: "bac xiu", quantity: 1 } });
  expect(refused.isError).toBe(true);
});

test("a quantity outside 1 to 5 is rejected", async () => {
  const response = await (await connect()).callTool({ name: "add_item", arguments: { order_id: "1041", item: "bac xiu", quantity: 6 } });
  expect(response.isError).toBe(true);
});
Run the tests
npx vitest run
Output
 Test Files  1 passed (1)
      Tests  6 passed (6)

The fourth test is the one to notice: it asserts that badly formatted input is stopped by the schema before it reaches the code of the tool. If someone removes the regex line from the schema one day, this test goes red immediately.

When should you use MCP, and when not?

In my opinion, MCP is worth using when your tools have to serve more than one application, or when you want to use tools that other people already built (there are many servers for popular services) without writing the bridge yourself. What you pay is one more process, one more protocol layer and an SDK that you must update when the standard changes.

If you have a single application and the tools never change, an ordinary function in the same code base is still simpler. The Mộc chatbot lived happily like that for seven posts. I moved to MCP because a second application appeared, not because MCP is fashionable. Ask yourself that question before you add it to your own project.

The tools are exposed, so who may use them and how?

There is one thing to think about carefully after this post. The add_item tool now sits behind a shared gate, and any application that connects to the server can call it. Meanwhile the chatbot still talks to customers in free text, and the model decides which tool to call based on what the customer writes. The MCP specification recommends that a human can always refuse a tool call, but a customer-support chatbot usually runs alone. What happens if a smooth-talking customer tries to make the model do something the café does not want, such as promising something the café never allows? How an agent gets talked into things, and how to defend against it, is the topic of the next posts.

You can follow the whole journey in Build your first AI agent. If you are preparing for interviews, the questions about AI agents are in the interview question bank.

Get the next post by email.

One email a week, only when there is something worth reading. No spam.