IamBishal
AI Engineering

Building a Production MCP Server: Tools, Resources, Transports and Failure Modes

An MCP server is an API whose client is a model, so its descriptions are part of the prompt and its errors have to be ones the model can act on.

Bishal Saha

20 min read

Failure changes too: a model can't branch on a stack trace it never sees.
Bishal Saha

A quickstart MCP server can pass every check you give it: it appears in the inspector, lists its tools and returns the expected response. Put a real agent in front of it and other problems show up. The model calls a generic list tool when it needed a search, pulls a whole ticket history into its context window, or waits on a downstream call that never returns. These are interface and operations problems, and quickstarts skip them.

An MCP server is an API whose client is a model. Ordinary API discipline applies, with two twists: tool names, descriptions and schemas become part of the prompt, and errors have to come back in a form the model can act on.

1. Your API's new client reads the docs on every call

My background is REST API design and integration architecture. The discipline that carries over to MCP is contract stability: consistent naming, error envelopes, pagination and deprecation policies.

My other focus is agent tool use, where two things change. A developer reads your docs once and writes code that keeps doing the same thing. A model rereads them on every request: the host puts your tool names, descriptions and schemas into its context, and the model picks a tool and its arguments from them. Failure changes too: a model can't branch on a stack trace it never sees.

The running example is an MCP server in front of an internal ticketing API: search tickets, get a ticket, add a comment. Spec details follow the current protocol revision, 2026-07-28. The snippets use v2 of the TypeScript SDK (@modelcontextprotocol/server with zod/v4), the release line that implements 2026-07-28. v1 (@modelcontextprotocol/sdk) is still maintained but uses different imports. The snippets are illustrative and haven't been run.

2. Tools, resources and prompts: who decides when each one is used

The spec defines the three server primitives by who they serve. Tools are functions for the AI model to execute. Resources are context and data for the user or the model to use. Prompts are templated messages and workflows for users.

In the ticketing server, add_ticket_comment is a tool: the model decides a comment is needed and makes the call. A single ticket is a resource, and so is the support team's SLA policy; the host can attach either when a conversation about a ticket starts. A "Triage this ticket" prompt is a workflow a user picks from a menu.

So: if the model decides when to call it, make it a tool; context to attach is a resource; a workflow a user starts is a prompt. If a host you target supports only tools, exposing reads as tools as well buys portability.

3. Designing ticketing tools a model can actually choose between

Wrap an existing API the quickstart way and you tend to get something like this:

Before: one tool for everything
server.registerTool("api_request", {
  description: "Call the ticketing API",
  inputSchema: z.object({ method: z.string(), path: z.string(), params: z.record(z.string(), z.unknown()) }),
}, handler);

Thin wrappers named get, list and post are no better: nothing says what they act on, untyped parameters invite invented field names, and some guesses succeed at the wrong thing.

The opposite mistake is one tool per endpoint. Every definition costs context on every request, and near-duplicates such as list_tickets, find_tickets and query_tickets turn the choice into a guess. Shape tools around tasks instead: search_tickets, get_ticket, add_ticket_comment.

Names are identifiers, so keep them stable and within the spec's recommended 1 to 128 letters, digits, underscores, hyphens and dots. Uniqueness is only per server, so a host that loads several servers should disambiguate, for example with a prefix. Put the human-readable label in the optional title, so you can improve what people see without touching the identifier that agents and logs rely on.

Here's the better search_tickets; TicketClient and toToolResult stand in for your code.

tools/search-tickets.ts
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";

export function registerSearchTickets(server: McpServer, tickets: TicketClient) {
  server.registerTool(
    "search_tickets",
    {
      title: "Search tickets",
      description:
        "Search support tickets by keyword, status or assignee. Use this when you do not " +
        "know the ticket id; use get_ticket when you already have one (e.g. ABC-123). " +
        "Returns up to `limit` matches with id, title, status, assignee and a short snippet, " +
        "plus next_cursor when more results exist. Does not return comments or attachments.",
      inputSchema: z.object({
        query: z.string().min(2).describe('Free-text keywords, e.g. "SSO login timeout"'),
        status: z.enum(["open", "pending", "resolved", "closed"]).optional()
          .describe("Filter by status. Omit to search all statuses."),
        assignee: z.email().optional().describe('Assignee email, e.g. "dana@example.com"'),
        limit: z.number().int().min(1).max(25).default(10),
        cursor: z.string().optional().describe("Opaque value from a previous next_cursor"),
        response_format: z.enum(["concise", "detailed"]).default("concise"),
      }),
    },
    async (args) => toToolResult(await tickets.search(args)),
  );
}

