# Building Production MCP Servers

> Architect, test, and ship high-reliability Model Context Protocol servers in TypeScript (SDK v2) and Python (FastMCP)—mastering stateless Streamable HTTP factories, Zod v4 & outputSchema, OAuth 2.1, MCP Inspector, and 10-question evals.

- **Topic:** [Agent Engineering](https://twelve-pages.com/topics/agent-engineering)
- **Web Edition:** https://twelve-pages.com/guides/agent-engineering/building-production-mcp-servers
- **Printable 12-Page PDF:** https://twelve-pages.com/guides/agent-engineering/building-production-mcp-servers/Building_Production_MCP_Servers_Complete_How_To_Guide.pdf (3.9 MB)
- **Version:** v1.0 (Updated 2026-11)
- **Reading Time:** 12 minutes (12 pages)
- **Authorship:** AI-authored under human editorial direction & print QA (https://twelve-pages.com/editorial)
- **Tags:** TypeScript SDK v2 · Python FastMCP · Streamable HTTP & stdio · Zod v4 & outputSchema · OAuth 2.1 & Tool Hints · MCP Inspector & Evals

## Core Takeaways

- **SDK v2 & FastMCP:** Build schema-strict tools in TypeScript @modelcontextprotocol/server v2 or Python FastMCP with Pydantic v2 validation.
- **Stateless Factories:** Spawn a fresh McpServer per HTTP request while pooling upstream clients at module scope for effortless horizontal scale.
- **Evaluated Reliability:** Verify contracts with scripts/smoke.ts, MCP Inspector, and a 10-question multi-hop evaluation harness before shipping.

## 1. Agent-Centric Design vs. Raw REST Wrappers

An MCP server is not a thin proxy over HTTP endpoints—it is an ergonomic user interface for a language model. Great servers pack high-signal data into tight context budgets while keeping destructive actions crystal clear.

### Quick Navigation

#### T Tools (Model-Controlled)

Executable functions the LLM chooses to invoke—from read-only searches to side-effecting writes—guided by JSON schemas and annotations.

#### R Resources (App-Controlled)

Read-only data addressed by URI or `ResourceTemplate` (e.g., `example://teams`) that host apps fetch and attach as context.

#### P Prompts (User-Controlled)

Named message templates with `completable()` argument autocomplete that users trigger explicitly via slash commands or menus.

### Architecture: Host -> Client -> Transport -> Stateless Factory -> Upstream

#### Context Efficiency Rule: Respect CHARACTER_LIMIT = 25_000

Never dump raw 100KB REST payloads into a model's context window. Cap every tool response around `25_000` characters by reducing returned items (e.g., halving the array and setting `next_offset`), defaulting to concise Markdown, and offering `response_format="json"` for programmatic chains.

## 2. SDK v2 Setup, v1-to-v2 Migration & Transports

Always start new TypeScript servers on SDK v2 (@modelcontextprotocol/server) with zod ^4.2.0 and Node >=20.3, or build in Python with FastMCP and Pydantic v2. Never mix v1 and v2 imports inside one repository.

### TypeScript SDK v2 Install & Imports

```
<code><span class="tok-cmt"># Core v2 server + Zod 4.2+ (Node >=20.3)</span>
npm install @modelcontextprotocol/server zod@^4.2.0
npm install @modelcontextprotocol/express @modelcontextprotocol/node express
npm install -D @modelcontextprotocol/client typescript tsx

<span class="tok-kw">import</span> { McpServer, createMcpHandler } <span class="tok-kw">from</span> <span class="tok-str">"@modelcontextprotocol/server"</span>;
<span class="tok-kw">import</span> { serveStdio } <span class="tok-kw">from</span> <span class="tok-str">"@modelcontextprotocol/server/stdio"</span>;
<span class="tok-kw">import</span> * <span class="tok-kw">as</span> z <span class="tok-kw">from</span> <span class="tok-str">"zod/v4"</span>;</code>
```

#### Migrating Legacy `@modelcontextprotocol/sdk` v1 Projects

Legacy v1 receives bug and security fixes only. Upgrade cleanly with the official codemod, resolve any flagged call sites, and verify types:
 `npx @modelcontextprotocol/codemod@latest v1-to-v2 .`
 Key rewrites: `server.tool` -> `registerTool`, `StdioServerTransport` -> `serveStdio`, `McpError` -> `ProtocolError`, `extra.signal` -> `ctx.mcpReq.signal`.

### Python FastMCP + Pydantic v2 Stack

```
<code><span class="tok-cmt"># Python 3.10+ with official mcp SDK & httpx</span>
pip install mcp pydantic httpx

<span class="tok-kw">from</span> mcp.server.fastmcp <span class="tok-kw">import</span> FastMCP, Context
<span class="tok-kw">from</span> pydantic <span class="tok-kw">import</span> BaseModel, Field, ConfigDict, field_validator
<span class="tok-kw">import</span> httpx

mcp = FastMCP(<span class="tok-str">"github_mcp"</span>) <span class="tok-cmt"># {service}_mcp convention</span></code>
```

#### ! Naming & Schema Discipline

- **Node/TS package:** `{service}-mcp-server` (lowercase hyphens, no versions).
- **Python server:** `{service}_mcp` (lowercase underscores).
- **Zod version floor:** Keep `zod` at `^4.2.0`; versions before `4.1.13` silently drop `.describe()` text from advertised JSON schemas!

### Transport Decision Matrix: Pick the Right Wire Protocol

| Transport Mode | Best Use Case | SDK v2 / FastMCP Wiring | Operational Tradeoffs |
| --- | --- | --- | --- |
| **`stdio`** Local Default | CLI tools, desktop apps, and local IDEs spawning the server as a child process. | `serveStdio(createServer)` in TS v2; `mcp.run()` in FastMCP. | Zero network config; single client per process. **Never write to stdout**—log strictly to `console.error` / `stderr`. |
| **Stateless Streamable HTTP** Remote Recommended | Cloud APIs, multi-user deployments, containers, serverless, and load-balanced pods. | `createMcpHandler(createServer)` + `createMcpExpressApp()` + `toNodeHandler()`. | Zero session affinity required; scales horizontally out of the box; supports 2025-era and 2026-07-28 clients alike. |
| **Stateful HTTP Sessions** | Long-lived subscriptions or server-initiated requests needing sticky in-memory session state. | Session store + `StreamableHTTPServerTransport` or Hono/Fastify session adapters. | Requires sticky routing or external Redis state; avoid unless tools genuinely need multi-turn server memory. |
| **Legacy SSE** Deprecated | Only for maintaining compatibility with un-upgraded 2024 MCP clients. | Separate `GET /sse` + `POST /messages` legacy endpoints. | Two-endpoint complexity, proxy buffering issues, and deprecated in the modern MCP spec. Migrate to Streamable HTTP. |

## 3. Annotated Tour: MCP Inspector & JSON-RPC Trace

Launch npx @modelcontextprotocol/inspector node dist/index.js to test every schema, behavioral hint, error banner, and live JSON-RPC frame before connecting an agent host.

MCP Inspector • github-mcp-server (v1.0.0)

Connected • 2026-07-28 Tools (4) • Resources (2)

Transport: Streamable HTTP URL: https://mcp.acme.dev/mcp Auth: Bearer ***9f2a

Tools Resources Prompts

**TOOLS LIST**

example_search_users

Search users by name or email

readOnly idempotent

example_get_user

Fetch user + outputSchema

readOnly

example_delete_user

Permanent account removal

destructive

**INPUT SCHEMA (ZOD v4)**

query *required (min 2, max 200)

"marketing"

limit (default 20)

10

offset (default 0)

0

response_format (enum)

"json"

Run Tool additionalProperties: false

**RESPONSE INSPECTOR**

content[0].text: "{\"total\":14,\"users\":[...]}"
 structuredContent: { total: 14, count: 10, has_more: true, next_offset: 10 }

**isError: true** — "Not found. Check the ID; example_search_users returns valid user IDs."

-> tools/call { "name": "example_search_users", "arguments": { "query": "marketing" } } | <- 200 OK (42ms) | notifications/cancelled wired to `ctx.mcpReq.signal`

### Inspector Control Legend: What to Verify on Every Build

**Transport & Bearer Auth Bar:** Switch between `stdio` subprocess launch and remote Streamable HTTP with custom `Authorization: Bearer` headers.

**Tool List & Hint Badges:** Confirm snake_case service prefixes and accurate `readOnlyHint` / `destructiveHint` badges appear immediately.

**Zod v4 / Pydantic Form:** Verify every parameter displays rich `.describe()` help text, defaults, min/max bounds, and strict rejection of unknown keys.

**Dual Response Inspector:** Ensure `structuredContent` matches your `outputSchema` and mirrors the serialized JSON in `content[0].text`.

**`isError: true` Recovery Banner:** Trigger a bad ID or 429 deliberately and read the message as an agent would—it must name the exact next tool or fix.

**Resources & URI Templates Tab:** Test static URIs and `ResourceTemplate` placeholders, ensuring missing IDs raise `ResourceNotFoundError`.

**JSON-RPC Frame & Cancellation Log:** Confirm zero stray stdout noise on `stdio` and verify client cancellation aborts upstream HTTP calls cleanly.

## 4. The Stateless createServer() Factory & Dual Transports

The single most important architectural rule in TypeScript SDK v2 is isolating per-request protocol state inside a cheap createServer() factory while keeping heavy upstream clients pooled at module scope.

*[Illustration: Isometric technical diorama showing parallel HTTP streams hitting a modular factory node that spawns translucent server pods over one shared crystalline database reservoir]*

**Stateless Concurrency Model:** Each incoming HTTP request spawns a lightweight, isolated `McpServer` pod via `createServer()` while closing over a single shared upstream API client, connection pool, and token verifier at module scope.

### Why Shared Singletons Crash Under Load

#### The Concurrency Trap: Error `-32603`

If you instantiate `const server = new McpServer(...)` once at module scope and return it from `createServer()`, your smoke test passes because it sends requests sequentially. In production, the moment two HTTP calls overlap, the second request fails with `-32603 Internal server error`!

- **Per-connection vs. per-request:** `serveStdio(createServer)` invokes your factory once for the subprocess; `createMcpHandler(createServer)` invokes it fresh on **every HTTP request**.
- **Keep factories fast:** Build HTTP agents, Redis pools, and config once at module scope, then close over them inside `createServer()`.
- **Host/Origin safety:** `createMcpExpressApp()` binds `127.0.0.1` and blocks DNS rebinding. On `0.0.0.0`, pass `allowedHosts: ["mcp.example.com"]`.

### One File Serving Both Transports

```
<code><span class="tok-cmt">// Shared client lives at module scope; factory stays cheap</span>
<span class="tok-kw">function</span> <span class="tok-fn">createServer</span>(): McpServer {
  <span class="tok-kw">const</span> server = <span class="tok-kw">new</span> McpServer({ name: <span class="tok-str">"example-mcp-server"</span>, version: <span class="tok-str">"1.0.0"</span> });
  <span class="tok-fn">registerUserTools</span>(server);
  <span class="tok-kw">return</span> server;
}
<span class="tok-kw">if</span> (process.env.TRANSPORT === <span class="tok-str">"http"</span>) {
  <span class="tok-kw">const</span> handler = <span class="tok-fn">createMcpHandler</span>(createServer);
  <span class="tok-kw">const</span> app = <span class="tok-fn">createMcpExpressApp</span>();
  <span class="tok-kw">const</span> nodeHandler = <span class="tok-fn">toNodeHandler</span>(handler);
  app.<span class="tok-fn">all</span>(<span class="tok-str">"/mcp"</span>, (req, res) => <span class="tok-kw">void</span> <span class="tok-fn">nodeHandler</span>(req, res, req.body));
  app.<span class="tok-fn">listen</span>(Number(process.env.PORT ?? <span class="tok-num">3000</span>), <span class="tok-str">"127.0.0.1"</span>);
} <span class="tok-kw">else</span> {
  <span class="tok-fn">serveStdio</span>(createServer);
  console.<span class="tok-fn">error</span>(<span class="tok-str">"example-mcp-server running on stdio"</span>); <span class="tok-cmt">// stderr only!</span>
}</code>
```

## 5. Tool Registration Anatomy: Schemas & Hints

Every tool registration defines a machine-verifiable contract: strict Zod v4 input validation, behavioral hints for host approval UIs, cancellation-aware upstream calls, and item-halving pagination under CHARACTER_LIMIT.

Color-Coded `server.registerTool(...)` Anatomy

1. Service-Prefixed Name: `"github_search_issues"` (snake_case, verb-first, zero ambiguity across multi-server hosts) -> 2. Description & Examples: State purpose, return shape, sibling tool to use instead, and 2 concrete example queries (JSDoc is ignored!) -> 3. z.strictObject Input: Rejects unknown keys; every field uses `.describe()` with examples -> 4. Annotations: `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint` -> 5. Cancellation Signal: `AbortSignal.any([ctx.mcpReq.signal, AbortSignal.timeout(30_000)])` -> 6. Dual Output: Return `structuredContent` validated by `outputSchema` plus serialized JSON or Markdown text.

```
<code><span class="tok-kw">const</span> SearchInput = z.<span class="tok-fn">strictObject</span>({
  query: z.<span class="tok-fn">string</span>().<span class="tok-fn">min</span>(<span class="tok-num">2</span>).<span class="tok-fn">max</span>(<span class="tok-num">200</span>).<span class="tok-fn">describe</span>(<span class="tok-str">"Match against names/emails, e.g. 'marketing'"</span>),
  limit: z.<span class="tok-fn">number</span>().<span class="tok-fn">int</span>().<span class="tok-fn">min</span>(<span class="tok-num">1</span>).<span class="tok-fn">max</span>(<span class="tok-num">100</span>).<span class="tok-fn">default</span>(<span class="tok-num">20</span>).<span class="tok-fn">describe</span>(<span class="tok-str">"Max users to return"</span>),
  offset: z.<span class="tok-fn">number</span>().<span class="tok-fn">int</span>().<span class="tok-fn">min</span>(<span class="tok-num">0</span>).<span class="tok-fn">default</span>(<span class="tok-num">0</span>).<span class="tok-fn">describe</span>(<span class="tok-str">"Pagination offset"</span>),
  response_format: z.<span class="tok-fn">enum</span>(ResponseFormat).<span class="tok-fn">default</span>(ResponseFormat.MARKDOWN)
});
server.<span class="tok-fn">registerTool</span>(<span class="tok-str">"example_search_users"</span>, {
  title: <span class="tok-str">"Search Users"</span>,
  description: <span class="tok-str">"Search users by name or email. Use example_get_user if you already know the ID."</span>,
  inputSchema: SearchInput,
  annotations: { readOnlyHint: <span class="tok-kw">true</span>, destructiveHint: <span class="tok-kw">false</span>, idempotentHint: <span class="tok-kw">true</span>, openWorldHint: <span class="tok-kw">true</span> }
}, <span class="tok-kw">async</span> ({ query, limit, offset, response_format }, ctx) => {
  <span class="tok-kw">const</span> raw = <span class="tok-kw">await</span> <span class="tok-fn">apiRequest</span>(<span class="tok-str">"users/search"</span>, { q: query, limit, offset }, ctx.mcpReq.signal);
  <span class="tok-kw">const</span> data = UserPageSchema.<span class="tok-fn">parse</span>(raw); <span class="tok-cmt">// Strips unadvertised upstream fields</span>
  <span class="tok-kw">return</span> <span class="tok-fn">paginateUnderCharLimit</span>(data, offset, response_format, <span class="tok-num">25_000</span>);
});</code>
```

### Behavioral Annotations Matrix

| Hint | Default | When to Set `true` |
| --- | --- | --- |
| `readOnlyHint` | `false` | Never mutates state (safe for auto-approve). |
| `destructiveHint` | `true` | Deletes, overwrites, or triggers irreversible changes. |
| `idempotentHint` | `false` | Repeating identical args produces no extra effect. |
| `openWorldHint` | `true` | Talks to external APIs, web, or third-party systems. |

### `outputSchema` & Item-Halving Rules

- **Always-JSON tools only:** Declare `outputSchema` only when a tool always returns structured JSON (omit on dual Markdown/JSON tools).
- **Mirror text & object:** When returning `structuredContent`, serialize the same object as JSON in `content[0].text` for backward-compatible clients.
- **Zod 4 API shifts:** Replace v3 `.strict()` with `z.strictObject({...})`, `z.nativeEnum(E)` with `z.enum(E)`, and `z.string().email()` with `z.email()`.
- **Slice arrays, never strings:** Halve items in a `while` loop until `text.length <= 25_000` so `next_offset` aligns cleanly.

## 6. Python FastMCP & Pydantic v2 Production Patterns

In Python, mcp.server.fastmcp turns typed Pydantic v2 models and docstrings directly into JSON Schemas. Pair strict ConfigDict settings with a shared httpx.AsyncClient and async lifespan hooks.

### Pydantic v2 Strict Input & Validators

```
<code><span class="tok-kw">class</span> <span class="tok-type">ResponseFormat</span>(str, Enum):
    MARKDOWN = <span class="tok-str">"markdown"</span>; JSON = <span class="tok-str">"json"</span>

<span class="tok-kw">class</span> <span class="tok-type">UserSearchInput</span>(BaseModel):
    model_config = <span class="tok-fn">ConfigDict</span>(
        str_strip_whitespace=<span class="tok-kw">True</span>, validate_assignment=<span class="tok-kw">True</span>, extra=<span class="tok-str">"forbid"</span>
    )
    query: str = <span class="tok-fn">Field</span>(..., min_length=<span class="tok-num">2</span>, max_length=<span class="tok-num">200</span>, description=<span class="tok-str">"Query e.g. 'team:mkt'"</span>)
    limit: int = <span class="tok-fn">Field</span>(default=<span class="tok-num">20</span>, ge=<span class="tok-num">1</span>, le=<span class="tok-num">100</span>)
    response_format: ResponseFormat = ResponseFormat.MARKDOWN

    @<span class="tok-fn">field_validator</span>(<span class="tok-str">"query"</span>)
    @<span class="tok-kw">classmethod</span>
    <span class="tok-kw">def</span> <span class="tok-fn">non_blank</span>(cls, v: str) -> str:
        <span class="tok-kw">if not</span> v.<span class="tok-fn">strip</span>(): <span class="tok-kw">raise</span> ValueError(<span class="tok-str">"Query cannot be empty"</span>)
        <span class="tok-kw">return</span> v</code>
```

### `@mcp.tool` & Shared `httpx.AsyncClient`

```
<code>mcp = <span class="tok-fn">FastMCP</span>(<span class="tok-str">"example_mcp"</span>)
_http = httpx.<span class="tok-fn">AsyncClient</span>(base_url=API_BASE_URL, timeout=<span class="tok-num">30.0</span>)

@mcp.<span class="tok-fn">tool</span>(name=<span class="tok-str">"example_search_users"</span>, annotations={
    <span class="tok-str">"title"</span>: <span class="tok-str">"Search Example Users"</span>, <span class="tok-str">"readOnlyHint"</span>: <span class="tok-kw">True</span>,
    <span class="tok-str">"destructiveHint"</span>: <span class="tok-kw">False</span>, <span class="tok-str">"openWorldHint"</span>: <span class="tok-kw">True</span>
})
<span class="tok-kw">async def</span> <span class="tok-fn">example_search_users</span>(params: UserSearchInput, ctx: Context) -> str:
    <span class="tok-str">"""Search users by name, email, or team."""</span>
    <span class="tok-kw">await</span> ctx.<span class="tok-fn">report_progress</span>(<span class="tok-num">0.2</span>, <span class="tok-str">"Querying upstream directory"</span>)
    <span class="tok-kw">try</span>:
        resp = <span class="tok-kw">await</span> _http.<span class="tok-fn">get</span>(<span class="tok-str">"/users/search"</span>, params=params.<span class="tok-fn">model_dump</span>())
        resp.<span class="tok-fn">raise_for_status</span>()
        <span class="tok-kw">return</span> <span class="tok-fn">format_users</span>(resp.<span class="tok-fn">json</span>(), params.response_format)
    <span class="tok-kw">except</span> (httpx.HTTPStatusError, httpx.TimeoutException) <span class="tok-kw">as</span> exc:
        <span class="tok-kw">return</span> <span class="tok-fn">handle_api_error</span>(exc)</code>
```

### Resources, Prompts & Lifespan State

```
<code>@<span class="tok-fn">asynccontextmanager</span>
<span class="tok-kw">async def</span> <span class="tok-fn">app_lifespan</span>():
    pool = <span class="tok-kw">await</span> <span class="tok-fn">create_db_pool</span>()
    <span class="tok-kw">yield</span> {<span class="tok-str">"db"</span>: pool}
    <span class="tok-kw">await</span> pool.<span class="tok-fn">close</span>()

@mcp.<span class="tok-fn">resource</span>(<span class="tok-str">"config://settings/{key}"</span>)
<span class="tok-kw">async def</span> <span class="tok-fn">get_setting</span>(key: str) -> str:
    <span class="tok-kw">return</span> json.<span class="tok-fn">dumps</span>(<span class="tok-fn">load_safe_setting</span>(key))

@mcp.<span class="tok-fn">prompt</span>()
<span class="tok-kw">def</span> <span class="tok-fn">team_audit_prompt</span>(team: str) -> str:
    <span class="tok-kw">return</span> <span class="tok-str">"Audit access for team "</span> + team + <span class="tok-str">" using example_search_users."</span></code>
```

### Python Production Rules

- **Never block the event loop:** Always use `httpx.AsyncClient` inside `async def` tools—never call synchronous `requests.get()`.
- **Use Pydantic v2 idioms:** Use `model_config = ConfigDict(...)`, `@field_validator` with `@classmethod`, and `model_dump()` (never deprecated v1 `Config` or `.dict()`).
- **Markdown vs. JSON formatting:** Format Markdown with human-readable UTC timestamps and `Name (ID)` headers; strip bulky avatar arrays.
- **Context superpowers:** Inject `ctx: Context` for `ctx.report_progress()`, `ctx.log_info()`, `ctx.elicit()`, and lifespan connections.
- **Dual run modes:** Default to `mcp.run()` for local `stdio`, or pass `mcp.run(transport="streamable_http", port=8000)` for HTTP.

## 7. Error Channels, OAuth 2.1 Auth & Hardening

Remote MCP servers must separate model-facing recovery hints from client-level JSON-RPC errors, enforce resource-scoped OAuth 2.1 tokens, and treat every upstream payload and path parameter as untrusted.

*[Illustration: Architectural dark glass inspection console and cube sorter gating luminous geometric artifacts through ten glowing emerald check prisms before a deployment portal]*

**Defense-in-Depth Validation Gate:** Every inbound call clears Host/Origin checks, OAuth 2.1 token audience verification, strict schema validation, and path/SSRF allowlists before touching downstream services.

### Two Distinct MCP Error Channels

- **Tool Errors (`isError: true`):** Seen directly by the LLM! Return `{ isError: true, content: [...] }` or throw a normal `Error` with an actionable next step (e.g., *"Rate limit exceeded. Wait 60s."*).
- **Protocol Errors (`ProtocolError`):** JSON-RPC errors handled by the host application; the model never sees them. Throw `ProtocolError(ProtocolErrorCode.InvalidParams, ...)` or `ResourceNotFoundError(uri.href)` inside resource and prompt handlers.

#### ! Hardening Checklist

- **Path traversal:** Resolve paths with `realpath()` and assert `resolved.startsWith(ROOT + path.sep)`.
- **SSRF & URL safety:** Allowlist schemes (`https:`) and block RFC1918 / link-local metadata IPs (`169.254.169.254`).
- **Upstream sanitization:** Validate API JSON via `Schema.parse(raw)` and strip raw HTML/script payloads.

### OAuth 2.1 Bearer Auth & Per-Caller Context

```
<code><span class="tok-kw">const</span> serverUrl = <span class="tok-kw">new</span> URL(<span class="tok-str">"https://mcp.example.com/mcp"</span>);
<span class="tok-kw">const</span> verifier: OAuthTokenVerifier = {
  <span class="tok-kw">async</span> <span class="tok-fn">verifyAccessToken</span>(token): Promise<AuthInfo> {
    <span class="tok-kw">const</span> claims = <span class="tok-kw">await</span> <span class="tok-fn">verifyJwt</span>(token);
    <span class="tok-kw">if</span> (!claims) <span class="tok-kw">throw new</span> <span class="tok-fn">OAuthError</span>(OAuthErrorCode.InvalidToken, <span class="tok-str">"Bad token"</span>);
    <span class="tok-kw">return</span> {
      token, clientId: claims.clientId, scopes: claims.scopes,
      expiresAt: claims.exp, <span class="tok-cmt">// Required: tokens without exp are rejected</span>
      resource: <span class="tok-kw">new</span> URL(claims.aud) <span class="tok-cmt">// Must match expectedResource</span>
    };
  }
};
<span class="tok-kw">const</span> app = <span class="tok-fn">createMcpExpressApp</span>({ host: <span class="tok-str">"0.0.0.0"</span>, allowedHosts: [<span class="tok-str">"mcp.example.com"</span>] });
<span class="tok-kw">const</span> auth = <span class="tok-fn">requireBearerAuth</span>({ verifier, requiredScopes: [<span class="tok-str">"mcp"</span>], expectedResource: serverUrl });
<span class="tok-kw">const</span> handler = <span class="tok-fn">createMcpHandler</span>(({ authInfo }) => <span class="tok-fn">createServer</span>(authInfo));
app.<span class="tok-fn">all</span>(<span class="tok-str">"/mcp"</span>, auth, (req, res) => <span class="tok-kw">void</span> <span class="tok-fn">toNodeHandler</span>(handler)(req, res, req.body));</code>
```

Inside tools, inspect `ctx.http?.authInfo` (undefined on `stdio`) to enforce tenant isolation and per-tool scopes.

## 8. 5 Real-World Copy-Paste MCP Recipes

Drop these five production primitives directly into your TypeScript v2 or Python FastMCP server to eliminate common protocol bugs, context overflows, and silent startup failures.

| Pattern & Goal | Copy-Paste TypeScript v2 / FastMCP Snippet | Production Guarantee |
| --- | --- | --- |
| **1. Dual-Transport Entrypoint** Serve local `stdio` by default and Streamable HTTP when `TRANSPORT=http`. | `if (process.env.TRANSPORT === "http") {` `const h = createMcpHandler(createServer);` `const app = createMcpExpressApp();` `app.all("/mcp", (q, s) => void toNodeHandler(h)(q, s, q.body));` `app.listen(3000, "127.0.0.1");` `} else { serveStdio(createServer); }` | One build artifact runs locally in IDEs and remotely in Docker/cloud with DNS-rebinding guards intact. |
| **2. `CHARACTER_LIMIT` Safe Paginator** Stay under 25,000 chars without slicing JSON mid-field. | `let items = data.users, res = render(items, offset);` `while (items.length > 1 && res.text.length > 25_000) {` `items = items.slice(0, Math.ceil(items.length / 2));` `res = render(items, offset);` `}` `return { content: [{ type: "text", text: res.text }] };` | Guarantees valid JSON/Markdown and sets `next_offset` accurately to the first omitted record. |
| **3. `outputSchema` + `structuredContent`** Return machine-validated JSON for typed downstream pipelines. | `server.registerTool("example_get_user", {` `inputSchema: z.strictObject({ user_id: z.string().min(1) }),` `outputSchema: UserSchema,` `annotations: { readOnlyHint: true }` `}, async ({ user_id }, ctx) => {` `const u = UserSchema.parse(await fetchUser(user_id, ctx.mcpReq.signal));` `return { content: [{ type: "text", text: JSON.stringify(u) }], structuredContent: u };` `});` | Strips unexpected upstream keys and satisfies both structured-output clients and plain-text agents. |
| **4. `scripts/smoke.ts` Self-Check** Verify built server over real `stdio` before shipping. | `const client = new Client({ name: "smoke", version: "1.0.0" });` `await client.connect(new StdioClientTransport({` `command: "node", args: ["dist/index.js"],` `env: { ...getDefaultEnvironment(), API_KEY: process.env.API_KEY ?? "" }` `}));` `const bad = await client.callTool({ name: "example_search_users", arguments: { query: "j" } });` `assert.equal(bad.isError, true);` | Catches broken builds, missing env forwarding, and silent Zod schema regressions in under 2 seconds. |
| **5. HTTP Status Error Mapper** Turn 401/403/404/429 into model-actionable recovery advice. | `function httpErrorMessage(status: number): string {` `switch (status) {` `case 401: return "Invalid API key. Check EXAMPLE_API_KEY.";` `case 404: return "Not found. Run example_search_users for IDs.";` `case 429: return "Rate limited. Wait 60s before retrying.";` `default: return "Upstream HTTP " + status + ".";` `}` `}` | Prevents blind retry loops by telling the LLM whether to stop, wait, or call a discovery tool first. |

#### Pro Tip: Pair `npm run build && npm run smoke` in Every CI Run

Because `tsx` skips TypeScript type-checking during local dev, always run `npm run build` (`tsc`) followed by `tsx scripts/smoke.ts` against `dist/index.js` so you verify the exact compiled binary hosts execute.

## 9. Packaging, Distribution & Multi-Host Rollout

Ship one predictable server artifact across local laptops and cloud clusters. Clean entrypoints, minimal Docker images, and portable JSON configs let teams adopt your tools in seconds.

### 1. Local `npx` & `uvx` Package Metadata

```
<code><span class="tok-cmt">// package.json (Node/TypeScript)</span>
{
  <span class="tok-str">"name"</span>: <span class="tok-str">"example-mcp-server"</span>,
  <span class="tok-str">"type"</span>: <span class="tok-str">"module"</span>,
  <span class="tok-str">"bin"</span>: { <span class="tok-str">"example-mcp-server"</span>: <span class="tok-str">"dist/index.js"</span> },
  <span class="tok-str">"files"</span>: [<span class="tok-str">"dist"</span>],
  <span class="tok-str">"engines"</span>: { <span class="tok-str">"node"</span>: <span class="tok-str">">=20.3"</span> }
}</code>
```

Start `src/index.ts` with `#!/usr/bin/env node` so `npx -y example-mcp-server` works immediately. For Python, declare `[project.scripts]` in `pyproject.toml` so hosts can run `uvx example-mcp`, or zip into a desktop `.mcpb` bundle with a `manifest.json`.

### 2. Stateless Docker Image (Streamable HTTP)

```
<code><span class="tok-kw">FROM</span> node:22-slim
<span class="tok-kw">WORKDIR</span> /app
<span class="tok-kw">COPY</span> package*.json ./
<span class="tok-kw">RUN</span> npm ci --omit=dev
<span class="tok-kw">COPY</span> dist ./dist
<span class="tok-kw">ENV</span> TRANSPORT=http PORT=3000
<span class="tok-kw">USER</span> node
<span class="tok-kw">EXPOSE</span> 3000
<span class="tok-kw">CMD</span> [<span class="tok-str">"node"</span>, <span class="tok-str">"dist/index.js"</span>]</code>
```

Bind to `0.0.0.0` inside containers and configure `allowedHosts` + `requireBearerAuth`. Never bake API secrets into image layers—inject them at runtime.

### 3. Registering Your Server Across Major AI Hosts

| Host Environment | Configuration / CLI Registration | Key Environment Notes |
| --- | --- | --- |
| **Claude Code** | `claude mcp add example -- npx -y example-mcp-server` Remote: `claude mcp add --transport http example https://mcp.acme.dev/mcp` | Supports project-scoped `.mcp.json` checked into Git (pass secrets via `${EXAMPLE_API_KEY}`). |
| **Claude Desktop** | Edit `claude_desktop_config.json` under `"mcpServers"` with `"command": "npx"`, `"args": ["-y", "example-mcp-server"]`, or drop a `.mcpb` bundle. | Desktop GUI spawns isolated env—list required API keys explicitly inside the entry's `"env"` object. |
| **Google Antigravity** | Add server under MCP settings (`mcp_config.json`) using either `command`/`args` for `stdio` or `serverUrl` for Streamable HTTP. | Exposes tools alongside built-in workspace capabilities; pair with `SKILL.md` workflows for higher-level playbooks. |
| **Codex / OpenAI Agents SDK** | `MCPServerStdio(params={"command": "uvx", "args": ["example-mcp"]})` or `MCPServerStreamableHttp(url=...)`. | Supports explicit tool filtering and tracing spans across multi-agent handoffs. |

#### Security Boundary for Shared Team Configs

Commit server coordinates (command, URL, and variable names like `${EXAMPLE_API_KEY}`) to repository configs, but keep actual tokens inside user-local `.env` or OS keychain vaults.

## 10. Cross-Tool Synergy & 10-Question Eval Pipeline

Compiling cleanly only proves syntax. True MCP quality is measured by whether a cold LLM—given only your tool schemas and descriptions—can solve realistic, multi-hop research tasks without getting lost.

### Four-Stage Verification & Evaluation Pipeline

### Designing 10 High-Signal Evaluation Questions

- **Read-only & independent:** Never require writes or depend on earlier question state.
- **Multi-hop & non-keyword:** Paraphrase concepts so the agent must page, cross-reference IDs, and synthesize across multiple tool calls.
- **Stable & verifiable:** Query closed/historical records (e.g., Q4 archived repos) whose single string answer never drifts over time.
- **Format-explicit:** State exact output formats in the question (e.g., *"Use YYYY/MM/DD"* or *"Provide only the username"*).

### XML Harness Format & Runner

```
<code><evaluation>
  <qa_pair>
    <question>Find the repository archived in Q3 2023 with the most prior forks. What was its primary language?</question>
    <answer>Python</answer>
  </qa_pair>
</evaluation>

<span class="tok-cmt"># Run against stdio or live Streamable HTTP endpoint</span>
python scripts/evaluation.py -t http -u https://mcp.acme.dev/mcp \
  -H "Authorization: Bearer $TOKEN" -o eval_report.md evaluation.xml</code>
```

#### Mine the Eval Report for Tool-Design Bugs

When accuracy dips or tool-call counts spike, read the agent's per-task feedback in `eval_report.md`: missing pagination hints, vague parameter descriptions, or oversized responses almost always explain why an agent stalled.

## 11. Troubleshooting Clinic & Pre-Flight Checklist

Diagnose the seven most common MCP production failures in ten seconds, then clear the six-point pre-flight gate before publishing or deploying.

| Symptom / Error | Root Cause | 10-Second Fix |
| --- | --- | --- |
| **1. Broken `stdio` JSON-RPC** Host disconnects with parse error. | Code or a dependency called `console.log()` or `print()`, writing logs to `stdout`. | Route every log exclusively to `console.error()` / `sys.stderr`; keep `stdout` pure JSON-RPC. |
| **2. Concurrent `-32603` Failures** Smoke test passes; parallel HTTP fails. | Factory returns one shared module-level `McpServer` instance across HTTP requests. | Instantiate `new McpServer(...)` and register tools *inside* `createServer()` on every call. |
| **3. Empty Schema Descriptions** Model guesses field formats blindly. | Project installed Zod `<4.2.0` (pre-`4.1.13` strips `.describe()` text) or omitted `.describe()`. | Pin `"zod": "^4.2.0"`, import via `import * as z from "zod/v4"`, and add `.describe()` everywhere. |
| **4. v1 / v2 Type & Import Clashes** `registerTool` missing or type errors. | Mixed legacy `@modelcontextprotocol/sdk` v1 imports with v2 `@modelcontextprotocol/server`. | Remove v1 packages or run `npx @modelcontextprotocol/codemod@latest v1-to-v2 .` across the project. |
| **5. Truncated Mid-Word Payloads** Invalid JSON or lost records. | Sliced response text at 25,000 characters instead of trimming whole result items. | Halve the array in a `while` loop until rendered output fits `25_000`, then set `next_offset`. |
| **6. Hanging Upstream Fetches** Cancelled calls leak sockets & quota. | `fetch()` lacked a timeout and ignored the client's MCP cancellation token. | Pass `signal: AbortSignal.any([ctx.mcpReq.signal, AbortSignal.timeout(30_000)])`. |
| **7. Wrong Tool Invoked** Agent calls sibling server's `search`. | Unprefixed generic names (`list_items`, `create_issue`) collide across connected servers. | Namespace every tool as `{service}_{action}_{resource}` and mention sibling tools in descriptions. |

### 6-Point Production Pre-Flight Checklist

- **☐ 1. Clean Factory Isolation:** `createServer()` constructs a fresh `McpServer` per call; shared HTTP pools live at module scope.
- **☐ 2. Strict Contracts & Hints:** Zod v4 `z.strictObject` / Pydantic v2 `extra="forbid"`, rich `.describe()`, and accurate annotations on every tool.
- **☐ 3. Bounded Context Payloads:** Pagination (`limit`/`offset`/`next_offset`) and item-halving cap responses under `25_000` characters.

- **☐ 4. Auth & Signal Wiring:** `requireBearerAuth` + `expectedResource` on remote HTTP; `ctx.mcpReq.signal` + 30s timeout on upstream calls.
- **☐ 5. Build & Smoke Verified:** `npm run build && npm run smoke` (or `py_compile`) and MCP Inspector checks pass with zero stdout pollution.
- **☐ 6. 10-Question Eval Passed:** Multi-hop read-only `evaluation.xml` passes with high accuracy and crisp tool-call efficiency.

---

## Edition Note & Attribution

This 12-page handbook, its topic structure, and its illustrations were generated with AI under human editorial direction and print-layout QA. Verify commands, pricing tiers, and security settings against official vendor documentation before production use.

- AI & Editorial Disclosure: https://twelve-pages.com/editorial
- Terms & Licensing: https://twelve-pages.com/terms
- Privacy & Cookie Notice: https://twelve-pages.com/privacy
