Filed underL06 · AI & Automation
Published
Reading time27 min
Updated
Field notes · L06 AI & Automation

Building MCP servers agents can actually useTool design, OAuth and remote vs local

How to build an MCP server agents use well: fewer, higher-level tools, actionable errors, OAuth on the 2026-07-28 spec, and when to go remote.

The short answer

Design an MCP server for a model, not for a developer. Expose a few high-level tools that each finish a whole task. Give them names and descriptions that make the right choice obvious. Return short, human-readable results with the IDs the next call needs, and send failures back as isError results that tell the model what to do next. Build remote servers on the 2026-07-28 specification. It is stateless, so any instance can serve any request, and your server acts as an OAuth 2.1 resource server: it publishes Protected Resource Metadata, checks token audience and asks for extra scopes only when a tool needs them. Ship a local stdio server only when the tool has to touch the user's machine.

The rest of this post covers what that looks like in code, what changed in the spec this summer, how to choose between remote and local, how to version a tool surface that a model has learnt to use, and a review scorecard to run before you ship.

01Why most MCP servers are hard for agents to use

Most first MCP servers wrap an existing REST API: one tool per endpoint, the same names, the same JSON. It feels like the obvious thing to build. In practice it is the main reason agents struggle with a server.

An API is built for a programmer who reads the docs once, writes code, and runs it a million times. A tool is used by a model that rereads the full tool list on every turn, picks a tool from its name and description alone, and pays in tokens for every byte you send back. Those are different users, and they need different interfaces.

The costs are measurable. Anthropic reported five popular MCP servers (GitHub, Slack, Sentry, Grafana, Splunk) whose 58 tools used about 55K tokens before the conversation even starts, and internal cases where tool definitions reached 134K tokens. In the same post, letting the model search for tools rather than loading them all raised accuracy on their MCP evaluation from 79.5% to 88.1% for Opus 4.5. A smaller, clearer tool surface beats a bigger one.

Anthropic's guide to writing tools for agents (September 2025) is still the best primary source on this. What follows is our opinionated reading of it, updated for the current protocol and SDKs.

02MCP tool design best practices

Build fewer, higher-level tools

Each tool should do one complete unit of work as the user would describe it, not one HTTP call. Anthropic's examples: replace list_users, list_events and create_event with schedule_event. Replace read_logs with search_logs. Fold get_customer_by_id, list_transactions and list_notes into get_customer_context.

The test we use: write down the five to ten tasks an agent will actually be asked to do with this system. If a common task needs more than two or three tool calls that always run in the same order, merge them into one tool. If a tool is never the right first step for any task, it may not need to exist.

You probably don't need a CRUD tool for every resource. You probably do need one good search tool, one context tool for each core entity, and a few deliberate write actions.

Name tools so the right choice is obvious

  • Namespace by service, then by resource: support_find_customer, support_issue_refund. Clients put tools from many servers into one list. The spec says tool names SHOULD be unique within a server, but nothing makes them unique across servers. Two servers that each expose search will confuse the model.
  • Keep to the allowed characters: 1–128 characters from A–Z a–z 0–9 _ - .. On Streamable HTTP the name is also copied into the Mcp-Name header, and names outside that set get Base64-encoded. That works, but it makes your gateway logs harder to read.
  • Use unambiguous parameter names: customer_id, not customer or id. amount_pence, not amount.
  • Use verbs that signal side effects: find_, get_ and search_ for reads. issue_, cancel_ and delete_ for writes.

Write descriptions as instructions to a new colleague

The description is the only documentation the model reads. Put in it the things an experienced engineer would know without being told:

  1. What the tool does, in one sentence.
  2. When to use it, and which tool to call instead when this is the wrong one.
  3. Where its inputs come from (for example, "customer_id from support_find_customer").
  4. Units, formats and limits (pence, ISO 8601, maximum 20 results).
  5. Side effects and lifetimes ("Irreversible", "baskets expire after 24 hours of inactivity").

Leave out marketing copy, version history and anything the model can't act on. Every word is paid for on every turn.

Return context, not raw data