Each sentence in that description has a job: what the tool does, when to use get_ticket instead, what comes back and what doesn't. The schema takes the guessing out. Status is an enum, limit is bounded, and the field descriptions show formats, so the model doesn't guess an assignee's format. Results stay lean too: only the fields the model needs, with response_format for detail on request.

Keep the schema strict, because it is part of the prompt. The current tools page counts input validation errors, such as a value out of range, as tool execution errors the model should see. TypeScript SDK v2 applies that before your handler runs: arguments that fail the schema come back as an isError: true result naming the field, and the model can fix its own call. Input that passes the schema but is still wrong, such as a ticket id that doesn't exist, is your handler's job, under the same rule: name the field and say what to try.

If this sounds like polish, Anthropic's Writing effective tools for agents reports that Claude Sonnet 3.5 reached state-of-the-art on SWE-bench Verified at the time, after precise refinements to its tool descriptions.

4. stdio or Streamable HTTP is a deployment decision

The choice comes down to who runs the server and where.

With stdio, the client launches your server as a subprocess and exchanges newline-delimited JSON-RPC over its standard streams, which suits single-user tools on a developer's machine. Expect it to run with the user's environment and credentials, and each user to run whatever version they last installed. The server must not write anything to stdout that isn't a valid MCP message, so one stray console.log corrupts the stream; logs go to stderr.

Streamable HTTP makes the server a shared remote service, which fits a ticketing server used by a whole support team. You take on the usual service concerns: load balancing, TLS, authentication and rate limiting.

The current revision removed protocol-level sessions and the standalone GET stream: every request is its own POST, answered with a JSON object or an SSE stream scoped to that request, and streams can't be resumed. Any instance can serve any request, so sticky routing is unnecessary. Closing a response stream is how a client cancels, so a proxy that cuts idle connections cancels calls mid-flight. Send X-Accel-Buffering: no on SSE responses so proxies don't buffer them.

flowchart LR
  subgraph Local[stdio: local]
    H1[Host app] -->|spawns| S1[MCP server process]
    S1 -->|stdin/stdout JSON-RPC| H1
  end
  subgraph Remote[Streamable HTTP: shared]
    C1[Agent A] -->|POST| G[MCP server]
    C2[Agent B] -->|POST| G
    G -->|JSON or SSE per request| C1
    G --> T[Ticketing API]
  end

Statelessness moves state into your tools. If a workflow needs it, the spec's guidance is an explicit handle: one tool returns an id, later calls pass it back, and the server checks the caller's authorization against that handle on every call.

The core stays the same; only who runs the server, and where, changes.

5. The failure path: errors the model can act on

The tools page defines two error mechanisms. Protocol errors are JSON-RPC errors for an unknown tool, a malformed request or a server error; clients may pass them to the model, though the spec says they are less likely to lead to recovery. Tool execution errors come back inside the result with isError: true and cover API failures, input validation and business logic. Clients should pass those to the model so it can correct itself.

Stack traces, internal hostnames and raw upstream bodies go to your logs, never to the model.

The add_ticket_comment handler below turns each failure it understands into an error that names the next step. In SDK v2, ctx.mcpReq.signal aborts when the client cancels the request or the connection closes, and the SDK never sends a response for a cancelled request; the handler combines that signal with its own deadline. commentKey, callerOf, NotFoundError, isTimeout, isServerError and logger are placeholders, and TOOL_BUDGET_MS is a value you choose. Permission and rate-limit branches follow the same pattern and are left out for length.

tools/add-ticket-comment.ts
async ({ ticket_id, body }, ctx) => {
  // One budget for the whole call, below the client's request timeout; the SDK aborts ctx.mcpReq.signal on cancel
  const deadline = AbortSignal.any([ctx.mcpReq.signal, AbortSignal.timeout(TOOL_BUDGET_MS)]);
  // Derived by the server from caller, ticket and body, so the model can't drop or change it
  const idempotencyKey = commentKey(callerOf(ctx), ticket_id, body);
  try {
    // Retries and backoff live inside tickets.addComment, reusing this key until the deadline
    const comment = await tickets.addComment(ticket_id, body, { idempotencyKey, signal: deadline });
    return { content: [{ type: "text" as const, text: `Comment ${comment.id} added to ${ticket_id}.` }] };
  } catch (err) {
    if (ctx.mcpReq.signal.aborted) {
      // The client cancelled; the SDK sends no response for this request, so only log it
      logger.info({ ticket_id }, "add_ticket_comment cancelled");
      return toolError("Cancelled by the client.");
    }
    if (err instanceof NotFoundError) {
      return toolError(`Ticket ${ticket_id} not found. Use search_tickets to find the correct id.`);
    }
    if (isTimeout(err) || isServerError(err)) {
      return toolError(
        `The ticketing API did not confirm the comment on ${ticket_id} in time; it may or may not have been added. ` +
          `Calling add_ticket_comment again with the same ticket_id and body will not add a second copy.`,
      );
    }
    logger.error({ err, ticket_id }, "add_ticket_comment failed");
    return toolError("The ticketing API returned an unexpected error. Do not retry; tell the user.");
  }
};

