Skip to content

cd .. && $ cat designing-an-mcp-server.md

Designing an MCP server for a caller you can't trust: tools, skills, gateways and the front door

How to build an MCP server for an agent that is fast, confident and sometimes wrong: one job per tool, errors the model can act on, writes behind a preview, a shipped skill as the manual, a gateway once servers multiply, and a /.well-known/ front door that links everything.

---
commit
d28642c
date
tags
[ ai-agents , mcp , api , security ]
stats
+2,772 words, 13 min read
---

Imagine an API client that reads only your function names and docstrings, never the README. It calls you at three in the morning with total confidence, and about one call in twenty passes a string where you wanted a UUID. You would not hand that client an endpoint called admin that takes action and payload. Yet that is how a lot of MCP servers look.

Most writing about MCP, mine included, looks at it from the agent’s side: who gets to write into the context, and how to stop them (Who writes your agent’s prompt: issues, vendors and the operating system). This piece looks from the other side of the wire. If you are the one building the server, the caller is the unreliable part. The thesis is simple: design your MCP server the way you would design a public API for a client you cannot fix. That means narrow tools, errors that say what to do next, writes that need a second step, a manual the server ships itself, a gateway once there are many servers, and a front door where agents can find all of it.

1. One tool, one job

The cleanest argument this month uses a ledger server (Your MCP tool is an API for an unreliable caller). Version one has a single tool, ledger_admin(action, payload), with an enum of twelve actions and a payload typed as “object, good luck”. The schema cannot validate much. The server has to switch on action before it can check permissions. And the audit log records the same thing every time: ledger_admin. Very helpful during an incident, like a stack trace that only says “something happened in main”.

Version two splits it into five tools: get_invoice, list_invoices, create_refund_request, approve_refund, send_refund. Each has typed inputs (invoiceId: z.string().uuid()), and the read-only ones carry readOnlyHint: true. The author’s rule of thumb is the best line in the piece: if the description needs the phrase “depending on the action”, you have more than one tool.

The naming rules are plain API hygiene: verb_resource, singular for one item, a list_ prefix for collections. And never fetch_data, handle, process or run, which are the utils.js of tool names. Inputs follow the same discipline. Money is amountMinor as an integer plus a currency, never a float. Timestamps are RFC 3339, states are enums, arrays are bounded, and pagination defaults to 20 with a maximum of 50.

The author is upfront about the limits. The comparison is “design accounting, not a measurement”: token use, latency and accuracy were not measured. Five tools with similar names can push the model into choosing by description alone. And for a small internal read-only tool, most of this is overkill. Fair. Nobody needs an idempotency key for get_weather.

2. Errors and output are part of the prompt

A REST client that gets a 400 is read by a developer, who opens the docs. An agent that gets an error reads it as its next instruction. So the error message is a prompt you write, whether you mean to or not.

The ledger example returns errors with a stable code, the actual numbers and a hint about what to do next: AMOUNT_EXCEEDS_LIMIT, 250000 against a limit of 100000, limitMinor: 100000, and the name of the tool that can request approval (Your MCP tool is an API for an unreliable caller). Terminal failures and retryable ones are kept apart, so the agent does not retry a permission error eleven times out of sheer optimism. No stack traces, no internal hostnames, no secrets. That rule is older than MCP, but an agent will quote your stack trace back into a pull request description, which makes it more urgent.

Output size is the other half. Every byte you return lands in someone’s context window. Apple’s new Safari MCP server is a good study here, because it was clearly designed by people who had used other browser servers (Safari’s built-in MCP server for AI coding agents):

  • get_page_content returns a compact text tree of the visible viewport by default, cuts paragraphs at 15 words and gives node IDs only to interactive elements.
  • Output of 32 kB or more goes to a temporary file, and the tool returns the path instead of the contents.
  • Screenshots are always written to disk and returned as a path, never as inline base64.
  • page_interactions takes a batch of clicks and keystrokes and returns a diff of what changed. It falls back to the full page only if more than half of it changed.

That last point is a pattern worth stealing for any server: return what changed, not the whole world again. Seventeen tools in total, compared with 24 in Playwright MCP. It also ties in with an earlier note that agent context is a budget you allocate, not a window you fill (Your AI Agent Has a Context Budget - Treat It Like a CPU Budget).

Safari also shows a small anti-pattern. If you have not enabled remote automation in Safari’s settings, the server still completes the handshake and lists all 17 tools. Then the first navigate_to_url fails with a WebDriver error. Advertising tools you cannot currently serve is a promise the agent will try to cash. Check your preconditions early and say so in the error.

