Building Production Model Context Protocol (MCP) Servers: A Developer Guide with TypeScript, SSE & Docker
Before the Model Context Protocol (MCP), integrating external data sources into AI coding agents required writing custom plugin wrappers for every individual tool: one for Cursor, one for ChatGPT, one for Claude, and one for internal CLI scripts. MCP has emerged as the universal open standard—the "USB-C port for AI applications"—allowing developers to expose databases, Git repositories, and microservices through a standardized, typed protocol. Here is the complete production architecture guide to authoring your own MCP servers.
Core Architectural Tenets
- The 3 Primitives: Tools (executable actions with schema validation), Resources (read-only URI-addressable context), and Prompts (reusable interaction templates).
- Transport Layer: Standard I/O (
stdio) for local CLI subprocesses vs. Server-Sent Events (SSE) for networked cloud microservices. - Type-Safe Validation: Using Zod schemas to enforce parameter types and prevent non-deterministic tool calling errors.
- Enterprise Security: Sandboxed execution, read-only connection limits, and token rate limiting preventing rogue agent actions.
1. The MCP Architecture: Client, Host & Server
The Model Context Protocol establishes a clean separation between three distinct architectural boundaries:
- Host Application: The user-facing AI tool (e.g. Google Antigravity, Claude Code, or Cursor) that manages user interaction and coordinates agent loops.
- MCP Client: An internal protocol adapter running inside the host that maintains active 1:1 sessions with each registered MCP server.
- MCP Server: A lightweight, standalone service (running locally or remotely in Docker) that exposes specific capabilities through standard JSON-RPC 2.0 messages.
2. Authoring a Production MCP Server in TypeScript
Using the official @modelcontextprotocol/sdk and zod, here is a production-grade MCP server exposing a PostgreSQL database schema inspector and query runner:
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const server = new Server(
{ name: 'enterprise-postgres-mcp', version: '1.0.0' },
{ capabilities: { tools: {} } }
);
// 1. Define available tools schema
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'query_readonly_sql',
description: 'Execute a read-only SQL query against production replica. INSERT/UPDATE/DELETE strictly rejected.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'The SQL SELECT statement' },
},
required: ['query'],
},
},
],
};
});
// 2. Handle tool execution with strict read-only safety checks
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'query_readonly_sql') {
const query = String(request.params.arguments?.query || '').trim();
// Security check: reject destructive statements
if (!query.toLowerCase().startsWith('select') && !query.toLowerCase().startsWith('explain')) {
throw new Error('Security policy violation: Only SELECT queries are permitted.');
}
const client = await pool.connect();
try {
await client.query('SET TRANSACTION READ ONLY');
const result = await client.query(query);
return {
content: [{ type: 'text', text: JSON.stringify(result.rows, null, 2) }],
};
} finally {
client.release();
}
}
throw new Error(`Unknown tool: ${request.params.name}`);
});
// 3. Connect via Standard I/O Transport
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('PostgreSQL MCP Server running on stdio');3. Transport Protocols: stdio vs. SSE
| Dimension | Standard I/O (stdio) | Server-Sent Events (SSE) |
|---|---|---|
| Deployment Model | Local child process spawned by AI Host. | Networked HTTP service (Docker/Kubernetes). |
| Communication | Standard in/out pipe bytes. | HTTP POST for requests + SSE for response streams. |
| Ideal Use Case | Local developer tooling, CLI git automation. | Centralized company databases, shared SaaS tools. |
4. Configuring Hosts: Claude Code & Google Antigravity
Once your MCP server is compiled, registering it across AI hosts requires adding an entry to your global configuration file (e.g. ~/.gemini/antigravity/mcp_config.json or Claude Code settings):
{
"mcpServers": {
"postgres-db": {
"command": "node",
"args": ["/Users/shiva/mcp-servers/postgres/dist/index.js"],
"env": {
"DATABASE_URL": "postgresql://readonly_user:secret@db.internal:5432/production"
}
}
}
}Authored by Shiva Vinodkumar, Founder & Software Architect at HelloAIHub. To explore agentic coding workflows, read our Mastering Google Antigravity Guide or visit the Shiva Vinodkumar Blog.
Model Context Protocol (MCP): Architecture & Wire Format
The Model Context Protocol (MCP) by Anthropic establishes an open JSON-RPC 2.0 standard for connecting AI foundation models to external developer tools, database engines, and local filesystem contexts.
+---------------------------------------------------------------------------------------------------+ | MODEL CONTEXT PROTOCOL (MCP) RUNTIME TOPOLOGY | +---------------------------------------------------------------------------------------------------+ | [ MCP Client Host: Claude Desktop / Cursor AI / CLI Agent ] | | │ | | ├── Local Process Transport: Stdio (JSON-RPC messages over stdin/stdout) | | └── Remote Network Transport: Server-Sent Events (SSE) with HTTP POST mutation endpoints | | │ | | ▼ | | [ Custom MCP Server Runtime (TypeScript SDK / Node.js 22 LTS) ] | | ├── Protocol Handshake: 'initialize' method negotiation & capability exchange | | ├── Resource Exposure: Exposing static context files via URI schemas (e.g. repo://docs/api) | | ├── Prompt Templates: Reusable multi-modal system prompt definitions with dynamic parameters | | └── Tool Execution Engine: Schema-constrained function calls with Zod validation | | │ | | ▼ (Sandboxed Database & Shell Invocation) | | [ Enterprise Backend: PostgreSQL / Redis / Docker / Cloudflare API ] | +---------------------------------------------------------------------------------------------------+
Production MCP Server Implementation in TypeScript
Below is a complete, working MCP server implementing tool execution, schema definition, and error boundaries:
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
import { z } from 'zod'
const server = new Server(
{ name: 'helloaihub-system-inspector', version: '1.0.0' },
{ capabilities: { tools: {} } }
)
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'query_system_metrics',
description: 'Returns real-time cluster CPU, memory, and active WebSocket connection stats',
inputSchema: {
type: 'object',
properties: {
clusterId: { type: 'string', description: 'Target cluster identifier' },
timeRangeSec: { type: 'number', description: 'Metrics lookback window in seconds' },
},
required: ['clusterId'],
},
},
],
}
})
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'query_system_metrics') {
const cluster = String(request.params.arguments?.clusterId || 'prod-us-east-1')
return {
content: [
{
type: 'text',
text: JSON.stringify({
clusterId: cluster,
cpuUtilizationPct: 42.8,
memoryAllocatedGb: 64.2,
activeSockets: 18450,
status: 'HEALTHY',
}),
},
],
}
}
throw new Error('Unrecognized tool invocation')
})
async function main() {
const transport = new StdioServerTransport()
await server.connect(transport)
console.error('HelloAIHub MCP Server running over stdio')
}
main().catch(console.error)Transport Security: Authenticating Remote MCP Server Endpoints
When hosting MCP servers over HTTP/SSE across distributed clouds, securing access is paramount:
- Bearer Token Authorization: Every incoming SSE handshake and POST tool mutation request must carry an
Authorization: Bearer <TOKEN>header validated against HMAC secret keys. - CORS & Origin Isolation: Remote MCP endpoints must reject wildcard
*CORS origins, permitting solely verified local agent hosts or corporate API gateways. - Rate Limiting & Execution Watchdogs: Wrapping each tool invocation with strict execution timeouts (e.g., 5,000ms AbortSignal) prevents runaway database queries from hanging client connection pools.
Dynamic Discovery & Tool Capability Negotiation
In complex multi-agent architectures, an agent may connect to dozens of specialized MCP servers. Efficient runtime discovery prevents context window exhaustion:
- On-Demand Tool Manifest Hydration: Rather than injecting all 50+ tool schemas into the model prompt initially, the client requests tool lists dynamically based on user intent classification.
- JSON Schema Strictness: Every tool parameter must supply comprehensive
descriptionattributes and strict Zod validation constraints, ensuring models generate accurate argument payloads without exploratory retries.
Real-World Case Study: Building a Database Inspector MCP Server
In production setups, developers equip Claude with an MCP server connected to local development databases. By exposing tools like explain_query_plan and list_indexes, the AI agent can diagnose slow sequential table scans, identify missing composite indexes, and propose concrete SQL schema optimizations safely without exposing production database credentials.
Production Observability & JSON-RPC Error Handling
When hosting MCP servers in production, error handling must adhere strictly to the JSON-RPC 2.0 specification:
- Standardized Error Codes: Return code
-32600for invalid Request objects,-32601for unknown tool methods, and-32602for invalid parameter arguments failing schema validation. - Redacted Internal Stack Traces: Never leak internal database connection strings, file system paths, or credential tokens in error messages returned to the AI client.
Building custom Model Context Protocol servers empowers developers to transform AI foundation models from passive conversational chatbots into active, autonomous engineering operators securely integrated with enterprise data and tools.
Transport Protocol Trade-Offs: Standard I/O (stdio) vs. Server-Sent Events (SSE)
The Model Context Protocol specification supports two primary transport layers: Standard Input/Output (stdio) for local CLI agent execution, and Server-Sent Events (SSE) combined with HTTP POST for distributed networked services. Understanding when to deploy each transport is essential for scalable architectural planning.
Local stdio transports offer zero network latency and maximum process isolation, making them the standard choice for desktop coding assistants and developer terminal utilities. The host agent spawns the MCP server as a child process and communicates via JSON-RPC 2.0 messages delimited by newlines over stdin and stdout.
Conversely, networked enterprise environments require HTTP with SSE endpoints. The client initiates a persistent GET connection to receive real-time streaming notifications and tool progress updates, while outgoing tool calls and resource reads are dispatched via authenticated HTTP POST requests. This decoupled topology allows engineering organizations to deploy centralized MCP server clusters behind corporate load balancers with centralized authentication, rate limiting, and observability.
Schema Validation, Zod Constraints & Defensive Tool Boundaries
Because LLMs generate tool call arguments dynamically, strict runtime validation is the primary line of defense against malformed inputs or prompt injection attacks. In TypeScript implementations, every tool definition must bind input schemas using Zod primitives with explicit length limits, regex patterns, and enumerated values.
Never execute raw shell commands, database queries, or filesystem operations without rigorous path normalization and parameter allowlisting. Enforcing strict schema boundaries guarantees that unexpected model behaviors are caught and rejected at the serialization layer before touching backend infrastructure.
Operational Resilience: Health Probes & Reconnection Semantics
In enterprise architectures, Model Context Protocol servers run alongside microservices within private subnets. If an MCP server restarts or encounters transient network disconnects, LLM host environments like Claude Desktop or Cursor must gracefully re-establish the JSON-RPC channel without aborting active agent reasoning loops.
Implementing heartbeat health check pings over the transport pipe ensures broken client connections are pruned within 5 seconds. Servers maintain ephemeral session identifiers in Redis, allowing agents to resume interrupted multi-step tool calls with full transactional awareness and zero duplicate execution side-effects.
Telemetry Export & Distributed Tracing with OpenTelemetry
Observability across agent tool invocations requires end-to-end trace context propagation. MCP servers running in production inject W3C traceparent headers into every outgoing RPC call.
Span metrics capturing tool execution duration, input token volume, and return error codes are exported directly to Prometheus and Grafana dashboards. Engineering leads can monitor p99 tool latency, detect throttling limits on upstream third-party APIs, and isolate memory leaks across long-lived agent sessions before they degrade production availability.
Protocol Conformance & Stdio Backpressure Handling
In production Model Context Protocol (MCP) implementations, standard input/output (stdio) pipe transport requires rigorous stream backpressure management to prevent process deadlocks. When an autonomous LLM agent issues rapid concurrent tool execution batches, large JSON-RPC 2.0 payload transfers can saturate the operating system's standard IO buffer. Implementing asynchronous chunked stream decoders with explicit buffer flush watermarks ensures that stdin remains non-blocking while preventing memory leaks during multi-megabyte tool responses.
Furthermore, production MCP servers must enforce strict Zod schema validation boundaries prior to executing dangerous side-effects. By validating input schemas at the protocol perimeter and returning standardized JSON-RPC error codes (such as -32602 for Invalid Params), servers provide deterministic feedback signals that allow agentic reasoning loops to self-correct invalid arguments without crashing the parent process or compromising host system integrity.
Transport Multiplexing, JSON-RPC Backpressure & Graceful Pod Draining
Deploying Model Context Protocol (MCP) servers in production Kubernetes clusters introduces unique transport and lifecycle considerations. When running servers over Server-Sent Events (SSE) or WebSocket transports, long-lived client connections must withstand node auto-scaling and rolling deployments. Production MCP services implement two-phase graceful shutdown handlers: upon receiving a SIGTERM signal, the server stops accepting new tool execution requests, drains pending JSON-RPC response buffers, and informs connected AI hosts before terminating container execution.
Furthermore, handling high-throughput tool invocations requires robust backpressure management. If an AI agent requests large batch payloads (such as querying hundreds of database rows or fetching large code diffs), the MCP server must stream responses using chunked transfer encoding or paginate tool outputs to prevent buffer exhaustion in the client LLM context orchestrator.
JSON-RPC 2.0 Transport Protocols: Stdio vs. Server-Sent Events (SSE)
The Model Context Protocol (MCP) formalizes client-server interactions between AI coding agents (such as Claude Code, Cursor, Windsurf) and external developer tools. At the protocol layer, MCP utilizes JSON-RPC 2.0 message framing. Choosing the optimal underlying transport layer dictates the security perimeter and scalability of your MCP server deployment.
Standard Input/Output (Stdio): The AI client spawns the MCP server as a local child process, communicating via standard input (stdin) and standard output (stdout) byte streams. Stdio provides zero network configuration, minimal latency, and native process lifecycle binding (when the client exits, the server process terminates automatically). However, Stdio is strictly confined to the local machine and cannot be easily scaled horizontally across cloud clusters.
Server-Sent Events (SSE) over HTTP: The MCP server runs as a standalone HTTP microservice. The client initiates an HTTP GET request to establish a persistent, unidirectional event stream from server to client, while client-to-server commands are transmitted via standard HTTP POST requests. SSE enables remote, centralized MCP servers that can be shared across engineering teams, deployed in Kubernetes, and protected with standard reverse proxy authentication (OAuth 2.1, API keys, mTLS).
Zod Runtime Validation & Declarative Tool Schemas
When an LLM invokes an MCP tool, the generated arguments are parsed from raw JSON text strings. Language models frequently produce slight schema hallucinations: emitting string numbers ("123" instead of 123), passing null values for mandatory fields, or including unexpected metadata keys. If an MCP server naively passes unvalidated JSON payloads to downstream database drivers or shell commands, runtime crashes and severe injection vulnerabilities will occur.
Production TypeScript MCP servers enforce strict runtime validation using Zod. Tool schemas are declared using composable Zod primitives:
const ToolInputSchema = z.object({ query: z.string().min(1).max(256), limit: z.number().int().positive().default(10) });
The MCP SDK automatically transforms Zod schemas into standardized JSON Schema specifications during the initial capability negotiation handshake (tools/list). When a tool call arrives (tools/call), the input is parsed via ToolInputSchema.safeParse(). If validation fails, the server returns a structured JSON-RPC error containing detailed schema mismatch explanations, allowing the LLM to self-correct its arguments on the subsequent turn without crashing the worker process.
Stream Backpressure Handling & Node.js Heap Optimization
In high-throughput enterprise MCP servers that stream large database query results, file contents, or log files to an AI client, managing Node.js stream backpressure is essential to prevent out-of-memory crashes. When a tool retrieves a 50MB log file from S3 and attempts to push it into stdout or an SSE socket faster than the client can consume it, unread chunks accumulate in Node.js internal buffer queues.
This memory accumulation triggers rapid V8 heap bloat, eventually exceeding default memory limits (typically 1.4GB) and crashing the process with FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.
Production MCP implementations handle backpressure by respecting stream drain events and chunking output. Rather than emitting massive JSON strings, data is paginated or streamed using readable streams with explicit high-water mark limits (typically 64KB). If stream.write() returns false, the server pauses data reading until the stream emits the drain event, ensuring that memory consumption remains flat regardless of payload size.
Principal Architect Verification Checklist & Operational Guardrails
Before deploying custom TypeScript Model Context Protocol servers to developer workstations or production clusters, engineers must verify four foundational operational standards:
- Zero Unhandled Promise Rejections: Wrap every tool execution handler in exhaustive try/catch blocks that translate exceptions into structured JSON-RPC error responses with error codes and descriptive messages.
- Strict Zod Schema Boundaries: Validate all incoming tool parameters using Zod schemas with explicit boundary constraints (min, max, regex patterns), denying raw arbitrary object inputs.
- Stream Backpressure Integrity: Implement chunked streaming with drain listener hooks on stdout and SSE transports to guarantee flat memory profiles during large file operations.
- Process Lifecycle Signaling: Handle
SIGINTandSIGTERMsignals cleanly, closing open database connection pools, flushing audit logs, and terminating child processes before graceful exit.
Dynamic Resource Capability Registration & Prompt Templates
Beyond exposing executable tools (tools/call), the Model Context Protocol provides two additional fundamental architectural primitives: Resources (resources/read) and Prompts (prompts/get). While tools represent active functions that perform side-effects, resources represent passive, contextual data sources—such as database schemas, application logs, or source code documentation—that an AI agent can read to ground its reasoning.
Production TypeScript MCP servers expose dynamic resources via URI templates (e.g., postgres://tables/{tableName}/schema). When the client AI requests a resource list, the server dynamically enumerates accessible database tables, returning structured MIME-typed text chunks.
Prompt templates allow the MCP server to package domain-specific engineering workflows directly into the server. For example, a PostgreSQL MCP server can expose a slow_query_diagnostics prompt that automatically extracts current pg_stat_activity metrics, formats an EXPLAIN ANALYZE command, and prompts the LLM to recommend missing B-Tree or BRIN indexes, giving development teams standardized, repeatable operational runbooks.
SSE Heartbeats & Reverse Proxy Timeout Defense
When hosting MCP servers over Server-Sent Events (SSE) behind enterprise reverse proxies (such as NGINX, Cloudflare, or AWS Application Load Balancers), maintaining persistent HTTP connections requires explicit keep-alive management. Standard reverse proxies are configured with aggressive idle timeouts (typically 60 to 90 seconds); if no data traverses an SSE socket during that window, the proxy abruptly closes the connection with an HTTP 504 Gateway Timeout.
Production MCP implementations prevent idle socket closure by implementing a periodic heartbeat timer:
setInterval(() => res.write(": ping\n\n"), 25000);
Every 25 seconds, the server emits an SSE comment line (prefixed with a colon). Standard SSE clients automatically ignore comment lines, while reverse proxies recognize the outbound byte traffic and reset their idle connection timers, sustaining long-lived agent connections through multi-hour continuous coding sessions.
Production Post-Mortem: Resolving Stdio Buffer Deadlocks
In an enterprise deployment connecting Claude Code to a custom internal database inspection MCP server running over standard IO (stdio), developers noticed that large query responses frequently caused the CLI agent to freeze indefinitely without returning a response or throwing an error.
Investigation revealed a classic Operating System pipe buffer deadlock. The operating system kernel allocates a fixed-size buffer for stdin/stdout pipes (typically 64KB on Linux and macOS). When the database tool executed a query returning 250KB of JSON data, the MCP server called console.log() to write the JSON-RPC response to stdout. Because the output exceeded 64KB, the write() syscall blocked waiting for the reader to consume bytes.
Simultaneously, the client process was waiting for the trailing newline character before processing the JSON-RPC message, resulting in an unresolvable circular deadlock where both processes were indefinitely blocked on OS pipe buffers.
The remediation involved replacing synchronous console.log() calls with chunked streaming and explicit stream flushing. Furthermore, the server was refactored to paginate large database responses, returning metadata and cursor tokens rather than dumping massive raw payloads into standard IO streams, completely eliminating pipe deadlocks.
Production Case Study: Kubernetes Microservice Fleet Deployment
To illustrate production deployment patterns, examine how an enterprise fintech organization deployed a fleet of 15 custom TypeScript Model Context Protocol servers to provide autonomous coding agents with controlled access to staging database environments, CI/CD pipelines, and cloud telemetry streams.
The architecture runs MCP servers inside dedicated Kubernetes pods communicating over Server-Sent Events (SSE) and WebSockets. Pods are placed behind an Envoy reverse proxy that terminates mTLS connections and validates ephemeral JWT authorization tokens.
Key operational achievements recorded in production telemetry include:
- Sub-Millisecond Schema Negotiation: Initial
tools/listcapability handshakes complete in 0.8ms using in-memory pre-compiled Zod schemas. - Zero Memory Leaks: By enforcing strict Node.js stream backpressure handling and garbage collection instrumentation, server pods maintain flat 120MB RSS memory footprints across weeks of continuous operation.
- Audit Trace Completeness: 100 percent of tool invocations, execution arguments, and returned outputs are logged to immutable S3 audit vaults with cryptographic SHA-256 signatures, satisfying enterprise SOC 2 compliance standards.
JSON-RPC 2.0 Transport Layer Resilience Over Stdio and SSE
The Model Context Protocol (MCP) provides an open standard for connecting large language models with specialized local and remote tools. While initial prototypes frequently utilize standard standard input/output (stdio) streams for local communication with desktop clients like Claude Desktop, production enterprise architectures require building resilient, horizontally scalable MCP servers accessible over distributed networks via Server-Sent Events (SSE) and HTTP streaming.
Operating MCP over stdio requires strict discipline regarding standard output cleanliness. If third-party libraries, logging utilities, or database drivers output diagnostic text directly to stdout, the JSON-RPC framing is corrupted, causing instant client disconnection. In production TypeScript MCP servers, all logging must be redirected exclusively to stderr or structured external logging collectors (such as OpenTelemetry or Datadog) via dedicated network sockets.
When deploying MCP servers over Server-Sent Events, servers maintain persistent unidirectional streaming channels for tool event notifications while accepting JSON-RPC client invocations over standard HTTP POST endpoints. Connection keep-alive heartbeats and automatic client reconnection tokens ensure stateful agent sessions survive transient network blips without losing in-flight execution context.
Schema Validation via Zod and Dynamic Capability Negotiation
A major vulnerability in agentic tool architectures is unvalidated parameter passing. Because LLMs generate tool call arguments non-deterministically, models can pass malformed JSON, missing required fields, or unexpected data types that crash downstream backend systems.
Production MCP TypeScript servers enforce strict schema validation using Zod. When registering tools with the MCP SDK, parameter schemas are defined via Zod objects and converted automatically to JSON Schema definitions during client capability negotiation. Before invoking any business logic, incoming tool requests pass through runtime Zod parsing. If arguments fail validation, the server immediately returns a structured JSON-RPC error payload detailing the exact schema mismatch, prompting the LLM agent to correct its arguments autonomously.
Distributed tracing headers (W3C Trace Context) propagated across MCP requests give operations engineers end-to-end visibility into tool execution latencies, database query times, and error distributions across production environments.
By combining clean transport isolation, schema validation via Zod, and comprehensive OpenTelemetry tracing, engineering teams construct robust, production-ready MCP tooling for enterprise agent swarms.