Return what the model needs to reason with and to make the next call. Usually that means names rather than UUIDs, with the one ID the follow-up call needs labelled clearly (customer_id=cus_8f2KxQ1a). Leave out internal fields such as created_by_service, etag and _links.

Give heavy tools a response_format parameter with values concise and detailed, and make concise the default. In Anthropic's example the concise response was 72 tokens against 206 for the detailed one.

Treat the size of each response as a budget, part of the wider job of context engineering for long-running agents. Claude Code warns at 10,000 tokens of MCP output and by default writes anything over 25,000 tokens to a file instead of the conversation. Paginate, filter, truncate, and when you truncate, say so and say how to get the rest.

Make errors actionable

The spec defines two kinds of error, and choosing the right one is part of tool design:

Failure Mechanism Who sees it Example
Unknown tool, malformed request, server crash JSON-RPC error (e.g. -32602) Client. It may pass it to the model Unknown tool: invalid_tool_name
Bad input, business rule, upstream API failure Result with isError: true Model. Clients SHOULD pass it on "Refund exceeds the refundable balance… retry with a smaller amount_pence"

The rule we follow: if the model could fix the problem by calling again differently, return a tool execution error that says exactly how. "Error 422" teaches it nothing. "No customers match 'acme'. Try the email domain (e.g. 'acme.com')" usually gets a correct second call. Bad tool arguments are one of the agent failure modes in production, and an actionable error is the cheapest recovery. Bugs and outages should still surface as real errors so they reach your alerting. Don't hide a database outage inside a polite isError result.

The TypeScript SDK already does part of this for you. When arguments fail schema validation it returns an isError result naming the field and the constraint. In our tests on @modelcontextprotocol/server 2.3.1, a too-short query came back as Input validation error: … query: Too small: expected string to have >=3 characters. So put your constraints in the schema (min, max, regex, enum), where both the model and the validator can see them.

Use structured output where a program reads the result

Since protocol version 2025-06-18 a tool can declare an outputSchema and return structuredContent. The 2026-07-28 revision loosened both: schemas may use any JSON Schema 2020-12 keyword, and structuredContent may be any JSON value, including an array. If you declare an output schema, your results MUST conform to it, and clients SHOULD validate them.

Use it when code downstream of the model reads the result: an orchestrator, a UI, or a code-execution sandbox. The spec also says a tool returning structured content SHOULD repeat it as serialised JSON in a text block, for older clients. We sometimes break that SHOULD on purpose and return a terse human-readable rendering in content instead, because that is often what the model sees. If you do the same, test it against the clients you care about. Don't add an output schema just because the SDK makes it easy. A schema the model never needs is wasted tokens.

Treat annotations as hints, not controls

readOnlyHint, destructiveHint, idempotentHint and openWorldHint help clients decide when to ask the user for confirmation. Set them honestly. But clients MUST treat annotations as untrusted unless the server is trusted, so they are not a security boundary. Enforce permissions on the server. How to do that properly is the subject of our post on securing AI agents: prompt injection, tool permissions and least privilege for MCP.

03What changed in the MCP spec in 2026

If your mental model of MCP dates from 2025, three changes in the 2026-07-28 revision matter more than the rest.

The protocol is stateless. There is no initialize handshake and no Mcp-Session-Id. Every request carries its protocol version, client info and capabilities in _meta (SEP-2575). Servers MUST implement server/discover, which clients can call to learn the supported versions and capabilities. tools/list MUST NOT vary per connection, though it MAY vary with the caller's authorisation. If you need state across calls, the spec's stateful tools guidance says to return an explicit handle (basket_id) and accept it as an ordinary argument, checking authorisation against that handle on every call.

Server-to-client requests became multi round-trip requests (MRTR). A server that needs user input no longer sends elicitation/create down an open stream. It returns a result with resultType: "input_required", and the client retries the original call with inputResponses (SEP-2322). Long-running work moved into the official Tasks extension (io.modelcontextprotocol/tasks), which uses polling via tasks/get.