The data you return matters as much as its shape. Pandex serves legislation and case law from 25 countries and the EU, with every past version and citation, so that agents quote the law instead of reconstructing it from training data (Pandex - Official European Law for AI Agents, over MCP). That is the strongest reason to build a server at all: you hold the authoritative source, and the model otherwise guesses.

3. Writes need a second step, and auth is not an argument

Reads can be forgiving. Writes cannot. The ledger post suggests a preview/confirm pair: preview_refund(paymentId, amount) returns a digest and a summary, and send_refund(digest) executes exactly those arguments (Your MCP tool is an API for an unreliable caller). The digest is bound to the arguments, expires quickly and works once. The model can’t “helpfully” change the amount between preview and send, because the send tool takes no amount. Pair that with an idempotency key on every write, so that a retry after a timeout does not refund twice.

Two warnings from the same post deserve bold type:

  • Annotations are labels, not enforcement. readOnlyHint, destructiveHint, idempotentHint and openWorldHint help clients decide what to ask the user about. They do not stop anything. A tool marked read-only that deletes rows is a tool that deletes rows.
  • Never accept tenantId or userId as a tool argument. Derive the principal from the authenticated session. Otherwise the security boundary of your multi-tenant system is whatever string the model types next. Log the principal, the tool, the redacted arguments and the result code, with a correlation ID in errors.

Safari again offers a physical version of the same idea. Control needs an explicit opt-in in the settings. The automated window is isolated from your history, cookies and AutoFill. It shows a banner naming the client and a Stop button. Passkey logins happen with your own finger on Touch ID, not through the agent (Safari’s built-in MCP server for AI coding agents). The human approves the step the agent must not do alone. That is preview/confirm with a fingerprint reader.

4. Ship the manual with the server

Until last week a server had two ways to explain itself: an MCP prompt that the user had to type as a slash command, or a resource with a polite request to read it. Agents mostly ignored both. Being an MCP resource is like being the second page of Google results. What worked was asking users to copy a skill into ~/.claude/skills by hand (Your MCP server can ship its own skill now).

Since 24 November a server can publish skills itself through the io.modelcontextprotocol/skills extension. Claude Code loads them like installed skills and shows them as server:skill (Claude Code v2.1.332). The flow is lean. The client calls server/discover, then skills/list, which returns only the name, a one-line description and a sha256. The full SKILL.md is read only when the skill is selected or the model decides it fits, and it is checked against that hash. Limits in Claude Code: 100 skills per server, 100 KB per text file, 400 KB per skill.

The cost is real. Skills require MCP revision 2026-07-28, which starts with server/discover instead of initialize. The 1.x TypeScript SDK cannot serve it, so the author runs both stacks side by side and routes legacy requests to the old handler. Her Python server needed about 140 hand-written lines plus tests. Her logs also show a nice detail: Claude Code had been calling server/discover since mid-November, about 2,400 times on one server, all answered with a 401. Clients were knocking for weeks before anyone opened the door.

What this means for design: tool descriptions say what a tool does, the skill says how to use the tools together. That is the right split. A 22 KB guide does not belong in twelve tool descriptions that load in every session.

And the security side, which the earlier article already flagged: a shipped skill is a new write path into the agent. The sha256 proves integrity, not intent. The spec itself calls server-served skills “a higher-risk surface than tool calls”. Approval binds to a version, and manual modes ask again when the digest changes, but according to the author’s replies the default auto mode does not. The matching guard, the PreSkillShellCommand hook that can refuse a skill’s inline shell commands, shipped in the same release (Claude Code v2.1.332). As a server author, assume your users will read your skill with the same suspicion they should apply to a stranger’s CLAUDE.md. Keep it short, keep shell out of it, version it visibly.

5. When servers multiply, put a gateway in front

One agent and one server is a weekend project. Five agents and ten servers raise the questions every API platform team has answered before: who may call what, with whose credentials, and where is the log? An MCP gateway gives agents a single endpoint, handles upstream auth including OAuth, filters which tools each caller sees, and logs every call (8 Best MCP Gateways).

The roundup compares eight options, from self-hosted (Bifrost, LiteLLM, IBM ContextForge, Docker MCP Gateway) to managed (Amazon Bedrock AgentCore, Azure API Management, Cloudflare MCP Server Portals, Kong). Two details are worth knowing before you shop. Azure’s MCP policies apply to all tools on a server, so per-tool rules get awkward. Docker runs each server in its own restricted container with signature checks. Treat the numbers with care: Bifrost’s claim that its Code Mode cuts input tokens by 58 to 93 percent comes from the vendor’s own benchmark.

More useful than the ranking are the two questions the author says separate real evaluations from demos:

  1. Can it block a risky call before it runs, for example a DELETE from an agent that may only read?
  2. Can it revoke one agent’s access immediately, without a redeploy?

