Updated
Covers the stable v2 TypeScript SDK and the MCP specification dated July 28, 2026.
Tested with
Node.js 24 · @modelcontextprotocol/server 2.x · Zod 4
A small MCP server is easy to demo. Register a tool, connect a client and return some text. The difficult part begins after that first successful call: malformed arguments arrive, an upstream API stalls, results become too large for the model's context, a user cancels halfway through a write, or a remote endpoint is exposed without the checks its transport assumes.
This article starts where the from-scratch tutorial ends. The goal is not another server with more features. It is a server whose behavior remains understandable when the surrounding system is unreliable.
Key takeaway
A reliable MCP server is a narrow protocol adapter around tested application services. Its tools have bounded contracts, explicit failure semantics and enough telemetry to explain every call without leaking private data.
For an MCP server, “up” is not the same as “useful.” A process can be running while its tool descriptions cause the model to select the wrong operation, its output schema drifts from the returned data, or its handler waits forever on a dependency.
I use five observable properties as the working definition:
| Property | What should be true |
|---|---|
| Discoverable | Names, descriptions and schemas let the model select the right tool |
| Deterministic | The same valid request has documented, bounded behavior |
| Recoverable | Expected failures reach the model as actionable tool errors |
| Governed | Authentication, authorization and side-effect rules are enforced outside model judgment |
| Observable | Every call can be traced by operation, duration and outcome without logging secrets |
This definition changes the design. The MCP layer should not own business rules, database queries, retry policy and response formatting in one large callback. It should validate a request, call an application service and translate the result into protocol content.
MCP client
│
▼
tool schema → handler adapter → application service → database or upstream API
│ │ │
│ ├─ tool error ├─ timeout / retry policy
│ ├─ bounded output └─ authorization / idempotency
│ └─ telemetry
▼
typed, compact resultKeeping that boundary thin also makes the core behavior testable without launching a desktop host or sending JSON-RPC by hand.
Consider a note-search tool. A weak version accepts an arbitrary query and returns every matching row. A reliable version constrains input, declares structured output, respects cancellation and limits what crosses the protocol boundary.
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";
const SearchInput = z.object({
query: z.string().trim().min(2).max(200),
limit: z.number().int().min(1).max(10).default(5),
});
const SearchOutput = z.object({
hits: z.array(
z.object({ id: z.string(), title: z.string(), excerpt: z.string() }),
),
truncated: z.boolean(),
});
type NoteSearch = {
search: (
input: { query: string; limit: number },
options: { signal: AbortSignal },
) => Promise<{ hits: Array<{ id: string; title: string; excerpt: string }>; total: number }>;
};
export const registerSearchNotes = (server: McpServer, notes: NoteSearch) => {
server.registerTool(
"search_notes",
{
description: "Search Markdown notes by topic. Use when the user asks about saved notes; do not use for web search.",
inputSchema: SearchInput,
outputSchema: SearchOutput,
},
async ({ query, limit }, ctx) => {
try {
const result = await notes.search(
{ query, limit },
{ signal: ctx.mcpReq.signal },
);
const output = {
hits: result.hits,
truncated: result.total > result.hits.length,
};
return {
content: [{ type: "text", text: `${output.hits.length} note matches` }],
structuredContent: output,
};
} catch {
return {
isError: true,
content: [{ type: "text", text: "Note search failed. Retry once or narrow the query." }],
};
}
},
);
};Several details do more work than they appear to:
- The description states both the intended use and a negative boundary. Tool descriptions are part of the selection interface presented to the model.
- The input schema rejects oversized or meaningless calls before they enter the service.
- The output schema gives clients a machine-readable contract instead of making them parse prose.
- The text block stays useful to clients that primarily display content, while
structuredContentpreserves typed fields. - The handler forwards the request's abort signal, so cancellation can stop real work rather than only hide its eventual result.
The service still needs its own timeout. Cancellation covers a client asking the server to stop; a deadline covers a dependency that never answers. Put both policies in the application or infrastructure layer, where they can be shared and tested, rather than duplicating them in every tool.
Tool failures and protocol failures have different audiences. A recoverable tool problem—missing data, rejected input or a temporary upstream outage—should normally return isError: true with a short message the model can act on. Resource, prompt and completion callbacks instead use protocol errors for the calling application.
Do not send stack traces, SQL fragments, access tokens or raw provider responses back to the model. Record detailed diagnostics in server telemetry and return a stable public message with a request ID when support needs correlation.
Do not turn every exception into a retry instruction
Retry only failures that may actually be transient. Authorization denial, invalid state and unsafe requests should fail clearly and permanently; otherwise an agent may repeat a side effect or amplify load.
For tools that mutate data, add an idempotency key to the application command. If a connection drops after the write succeeds but before the response arrives, the client may repeat the call. The second call should return the first result rather than create a second ticket, payment or deployment.
MCP makes data reachable; it does not make the context window infinite. Unbounded rows, full log files and binary payloads make the next model step slower and less reliable.
A practical result contract should include:
- a small, ranked result set;
- stable identifiers for follow-up calls;
- an explicit
truncatedornextCursorsignal; - short excerpts rather than complete records;
- resource links when the full object can be fetched separately.
The server, not the model, must enforce the limit. A prompt that says “request at most ten” is guidance; max(10) in the schema and a database LIMIT are controls.
For a local stdio server, standard output belongs to the JSON-RPC protocol. One debug line can corrupt the stream and make the host disconnect. Diagnostics go to standard error or a dedicated telemetry sink.
console.log("notes server started");
console.error("notes server started"); Stdio is appropriate when a trusted host launches one local process and owns its lifetime. Streamable HTTP is appropriate when several clients connect to a remote service, but it adds web-server responsibilities. The official handler does not automatically verify bearer tokens or validate Host and Origin; those checks belong in front of it. Local HTTP without host validation is vulnerable to DNS rebinding, while a public endpoint without authorization turns every exposed tool into an unauthenticated API.
For HTTP, build a fresh, cheap server instance per request and keep durable state in application services or external stores. Module-level connection pools and caches are fine; request identity, authorization and mutable workflow state should not live in a shared McpServer object.
Cancellation is cooperative. A handler must pass the signal into fetch calls, database work and long loops, then check it between units of work. But stopping the handler does not undo an external side effect that already committed.
For a long-running mutation, separate three states:
- Accepted: the server validated and durably recorded the operation.
- Running: a worker is processing it and may report progress.
- Completed or failed: the final state can be read by a stable operation ID.
This design is safer than holding one tool call open through minutes of work. It also gives reconnecting clients something concrete to query. If the operation must remain synchronous, define the cancellation point and document whether cancellation means “not started,” “best effort to stop,” or only “the client stopped waiting.”
The Inspector is useful, but manual success is the final check, not the test strategy. Build confidence in layers so failures point to one boundary.
- Test schemas. Reject empty queries, oversized strings, unknown fields and limits outside the allowed range.
- Test the application service. Verify authorization, deadlines, pagination and idempotency without MCP or a transport.
- Test the handler in memory. Connect an SDK client to the server, list tools, call the tool and assert both
contentandstructuredContent. - Test failure paths. Simulate upstream timeout, cancellation, malformed provider data and duplicate mutation requests.
- Test each supported transport. For stdio, verify stdout stays clean and the child exits. For HTTP, verify authentication plus rejected Host and Origin values.
- Run the Inspector and at least one real host. Confirm discovery, tool selection and the messages a user actually sees.
Contract tests deserve special attention. Clients cache tool lists and build UI or model context from schemas. Renaming a field, changing an optional value to required, or silently changing the meaning of a tool can break a host even when TypeScript compiles inside the server repository.
Treat a published tool schema like a small public API. Additive changes are usually the safest: introduce an optional input with a server-side default, or add an output field while preserving the existing fields and meaning. A required input, a renamed enum value or a different side effect is a breaking change even if the tool keeps the same name.
When semantics must change, register a new tool such as search_notes_v2 beside the old one. Give the older description a clear deprecation note, measure whether clients still call it, and remove it only after a deliberate compatibility window. Dynamic tool-list notifications can tell connected clients that a registration changed, but they do not make an incompatible contract safe.
Version the server implementation separately from the protocol revision it supports. The server's version identifies your product release; protocol negotiation decides which MCP wire contract a connection uses. Combining those concepts makes incident reports and compatibility tests needlessly ambiguous.
I also keep one captured response for every public tool contract. The fixture is not a substitute for end-to-end tests, but it makes review concrete: a schema diff, result diff and description diff can be inspected together. If a change would make the old fixture misleading, it deserves an explicit compatibility decision rather than an incidental edit.
For each call, record the tool name, request ID, authenticated principal or tenant identifier, duration, outcome, result count and dependency status. Avoid recording raw arguments and returned content by default; they may contain source code, personal notes or credentials.
The first useful dashboard is small:
- calls and failures by tool;
- latency percentiles by tool and upstream dependency;
- cancellations and timeouts;
- validation failures;
- result sizes and truncation rate;
- duplicate idempotency-key hits for mutating tools.
These signals answer operational questions that chat transcripts cannot: whether a tool is slow, selected incorrectly, returning too much data or repeatedly failing on the same dependency.
Before exposing a server beyond a development machine, I want every answer below to be explicit:
- Can a tool call escape its input and output bounds?
- Which errors are retryable, and can a retry duplicate a side effect?
- Do cancellation and timeouts reach the underlying work?
- Are secrets and raw content absent from results and default logs?
- Does stdio reserve stdout exclusively for protocol traffic?
- Does HTTP validate Host, Origin, authentication and authorization before the MCP handler?
- Can a test client exercise success, failure and cancellation without a GUI host?
- Can one request be traced across the handler, service and dependency?
- Is every breaking contract change versioned or coordinated with clients?
None of these controls are unique to MCP. That is the point. MCP standardizes how capabilities are described and invoked; reliability still comes from ordinary software engineering applied at a new boundary.
- Build your first MCP server — official v2 TypeScript SDK tutorial and stdio guidance.
- MCP TypeScript SDK: server errors — tool-result errors and protocol-error semantics.
- MCP TypeScript SDK: serve over HTTP — per-request factories, shutdown, Host/Origin validation and authentication boundaries.
- MCP TypeScript SDK reference server — progress, cancellation, structured output and end-to-end transport examples.
- Model Context Protocol specification — protocol lifecycle and capability contracts covered by this article.