// A tool execution error, in the result shape the tools page defines
function toolError(text: string) {
  return { content: [{ type: "text" as const, text }], isError: true };
}

If the stream drops before the result arrives, the client sees a cancelled call and the model may simply call again, whether or not the comment was written. The promise that a repeat is safe holds under two conditions. The server derives the key, so the model can't forge or drop it; if it rewords the body, that is a new comment by design, which is why the message says to resend the same body. And the ticketing API honours idempotency keys, which is an assumption about this hypothetical API; if yours doesn't, deduplicate in the server or stop making the promise.

The key's lifetime comes from the API's retention window for keys, not from the hash. Inside that window, a comment deliberately identical to an earlier one collapses into it. If you add a time bucket to the key instead, a retry that straddles a bucket boundary gets a new key and can post twice.

One budget covers the whole call. Set it below the MCP client's request timeout and make every attempt and backoff spend from it, so the server answers before the client gives up. One level up, a circuit breaker for agent tool calls bounds the same problem across calls.

Retries depend on the operation. Writes retry with the same key until the budget runs out; if the API ignores keys, make one attempt. Validation and business errors fail the same way every time, so never retry them.

Errors come back as tool results the model can act on, not protocol failures.
Failure modeWhat the model seesHow to handle it
Unknown tool nameA JSON-RPC error, which the host may not pass onStable names; count Mcp-Name at the gateway
Arguments break the schemaAn isError result naming the invalid fieldStrict schema; SDK v2 returns it before the handler runs
Read timeout, retry succeedsA normal resultRetry with backoff inside the budget
Read retries exhausted"Ticketing API unavailable; try later or tell the user"Stop at the budget
Write timeout or server error"Comment unconfirmed; same arguments are safe to resend"Keyed retries, then the model decides
Not found"Ticket ABC-123 not found; use search_tickets"Point to the right tool
Permission denied downstream"Not allowed to comment on ABC-123; ask the user"Don't retry
Rate limited"Rate limited; finish other steps or tell the user"Back off within the budget first
Oversized resultFirst page, total count, a narrower-filter hintPaginate
Client cancelled or stream droppedNothing; the client stopped waitingAbort downstream work; log a cancellation

6. Large results: paginate, truncate, return references

The protocol paginates tools/list itself. Do the same for tool results.

search_tickets returns a bounded page and an opaque next_cursor rather than an offset, so you can change the query, sort order or index without breaking anyone. Return references instead of payloads: search results carry ticket ids, and full bodies sit behind get_ticket or a resource link the tool returns for the client to fetch. When you truncate, say how many matches exist and which filters would narrow them. Otherwise the model will reasonably treat the list as complete.

A concise page with limit: 3 might read:

text
3 of 41 matches. Narrow with status or assignee, or pass next_cursor: c2VhcmNoOjM
ABC-123  open     dana@example.com  SSO login timeout after IdP change
ABC-131  pending  sam@example.com   SSO loop on mobile app
ABC-140  open     (unassigned)      Login timeout for EU tenants

7. Changing a tool without breaking the agents that use it

Beyond the usual breaking changes (renamed tools, removed or retyped parameters, new required fields, a different output shape), one is new. Rewording a description changes how the model chooses between tools, even though no schema breaks.

Prefer additive changes. When a tool needs a different contract, ship a new tool beside the old one and mark the old one deprecated in its description, since models read descriptions. Remove it after a published window. Return tools/list in a deterministic order as well: the spec recommends it because a stable list improves prompt-cache hit rates when tools sit in the model's context.

