How to build an MCP server in TypeScript
AI Techbom · AI Agents · · 7 min read
The Model Context Protocol (MCP) is a standard way for AI applications to use tools and data that live outside the model. An MCP server exposes tools, such as looking up an order or checking stock, and any MCP client can discover and call them. This tutorial builds a small server in TypeScript, tests it with a client, and shows the output it actually produced.
Tested on 21 November 2026 with Node.js 26, @modelcontextprotocol/sdk 1.32.2, zod 4.3.6 and tsx 4. The server type-checks with TypeScript 5 in strict mode.
1. Set up the project
mkdir stock-server && cd stock-server
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/sdk@1.32.2 zod@4.3.6
npm install -D tsx@4 typescript@5 @types/node@242. Write the server
The server has one tool, check_stock, which takes a product SKU and returns how many units are available. The stock list is an object here; in a real server it would be your database or an API.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// In a real server this would be your database or API.
const stock: Record<string, { name: string; available: number }> = {
"PAR-500": { name: "Paracetamol 500 mg, 20 tablets", available: 42 },
"IBU-200": { name: "Ibuprofen 200 mg, 16 tablets", available: 0 },
};
const server = new McpServer({ name: "stock-server", version: "1.0.0" });
server.registerTool(
"check_stock",
{
title: "Check stock",
description: "Look up how many units of a product are available, by SKU.",
inputSchema: { sku: z.string().describe("Product SKU, for example PAR-500") },
outputSchema: { sku: z.string(), name: z.string(), available: z.number() },
},
async ({ sku }) => {
const item = stock[sku.toUpperCase()];
if (!item) {
return {
isError: true,
content: [{ type: "text", text: `No product with SKU ${sku}.` }],
};
}
const result = { sku: sku.toUpperCase(), name: item.name, available: item.available };
return {
content: [{ type: "text", text: `${result.name}: ${result.available} available.` }],
structuredContent: result,
};
},
);
const transport = new StdioServerTransport();
await server.connect(transport);
// stdout carries the protocol, so log to stderr.
console.error("stock-server running on stdio");3. What matters in that code
- inputSchema validates the arguments before your handler runs. The description on each field is what the model reads to decide how to call the tool.
- outputSchema plus structuredContent returns data a program can use directly. The text content is there for clients that only show text.
- isError: true reports an expected failure, such as an unknown SKU, as a tool result. The model sees it and can correct itself instead of the call crashing.
- Over stdio, standard output carries the protocol messages. Anything you print with console.log would corrupt them, so log with console.error.
4. Test it with a client
Before connecting the server to an AI app, test it with the SDK's own client. This script starts the server, lists its tools and calls the tool twice: once with a real SKU in lower case and once with one that does not exist.
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const transport = new StdioClientTransport({ command: "npx", args: ["tsx", "server.ts"] });
const client = new Client({ name: "test-client", version: "1.0.0" });
await client.connect(transport);
const { tools } = await client.listTools();
console.log("Tools:", tools.map((tool) => tool.name));
const found = await client.callTool({ name: "check_stock", arguments: { sku: "par-500" } });
console.log("Found:", JSON.stringify(found.structuredContent));
const missing = await client.callTool({ name: "check_stock", arguments: { sku: "XYZ-1" } });
console.log("Missing:", missing.isError, JSON.stringify(missing.content));
await client.close();Run it with npx tsx client.ts. This is the output it produced:
stock-server running on stdio
Tools: [ 'check_stock' ]
Found: {"sku":"PAR-500","name":"Paracetamol 500 mg, 20 tablets","available":42}
Missing: true [{"type":"text","text":"No product with SKU XYZ-1."}]The first line is the server's own log on standard error. The lower-case SKU was normalised, the structured result matches the output schema, and the unknown SKU came back as an error result rather than an exception.
5. Connect it to an AI app
Desktop MCP clients start a stdio server the same way the test client does: with a command and its arguments. Most take a JSON entry like the one below; where the file lives depends on the client, so check its documentation. Use an absolute path to server.ts. We tested the server with the SDK client above, not inside a specific desktop app.
{
"mcpServers": {
"stock": {
"command": "npx",
"args": ["tsx", "/absolute/path/to/stock-server/server.ts"]
}
}
}6. From example to production
- Replace the object with a real data source, and start with read-only tools.
- Give tools that change data, such as placing an order, an approval step outside the model before they act.
- If the server runs over HTTP instead of stdio, add authentication: anyone who can reach it can call its tools.
- Log every call with its arguments and result, so you can see what the model asked for and why.
- Keep tool names and descriptions specific. Vague descriptions are the most common reason a model calls the wrong tool.
Need agents connected to your own systems? AI agent development