HTTP got friendlier to infrastructure. Every POST carries MCP-Protocol-Version, Mcp-Method and, for tools/call, Mcp-Name headers, so a gateway or WAF can route and rate-limit by tool without parsing the body (SEP-2243). A tool can mark a parameter with x-mcp-header to copy it into a header such as Mcp-Param-Region. Servers must reject requests where the headers and body disagree. List results now carry ttlMs and cacheScope, and servers SHOULD return tools in a deterministic order, which keeps your tool list byte-stable and helps LLM prompt-cache hits.

Also deprecated: Sampling, Roots and Logging (SEP-2577), the old HTTP+SSE transport, and Dynamic Client Registration in favour of Client ID Metadata Documents. SSE resumability (Last-Event-ID) is gone. If a stream breaks, the client re-issues the request.

On SDKs, TypeScript v2 (@modelcontextprotocol/server) went stable as 2.0.0 on 27 July 2026 and was at 2.3.1 when we wrote this. Python mcp 2.0.0 shipped on 28 July and is at 2.3.0. Both still talk to 2025-era peers. Clients fall back to initialize when they hit an older server, and the TypeScript HTTP handler serves legacy traffic statelessly by default. Go and C# shipped betas in June and went stable on 28 July too: the Go SDK in v1.7.0 (now 1.8.0), on the same module path, and the C# ModelContextProtocol packages in 2.0.0 (now 2.2.0). The Go HTTP transport only serves 2026-07-28 when you set StreamableHTTPOptions.Stateless = true; otherwise clients negotiate down to 2025-11-25.

04A reference MCP server in TypeScript

The code below is a complete support-desk server with three tools on SDK 2.3.1. It type-checks under strict, and we exercised the error and scope paths against a stubbed domain layer. It puts the design rules above into practice: namespaced names, one consolidated context tool, a concise default, schema constraints, actionable errors, honest annotations, and a scope step-up on the one destructive tool.

bash
npm install @modelcontextprotocol/server @modelcontextprotocol/node zod jose
ts
// src/tools.ts
import { McpServer, requireScopes, type AuthInfo } from '@modelcontextprotocol/server';
import * as z from 'zod';

// Stand-ins for your real domain layer.
declare const db: {
  searchCustomers(q: string, limit: number): Promise<Array<{ id: string; name: string; email: string; plan: string }>>;
  customerContext(id: string, tenant: string): Promise<CustomerContext | null>;
  refund(input: { customerId: string; chargeId: string; amountPence: number; reason: string; idempotencyKey: string; actor: string }): Promise<{ refundId: string; status: 'pending' | 'succeeded' }>;
};
type CustomerContext = {
  id: string; name: string; plan: string; mrrPence: number;
  openTickets: Array<{ id: string; subject: string; ageDays: number }>;
  recentCharges: Array<{ id: string; amountPence: number; status: string; createdAt: string }>;
  notes: Array<{ author: string; body: string; createdAt: string }>;
};

const ResponseFormat = z.enum(['concise', 'detailed']).default('concise')
  .describe("'concise' returns names and the fields needed for follow-up calls. 'detailed' adds raw IDs and timestamps. Prefer 'concise'.");

const text = (s: string) => [{ type: 'text' as const, text: s }];
const toolError = (s: string) => ({ isError: true, content: text(s) });