The protocol revision is a second contract, and it moves independently of yours. 2026-07-28 removed protocol-level sessions and resumable streams, and 2025-06-18 listed invalid arguments as protocol errors, so older servers and SDKs may still report them that way. Pin the SDK and record protocol changes and tool changes as separate changelog entries. Before shipping either, re-run an evaluation set of realistic agent tasks, like contract tests.

8. Tracing tool calls end to end

When an agent misbehaves, the first question is what it actually called. Wrap each handler in one OpenTelemetry span that records the tool name, allowlisted argument fields and result size, and marks the span as an error when the result has isError: true. Otherwise error-rate dashboards miss the failures that show which contracts confuse the model. An instrumented HTTP client adds a child span for each downstream attempt.

tracing.ts
import { SpanStatusCode, trace } from "@opentelemetry/api";

const tracer = trace.getTracer("ticketing-mcp");

type ToolResult = { content: unknown[]; isError?: boolean };

// One span per tool call. Argument fields are allowlisted, never masked after the fact.
export function traced<A extends Record<string, unknown>, C, R extends ToolResult>(
  tool: string,
  loggedFields: (keyof A & string)[],
  handler: (args: A, ctx: C) => Promise<R>,
) {
  return (args: A, ctx: C): Promise<R> =>
    tracer.startActiveSpan(`tool ${tool}`, async (span) => {
      span.setAttribute("tool.name", tool);
      for (const field of loggedFields) span.setAttribute(`tool.arg.${field}`, String(args[field]));
      try {
        const result = await handler(args, ctx);
        span.setAttribute("tool.result.size", JSON.stringify(result.content).length);
        // A tool error is a failure even though nothing was thrown
        if (result.isError) span.setStatus({ code: SpanStatusCode.ERROR, message: "tool error" });
        return result;
      } catch (err) {
        span.recordException(err as Error);
        span.setStatus({ code: SpanStatusCode.ERROR });
        throw err;
      } finally {
        span.end();
      }
    });
}

// Usage: server.registerTool("get_ticket", config, traced("get_ticket", ["ticket_id"], getTicket));

Extract a W3C traceparent header as the parent context when the client sends one. Otherwise, including on stdio, which has no header layer, start a root span and record the JSON-RPC request id so logs can be joined.

The wrapper only sees calls that reach a handler. On Streamable HTTP, clients mirror the method and tool name into Mcp-Method and Mcp-Name headers, so a gateway can count calls per tool, including unknown names, rejected requests and schema failures that never reach your code. Those counts point at naming problems and stale clients.

9. Security basics, and where authorization lives

The spec overview requires hosts to obtain explicit user consent before invoking any tool. I'd still assume some approvals are given without much thought, and limit what any single approved call can do.

Annotations help disclose which tools make destructive changes or reach the open world, and clients must treat them as untrusted unless the server is trusted. add_ticket_comment only adds, so it isn't destructive. Whether a comment customers can read counts as open-world is arguable, so say it in the description. The server still enforces what each caller may do.

Prompt injection is the central risk for this server. Anyone who can file a ticket can write instructions into its body, and your server hands that text to a model that can also post comments colleagues and customers read. A read path over attacker-written text plus a write path to other people is an exfiltration route. The tools page makes servers sanitise outputs and asks clients to confirm sensitive operations and show tool inputs before calling. For this server I'd also label ticket text in results as quoted ticket content, post agent comments as internal notes by default if the ticketing API supports them, and keep add_ticket_comment behind confirmation.

Keep closing and deleting tickets as separate, explicit tools. Give the downstream credential only the privileges the tools need, and rate-limit per caller. If you run Streamable HTTP on a developer's machine, bind it to 127.0.0.1; the spec requires validating the Origin header in any case, to stop DNS rebinding.

OAuth, token handling and token passthrough are covered in MCP server authorization: token passthrough, token exchange and the confused deputy.

10. Where this discipline costs more than it saves

A personal stdio tool doesn't need idempotency keys, OpenTelemetry and a deprecation policy. Match the rigour to how many people and agents depend on the server. And for a fixed workflow inside one application, I think plain function calling is often simpler, the same reasoning that favours a graph workflow over an open agent loop for known paths. MCP earns its overhead when several hosts or teams need the same capabilities.

11. Where to start

If the server is shared, add tracing first. If agents misuse tools, fix names and descriptions before adding features. Then pick one of your tool descriptions and rewrite it as if you were documenting a public API for a new hire: what it's for, when to use it, when not to, its inputs, its outputs and its limits. Run the same agent tasks again and watch how the agent's tool choice changes.

View All Articles

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.