If the answer to either is “well, sort of”, you have a logging proxy, not a gateway.

Coral pushes the idea one step further (Coral - Open-source gateway where agents write their own tools). Agents do not call tools one at a time. They write short TypeScript programs against the gateway, every call is checked against policy and gets credentials injected, and programs that work can be saved as custom tools. In its example, an agent posts unreviewed pull requests to Slack, needs approval once, and reuses its saved tool the next day. It is the same idea as Claude Code’s Code Mode (Claude Code Just Dropped Code Mode (HOLY SHT)), moved to the server side where policy lives. The interesting consequence for server authors: if callers compose your tools in code, small and predictable tools become even more valuable. Nobody wants to write a program against ledger_admin.

6. The front door: /.well-known/

The last question is how an agent finds your server in the first place. The answer is crowding into one folder. A live catalog now tracks 119 paths under /.well-known/: 63 permanent and 39 provisional IANA registrations, 5 deprecated or obsoleted, and 12 in use but never registered (Well-Known URIs). The agent era is mostly skipping registration. MCP Server Cards point domain discovery at /.well-known/ai-catalog.json, which is not registered. Older attempts like /.well-known/mcp.json and /.well-known/agent.json are superseded but still served, and ChatGPT’s retired ai-plugin.json still lingers on the web like a <marquee> tag (The Well-Known Folder Is Filling Up).

Kin Lane’s follow-up turns the catalog into a recommendation, grouped by what each file says (What Your Agentic Front Door Should Look Like In .well-known):

  • What you have: api-catalog (RFC 9727) pointing at your OpenAPI. “If you only publish one thing”, this is it. Optionally apis.json as a richer index.
  • How an agent works with you: an A2A agent-card.json and an MCP server card, reached through ai-catalog.json.
  • How to get in: oauth-protected-resource (RFC 9728), which MCP clients rely on to find the authorization server, plus oauth-authorization-server or openid-configuration.
  • How to trust you: security.txt and the http-message-signatures-directory behind Web Bot Auth.
  • Outside the folder: llms.txt, robots.txt and an OpenAPI at a stable URL.

The key point is not the list but the linking. Each of these files is reasonable on its own, and together they are a lot to keep current. The ones that exist often go stale (The Well-Known Folder Is Filling Up). Lane’s answer is not fewer standards but files that point at each other: the API catalog links to the OpenAPI, the agent card, the MCP server card and the onboarding descriptor, and the protected resource metadata points at the authorization server. An agent that lands on any one door should find the rest. Hypermedia, it turns out, was right all along. It just needed a client patient enough to follow links.

One caution. This part is advisory. ai-catalog.json is not registered, the MCP discovery story has already changed once, and the article gives no adoption data. Publish api-catalog and oauth-protected-resource now, since both are RFCs. Treat the rest as a bet you may have to move.

7. The checklist

Layer Instead of Do Example
Tools One admin(action, payload) tool One job per tool, verb_resource names, typed inputs Five ledger tools with z.string().uuid()
Errors Free text, stack traces Stable codes, real numbers, a hint naming the next tool AMOUNT_EXCEEDS_LIMIT with limitMinor
Output Full pages, inline base64 Small defaults, diffs, spill large output to a file path Safari’s text tree and 32 kB file spillover
Preconditions Listing tools you cannot serve Check setup early and say so in the error Safari listing 17 tools with automation off
Writes Direct send_refund(amount) Preview returns a digest, send takes only the digest, idempotency keys preview_refund → send_refund(digest)
Auth tenantId as an argument, trusting annotations Principal from the session, annotations as labels only One server per tenant or a session-to-principal map
Manual MCP prompts and resources nobody reads Ship a skill, keep it short, no shell, versioned io.modelcontextprotocol/skills, 5-minute cache
Many servers Every agent with every credential A gateway that blocks before execution and revokes without redeploy Docker MCP Gateway, Coral
Discovery A blog post with the server URL api-catalog and oauth-protected-resource, all files linking to each other /.well-known/ plus llms.txt

The takeaway

None of this is new. Narrow endpoints, typed inputs, actionable errors, idempotent writes, auth from the session, an API gateway, a discovery document: that is the API design book from fifteen years ago. What changed is the client. A human developer forgives a vague endpoint because they read the docs, ask a colleague or open Stack Overflow. An agent does none of that. It reads your tool names, guesses, and acts on the guess at machine speed.

So every shortcut in your server becomes a behaviour in someone’s agent. The good news is that the fix is boring. Write the API you would want to receive at three in the morning from a stranger with root access, and then assume the stranger is the model.

Sources