TL;DR - Advanced MCP Development
Build production-ready Model Context Protocol (MCP) servers with enterprise authentication, Streamable HTTP transport, structured error recovery, cursor-based pagination, and automated testing. When frontier reasoning models such as Claude Opus 4.6, GPT-5.4, and Gemini 3.1 Pro (compare tool-calling latencies on our LLM Benchmarks hub) orchestrate mission-critical enterprise workflows, your MCP server must guarantee deterministic schema validation, sub-second response times, and zero credential leakage. For foundational concepts, see our MCP Introduction guide.
Key Takeaways
- Streamable HTTP & Async Tasks (
2025-11-25Spec): Production remote MCP servers replace the deprecatedHTTP+SSEtransport with Streamable HTTP (modelcontextprotocol.io), using a single/mcpendpoint (POSTandGET) withMcp-Session-Idstate management, SSE stream resumption (Last-Event-ID), and asynchronous Tasks for background jobs lasting 30 seconds to 15+ minutes. - OAuth 2.1 Resource Server Security: Remote MCP servers operate as OAuth 2.1 Resource Servers (MCP Authorization Spec), publishing Protected Resource Metadata at
/.well-known/oauth-protected-resource(RFC 9728), enforcing PKCE (S256), and supporting Client ID Metadata Documents (CIMD) (client_idas an HTTPS URL). - Context & Latency Engineering: Enforcing cursor-based pagination (
limit: 20, max 4KB to 8KB per tool payload) and in-memory/Redis TTL caching (300s default TTL) cuts downstream API costs by 45% to 70% and prevents multi-megabyte JSON dumps from overflowing a128Kcontext window. - Cross-Pillar Developer Workflow: Validate your tool input schemas with our JSON Schema Validator, model your microservice architecture using our AI System Design Generator, and generate edge-case test suites with our AI Test Case Generator.
Production Architecture Decision: When to Upgrade from stdio to Streamable HTTP (Click to Expand)
- Keep
stdioTransport for single-tenant developer CLI tools, local filesystem/Git inspection, or desktop IDE plugins where zero-network IPC (2ms–8ms latency) is paramount. - Upgrade to Streamable HTTP when deploying multi-tenant organizational MCP servers on AWS ECS/EKS, Cloudflare Workers, or Kubernetes where centralized OAuth 2.1 token validation, horizontal load balancing, and audit logging are required.
| Directory / Module | Architectural Responsibility | Production Best Practice |
|---|---|---|
src/index.ts & src/server.ts | Server bootstrap & transport binding (StdioServerTransport or StreamableHTTPServerTransport) | Support graceful SIGTERM shutdown and route all logs to stderr |
src/tools/ (query.ts, action.ts) | Tool definitions, Zod input validation, and structured isError responses | Cap single tool output at 2,000 tokens; use cursor pagination |
src/services/api-client.ts | Upstream REST/GraphQL/SQL client with retry, timeout, and circuit breaking | Enforce 5,000ms–10,000ms socket timeouts and Retry-After backoff |
src/utils/ (auth.ts, pagination.ts, errors.ts) | OAuth 2.1 token verification, cursor encoding, and typed error classes | Refresh OAuth tokens 300 seconds before expiration |
src/types/index.ts & tests/ | Shared TypeScript interfaces plus unit and MCP Inspector integration suites | Achieve 90%+ branch coverage on schema validation and error paths |
Prerequisites
Before building advanced production MCP servers, ensure your engineering environment and foundational knowledge cover these core requirements:
- ✓ Completed Building Your First MCP Server and tested a basic tool handler with
@modelcontextprotocol/inspector - ✓ Proficient with TypeScript 5.x (Node.js v20/v22 LTS) or Python 3.11+ (
FastMCPandasyncio) - ✓ Understand asynchronous concurrency, HTTP status codes (
401,403,429,503), and OAuth 2.1 bearer token flows - ✓ Have a target internal API, database cluster, or SaaS service ready to integrate
Enterprise Deployment Topologies
| Deployment | Description | Typical Latency & Scaling Profile |
|---|---|---|
Local (stdio) | Traditional npx / uvx child process spawned by desktop IDE | 2ms–8ms IPC latency; single-user local machine |
| AWS Managed (ECS/EKS) | Containerized Streamable HTTP MCP clusters behind ALB / API Gateway | 15ms–45ms VPC latency; auto-scales to 1,000+ concurrent sessions |
| Docker Containers | Immutable, rootless container images with read-only bind mounts | 5ms–12ms local bridge latency; reproducible CI/CD execution |
| Kubernetes + MCP Gateway | Multi-server federated gateway with centralized OAuth 2.1 and RBAC | 20ms–60ms cluster latency; enterprise multi-team governance |
Project Structure
A maintainable production MCP server separates protocol transport wiring (src/index.ts, src/server.ts) from domain business logic (src/services/api-client.ts), tool schema validation (src/tools/), and cross-cutting utilities (src/utils/). As your server grows from 2 tools to 20+ tools, keeping all handlers in a single monolithic index.ts file makes unit testing impossible and causes merge conflicts across engineering teams. By isolating each tool and resource into its own module with dedicated Zod schemas and unit tests (tests/tools.test.ts), you can test business logic in under 50ms without spinning up a full MCP transport. For broader architectural patterns on structuring AI backend services, see our Building Your First AI Application guide.
Recommended Layout
| Path | Purpose | Key Exports & Contents |
|---|---|---|
src/index.ts | CLI / HTTP entrypoint | Initializes StdioServerTransport or StreamableHTTPServerTransport and binds process signals |
src/server.ts | MCP Server factory | Exports createServer() registering ListTools, CallTool, and ListResources handlers |
src/tools/ (index.ts, search.ts, create.ts) | Modular tool handlers | Exports typed Tool schemas and validated execution handlers |
src/resources/items.ts | URI resource providers | Handles resources/list and resources/read for static/dynamic datasets |
src/services/api-client.ts | Upstream HTTP/DB client | Encapsulates fetch calls, connection pooling, retries, and response parsing |
src/utils/ (auth.ts, pagination.ts, errors.ts) | Shared infrastructure | OAuth 2.1 token management, cursor pagination, and McpError subclasses |
tests/ (tools.test.ts, integration.test.ts) | Automated test suite | Jest / Vitest unit tests and full JSON-RPC request/response integration tests |
Package.json Setup
{
"name": "mcp-server-myservice",
"version": "1.0.0",
"description": "MCP server for MyService API",
"main": "dist/index.js",
"bin": {
"mcp-server-myservice": "dist/index.js"
},
"scripts": {
"build": "tsc",
"dev": "ts-node src/index.ts",
"test": "jest",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.0.0",
"jest": "^29.0.0"
}
}Authentication Patterns
Authentication is the single most critical security boundary for production MCP servers. In local stdio deployments, credentials should be injected exclusively through the host configuration’s env block and validated at server startup (getApiKey()), failing fast with a descriptive configuration message if missing. In remote Streamable HTTP deployments under the 2025-11-25 MCP specification, your MCP server acts as an OAuth 2.1 Resource Server (RFC 9728) that validates incoming Authorization: Bearer <token> headers, publishes Protected Resource Metadata at /.well-known/oauth-protected-resource, and proactively refreshes upstream access tokens 300 seconds (5 minutes) before expiry so long-running agentic workflows never fail mid-task. For related concepts on securing backend AI integrations, see the Building Your First AI Application guide and our MCP Security & Hardening Guide.
Pattern 1: API Key from Environment
// src/utils/auth.ts
export function getApiKey(): string {
const apiKey = process.env.MYSERVICE_API_KEY;
if (!apiKey) {
throw new Error(
"MYSERVICE_API_KEY environment variable is required"
);
}
return apiKey;
}
// Usage in API client
import { getApiKey } from "./utils/auth";
export class ApiClient {
private apiKey: string;
constructor() {
this.apiKey = getApiKey();
}
async request(endpoint: string, options: RequestInit = {}) {
return fetch(`https://api.myservice.com${endpoint}`, {
...options,
headers: {
"Authorization": `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
...options.headers,
},
});
}
}Pattern 2: OAuth Token Refresh
// src/utils/auth.ts
interface TokenData {
accessToken: string;
refreshToken: string;
expiresAt: number;
}
class AuthManager {
private tokenData: TokenData | null = null;
async getAccessToken(): Promise<string> {
if (!this.tokenData) {
throw new Error("Not authenticated");
}
// Refresh if expires in next 5 minutes
if (Date.now() > this.tokenData.expiresAt - 300000) {
await this.refreshToken();
}
return this.tokenData.accessToken;
}
private async refreshToken(): Promise<void> {
const response = await fetch("https://api.service.com/oauth/token", {
method: "POST",
body: JSON.stringify({
grant_type: "refresh_token",
refresh_token: this.tokenData?.refreshToken,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
}),
});
const data = await response.json();
this.tokenData = {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: Date.now() + data.expires_in * 1000,
};
}
}
export const authManager = new AuthManager();Pattern 3: Multiple Auth Methods
// src/utils/auth.ts
type AuthMethod = "api_key" | "oauth" | "basic";
interface AuthConfig {
method: AuthMethod;
credentials: Record<string, string>;
}
export function getAuthHeaders(config: AuthConfig): Record<string, string> {
switch (config.method) {
case "api_key":
return { "X-API-Key": config.credentials.apiKey };
case "oauth":
return { "Authorization": `Bearer ${config.credentials.token}` };
case "basic":
const encoded = Buffer.from(
`${config.credentials.username}:${config.credentials.password}`
).toString("base64");
return { "Authorization": `Basic ${encoded}` };
}
}Error Handling
Proper error handling transforms a brittle MCP prototype into a self-healing agentic tool provider. In the Model Context Protocol, you must distinguish between protocol-level JSON-RPC errors (such as malformed JSON frames or unknown method names) and tool execution errors (such as 404 Not Found, 429 Too Many Requests, or Zod validation failures). When a tool call fails due to invalid arguments or transient upstream API conditions, return a normal tool result object with isError: true and an actionable text explanation, for example, including the exact Retry-After duration in seconds or suggesting which lookup tool the LLM should call first. This allows the AI model to self-correct its parameters and retry autonomously rather than crashing the MCP transport session. For more on debugging CLI and agentic tool pipelines, see the CLI Tools for AI guide.
Structured Error Types
// src/utils/errors.ts
export class McpError extends Error {
constructor(
message: string,
public code: string,
public statusCode?: number,
public details?: Record<string, unknown>
) {
super(message);
this.name = "McpError";
}
}
export class AuthenticationError extends McpError {
constructor(message: string) {
super(message, "AUTHENTICATION_ERROR", 401);
}
}
export class RateLimitError extends McpError {
constructor(public retryAfter: number) {
super(`Rate limited. Retry after ${retryAfter} seconds`, "RATE_LIMITED", 429);
}
}
export class NotFoundError extends McpError {
constructor(resource: string, id: string) {
super(`${resource} with id ${id} not found`, "NOT_FOUND", 404);
}
}Error Handling in Tools
// src/tools/query.ts
import { McpError, NotFoundError, RateLimitError } from "../utils/errors";
export async function queryTool(params: QueryParams): Promise<ToolResult> {
try {
const result = await apiClient.query(params);
return {
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
};
} catch (error) {
if (error instanceof NotFoundError) {
return {
content: [{ type: "text", text: `Not found: ${error.message}` }],
isError: true,
};
}
if (error instanceof RateLimitError) {
return {
content: [{
type: "text",
text: `Rate limited. Please wait ${error.retryAfter} seconds.`,
}],
isError: true,
};
}
// Unknown error
console.error("Unexpected error:", error);
return {
content: [{ type: "text", text: "An unexpected error occurred" }],
isError: true,
};
}
}API Response Error Handling
// src/services/api-client.ts
async function handleResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const body = await response.text();
switch (response.status) {
case 401:
throw new AuthenticationError("Invalid or expired credentials");
case 403:
throw new McpError("Access forbidden", "FORBIDDEN", 403);
case 404:
throw new NotFoundError("Resource", "unknown");
case 429:
const retryAfter = parseInt(response.headers.get("Retry-After") || "60");
throw new RateLimitError(retryAfter);
default:
throw new McpError(
`API error: ${body}`,
"API_ERROR",
response.status
);
}
}
return response.json();
}Pagination Handling
Unbounded tool responses are the number-one cause of context window exhaustion and runaway token costs in production MCP deployments. If an LLM calls list_items or search_logs against a production database containing 50,000 records and your MCP server serializes the entire dataset into a single JSON string, that single response can inject 100,000+ tokens into the conversation, instantly blowing past the context window or adding $0.50 to $2.00+ per turn. Always enforce strict cursor-based pagination with a conservative default page size (limit: 20, maximum 100) and return an explicit nextCursor token in the response text so the LLM only fetches additional pages when specifically needed.
Cursor-Based Pagination
// src/utils/pagination.ts
interface PaginatedResponse<T> {
items: T[];
nextCursor?: string;
hasMore: boolean;
}
export async function fetchAllPages<T>(
fetchPage: (cursor?: string) => Promise<PaginatedResponse<T>>,
maxPages = 10
): Promise<T[]> {
const allItems: T[] = [];
let cursor: string | undefined;
let pageCount = 0;
do {
const response = await fetchPage(cursor);
allItems.push(...response.items);
cursor = response.nextCursor;
pageCount++;
} while (cursor && pageCount < maxPages);
return allItems;
}Paginated Tool Implementation
// src/tools/list.ts
export const listItemsTool: Tool = {
name: "list_items",
description: "List items with pagination",
inputSchema: {
type: "object",
properties: {
limit: { type: "number", description: "Items per page", default: 20 },
cursor: { type: "string", description: "Pagination cursor" },
},
},
async handler(params: ListParams): Promise<ToolResult> {
const { items, nextCursor, total } = await api.listItems({
limit: params.limit || 20,
cursor: params.cursor,
});
let response = `Found ${total} items.\n\n`;
response += items.map(item => `- ${item.name} (${item.id})`).join("\n");
if (nextCursor) {
response += `\n\nMore items available. Use cursor: ${nextCursor}`;
}
return { content: [{ type: "text", text: response }] };
},
};Streaming Responses
Streaming and incremental progress notifications are essential whenever an MCP tool performs operations that take longer than 2,000ms to 5,000ms, such as multi-page web crawling, large dataset aggregation, container builds, or batch database migrations. Without streaming progress updates or the 2025-11-25 Tasks primitive for asynchronous background execution, MCP clients may hit socket read timeouts (typically 30 to 60 seconds) and terminate the request prematurely. By yielding incremental progress notifications every 10% of completion over StreamableHTTPServerTransport (or notifications/progress frames), you keep the transport connection alive and give the host UI real-time status feedback. For more on managing large context payloads and streaming token budgets, see the Tokens, Context Windows & Parameters guide.
Long-Running Operations
// src/tools/process.ts
import { PassThrough } from "stream";
export const processDataTool: Tool = {
name: "process_large_data",
description: "Process large dataset with progress updates",
async *handler(params: ProcessParams): AsyncGenerator<Partial<ToolResult>> {
const items = await fetchLargeDataset(params.datasetId);
const total = items.length;
let processed = 0;
// Initial progress
yield {
content: [{ type: "text", text: `Processing ${total} items...` }],
};
const results = [];
for (const item of items) {
const result = await processItem(item);
results.push(result);
processed++;
// Progress update every 10%
if (processed % Math.ceil(total / 10) === 0) {
yield {
content: [{
type: "text",
text: `Progress: ${Math.round(processed / total * 100)}%`,
}],
};
}
}
// Final result
yield {
content: [{ type: "text", text: `Completed! Processed ${total} items.` }],
};
},
};Input Validation
Never trust raw tool arguments generated by an LLM without strict runtime schema validation. Even frontier models with 90%+ tool-calling accuracy occasionally hallucinate parameter names, pass stringified numbers ("20" instead of 20), omit required filter fields, or pass out-of-range pagination limits (limit: 99999). Using Zod (z.object()) in TypeScript or Pydantic v2 in Python allows you to enforce length bounds (.min(1).max(500)), numeric constraints (.int().min(1).max(100)), enum allowlists, and ISO-8601 datetime formats before your handler ever touches a database or external REST API. You can also test your generated JSON Schemas interactively in our JSON Schema Validator.
Zod Schema Validation
// src/utils/validation.ts
import { z } from "zod";
export const SearchParamsSchema = z.object({
query: z.string().min(1, "Query is required").max(500),
limit: z.number().int().min(1).max(100).default(20),
filters: z.object({
status: z.enum(["active", "archived", "all"]).optional(),
dateFrom: z.string().datetime().optional(),
dateTo: z.string().datetime().optional(),
}).optional(),
});
export type SearchParams = z.infer<typeof SearchParamsSchema>;
export function validateInput<T>(
schema: z.ZodSchema<T>,
input: unknown
): T {
const result = schema.safeParse(input);
if (!result.success) {
throw new McpError(
`Validation error: ${result.error.message}`,
"VALIDATION_ERROR",
400
);
}
return result.data;
}Validated Tool
// src/tools/search.ts
import { SearchParamsSchema, validateInput } from "../utils/validation";
export const searchTool: Tool = {
name: "search",
description: "Search with validated parameters",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search query" },
limit: { type: "number", description: "Max results" },
filters: { type: "object", description: "Optional filters" },
},
required: ["query"],
},
async handler(rawParams: unknown): Promise<ToolResult> {
const params = validateInput(SearchParamsSchema, rawParams);
const results = await api.search(params);
return formatResults(results);
},
};Caching Strategies
Intelligent caching inside your MCP server dramatically reduces tool execution latency (dropping repeated API lookups from 350ms–800ms down to under 1ms) and protects upstream SaaS APIs from rate-limit exhaustion (HTTP 429). During multi-turn agentic debugging or research sessions, an LLM frequently calls the same lookup tool (get_item, get_schema, get_user_profile) multiple times as it refines its reasoning plan. Implementing a lightweight in-memory TTL cache (SimpleCache with a default 300,000ms / 5-minute TTL) for single-instance stdio servers, or a shared Redis cache for horizontally scaled Streamable HTTP servers, can cut redundant external API requests by 45% to 70%. Always pair read caching with targeted cache invalidation (cache.invalidate()) whenever a write or mutation tool executes. For broader infrastructure cost optimization strategies, see the Running LLMs Locally guide.
Simple In-Memory Cache
// src/utils/cache.ts
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
class SimpleCache<T> {
private cache = new Map<string, CacheEntry<T>>();
constructor(private defaultTtl = 300000) {} // 5 minutes
get(key: string): T | undefined {
const entry = this.cache.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expiresAt) {
this.cache.delete(key);
return undefined;
}
return entry.value;
}
set(key: string, value: T, ttl = this.defaultTtl): void {
this.cache.set(key, {
value,
expiresAt: Date.now() + ttl,
});
}
invalidate(pattern?: string): void {
if (!pattern) {
this.cache.clear();
} else {
for (const key of this.cache.keys()) {
if (key.includes(pattern)) {
this.cache.delete(key);
}
}
}
}
}
export const cache = new SimpleCache();Cached API Calls
// src/services/api-client.ts
import { cache } from "../utils/cache";
export async function getItem(id: string): Promise<Item> {
const cacheKey = `item:${id}`;
// Check cache
const cached = cache.get<Item>(cacheKey);
if (cached) return cached;
// Fetch and cache
const item = await fetchItem(id);
cache.set(cacheKey, item);
return item;
}Testing
A production-grade MCP testing strategy combines three verification layers: fast isolated unit tests (tests/tools.test.ts), protocol-level JSON-RPC integration tests (tests/integration.test.ts), and interactive visual debugging with the official @modelcontextprotocol/inspector. Unit tests should mock external HTTP/database dependencies to verify Zod input validation, pagination boundaries, and isError: true formatting in under 100ms. Integration tests instantiate the full Server instance from @modelcontextprotocol/sdk (InMemoryTransport or StdioServerTransport) to confirm that tools/list exposes valid JSON Schemas and tools/call serializes responses accurately. To accelerate test creation, use our AI Test Case Generator, and for automating CI/CD verification pipelines, see the AI-Powered Workflows guide.
Unit Tests
// tests/tools.test.ts
import { searchTool } from "../src/tools/search";
describe("searchTool", () => {
test("returns results for valid query", async () => {
const result = await searchTool.handler({ query: "test" });
expect(result.content).toBeDefined();
expect(result.isError).toBeFalsy();
});
test("handles empty query", async () => {
const result = await searchTool.handler({ query: "" });
expect(result.isError).toBe(true);
});
test("respects limit parameter", async () => {
const result = await searchTool.handler({ query: "test", limit: 5 });
const parsed = JSON.parse(result.content[0].text);
expect(parsed.length).toBeLessThanOrEqual(5);
});
});Integration Tests
// tests/integration.test.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { createServer } from "../src/server";
describe("MCP Server Integration", () => {
let server: Server;
beforeAll(async () => {
server = createServer();
});
test("lists available tools", async () => {
const tools = await server.listTools();
expect(tools.length).toBeGreaterThan(0);
expect(tools.map(t => t.name)).toContain("search");
});
test("executes search tool", async () => {
const result = await server.callTool("search", { query: "test" });
expect(result).toBeDefined();
});
});MCP Inspector Testing
# Install the inspector
npm install -g @modelcontextprotocol/inspector
# Run your server with the inspector
npx mcp-inspector node dist/index.jsPublishing Your MCP
Ready to share your MCP server with the open-source ecosystem or your internal enterprise developer portal? Packaging an MCP server for distribution requires compiling TypeScript down to clean ES2022/Node16 JavaScript (dist/), declaring an executable bin entry in package.json with a #!/usr/bin/env node shebang at the top of dist/index.js, and documenting every required environment variable and tool schema in your README.md. Once published to npm (for TypeScript/Node.js) or PyPI (for Python uvx), developers worldwide can launch your server with zero manual installation via npx -y mcp-server-myservice. For an overview of the broader MCP ecosystem and official registries, see the MCP Introduction guide and the official Linux Foundation AAIF announcement.
Prepare for Publishing
- Update package.json:
{
"name": "mcp-server-myservice",
"version": "1.0.0",
"description": "MCP server for MyService",
"keywords": ["mcp", "myservice", "ai-tools"],
"repository": {
"type": "git",
"url": "https://github.com/yourname/mcp-server-myservice"
},
"license": "MIT",
"files": ["dist", "README.md"]
}- Create comprehensive READMEsections:
# MCP Server for MyService
Connect MyService to AI assistants via MCP.
### Installation
npm install -g mcp-server-myservice
### Configuration (claude_desktop_config.json)
{
"mcpServers": {
"myservice": {
"command": "npx",
"args": ["-y", "mcp-server-myservice"],
"env": {
"MYSERVICE_API_KEY": "your-api-key"
}
}
}
}
### Available Tools
- search: Search for items with cursor pagination
- create: Create a new item with Zod validation
- update: Update an existing item by ID- Publish:
npm publishSubmit to MCP Registry
- Go to the official MCP Registry or community directory at mcp.so
- Submit your server metadata (
server.jsonmanifest, npm/PyPI package name, GitHub repository URL, and required environment variables) - Verify that automated security scanners pass with zero high-severity dependency vulnerabilities
Production Checklist
Before promoting any custom MCP server from local developer testing into enterprise production, run through this operational readiness review across reliability, security hardening, and context-window performance. Ensuring that every tool enforces strict input validation, redacts sensitive PII/credentials from stderr logs, and caps response payload sizes prevents both security incidents and runaway LLM token bills. For broader security considerations when deploying agentic AI tools, see the Understanding AI Safety, Ethics, and Limitations guide and our MCP Security Best Practices.
| Readiness Pillar | Verification Item | Target Production Standard |
|---|---|---|
| Reliability & Error Recovery | Graceful isError: true handling, Zod/Pydantic validation, and Retry-After rate-limit backoff | 100% of tool exceptions caught and returned as structured JSON-RPC results |
| Security & Zero-Trust Auth | OAuth 2.1 Resource Server (RFC 9728) or scoped env secrets; zero hardcoded keys or stdout leaks | 0 secrets in source control; least-privilege read/write token scopes |
| Performance & Context Hygiene | Cursor-based pagination (limit <= 100), TTL caching (300s), and Streamable HTTP progress updates | Single tool response capped under 4KB–8KB (under 2,000 tokens); p95 latency under 500ms |
Summary
Building advanced MCP servers requires:
- ✓ Proper auth handling - API keys, OAuth, refresh
- ✓ Error handling - Structured, informative errors
- ✓ Pagination - Handle large datasets gracefully
- ✓ Validation - Validate all inputs
- ✓ Testing - Unit and integration tests
- ✓ Documentation - Clear usage instructions
2025 Enterprise Options:
- AWS Managed MCP Servers (EKS/ECS preview Nov 2025)
- Docker containerization for MCP components
- Kubernetes orchestration for scaling
- MCP Registry for discovery (Sept 2025 preview)
Key patterns:
- Separate concerns (tools, services, utils)
- Use TypeScript for type safety
- Cache expensive operations
- Stream long-running tasks
- Handle rate limits gracefully
For combining multiple MCP servers, see the MCP Combinations guide. You can also inspect production cloud, database, and security patterns in our AWS MCP Server Guide, Cloudflare MCP Server Guide, MongoDB MCP Server Guide, and MCP Security Best Practices.
Ready to publish?
- Complete documentation
- Comprehensive tests
- Submit to MCP Registry
Congratulations on completing the MCP Library!
Questions about building MCPs? Check the official docs or the MCP Registry.