export function buildServer(auth?: AuthInfo): McpServer {
  const tenant = auth?.extra?.tenant as string | undefined;
  const server = new McpServer(
    { name: 'support-mcp', version: '3.2.0' },
    {
      capabilities: { tools: {} },
      instructions:
        'Customer support tools. Start with support_find_customer unless you already have a customer ID. ' +
        'Amounts are integers in pence. Refunds are irreversible and require the refunds:write scope.',
    },
  );

  server.registerTool(
    'support_find_customer',
    {
      title: 'Find customer',
      description:
        'Find customers by name, email or email domain. Returns at most `limit` matches, best first. ' +
        'Use this to get a customer_id before calling support_get_customer_context. ' +
        'Do not use it to list all customers; it requires a query of 3+ characters.',
      inputSchema: z.object({
        query: z.string().min(3).describe('Name, full email, or domain such as "acme.com"'),
        limit: z.number().int().min(1).max(20).default(5),
      }),
      annotations: { readOnlyHint: true, openWorldHint: false },
    },
    async ({ query, limit }) => {
      const rows = await db.searchCustomers(query, limit + 1);
      if (rows.length === 0) {
        return toolError(
          `No customers match "${query}". Try the email domain (e.g. "acme.com") or a shorter name fragment.`,
        );
      }
      const shown = rows.slice(0, limit);
      const more = rows.length > limit ? `\n(More matches exist; refine the query or raise limit, max 20.)` : '';
      return {
        content: text(shown.map(c => `${c.name} <${c.email}> plan=${c.plan} customer_id=${c.id}`).join('\n') + more),
        structuredContent: { customers: shown, truncated: rows.length > limit },
      };
    },
  );

  server.registerTool(
    'support_get_customer_context',
    {
      title: 'Get customer context',
      description:
        'Everything a support agent needs about one customer in a single call: plan, MRR, open tickets, ' +
        'last 5 charges and last 3 internal notes. Call this instead of fetching tickets, charges and notes separately.',
      inputSchema: z.object({
        customer_id: z.string().regex(/^cus_[A-Za-z0-9]{8,}$/).describe('From support_find_customer, e.g. "cus_8f2KxQ1a"'),
        response_format: ResponseFormat,
      }),
      annotations: { readOnlyHint: true, openWorldHint: false },
    },
    async ({ customer_id, response_format }) => {
      if (!tenant) return toolError('No tenant on this token. Re-authorise the connection.');
      const c = await db.customerContext(customer_id, tenant);
      if (!c) {
        return toolError(
          `Customer ${customer_id} not found in this workspace. Call support_find_customer to look up the correct ID.`,
        );
      }
      const pounds = (p: number) => `£${(p / 100).toFixed(2)}`;
      const lines = [
        `${c.name} — ${c.plan}, MRR ${pounds(c.mrrPence)}`,
        `Open tickets (${c.openTickets.length}): ` + c.openTickets.map(t => `${t.subject} [${t.ageDays}d]`).join('; '),
        'Recent charges: ' + c.recentCharges.slice(0, 5).map(ch =>
          response_format === 'detailed'
            ? `${ch.id} ${pounds(ch.amountPence)} ${ch.status} ${ch.createdAt}`
            : `${pounds(ch.amountPence)} ${ch.status} (charge_id=${ch.id})`).join('; '),
        'Notes: ' + c.notes.slice(0, 3).map(n => `${n.author}: ${n.body.slice(0, 200)}`).join(' | '),
      ];
      return { content: text(lines.join('\n')) };
    },
  );

  server.registerTool(
    'support_issue_refund',
    {
      title: 'Issue refund',
      description:
        'Refund all or part of one charge. Irreversible. Only call after the user has explicitly confirmed the ' +
        'amount and charge. Partial refunds are allowed; the total refunded cannot exceed the charge amount.',
      inputSchema: z.object({
        customer_id: z.string().regex(/^cus_[A-Za-z0-9]{8,}$/),
        charge_id: z.string().regex(/^ch_[A-Za-z0-9]{8,}$/).describe('From support_get_customer_context'),
        amount_pence: z.number().int().positive().describe('Integer pence. £12.50 is 1250.'),
        reason: z.enum(['duplicate', 'fraudulent', 'requested_by_customer', 'service_failure']),
        idempotency_key: z.string().uuid().describe('Generate one UUID per intended refund and reuse it on retries.'),
      }),
      annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
      scopeChallenge: requireScopes('refunds:write'),
    },
    async (args) => {
      try {
        const r = await db.refund({
          customerId: args.customer_id, chargeId: args.charge_id, amountPence: args.amount_pence,
          reason: args.reason, idempotencyKey: args.idempotency_key, actor: auth?.clientId ?? 'unknown',
        });
        return {
          content: text(`Refund ${r.refundId} ${r.status} for £${(args.amount_pence / 100).toFixed(2)}.`),
          structuredContent: r,
        };
      } catch (e) {
        if (e instanceof Error && e.message === 'EXCEEDS_REFUNDABLE') {
          return toolError(
            'Refund exceeds the refundable balance for this charge. Call support_get_customer_context with ' +
            "response_format='detailed' to see prior refunds, then retry with a smaller amount_pence.",
          );
        }
        throw e; // unexpected: let it surface as a protocol/server error and alert on it
      }
    },
  );

  return server;
}

