Building a Model Context Protocol (MCP) server correctly means applying rigorous API design discipline to a consumer that reasons at runtime rather than reading documentation once.
Overview
- MCP is an open standard (Anthropic, November 2024) that replaces one-off function-calling glue between models and backends with a shared JSON-RPC 2.0 wire format and a fixed set of primitives.
- The architecture separates concerns cleanly: an MCP host (the AI app) embeds an MCP client, which connects to one or more MCP servers, each wrapping exactly one backend system.
- The core design challenge is that your consumer is a language model deciding at runtime which capability to invoke and with what arguments - not a human reading docs or a deterministic client hitting fixed endpoints.
- Three primitives cover everything a server exposes: tools (model-invoked, side-effect-capable actions), resources (host-mediated passive context), and prompts (reusable interaction templates).
- The spec moves fast - pin a version explicitly and negotiate it during
initializerather than assuming today's behavior is permanent.
Key Concepts
Tools vs. Resources vs. Prompts
- Tools: functions the model decides to call with structured, schema-validated arguments; discovered via
tools/list, invoked viatools/call. Can have side effects. - Resources: readable context (files, DB rows, API responses) attached to a conversation under host/application control, not the model's discretion - the right choice for large or sensitive reference data.
- Prompts: parameterized templates a server exposes so hosts standardize common interactions (e.g., a "summarize this ticket" prompt owned by the issue-tracker server).
- Getting tools vs. resources wrong has real consequences: exposing a "read file" as a tool means the model decides when to fetch it (mixed into its reasoning); exposing it as a resource means the host controls entry into context.
Transports: stdio vs. Streamable HTTP
- stdio: server runs as a local subprocess, exchanges newline-delimited JSON-RPC over stdin/stdout. Right for local dev tools, IDE integrations, same-machine use.
- Streamable HTTP: introduced in the 2025-03-26 revision to replace an earlier HTTP+SSE design. A single HTTP endpoint (POST + GET) serves multiple remote clients, with optional SSE for server-to-client streaming. Use when a server must be shared, centrally deployed, or scaled horizontally.
Tool Granularity Trade-off
- Too broad (e.g., one
execute_queryaccepting arbitrary SQL) = maximum flexibility, minimum safety - effectively an unguarded text-to-SQL system. - Too narrow (many near-duplicate tools) = bloated tool list, higher token overhead, higher chance the model picks the wrong tool.
- No universal answer: tolerance for breadth should scale with how expensive a wrong call is (a read-only reporting tool can be looser than one issuing refunds).
Schema Validation and Structured Error Handling
- Tool descriptions and JSON Schemas are the interface - the model reads them the way a new engineer reads sparse docs, so ambiguity there causes wrong or wasted calls.
- Validate inputs with a schema library (Zod in TypeScript, Pydantic/type hints in Python) so malformed arguments never reach downstream systems.
- Return failures as structured results with
isError: true, not thrown exceptions - a crashed transport gives the model nothing to reason about; a structured error gives it something actionable.
// Structured failure the model can act on, instead of an unhandled throw
return {
content: [{ type: "text", text: `Order lookup failed: ${(err as Error).message}` }],
isError: true,
};
Security as a First-Class Concern
- The 2025-06-18 revision classifies HTTP-exposed MCP servers as OAuth 2.0 Resource Servers, requiring Resource Indicators (RFC 8707) so a token issued for one server can't be replayed against another.
- Remote servers: validate bearer tokens on every request, scope narrowly, reject audience mismatches.
- Local stdio servers: sandbox to least-privilege filesystem/network access (e.g., a specific directory tree, never the full home directory).
Observability and Versioning
- Log every tool call with enough context to reconstruct what was asked, supplied, and returned.
- Adopt W3C Trace Context propagation via the protocol's
_metafield early, rather than bolting on custom correlation IDs later. - Evolve schemas additively (new optional fields, not renamed required ones) and rely on
initialize-time capability negotiation so older clients keep working against servers that have gained new tools.
Trade-offs / Caveats
- The spec is versioned and moving fast: the 2025-06-18 revision (most production servers today) differs substantially from the 2026-07-28 release candidate, which drops the
Mcp-Session-Idsession model for explicit state handles passed as tool arguments, adds an extensions framework, and deprecates the Roots, Sampling, and Logging primitives. - Treating an MCP server as stateless like a typical REST handler - then stashing conversation state in the
Mcp-Session-Idheader - creates bugs on reconnects, load-balancer rerouting, or session expiry, since that state is invisible to the model. - There's no universally correct tool granularity; the right choice depends on the cost of a wrong call for that specific operation class.
- Security requirements differ by transport: OAuth/Resource Server rules apply to remote HTTP servers, while stdio servers rely on OS-level sandboxing instead.
Example in Practice
A get_order_status tool (shown in both TypeScript with the official @modelcontextprotocol/sdk + Zod, and Python with FastMCP + Pydantic) illustrates the pattern end to end: a single narrow tool, a regex-constrained orderId argument validated before it reaches the backend, a description stating exactly when the tool should be used, and failures returned as isError: true text rather than thrown exceptions. Both implementations deliberately avoid a generic "call the orders API" passthrough - narrow, tightly-schemed tools trade some flexibility for validation, auditability, and a much smaller blast radius when something goes wrong.
Related topics
- REST and gRPC API design history as the precedent for MCP's decoupling model
- OAuth 2.0 Resource Server architecture and RFC 8707 Resource Indicators
- W3C Trace Context and distributed tracing conventions
- Unix philosophy (small, composable, single-purpose tools) as a design analogy