Skip to main content

BlogAI

Build a Claude Code MCP Server in TypeScript

Build an MCP server for Claude Code with the v2 TypeScript SDK: tools with Zod schemas, a resource, a prompt, stdio, claude mcp add and a real headless test.

By LearnWebCraft Team27 min read

If you search for "claude mcp server" right now, you are in good company. I checked Google Trends before writing this. Over the last three months the top queries people search alongside "MCP server" are "mcp server claude", "claude mcp server" and "ai mcp server", and the fastest rising related topic is Claude Code, up 1,100%. Over the past month, "MCP server" also drew more search interest worldwide than "Next.js" did.

So lots of people want to build an MCP server and plug it into Claude Code. The problem is that most tutorials you will find were written for version 1 of the TypeScript SDK. In July 2026 the SDK shipped version 2, split into new packages, renamed the server entry points and added support for the 2026-07-28 revision of the protocol. Copy a v1 tutorial today and you will install @modelcontextprotocol/sdk, which npm still tags as latest, and its own README will tell you that you are on the maintenance line.

This post builds a small but real MCP server with the v2 SDK, step by step, then connects it to Claude Code and asks Claude a question that it can only answer through the server. Everything below was compiled and run on Windows 11 on 3 December 2026 with these versions:

  • @modelcontextprotocol/server and @modelcontextprotocol/client 2.4.0
  • zod 4.6.7
  • TypeScript 7.0.2 and Node.js 24.22.2
  • Claude Code 2.1.318

Here is the plan:

  1. What an MCP server is, in plain terms, and when you actually need one.
  2. What changed between SDK v1 and v2, so old tutorials stop confusing you.
  3. Project setup.
  4. Two tools with Zod input and output schemas.
  5. A resource and a prompt.
  6. Serving over stdio, and a client script that tests every piece.
  7. Adding the server to Claude Code with claude mcp add or .mcp.json.
  8. A real headless run, with the answer, turn count and cost.
  9. HTTP transport, security and the mistakes I made.

What an MCP server is

The Model Context Protocol is a JSON-RPC protocol that lets an AI application talk to outside programs in a standard way. The application, Claude Code in our case, is the client. Your program is the server. The server advertises three kinds of things:

  • Tools: functions the model can decide to call, like search_docs or create_ticket. Each one has a name, a description and a JSON Schema for its arguments.
  • Resources: read-only data addressed by a URI, like docs://index. The application decides when to read them, not the model.
  • Prompts: reusable prompt templates with arguments, which a user can pick by name.

The value is that you write the integration once. A server that works with Claude Code also works with any other client that speaks MCP, and Claude Code doesn't need to know anything about your system beyond what the server tells it.

If you want the bigger picture of how the protocol is put together, I wrote a longer piece on MCP architecture and how context protocols work. This post stays practical.

When you actually need one

Claude Code can already read files and run shell commands. So before you build a server, ask whether a plain script would do. In my experience an MCP server earns its keep in three situations.

The first is when the data lives somewhere Claude can't reach with a shell command: an internal API with auth, a database you don't want it to query freely, a SaaS product. The second is when you want a narrow, safe interface. A tool that can only search a docs folder is much easier to allow without prompts than "run any shell command". The third is when you want the same capability in several AI tools. Write it as a server and every MCP client gets it.

If none of those apply, a script in your repo plus a line in CLAUDE.md saying when to run it is simpler. I mean that. Not everything has to be a server.

What changed in the v2 TypeScript SDK

This section exists because it's the source of most of the confusion I saw while researching. If you have never used v1, skim it and move on.

Version 1 was one package, @modelcontextprotocol/sdk, and you imported deep paths with .js on the end. Version 2 splits it up:

What v1 v2
Server package @modelcontextprotocol/sdk @modelcontextprotocol/server
Client package @modelcontextprotocol/sdk @modelcontextprotocol/client
Stdio server new StdioServerTransport() + server.connect() serveStdio(factory)
HTTP server StreamableHTTPServerTransport createMcpHandler(factory)
Stdio client import @modelcontextprotocol/sdk/client/stdio.js @modelcontextprotocol/client/stdio
Register a tool server.tool() (now deprecated) server.registerTool()
Error class McpError ProtocolError
Spec revision up to 2025-11-25 2026-07-28, and still serves 2025 clients

The other packages in the family are @modelcontextprotocol/core for the shared Zod schemas and adapters for Node, Express, Hono and Fastify. The v2 packages need Node.js 20 or newer and depend on Zod 4.

The biggest conceptual change is the factory. In v2 you don't create one server object and connect it. You hand the SDK a function that builds a server, and the SDK calls it when it needs an instance. Over stdio that is once per connection. Over HTTP it is once per request, because the 2026-07-28 revision of the protocol is stateless per request. There's no Mcp-Session-Id header any more.

That sounds like a big deal, but for a typical server it just means you put your registerTool calls inside a function. We'll do exactly that.

If you are migrating an existing v1 server, the SDK team ships a codemod:

Fig. 1bash
npx @modelcontextprotocol/codemod@latest v1-to-v2 .
grep -rn '@mcp-codemod-error' .

The second line finds the places the codemod couldn't fix on its own. I didn't run the codemod for this post, since we're starting fresh, so treat that part as the documented path rather than something I tested.

What we're building

A server called team-docs that gives Claude access to a folder of internal markdown docs. It has:

  • a search_docs tool that finds lines matching a query,
  • a read_doc tool that returns one whole file,
  • a docs://index resource listing every file,
  • an answer_from_docs prompt that tells the model to cite its sources.

It's small on purpose, but it's not a toy. "Let the agent search our runbooks and only our runbooks" is a real request, and it shows every part of the server API. It also has one real security concern, path traversal, which we'll handle.

The sample docs folder has three files. auth.md says access tokens expire after 15 minutes and refresh tokens last 30 days. deploy.md describes deploying and rolling back with fly. oncall.md is a three-step checklist. Make your own or use real ones.

Project setup

Create a folder and install the packages:

Fig. 2bash
mkdir team-docs-mcp && cd team-docs-mcp
npm init -y
npm install @modelcontextprotocol/server zod
npm install -D typescript @types/node @modelcontextprotocol/client

The client package is only a dev dependency because we use it for a test script. Claude Code brings its own client.

Set "type": "module" in package.json so Node treats the compiled output as ES modules, and add a build script:

Fig. 3json
{
  "type": "module",
  "scripts": {
    "build": "tsc"
  }
}

Then a tsconfig.json:

Fig. 4json
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "outDir": "build",
    "rootDir": "src",
    "strict": true,
    "types": ["node"]
  },
  "include": ["src"]
}

That "types": ["node"] line matters. Since TypeScript 6.0 the compiler no longer pulls in every @types/* package automatically, and the SDK's published type definitions reference Node's Buffer. Leave the line out and you get type errors from inside node_modules that have nothing to do with your code. The SDK README calls this out, and it's easy to miss. I compiled with TypeScript 7.0.2, the Go-based compiler, and it handled the SDK types without complaint. If you haven't tried 7 yet, I wrote up what moving a real project to the TypeScript 7 Go compiler was like.

The skeleton: a factory and serveStdio

Create src/server.ts. Start with the imports and two helpers that the tools will share:

Fig. 5ts
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';

const DOCS_DIR = path.resolve(process.env.DOCS_DIR ?? './docs');

async function listDocs(): Promise<string[]> {
  const entries = await readdir(DOCS_DIR, { recursive: true });
  return entries
    .filter((name) => name.endsWith('.md'))
    .map((name) => name.split(path.sep).join('/'))
    .sort();
}

// Resolve a doc path and refuse anything that escapes DOCS_DIR.
function safeDocPath(relative: string): string {
  const full = path.resolve(DOCS_DIR, relative);
  if (full !== DOCS_DIR && !full.startsWith(DOCS_DIR + path.sep)) {
    throw new Error(`Path is outside the docs folder: ${relative}`);
  }
  return full;
}

A few choices here are deliberate.

The docs folder comes from an environment variable. Claude Code starts your server as a child process, and the working directory it uses won't always be the one you expect. An explicit DOCS_DIR set in the MCP config removes the guesswork.

listDocs converts Windows backslashes to forward slashes. The model will pass these paths back to read_doc, and deploy.md or guides/setup.md is friendlier to a model than guides\\setup.md inside a JSON string.

safeDocPath is the one piece of security in this server, and it's the piece people skip. The model chooses the arguments to your tools. If read_doc simply joined whatever path it got onto the docs folder, then ../../.env would read your secrets. Resolving the full path and checking that it still starts with the docs folder closes that hole. Note the + path.sep: without it, a sibling folder called docs-private would pass a plain startsWith(DOCS_DIR) check.

Now the bottom of the file:

Fig. 6ts
function buildServer() {
  const server = new McpServer({ name: 'team-docs', version: '1.0.0' });

  // tools, resource and prompt go here

  return server;
}

const handle = serveStdio(buildServer);
process.on('SIGINT', () => {
  void handle.close();
});
console.error(`team-docs MCP server reading ${DOCS_DIR}`);

serveStdio takes the factory, owns the stdio transport, and returns a handle you can close. It also decides per connection whether the client speaks the 2026-07-28 protocol or the older 2025 one, and serves either from the same factory. You don't write any of that.

Look at the last line. It uses console.error, not console.log. Over stdio, standard output is the protocol channel. Every byte your server prints to stdout must be a valid JSON-RPC message. A stray console.log('starting up') corrupts the stream and the client drops the connection, usually with an error message that doesn't point anywhere near the real cause. Log to stderr, always. If you remember one thing from this post, make it this.

Tool one: search_docs with input and output schemas

Inside buildServer, register the search tool:

Fig. 7ts
server.registerTool(
  'search_docs',
  {
    title: 'Search team docs',
    description:
      'Search the internal markdown docs for a word or phrase. Returns matching files with the matching lines.',
    inputSchema: z.object({
      query: z.string().min(2).describe('Text to look for, case-insensitive'),
      limit: z.number().int().min(1).max(20).default(5).describe('Max files to return'),
    }),
    outputSchema: z.object({
      matches: z.array(
        z.object({
          file: z.string(),
          lines: z.array(z.string()),
        }),
      ),
    }),
    annotations: { readOnlyHint: true, openWorldHint: false },
  },
  async ({ query, limit }) => {
    const needle = query.toLowerCase();
    const matches: { file: string; lines: string[] }[] = [];

    for (const file of await listDocs()) {
      const text = await readFile(safeDocPath(file), 'utf8');
      const lines = text
        .split('\n')
        .filter((line) => line.toLowerCase().includes(needle))
        .map((line) => line.trim());
      if (lines.length > 0) matches.push({ file, lines });
      if (matches.length >= limit) break;
    }

    const summary =
      matches.length === 0
        ? `No docs mention "${query}".`
        : matches.map((m) => `${m.file}\n  ${m.lines.join('\n  ')}`).join('\n');

    return {
      content: [{ type: 'text', text: summary }],
      structuredContent: { matches },
    };
  },
);

There's a lot packed into this, so let's go through it.

The description is a prompt

The model decides whether to call your tool from its name and description, and nothing else. "Search docs" is too vague. Say what it searches, what it returns, and when to use it. I've seen agents skip a perfectly good tool because the description didn't make clear it covered their question, then go and grep the file system instead. Write descriptions as if you were explaining the tool to a new teammate in one sentence.

Zod becomes JSON Schema

inputSchema is a Zod object. The SDK converts it to JSON Schema for the client, and the .describe() strings come through as description fields. This is the schema Claude Code actually received from the server in my test:

Fig. 8json
{
  "type": "object",
  "properties": {
    "query": { "type": "string", "minLength": 2, "description": "Text to look for, case-insensitive" },
    "limit": { "default": 5, "description": "Max files to return", "type": "integer", "minimum": 1, "maximum": 20 }
  },
  "required": ["query"],
  "$schema": "https://json-schema.org/draft/2020-12/schema"
}

Notice that limit isn't in required, because it has a default. Inside the handler, though, limit is typed as number, not number | undefined, because the SDK has already parsed the arguments with Zod and applied the default. You get validated, typed arguments without writing a single check.

Validation also runs before your handler. When my test client called search_docs with query: "x", the handler never ran. The client got back isError: true with this text:

Fig. 9text
Input validation error: Invalid arguments for tool search_docs: query: Too small: expected string to have >=2 characters

That message goes back to the model, which can read it and retry with a better argument. That's the behavior you want: bad input becomes feedback, not a crash.

Output schema and structuredContent

outputSchema is optional, and most tutorials leave it out. When you set it, the handler returns structuredContent alongside the usual content, and the SDK validates the structured part against the schema before it leaves the server. Clients that understand structured output get typed JSON. Everything else still gets the text in content.

I return both on purpose. The text version is what the model reads in most clients today, and it's short. The structured version is there for programs, and for clients that prefer it.

Annotations are hints

readOnlyHint: true tells the client this tool doesn't change anything. openWorldHint: false says it only touches a closed set of data, not the open internet. Other hints are destructiveHint and idempotentHint. The SDK docs are clear that annotations never change how a tool runs. They're hints a client may use when deciding how much to trust a tool or whether to ask the user first. Don't rely on them for security, but do set them honestly.

Tool two: read_doc and returning errors properly

Fig. 10ts
server.registerTool(
  'read_doc',
  {
    title: 'Read a doc',
    description: 'Return the full markdown of one doc. Use a path from search_docs.',
    inputSchema: z.object({
      file: z.string().describe('Path relative to the docs folder, e.g. deploy.md'),
    }),
    annotations: { readOnlyHint: true, openWorldHint: false },
  },
  async ({ file }) => {
    try {
      const text = await readFile(safeDocPath(file), 'utf8');
      return { content: [{ type: 'text', text }] };
    } catch (error) {
      return {
        isError: true,
        content: [{ type: 'text', text: `Could not read ${file}: ${(error as Error).message}` }],
      };
    }
  },
);

The description says "Use a path from search_docs". That small hint tells the model how the two tools fit together, and in my headless run Claude followed it: search first, then read.

The catch returns a result with isError: true instead of throwing. MCP distinguishes two kinds of failure. A protocol error means the request itself was broken: unknown tool, malformed JSON. A tool error means the tool ran and something went wrong in your domain: the file doesn't exist, the API returned 404. Tool errors should come back as a normal result with isError: true, so the model sees the message and can adjust. If you throw, the model gets a much less useful error.

My test client asked read_doc for ../package.json. It got back:

Fig. 11text
Could not read ../package.json: Path is outside the docs folder: ../package.json

That's the path check doing its job, and the model reading a message it can understand.

One v2 change worth knowing here: calling a tool name that doesn't exist now rejects as a protocol error. In v1 it came back as a result with isError: true. If you have client code that checked for that, update it.

A resource and a prompt

Tools are the part most people care about, but the other two primitives are cheap to add and worth knowing.

Fig. 12ts
server.registerResource(
  'docs-index',
  'docs://index',
  {
    title: 'Docs index',
    description: 'Every markdown file the server can read',
    mimeType: 'text/plain',
  },
  async (uri) => ({
    contents: [{ uri: uri.href, text: (await listDocs()).join('\n') }],
  }),
);

server.registerPrompt(
  'answer_from_docs',
  {
    title: 'Answer from docs',
    description: 'Answer a question using only the team docs, with file citations',
    argsSchema: z.object({
      question: z.string().describe('The question to answer'),
    }),
  },
  ({ question }) => ({
    messages: [
      {
        role: 'user' as const,
        content: {
          type: 'text' as const,
          text: `Use the search_docs and read_doc tools to answer: ${question}\nCite the file for every fact. If the docs do not say, answer "not documented".`,
        },
      },
    ],
  }),
);

The resource has a fixed URI, docs://index. For parameterized URIs like users://{userId}/profile, the SDK has a ResourceTemplate class. In Claude Code you can reference a resource with an @ mention in the format @server:protocol://path, so @team-docs:docs://index pulls the file list straight into your message, without the model having to call a tool. The docs note that in headless claude -p runs, a resource mention stays plain text.

The prompt shows up in Claude Code as a slash command. According to the Claude Code docs, the / menu lists MCP prompts as /servername:promptname (MCP), and typing /mcp__servername__promptname runs one too, so this one is /mcp__team-docs__answer_from_docs. That's a nice way to ship a team's "ask the runbooks" workflow without anyone needing to remember the exact wording.

The as const on role and type is there because TypeScript otherwise widens them to string, which doesn't match the literal types the SDK expects.

Test it with a client script before Claude Code

Here's a habit that will save you time: don't debug your server through Claude Code first. When something fails inside an agent, you see the failure through the agent's interpretation of it. Test the server directly with the client SDK, then plug it in.

Create src/client-test.ts:

Fig. 13ts
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';

const client = new Client({ name: 'smoke-test', version: '1.0.0' });
const transport = new StdioClientTransport({
  command: 'node',
  args: ['build/server.js'],
});
await client.connect(transport);

const { tools } = await client.listTools();
console.log('tools:', tools.map((t) => t.name));

const hit = await client.callTool({ name: 'search_docs', arguments: { query: 'token' } });
console.log('search token ->', JSON.stringify(hit.structuredContent));

const bad = await client.callTool({ name: 'search_docs', arguments: { query: 'x' } });
console.log('query too short -> isError:', bad.isError);

const escape = await client.callTool({ name: 'read_doc', arguments: { file: '../package.json' } });
console.log('path escape -> isError:', escape.isError, JSON.stringify(escape.content));

const index = await client.readResource({ uri: 'docs://index' });
console.log('index:', JSON.stringify(index.contents[0]));

const prompt = await client.getPrompt({
  name: 'answer_from_docs',
  arguments: { question: 'How long do refresh tokens last?' },
});
console.log('prompt:', JSON.stringify(prompt.messages[0].content));

await client.close();

Build and run it:

Fig. 14bash
npx tsc -p .
node build/client-test.js

This is the output I got, trimmed a little for width:

Fig. 15text
team-docs MCP server reading C:\...\team-docs-mcp\docs
tools: [ 'search_docs', 'read_doc' ]
search token -> {"matches":[{"file":"auth.md","lines":["# Auth tokens","Access tokens expire after 15 minutes. Refresh tokens live for 30 days"]}]}
query too short -> isError: true
path escape -> isError: true [{"type":"text","text":"Could not read ../package.json: Path is outside the docs folder: ../package.json"}]
index: {"uri":"docs://index","text":"auth.md\ndeploy.md\noncall.md"}
prompt: {"type":"text","text":"Use the search_docs and read_doc tools to answer: How long do refresh tokens last?\nCite the file for every fact. ..."}

The first line is the server's stderr log, which the stdio client passes through to your terminal by default. Every primitive works, the validation error fires, and the path check holds. Now we know any problem in Claude Code is about configuration, not the server.

The MCP docs also suggest the Inspector, a web UI for poking at a server by hand: npx @modelcontextprotocol/inspector node build/server.js. I stuck with the script because it's repeatable. You can turn it into a real test suite with a few assertions, which is worth doing once a server has more than a couple of tools. If you're setting up tests for the first time, my guide to unit, integration and end-to-end testing covers how to pick what to test at each level.

Which protocol version did we just speak?

Here's a detail that surprised me. By default, the v2 client still opens with the 2025-era initialize handshake, not the new protocol. You opt in to the 2026-07-28 revision with versionNegotiation. I checked both with a short script against the same server:

Fig. 16js
const legacy = new Client({ name: 'era', version: '1.0.0' });
// ...connect...
legacy.getProtocolEra(); // 'legacy'

const modern = new Client(
  { name: 'era', version: '1.0.0' },
  { versionNegotiation: { mode: 'auto' } },
);
// ...connect...
modern.getProtocolEra(); // 'modern'

The first client reported legacy, the second modern, and the server code didn't change at all. That's the point of serveStdio deciding the era per connection: one server, both generations of clients. In practice it means you can ship a v2 server today without worrying about which protocol version Claude Code or anyone else's client speaks.

Add the server to Claude Code

There are two ways: the CLI, or a JSON file.

Option 1: claude mcp add

Fig. 17bash
claude mcp add team-docs -e DOCS_DIR=/absolute/path/to/docs -- node /absolute/path/to/build/server.js

The -- matters. Everything before it is an option for Claude Code: the name, -e for environment variables, -s for scope. Everything after it is the command that starts your server, passed through untouched. Without the --, flags meant for your server get read as flags for claude.

The transport defaults to stdio, so you don't need --transport stdio here. The Claude Code docs point out one trap with --env: it accepts several KEY=value pairs, so if the server name comes right after it, the CLI tries to read the name as another pair and rejects it. Put the name first, as above, or put another option in between.

Use absolute paths. Claude Code starts the server from wherever you launched Claude, which is often not the server's folder. On Windows, forward slashes in paths work fine for Node, and they spare you from escaping backslashes in JSON.

Scopes: local, project and user

The -s flag picks where the config is stored:

  • local is the default. Only you, only this project. It's stored in your ~/.claude.json under the project's path.
  • project writes a .mcp.json file at the project root, meant to be committed so the whole team gets the server.
  • user makes the server available to you in every project.

For a team docs server, project is usually right. Claude Code asks each person to approve servers from a project's .mcp.json before it starts them in an interactive session, which is a sensible guard against a repository quietly starting programs on your machine.

Option 2: .mcp.json

The project-scoped file looks like this:

Fig. 18json
{
  "mcpServers": {
    "team-docs": {
      "command": "node",
      "args": ["./tools/team-docs-mcp/build/server.js"],
      "env": {
        "DOCS_DIR": "./docs"
      }
    }
  }
}

For an HTTP server you would use "type": "http" and a "url" instead of command and args.

Inside Claude Code, run /mcp to see every server, its status and its tools. From the shell, claude mcp list shows the same status, with labels like Connected or Failed to connect. When a server fails, check two things first: did it print anything to stdout, and is the path in args correct from the directory where Claude Code was started? Those two causes cover most of the failures I've seen people post about.

How Claude Code names your tools

Inside Claude Code, the tools become mcp__team-docs__search_docs and mcp__team-docs__read_doc. That's the name you use in permission rules, in a skill's allowed-tools list or in a hook matcher. Allowing both read-only tools means Claude can search the docs without asking you each time, while everything else keeps its normal prompts.

A real run: Claude answers from the server

Time to see it work end to end. I wrote the config to a standalone file, mcp.json, in the same format as above but with absolute paths, so the test wouldn't touch any of my real Claude Code settings. Then I ran Claude Code headless:

Fig. 19bash
claude -p "How long do refresh tokens last, and how do I roll back a deploy? Use only the team-docs MCP tools, cite files." \
  --mcp-config mcp.json \
  --strict-mcp-config \
  --allowedTools "mcp__team-docs__search_docs" "mcp__team-docs__read_doc" \
  --output-format json \
  --model haiku

What each flag does:

  • --mcp-config loads servers from the file for this run only.
  • --strict-mcp-config ignores every other MCP server configured on the machine, so nothing else can answer the question.
  • --allowedTools pre-approves the two read-only tools, because a headless run has nobody to click Allow.
  • --model haiku keeps the test cheap. The question doesn't need a bigger model.

This is the answer Claude returned:

Fig. 20text
Refresh tokens: 30 days. Access tokens last 15 minutes. Refresh tokens rotate on every use. (auth.md)

Rollback: fly releases to find the previous release, then fly deploy --image <previous>. (deploy.md)

Gap: the doc doesn't say what <previous> is or where to get it from fly releases output.
Check the image name there before running it. Staging app is api-staging. (deploy.md)

Every fact is right, every fact is cited, and none of it could have come from anywhere but the server. My favorite part is the last paragraph. Claude noticed that the rollback doc is vague about where the image name comes from and said so, instead of inventing an answer. That's partly the model and partly the tool design: read_doc returns the whole file, so Claude saw exactly what the doc does and doesn't say.

The JSON output reported 6 turns, a total cost of $0.0065 at API rates, and the whole command took 9.4 seconds of wall time, including starting the server. That's one data point on one machine, not a benchmark, but it shows the overhead of a local stdio server is small.

Serving over HTTP instead

Stdio is right when the server runs on the same machine as the client, which covers most personal and team tools. When you want one server that many people or machines connect to, use Streamable HTTP. In v2 the entry point is createMcpHandler:

Fig. 21ts
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';

const handler = createMcpHandler(() => {
  const server = new McpServer({ name: 'team-docs', version: '1.0.0' });
  // same registerTool / registerResource / registerPrompt calls
  return server;
});

// On a web-standard runtime (Workers, Deno, Bun):
export default handler;

The handler exposes a standard fetch(request) function, so it runs anywhere that speaks Request and Response. For Node's http module there's a toNodeHandler adapter in @modelcontextprotocol/node, and there are adapters for Express, Hono and Fastify.

Because the factory runs on every request, keep it cheap. Build tool registrations there, but open database pools and load config outside it, once, at startup.

Two warnings from the docs that you shouldn't skip. First, the handler itself checks no Host header, no Origin and no token. If you bind it to localhost, put the SDK's localhostHostValidation() and localhostOriginValidation() guards in front of it, or a web page in your browser could talk to your local server. If you expose it beyond localhost, you need real authentication. Second, the v2 server never serves the old SSE transport. If you have clients that still use SSE, there's a frozen legacy package, but it's deprecated.

Connecting Claude Code to an HTTP server is one line:

Fig. 22bash
claude mcp add --transport http team-docs https://mcp.example.com/mcp

Add --header "Authorization: Bearer ..." if your server expects a token. I only tested the stdio path end to end for this post, so treat the HTTP part as the documented route rather than something I measured.

Things that tripped me up, and limits to know

A few things I either got wrong or nearly did.

I installed @modelcontextprotocol/sdk first, out of habit. npm still tags 1.32.2 as latest, so a plain install gives you v1. It works, and it gets security fixes until at least January 2027, but it won't speak the 2026-07-28 protocol. For a new server, install @modelcontextprotocol/server.

Zod import path. The docs use import * as z from 'zod/v4'. With Zod 4 installed, plain 'zod' gives you v4 as well, but sticking to the documented path avoids surprises if a different major version ever lands in your tree.

Large results. Claude Code caps MCP tool output at 25,000 tokens by default (MAX_MCP_OUTPUT_TOKENS changes it). Results over the limit get saved to a file and replaced with a reference to that file, which costs the model an extra step to read. A read_doc on a huge file would hit this. That's why search_docs returns only matching lines and has a limit. If you want a rough feel for how many tokens a document is, paste it into the LLM token estimator before you decide whether a tool should return it whole.

Timeouts. MCP_TIMEOUT controls how long Claude Code waits for a server to start, for example MCP_TIMEOUT=10000 claude for 10 seconds. A server that does heavy work at startup, like indexing a large docs folder, should do it lazily or in the background, so the handshake isn't stuck waiting on it.

The naive search. search_docs is a substring match. It won't find "token" when the doc says "credential". For a few dozen files that's fine, and the model compensates by trying more than one query. For hundreds of files you'd want proper full-text search, or embeddings. If you go the embeddings route, my comparison of pgvector and dedicated vector databases for hybrid search is a good place to start.

Tool count. Every tool's name, description and schema is sent to the model, so each one costs context on every request. Two good tools beat ten overlapping ones. If two tools do nearly the same thing, the model will sometimes pick the wrong one, and you can't fix that with a better description.

Where to go next

You now have a server that Claude Code can use, a test script that proves it works without Claude in the loop, and a config you can commit for your team. Some directions from here:

  • Swap the docs folder for something you actually need: your issue tracker's API, a read-only database view, your deploy system's status page.
  • Add a write tool, with destructiveHint: true, and leave it out of --allowedTools so Claude always asks before using it.
  • Move to HTTP with authentication when more than one machine needs the server.
  • Turn client-test.ts into a proper test with assertions and run it in CI.

The MCP part turned out to be the easy bit. Most of the work went into the same things any API needs: clear names, tight inputs, useful errors, and outputs small enough to read. If you get those right, the model does the rest.

§98Tools

Tools for this topic

Interactive tools that match this article's subject.