Three details are easy to miss:

  • The idempotency key is a tool argument. Models retry. Networks drop. Under 2026-07-28 a broken stream loses the in-flight request and the client re-issues it. A write tool without an idempotency key will eventually refund twice. The pattern is the same as for any public API. Our post on idempotency keys covers the storage side.
  • instructions is server-level context. It comes back from server/discover. Use it for rules that span tools, such as order of operations and units, rather than repeating them in every description.
  • The factory receives the caller's authInfo. The SDK builds a fresh server instance per HTTP request, so you can register a different tool set per tenant or scope. The spec explicitly allows tools/list to vary by authorisation.

05OAuth for remote MCP servers

The flow, from the server's side

Under the authorization spec, your MCP server is an OAuth 2.1 resource server. It does not issue tokens. Your existing identity provider, or a dedicated authorization server, does that.

Diagram
 MCP client                          MCP server (resource server)          Authorization server
     |  POST /mcp  (no token)                  |                                     |
     |---------------------------------------->|                                     |
     |  401  WWW-Authenticate: Bearer          |                                     |
     |       resource_metadata=".../oauth-protected-resource/mcp", scope="support:read"
     |<----------------------------------------|                                     |
     |  GET /.well-known/oauth-protected-resource/mcp  (RFC 9728)                    |
     |---------------------------------------->|  { resource, authorization_servers }|
     |  GET /.well-known/oauth-authorization-server  (RFC 8414 / OIDC discovery)     |
     |------------------------------------------------------------------------------>|
     |  authorize: PKCE + resource=https://mcp.example.com/mcp (RFC 8707)            |
     |  client_id = https URL of a Client ID Metadata Document                       |
     |------------------------------------------------------------------------------>|
     |  token (aud = https://mcp.example.com/mcp)                                    |
     |<------------------------------------------------------------------------------|
     |  POST /mcp  Authorization: Bearer …     |  verify sig, iss, aud, exp, scope   |
     |---------------------------------------->|                                     |
     |  tools/call support_issue_refund        |                                     |
     |  403 insufficient_scope scope="refunds:write"  -> client steps up, retries    |

The flow above gives the server four jobs:

  1. Publish Protected Resource Metadata (MUST), and point to it from the WWW-Authenticate header on every 401.
  2. Validate audience. Servers MUST validate that tokens were issued specifically for them, and MUST NOT accept or pass on any other token. Clients send resource=<your canonical URI> on both the authorisation and token requests (RFC 8707), so your authorization server needs to put that URI in aud. If it ignores resource, fix that before you ship. Otherwise a token issued for some other API will work against your MCP server.
  3. Advertise minimal scopes, then step up. scopes_supported should be the minimum needed for basic use. When a call needs more, return 403 with error="insufficient_scope" and every scope the operation needs in one challenge. The spec says not to dribble them out one at a time.
  4. Never pass the MCP token through to upstream APIs. If your tool calls another protected API, get a separate token for that audience, for example via token exchange or the server's own credentials. Passing the token through is how you build a confused deputy. The spec's security best practices and our MCP security post go deeper.

On client registration: Client ID Metadata Documents are now the recommended route. The client's client_id is an HTTPS URL that serves its metadata, and your authorization server advertises client_id_metadata_document_supported: true. Dynamic Client Registration still works but is deprecated. If your IdP supports neither, pre-registration with a published client ID is fine for internal servers. For machine-to-machine use and centrally managed enterprise access, look at the OAuth Client Credentials and Enterprise-Managed Authorization extensions.

Wiring it up

ts
// src/http.ts
import { createServer } from 'node:http';
import { createMcpHandler, requireBearerAuth, OAuthError, OAuthErrorCode, type AuthInfo } from '@modelcontextprotocol/server';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createRemoteJWKSet, jwtVerify } from 'jose';
import { buildServer } from './tools.js';

const RESOURCE = new URL('https://mcp.example.com/mcp');        // canonical server URI (RFC 8707)
const ISSUER = 'https://auth.example.com';                      // your authorization server
const PRM_PATH = '/.well-known/oauth-protected-resource/mcp';   // RFC 9728, path-inserted
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`));

const verifier = {
  async verifyAccessToken(token: string): Promise<AuthInfo> {
    try {
      const { payload } = await jwtVerify(token, jwks, { issuer: ISSUER, audience: RESOURCE.href });
      return {
        token,
        clientId: String(payload.client_id ?? payload.azp ?? ''),
        scopes: String(payload.scope ?? '').split(' ').filter(Boolean),
        expiresAt: payload.exp,
        resource: RESOURCE,
        extra: { sub: payload.sub, tenant: payload.tenant },
      };
    } catch {
      throw new OAuthError(OAuthErrorCode.InvalidToken, 'Token invalid, expired or not issued for this server');
    }
  },
};

const gate = requireBearerAuth({
  verifier,
  expectedResource: RESOURCE,
  requiredScopes: ['support:read'],
  resourceMetadataUrl: new URL(PRM_PATH, RESOURCE).href,
});

// One fresh McpServer per request: there is no session to keep.
const mcp = createMcpHandler(({ authInfo }) => buildServer(authInfo), { legacy: 'stateless' });

async function handle(request: Request): Promise<Response> {
  const url = new URL(request.url);
  if (url.pathname === PRM_PATH) {
    return Response.json({
      resource: RESOURCE.href,
      authorization_servers: [ISSUER],
      scopes_supported: ['support:read'],          // minimal set; refunds:write is requested by step-up
      bearer_methods_supported: ['header'],
    });
  }
  if (url.pathname !== RESOURCE.pathname) return new Response('Not found', { status: 404 });
  const auth = await gate(request);
  if (auth instanceof Response) return auth;       // 401/403 with WWW-Authenticate already set
  return mcp.fetch(request, { authInfo: auth });
}

createServer(toNodeHandler({ fetch: handle })).listen(8080);

When we called support_issue_refund with a token holding only support:read, the handler returned 403 with WWW-Authenticate: Bearer error="insufficient_scope", error_description="Insufficient scope", scope="refunds:write", resource_metadata="…". That is exactly the shape the spec asks for. The JWKS path and the tenant claim are assumptions about your IdP. Adjust them, and if your IdP issues opaque tokens, use introspection (RFC 7662) instead. Because handle is a web-standard fetch function, the same code runs on Workers, Deno or Bun without the Node adapter.

06Remote vs local MCP servers

The decision

Local (stdio) Local (HTTP on 127.0.0.1) Remote (Streamable HTTP)
Runs where Child process of the client User's machine, long-lived Your infrastructure
Credentials Environment variables. The spec says stdio SHOULD NOT use the OAuth flow Environment, or OAuth OAuth 2.1, per user
Distribution npx/uvx/container. Every user updates separately Same Deploy once. Everyone gets the fix
Good for Filesystem, local git, IDE state, dev databases, CLIs Several clients sharing one local process SaaS data, shared systems, anything multi-user
Main risks Supply chain. It runs with the user's full privileges DNS rebinding (bind to localhost, MUST validate Origin) A public endpoint: auth, rate limits, tenancy
Observability Whatever the user's client logs Same Yours: traces, metrics, audit log

Our default: remote, unless the tool has to touch the user's machine. A remote server is one deployment you can patch, observe, rate-limit and revoke. A local server is a fleet of copies you can't see, each running with whatever credentials the user pasted into a config file. If the data is already behind an API, make the MCP server remote too.

Local is the right call for tools that operate on local state, such as a repository, a running dev server or a desktop app, and for developer tools where requiring a network round trip and a login would be absurd. If you ship one:

  • On stdio, stdout is the protocol channel. One stray console.log corrupts the stream. Log to stderr, which the spec now recommends in place of the deprecated Logging feature.
  • Pin and sign what you publish. Publish server.json to the MCP Registry (still in preview) under a namespace you own, so users can check that the server comes from you.
  • Read credentials from the environment and request the narrowest token your upstream allows.
ts
// src/stdio.ts
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { buildServer } from './tools.js';

// Local: credentials come from the environment, never from OAuth.
// stdout is the protocol channel. Log to stderr only.
serveStdio(() => buildServer({ token: '', clientId: 'local', scopes: ['support:read', 'refunds:write'], extra: { tenant: process.env.SUPPORT_TENANT } }));

The same buildServer serves both transports. That is the reason to keep tool definitions separate from transport code.

Running remote servers in production

Statelessness is the biggest operational change of 2026. Any instance can answer any request, so:

Diagram
             ┌──────────── edge / WAF ─────────────┐
 clients ──► │ route + rate-limit on Mcp-Method,    │──► MCP instances (stateless, N replicas)
             │ Mcp-Name; reject header/body mismatch│        │  verify JWT locally (cached JWKS)
             └──────────────────────────────────────┘        │  tool handlers ──► domain APIs / DB
                                                             │  handles (basket_id) ──► Redis/Postgres
                     subscriptions/listen (SSE) ◄─── shared event bus for list_changed (optional)
  • Plain round-robin load balancing works. You need no sticky sessions and no session store for the protocol. State you create yourself, such as handles, belongs in your own datastore and should have a stated time to live.
  • Rate-limit per tool at the edge using Mcp-Name. A destructive tool should have a far lower limit than a search tool.
  • Set X-Accel-Buffering: no on SSE responses if nginx sits in front. The transport spec recommends it, because buffering breaks progress notifications.
  • Propagate trace context. The spec now documents traceparent, tracestate and baggage in _meta, so a tool call can join the same trace as the API calls it makes. The approach is the one in our post on the anatomy of a request.
  • subscriptions/listen needs a shared bus if you run several replicas and emit list_changed. The SDK's default bus is in-process. If your tool list only changes on deploy, you probably don't need this at all.

07How to version an MCP server

Versioning has three separate layers, and teams tend to mix them up.

1. Protocol version. This is negotiated per request. Clients send io.modelcontextprotocol/protocolVersion. You answer or return UnsupportedProtocolVersionError listing what you support. Use the SDK and keep the legacy path on (legacy: 'stateless') until your clients' logs show no 2025-era traffic. The new feature lifecycle policy promises at least twelve months between a feature being deprecated and becoming eligible for removal, which gives you a predictable upgrade window.

2. Server version (serverInfo.version). This is informational. Use semver and put it in your logs. No model sees it.

3. The tool contract. This is the layer that actually breaks things. The model, your evals and your users' saved prompts depend on tool names, parameter names and behaviour. Treat it like a public API, with one extra rule: a description change is a behaviour change, because it changes what the model does.

Change Safe? How
Add an optional parameter with a sensible default Yes Ship it, then run evals
Add a new tool Usually Watch for the model choosing it wrongly instead of an existing tool
Rewrite a description Treat as breaking Run your eval set before and after
Rename a tool or parameter Breaking Add the new one, keep the old one with "Deprecated: use X" in its description, remove it after the window
Change semantics under the same name Never Make a new tool
Tighten validation Breaking for some callers Return an actionable isError that explains the new rule

Keep tools/list byte-stable between deploys: deterministic ordering and no timestamps in descriptions. Clients and model providers can then cache it. This matters more than it sounds. A tool list that changes on every request defeats prompt caching on every turn. Our post on building LLM evals covers the regression suite that should gate tool-contract changes.

08The MCP server readiness scorecard

This is the review we run on an MCP server before it reaches users. Score each line 0 (no), 1 (partly) or 2 (yes). Below 28 out of 40, it isn't ready. Any 0 in the bold rows blocks the release, whatever the total.

Tool surface

# Check Score
1 Every tool maps to a task a user would name, not to an endpoint
2 Tool count is justified. Each common task takes 3 calls or fewer
3 Names are namespaced (service_verb_object) and use only [A-Za-z0-9_.-]
4 Each description says when not to use the tool, and which tool to use instead
5 Units, formats and limits appear in the schema, not only in prose
6 Full tools/list is under a token budget you have written down (see below)

Responses and errors

# Check Score
7 Default responses are concise. IDs for follow-up calls are labelled
8 Large results paginate or truncate, and say how to get more
9 Recoverable failures return isError with a concrete next step
10 Bugs and outages surface as real errors and reach alerting
11 outputSchema only where a program reads the result, and results conform

Auth and safety

# Check Score
12 Remote: tokens validated for signature, issuer, expiry and audience = this server's canonical URI
13 No token passthrough to upstream APIs
14 Protected Resource Metadata served. 401s carry resource_metadata
15 Minimal scopes_supported. Destructive tools require step-up scopes
16 Write tools take an idempotency key
17 Annotations set honestly, and permissions enforced on the server regardless
18 Local HTTP: bound to 127.0.0.1 and Origin validated. stdio: nothing written to stdout but protocol

Operations and versioning

# Check Score
19 Per-tool rate limits, metrics (calls, errors, latency, response tokens) and an audit log of writes
20 An eval set runs on every change to a tool name, schema or description

The token budget for check 6. Here is a worked example. The assumptions are labelled; replace them with your own numbers.

  • Anthropic's sample of 58 tools at about 55K tokens works out to roughly 950 tokens per tool on average (55,000 ÷ 58).
  • An endpoint-per-tool server with 30 tools: 30 × 950 ≈ 28,500 tokens of definitions on every model call.
  • An agent run of 20 model turns (assumption) sends those definitions 20 times: 570,000 input tokens per run, before your prompt or any results.
  • At an assumed $3 per million input tokens, that is about $1.71 per run in tool definitions alone, uncached. Prompt caching reduces it a lot, but only if the list is byte-stable, which is check 6's partner.
  • A consolidated server with 6 tools at about 400 tokens each (assumption) costs 2,400 tokens per call, or 48,000 per run: roughly a twelfth of the first, and a much shorter menu to choose from.

Clients that support tool search, which Claude Code enables by default, defer loading definitions and reduce this further. Don't count on it. Your server will be used by clients that don't search.

09Where MCP servers cross into the rest of the stack

An MCP server looks like an AI project, but most of the hard parts belong to other layers. The authorization server is your identity provider, which means Managed IT and Security own audience configuration, scopes and offboarding. The tenancy check in get_customer_context is a data-layer guarantee. If your database enforces it with Postgres row-level security, the tool can't leak across tenants even when the model passes the wrong ID. The edge rules that rate-limit Mcp-Name: support_issue_refund are Cloud & DevOps. And a good set of consolidated tools is mostly the result of a well-designed domain API underneath. Teams that struggle to build good tools usually have an API problem first.

10FAQ

How many tools should an MCP server expose?

As few as cover the tasks you wrote down: often 3–15. There is no spec limit. The cost is tokens on every turn and a less accurate choice of tool. If you need more, split by audience (support vs finance) into separate servers, or vary tools/list by the caller's scopes, which the spec explicitly allows.

Should I wrap my existing REST API one-to-one?

No. Start from the tasks and build tools that call your API underneath. A one-to-one wrapper hands the model the job of orchestration, and it will do that job worse and more expensively than your code would.

Do I need OAuth for an internal MCP server?

If it's remote and touches real data, yes. Treat it like any other internal API. The spec's flow plugs into your existing IdP. Shared static API keys in client configs are hard to rotate, can't be scoped per user and leave no per-user audit trail. For local stdio servers, read credentials from the environment instead.

What does the stateless 2026-07-28 spec mean for an existing server?

If you use an SDK, upgrading is mostly mechanical. The TypeScript and Python v2 SDKs serve both protocol eras from one tool definition. The real work is in any server that kept per-session state: move it into explicit handles passed as tool arguments, with server-side authorisation checks and stated lifetimes. You can drop sticky sessions from your load balancer.

When should I use structuredContent and outputSchema?

When a program, not just the model, reads the result: an orchestrator, a UI, or a code-execution sandbox that processes data before it reaches the model. Anthropic's code execution with MCP example cut one workflow from 150,000 to 2,000 tokens by keeping data out of the context entirely. For tools whose only consumer is the model, a well-written text result is usually enough.

Remote or local for a developer tool?

Local if it operates on the developer's machine: the repo, a running process, the IDE. Remote if it wraps a shared service such as CI, issue tracking or an observability backend. In that case the developer gets OAuth sign-in and automatic updates, and you get logs.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →