[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HPY28B6BCAKQVTSYN79JY":3,"skill-same:01M77HPY28B6BCAKQVTSYN79JY":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77HPY28B6BCAKQVTSYN79JY","greenhelix-mcp-server-development",null,"MCP Server Development & Monetization Guide: Build, Publish, and Profit from the Tool Integration Standard. Complete guide to building, publishing, and monetizing MCP servers. Covers the MCP specification, server development patterns, registry publishing, enterprise governance, and business models for the tool integration standard powering 10,000+ servers.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-mcp-server-development\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-mcp-server-development\nversion: \"1.3.1\"\ndescription: \"MCP Server Development & Monetization Guide: Build, Publish, and Profit from the Tool Integration Standard. Complete guide to building, publishing, and monetizing MCP servers. Covers the MCP specification, server development patterns, registry publishing, enterprise governance, and business models for the tool integration standard powering 10,000+ servers.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [mcp, model-context-protocol, tool-integration, agent-infrastructure, monetization, greenhelix, openclaw, ai-agent, guide]\nprice_usd: 49.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - STRIPE_API_KEY\n    primaryEnv: STRIPE_API_KEY\n---\n# MCP Server Development & Monetization Guide: Build, Publish, and Profit from the Tool Integration Standard\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nThe Model Context Protocol has become the standard interface between AI models and external tools. In under eighteen months, the ecosystem has grown from a single Anthropic specification to over 10,000 registered servers, adopted by every major AI platform -- Claude, GPT, Gemini, Copilot, and dozens of open-source frameworks. MCP servers are the new APIs. They are how AI agents read databases, call services, execute code, and interact with the physical world. If you can build an API, you can build an MCP server. If you can build an MCP server, you can monetize it. This guide covers both: the engineering of production-grade MCP servers and the business models that turn them into revenue. It starts with the protocol architecture, moves through implementation in Python and TypeScript, covers advanced patterns like authentication, streaming, and composition, then walks through registry publishing, enterprise governance, monetization strategies, and production operations. Every chapter includes working code. By the end, you will have the knowledge to build, publish, and profit from MCP servers.\n1. [MCP Architecture Deep Dive](#chapter-1-mcp-architecture-deep-dive)\n2. [Building Your First MCP Server](#chapter-2-building-your-first-mcp-server)\n\n## What You'll Learn\n- Chapter 1: MCP Architecture Deep Dive\n- Chapter 2: Building Your First MCP Server\n- Chapter 3: Advanced Server Patterns\n- Chapter 4: Publishing to the MCP Registry\n- Chapter 5: Enterprise MCP Governance\n- Chapter 6: Monetization Strategies\n- Chapter 7: Production Operations\n- Chapter 8: Case Studies\n- What's Next\n\n## Full Guide\n\n# MCP Server Development & Monetization Guide: Build, Publish, and Profit from the Tool Integration Standard\n\nThe Model Context Protocol has become the standard interface between AI models and external tools. In under eighteen months, the ecosystem has grown from a single Anthropic specification to over 10,000 registered servers, adopted by every major AI platform -- Claude, GPT, Gemini, Copilot, and dozens of open-source frameworks. MCP servers are the new APIs. They are how AI agents read databases, call services, execute code, and interact with the physical world. If you can build an API, you can build an MCP server. If you can build an MCP server, you can monetize it. This guide covers both: the engineering of production-grade MCP servers and the business models that turn them into revenue. It starts with the protocol architecture, moves through implementation in Python and TypeScript, covers advanced patterns like authentication, streaming, and composition, then walks through registry publishing, enterprise governance, monetization strategies, and production operations. Every chapter includes working code. By the end, you will have the knowledge to build, publish, and profit from MCP servers.\n\n---\n\n## Table of Contents\n\n1. [MCP Architecture Deep Dive](#chapter-1-mcp-architecture-deep-dive)\n2. [Building Your First MCP Server](#chapter-2-building-your-first-mcp-server)\n3. [Advanced Server Patterns](#chapter-3-advanced-server-patterns)\n4. [Publishing to the MCP Registry](#chapter-4-publishing-to-the-mcp-registry)\n5. [Enterprise MCP Governance](#chapter-5-enterprise-mcp-governance)\n6. [Monetization Strategies](#chapter-6-monetization-strategies)\n7. [Production Operations](#chapter-7-production-operations)\n8. [Case Studies](#chapter-8-case-studies)\n\n---\n\n## Chapter 1: MCP Architecture Deep Dive\n\n### What MCP Actually Is\n\nThe Model Context Protocol is a client-server protocol that standardizes how AI models interact with external data sources and tools. Before MCP, every AI platform had its own way of defining tool interfaces. OpenAI used function calling with JSON Schema. Anthropic used tool use with a similar but incompatible schema. LangChain had its own tool abstraction. Every integration was bespoke. MCP replaces this fragmentation with a single protocol that any client can speak to any server.\n\nThe protocol has three roles:\n\n- **Host**: The application that contains the AI model. Claude Desktop, VS Code with Copilot, a custom LangChain app -- these are hosts. The host manages the lifecycle of MCP connections and mediates between the model and the servers.\n- **Client**: A protocol client that lives inside the host. Each client maintains a one-to-one connection with a single MCP server. The client handles capability negotiation, request routing, and response marshaling.\n- **Server**: A lightweight program that exposes tools, resources, and prompts through the MCP protocol. This is what you build. A server might wrap a database, an API, a file system, a computation engine, or any other capability that an AI model needs to access.\n\nThe separation between host and client matters for security. The host controls which servers the model can access, what permissions each server has, and whether to require human approval for sensitive operations. The client is a protocol implementation detail -- you rarely interact with it directly.\n\n### The Transport Layer\n\nMCP is transport-agnostic. The protocol defines the message format and semantics; the transport defines how those messages move between client and server. Three transports are in common use as of April 2026.\n\n**stdio (Standard Input\u002FOutput)**\n\nThe simplest transport. The host launches the server as a subprocess. Messages flow over stdin and stdout as newline-delimited JSON. stderr is reserved for logging. This is how most local MCP servers work -- Claude Desktop, for example, spawns each configured server as a child process and communicates over pipes.\n\n```\nHost Process\n    |\n    +-- spawns --> Server Process\n    |                  |\n    stdin  \u003C---------> stdout  (JSON-RPC messages)\n    stderr ----------> (logging)\n```\n\nAdvantages: Zero network configuration. No ports to open. No TLS to configure. The operating system handles the IPC. Process isolation is automatic -- if the server crashes, the host detects the broken pipe and can restart it.\n\nDisadvantages: Only works for local servers. Cannot be shared across machines. Cannot be load-balanced. Each host-server pair requires a separate process.\n\nWhen to use: Local development. Personal tools. Servers that access local files or databases. Servers where latency must be minimal (no network hop).\n\n**HTTP with Server-Sent Events (SSE)**\n\nThe original remote transport in the MCP specification. The client connects to the server over HTTP. The server uses Server-Sent Events (SSE) to push notifications and responses back to the client. This transport enables remote servers, shared servers, and server-to-client notifications.\n\nThe connection flow:\n\n1. Client sends HTTP GET to the server's SSE endpoint (typically `\u002Fsse`).\n2. Server responds with `Content-Type: text\u002Fevent-stream` and keeps the connection open.\n3. Server sends an `endpoint` event containing a URL for the client to POST requests to.\n4. Client sends JSON-RPC requests via HTTP POST to that endpoint.\n5. Server sends JSON-RPC responses and notifications via the SSE stream.\n\n```python\n# Simplified SSE transport flow\n# Server side\n@app.get(\"\u002Fsse\")\nasync def sse_endpoint():\n    async def event_stream():\n        yield f\"event: endpoint\\ndata: \u002Fmessages\u002F{session_id}\\n\\n\"\n        while True:\n            message = await outgoing_queue.get()\n            yield f\"event: message\\ndata: {json.dumps(message)}\\n\\n\"\n    return StreamingResponse(event_stream(), media_type=\"text\u002Fevent-stream\")\n\n@app.post(\"\u002Fmessages\u002F{session_id}\")\nasync def handle_message(session_id: str, request: Request):\n    body = await request.json()\n    # Process JSON-RPC request, put response on outgoing_queue\n```\n\nAdvantages: Works over the network. Supports server-to-client push. Compatible with existing HTTP infrastructure (load balancers, proxies, CDNs).\n\nDisadvantages: SSE is unidirectional (server-to-client only), so the client must use a separate HTTP POST channel for requests. This creates two connections per session. Some proxies and firewalls struggle with long-lived SSE connections. Connection resumption after network interruption requires custom logic.\n\nWhen to use: Remote servers behind a web server. Servers that need to push updates. Production deployments where you already have HTTP infrastructure.\n\n**Streamable HTTP**\n\nThe newest transport, introduced in the MCP specification revision of March 2026. Streamable HTTP simplifies the SSE transport by using a single HTTP endpoint for both requests and responses. The client sends a POST request. The server can respond with either a regular JSON response (for simple request-response patterns) or upgrade to SSE for streaming responses and follow-up notifications.\n\n```\nClient                              Server\n  |                                    |\n  |  POST \u002Fmcp                         |\n  |  {\"jsonrpc\":\"2.0\",\"method\":\"...\"}  |\n  |----------------------------------->|\n  |                                    |\n  |  200 OK                            |\n  |  Content-Type: text\u002Fevent-stream   |\n  |  (or application\u002Fjson for simple)  |\n  |\u003C-----------------------------------|\n```\n\nAdvantages: Single endpoint. Backward-compatible with simple HTTP clients. Supports streaming when needed. Easier to deploy behind reverse proxies. No persistent connection required for basic operations.\n\nDisadvantages: Newer, so not all clients support it yet. Streaming mode still has the SSE proxy compatibility issues.\n\nWhen to use: New remote deployments. Servers that need to work with both streaming-capable and simple HTTP clients.\n\n### The Message Format: JSON-RPC 2.0\n\nEvery MCP message is a JSON-RPC 2.0 message. This is not a custom format -- it is the same JSON-RPC used by Ethereum, Language Server Protocol, and dozens of other systems. The format has three message types.\n\n**Request**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"tools\u002Fcall\",\n  \"params\": {\n    \"name\": \"query_database\",\n    \"arguments\": {\n      \"sql\": \"SELECT count(*) FROM users\"\n    }\n  }\n}\n```\n\nThe `id` field correlates requests with responses. The `method` field identifies the operation. The `params` field carries the operation-specific data.\n\n**Response**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"result\": {\n    \"content\": [\n      {\n        \"type\": \"text\",\n        \"text\": \"Query returned 42,531 rows.\"\n      }\n    ]\n  }\n}\n```\n\n**Error Response**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"error\": {\n    \"code\": -32602,\n    \"message\": \"Invalid params\",\n    \"data\": \"Column 'nonexistent' does not exist in table 'users'\"\n  }\n}\n```\n\nStandard JSON-RPC error codes apply: -32700 (parse error), -32600 (invalid request), -32601 (method not found), -32602 (invalid params), -32603 (internal error). MCP adds no custom error codes -- use the standard codes plus descriptive messages and data fields.\n\n**Notification**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"method\": \"notifications\u002Ftools\u002Flist_changed\"\n}\n```\n\nNotifications have no `id` field and expect no response. They are fire-and-forget messages used for events like \"the tool list has changed\" or \"a resource has been updated.\"\n\n### Capabilities Negotiation\n\nWhen a client connects to a server, the first message exchange is capabilities negotiation via the `initialize` method. The client sends its capabilities; the server responds with its own.\n\n```json\n\u002F\u002F Client -> Server\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"initialize\",\n  \"params\": {\n    \"protocolVersion\": \"2025-03-26\",\n    \"capabilities\": {\n      \"roots\": { \"listChanged\": true },\n      \"sampling\": {}\n    },\n    \"clientInfo\": {\n      \"name\": \"claude-desktop\",\n      \"version\": \"1.5.0\"\n    }\n  }\n}\n\n\u002F\u002F Server -> Client\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"result\": {\n    \"protocolVersion\": \"2025-03-26\",\n    \"capabilities\": {\n      \"tools\": { \"listChanged\": true },\n      \"resources\": { \"subscribe\": true, \"listChanged\": true },\n      \"prompts\": { \"listChanged\": true },\n      \"logging\": {}\n    },\n    \"serverInfo\": {\n      \"name\": \"database-server\",\n      \"version\": \"2.1.0\"\n    }\n  }\n}\n```\n\nAfter the server responds, the client sends an `initialized` notification to confirm the handshake is complete. Only then can the client call tools, read resources, or use prompts.\n\nKey fields in the server capabilities:\n\n- `tools`: The server exposes callable tools. `listChanged` means the server will notify the client if the tool list changes at runtime.\n- `resources`: The server exposes readable resources (files, database records, API responses). `subscribe` means the client can subscribe to resource change notifications.\n- `prompts`: The server exposes prompt templates that the model can use.\n- `logging`: The server supports structured logging that the client can consume.\n\nCapabilities negotiation is important because it allows both sides to adapt. A server that exposes only tools does not need to handle resource subscriptions. A client that does not support sampling will never receive sampling requests from the server.\n\n### The Three Primitives: Tools, Resources, and Prompts\n\nMCP servers expose capabilities through three primitives. Understanding which primitive to use for which purpose is the most important design decision you will make.\n\n**Tools**\n\nTools are functions that the AI model can call. They take structured input, perform an action, and return a result. Tools are the most common primitive and the one you will use most often.\n\nA tool has:\n- A name (string, unique within the server)\n- A description (string, used by the model to decide when to call the tool)\n- An input schema (JSON Schema, validated before execution)\n- A handler function (your code that executes when the tool is called)\n\n```python\n@server.tool()\nasync def query_database(sql: str) -> str:\n    \"\"\"Execute a read-only SQL query against the analytics database.\n\n    Use this tool when the user asks about data, metrics, counts,\n    or any question that can be answered with a database query.\n    Only SELECT statements are allowed.\n    \"\"\"\n    if not sql.strip().upper().startswith(\"SELECT\"):\n        raise ValueError(\"Only SELECT queries are allowed\")\n    result = await db.execute(sql)\n    return format_result(result)\n```\n\nTools are model-controlled -- the AI model decides when to call them based on the description and the current conversation context. The host may require human approval before executing a tool call (this is configurable per-server and per-tool).\n\nWhen to use tools: Any operation that has side effects (creating records, sending emails, modifying state). Any computation that the model cannot do itself (database queries, API calls, mathematical operations). Any action where the model needs to act on behalf of the user.\n\n**Resources**\n\nResources are data that the AI model can read. They are identified by URIs and return content in a structured format. Resources are like GET endpoints in a REST API -- they retrieve data without modifying anything.\n\nA resource has:\n- A URI (string, following the `scheme:\u002F\u002Fpath` pattern)\n- A name (string, human-readable)\n- A description (string, optional)\n- A MIME type (string, optional)\n- Content (text or binary, returned when the resource is read)\n\n```python\n@server.resource(\"config:\u002F\u002Fapp\u002Fsettings\")\nasync def get_app_settings() -> str:\n    \"\"\"Current application configuration settings.\"\"\"\n    settings = await load_settings()\n    return json.dumps(settings, indent=2)\n```\n\nResources can also be dynamic using URI templates:\n\n```python\n@server.resource(\"db:\u002F\u002Ftables\u002F{table_name}\u002Fschema\")\nasync def get_table_schema(table_name: str) -> str:\n    \"\"\"Schema definition for a database table.\"\"\"\n    schema = await db.get_schema(table_name)\n    return json.dumps(schema, indent=2)\n```\n\nResources are application-controlled -- the host application decides when to expose them to the model, often by attaching them to the conversation context. The model does not call resources directly; instead, the host includes resource content in the model's context window.\n\nWhen to use resources: Configuration data. Reference documentation. Database schemas. File contents. Anything the model needs to read but should not modify.\n\n**Prompts**\n\nPrompts are reusable templates that the AI model or the user can invoke. They generate structured message sequences that set up the model's context for a specific task.\n\nA prompt has:\n- A name (string, unique within the server)\n- A description (string, explains what the prompt does)\n- Arguments (list of named parameters, some required, some optional)\n- A handler that returns a list of messages\n\n```python\n@server.prompt()\nasync def analyze_table(table_name: str, question: str) -> list:\n    \"\"\"Analyze a database table to answer a specific question.\"\"\"\n    schema = await db.get_schema(table_name)\n    sample = await db.execute(f\"SELECT * FROM {table_name} LIMIT 5\")\n    return [\n        {\n            \"role\": \"user\",\n            \"content\": f\"Here is the schema for {table_name}:\\n{schema}\\n\\n\"\n                       f\"Sample data:\\n{sample}\\n\\n\"\n                       f\"Question: {question}\"\n        }\n    ]\n```\n\nPrompts are user-controlled -- the user explicitly selects them (like choosing a slash command). They are useful for workflows that require a specific context setup.\n\nWhen to use prompts: Complex workflows that need specific context. Onboarding sequences. Analysis templates where the model needs schema + sample data + instructions.\n\n### Server Lifecycle\n\nAn MCP server goes through a defined lifecycle:\n\n1. **Initialization**: Client sends `initialize` with its capabilities. Server responds with its capabilities and info. Client sends `initialized` notification.\n2. **Operation**: Client and server exchange requests, responses, and notifications. The client can call tools, read resources, and invoke prompts. The server can send logging messages and change notifications.\n3. **Shutdown**: Client sends a shutdown request or closes the transport. The server cleans up resources and exits.\n\nFor stdio servers, the lifecycle is tied to the process lifetime. When the host terminates the subprocess, the server is gone. For HTTP servers, sessions can persist across multiple HTTP connections, and the server process can serve multiple clients simultaneously.\n\nThe lifecycle matters for resource management. If your server opens database connections, file handles, or network sockets during initialization, it must close them during shutdown. The Python and TypeScript SDKs provide lifecycle hooks for this purpose.\n\n```python\nfrom contextlib import asynccontextmanager\nfrom mcp.server import Server\n\n@asynccontextmanager\nasync def server_lifespan(server: Server):\n    # Startup: open connections\n    db = await create_db_pool()\n    server.state[\"db\"] = db\n    try:\n        yield\n    finally:\n        # Shutdown: close connections\n        await db.close()\n```\n\n---\n\n## Chapter 2: Building Your First MCP Server\n\n### Environment Setup\n\nYou need Python 3.10 or later for the Python SDK, or Node.js 18 or later for the TypeScript SDK. Both SDKs are actively maintained and track the latest protocol specification.\n\n**Python**\n\n```bash\npip install mcp\n```\n\nThe `mcp` package includes the server framework, all three transports (stdio, SSE, streamable HTTP), and the client library for testing. It pulls in `pydantic` for schema validation and `httpx` for HTTP transport.\n\n**TypeScript**\n\n```bash\nnpm install @modelcontextprotocol\u002Fsdk\n```\n\nThe TypeScript SDK includes the same server framework, transports, and client library.\n\n### A Minimal Python MCP Server\n\nHere is the simplest possible MCP server -- a single tool that adds two numbers:\n\n```python\n\"\"\"minimal_server.py -- A minimal MCP server with one tool.\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"calculator\")\n\n@server.tool()\nasync def add(a: float, b: float) -> str:\n    \"\"\"Add two numbers together.\n\n    Use this tool when the user asks you to add, sum, or total\n    two numeric values.\n    \"\"\"\n    result = a + b\n    return str(result)\n\nif __name__ == \"__main__\":\n    server.run(transport=\"stdio\")\n```\n\nThat is 15 lines of code. Let us break down what each part does.\n\n`FastMCP(\"calculator\")` creates a server instance with the name \"calculator\". This name appears in capabilities negotiation and helps the client identify the server.\n\n`@server.tool()` registers the decorated function as a tool. The function name becomes the tool name. The docstring becomes the tool description. The function signature is automatically converted to a JSON Schema input schema -- `a: float, b: float` becomes:\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"a\": { \"type\": \"number\" },\n    \"b\": { \"type\": \"number\" }\n  },\n  \"required\": [\"a\", \"b\"]\n}\n```\n\nThe return type `str` means the tool returns text content. MCP tools always return content blocks -- text, images, or embedded resources. The SDK handles wrapping your string return value into the proper content block format.\n\n`server.run(transport=\"stdio\")` starts the server using the stdio transport. It reads JSON-RPC messages from stdin and writes responses to stdout.\n\n### Running and Testing Locally\n\n**With Claude Desktop**\n\nAdd the server to your Claude Desktop configuration file (`claude_desktop_config.json`):\n\n```json\n{\n  \"mcpServers\": {\n    \"calculator\": {\n      \"command\": \"python\",\n      \"args\": [\"\u002Fpath\u002Fto\u002Fminimal_server.py\"]\n    }\n  }\n}\n```\n\nRestart Claude Desktop. The calculator tool will appear in the tools list. Ask Claude \"What is 17.5 plus 23.8?\" and it will call the `add` tool.\n\n**With the MCP Inspector**\n\nThe MCP Inspector is a web-based debugging tool that connects to your server and lets you interact with it directly:\n\n```bash\nnpx @modelcontextprotocol\u002Finspector python minimal_server.py\n```\n\nThis opens a browser interface where you can see the server's capabilities, call tools manually, browse resources, and view the raw JSON-RPC messages.\n\n**With the Python Client Library**\n\nFor automated testing, use the MCP client library:\n\n```python\n\"\"\"test_minimal_server.py -- Test the calculator server.\"\"\"\n\nimport asyncio\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\nasync def test_add():\n    server_params = StdioServerParameters(\n        command=\"python\",\n        args=[\"minimal_server.py\"],\n    )\n    async with stdio_client(server_params) as (read, write):\n        async with ClientSession(read, write) as session:\n            await session.initialize()\n\n            # List tools\n            tools = await session.list_tools()\n            assert len(tools.tools) == 1\n            assert tools.tools[0].name == \"add\"\n\n            # Call the add tool\n            result = await session.call_tool(\"add\", {\"a\": 17.5, \"b\": 23.8})\n            assert result.content[0].text == \"41.3\"\n\nasyncio.run(test_add())\n```\n\n### A TypeScript MCP Server\n\nThe equivalent server in TypeScript:\n\n```typescript\n\u002F\u002F minimal_server.ts -- A minimal MCP server with one tool.\n\nimport { McpServer } from \"@modelcontextprotocol\u002Fsdk\u002Fserver\u002Fmcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol\u002Fsdk\u002Fserver\u002Fstdio.js\";\nimport { z } from \"zod\";\n\nconst server = new McpServer({\n  name: \"calculator\",\n  version: \"1.0.0\",\n});\n\nserver.tool(\n  \"add\",\n  \"Add two numbers together. Use this tool when the user asks you to add, sum, or total two numeric values.\",\n  {\n    a: z.number().describe(\"First number\"),\n    b: z.number().describe(\"Second number\"),\n  },\n  async ({ a, b }) => ({\n    content: [{ type: \"text\", text: String(a + b) }],\n  })\n);\n\nasync function main() {\n  const transport = new StdioServerTransport();\n  await server.connect(transport);\n}\n\nmain();\n```\n\nThe TypeScript SDK uses Zod for schema definition instead of Python type hints. The structure is the same: create a server, register tools, connect a transport.\n\n### Defining Tools with Schemas\n\nReal tools need more sophisticated input schemas. Here is a database query tool with proper validation:\n\n```python\n\"\"\"db_server.py -- MCP server for database access.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"database\")\n\n# Allowed tables for security\nALLOWED_TABLES = {\"users\", \"orders\", \"products\", \"analytics\"}\n\n# Maximum rows to return\nMAX_ROWS = 1000\n\n@server.tool()\nasync def query_database(\n    sql: str,\n    max_rows: int = 100,\n    format: str = \"table\",\n) -> str:\n    \"\"\"Execute a read-only SQL query against the analytics database.\n\n    Use this tool to answer questions about users, orders, products,\n    or analytics data. Only SELECT statements are allowed.\n    Dangerous operations (DROP, DELETE, UPDATE, INSERT) are blocked.\n\n    Args:\n        sql: The SQL query to execute. Must be a SELECT statement.\n        max_rows: Maximum number of rows to return (1-1000, default 100).\n        format: Output format -- \"table\" for ASCII table, \"csv\" for CSV,\n                \"json\" for JSON array.\n    \"\"\"\n    # Validate SQL\n    normalized = sql.strip().upper()\n    if not normalized.startswith(\"SELECT\"):\n        raise ValueError(\"Only SELECT queries are allowed\")\n\n    dangerous = [\"DROP\", \"DELETE\", \"UPDATE\", \"INSERT\", \"ALTER\", \"TRUNCATE\"]\n    for keyword in dangerous:\n        if keyword in normalized:\n            raise ValueError(f\"Dangerous keyword '{keyword}' is not allowed\")\n\n    # Validate max_rows\n    max_rows = min(max(1, max_rows), MAX_ROWS)\n\n    # Validate format\n    if format not in (\"table\", \"csv\", \"json\"):\n        raise ValueError(f\"Invalid format '{format}'. Use table, csv, or json.\")\n\n    # Execute query (using your database connection)\n    result = await execute_query(sql, limit=max_rows)\n\n    # Format output\n    if format == \"json\":\n        return json.dumps(result, indent=2, default=str)\n    elif format == \"csv\":\n        return format_as_csv(result)\n    else:\n        return format_as_table(result)\n\n\n@server.tool()\nasync def list_tables() -> str:\n    \"\"\"List all available database tables and their row counts.\n\n    Use this tool to discover what data is available before\n    writing a query.\n    \"\"\"\n    tables = []\n    for table in sorted(ALLOWED_TABLES):\n        count = await get_row_count(table)\n        tables.append(f\"  {table}: {count:,} rows\")\n    return \"Available tables:\\n\" + \"\\n\".join(tables)\n\n\n@server.tool()\nasync def describe_table(table_name: str) -> str:\n    \"\"\"Get the schema (columns, types, constraints) for a database table.\n\n    Use this tool to understand a table's structure before\n    writing a query against it.\n\n    Args:\n        table_name: The name of the table to describe.\n    \"\"\"\n    if table_name not in ALLOWED_TABLES:\n        raise ValueError(\n            f\"Table '{table_name}' is not available. \"\n            f\"Available tables: {', '.join(sorted(ALLOWED_TABLES))}\"\n        )\n    schema = await get_table_schema(table_name)\n    return format_schema(schema)\n```\n\nKey patterns to notice:\n\n1. **Descriptive docstrings**: The model reads these to decide when to call each tool. Be specific about what the tool does and when to use it. Include examples of the kinds of questions each tool can answer.\n\n2. **Input validation**: Validate every input before using it. MCP validates the JSON Schema types, but you must validate semantic constraints (allowed tables, safe SQL, value ranges).\n\n3. **Default values**: Use sensible defaults so the model does not need to specify every parameter. `max_rows=100` and `format=\"table\"` cover the common case.\n\n4. **Error messages**: Raise `ValueError` with clear messages. The error text is sent back to the model, which can use it to correct its tool call. \"Table 'nonexistent' is not available. Available tables: users, orders, products, analytics\" is much more useful than \"Invalid table.\"\n\n5. **Discovery tools**: Always provide tools that help the model discover what is available. `list_tables` and `describe_table` let the model explore the database schema before writing queries. Without these, the model has to guess table and column names.\n\n### Input Validation Deep Dive\n\nMCP servers receive input from AI models, which means the input is generated, not typed by a human. Models make mistakes -- they hallucinate column names, invent parameters, and sometimes pass the wrong types despite the schema. Robust input validation is not optional.\n\nThe Python SDK validates JSON Schema types automatically. If your tool expects `a: float` and the model sends `\"hello\"`, the SDK returns an error before your code runs. But type validation is just the first layer.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\nimport re\n\n\n@dataclass\nclass ValidationResult:\n    \"\"\"Result of input validation.\"\"\"\n    valid: bool\n    error: Optional[str] = None\n    sanitized_value: Optional[str] = None\n\n\ndef validate_sql(sql: str) -> ValidationResult:\n    \"\"\"Validate a SQL query for safety and correctness.\"\"\"\n    if not sql or not sql.strip():\n        return ValidationResult(False, \"SQL query cannot be empty\")\n\n    normalized = sql.strip()\n    upper = normalized.upper()\n\n    # Must start with SELECT\n    if not upper.startswith(\"SELECT\"):\n        return ValidationResult(False, \"Only SELECT queries are allowed\")\n\n    # Block dangerous keywords\n    dangerous_patterns = [\n        r\"\\bDROP\\b\", r\"\\bDELETE\\b\", r\"\\bUPDATE\\b\", r\"\\bINSERT\\b\",\n        r\"\\bALTER\\b\", r\"\\bTRUNCATE\\b\", r\"\\bEXEC\\b\", r\"\\bEXECUTE\\b\",\n        r\"\\bCREATE\\b\", r\"\\bGRANT\\b\", r\"\\bREVOKE\\b\",\n    ]\n    for pattern in dangerous_patterns:\n        if re.search(pattern, upper):\n            keyword = re.search(pattern, upper).group()\n            return ValidationResult(\n                False, f\"Dangerous keyword '{keyword}' is not allowed\"\n            )\n\n    # Block multiple statements (SQL injection via semicolons)\n    if \";\" in normalized[:-1]:  # Allow trailing semicolon\n        return ValidationResult(\n            False, \"Multiple SQL statements are not allowed\"\n        )\n\n    # Block comments (potential injection vector)\n    if \"--\" in normalized or \"\u002F*\" in normalized:\n        return ValidationResult(False, \"SQL comments are not allowed\")\n\n    return ValidationResult(True, sanitized_value=normalized.rstrip(\";\"))\n\n\ndef validate_table_name(name: str, allowed: set) -> ValidationResult:\n    \"\"\"Validate a table name against an allowlist.\"\"\"\n    if not name or not name.strip():\n        return ValidationResult(False, \"Table name cannot be empty\")\n\n    cleaned = name.strip().lower()\n\n    # Only allow alphanumeric and underscores\n    if not re.match(r\"^[a-z][a-z0-9_]*$\", cleaned):\n        return ValidationResult(\n            False,\n            f\"Invalid table name '{cleaned}'. \"\n            \"Use only lowercase letters, numbers, and underscores.\"\n        )\n\n    if cleaned not in allowed:\n        return ValidationResult(\n            False,\n            f\"Table '{cleaned}' is not available. \"\n            f\"Available: {', '.join(sorted(allowed))}\"\n        )\n\n    return ValidationResult(True, sanitized_value=cleaned)\n```\n\n### Error Handling Patterns\n\nMCP tools should return errors in a way that helps the model recover. There are two kinds of errors:\n\n1. **Tool errors**: The tool executed but the operation failed. Return an error result with `is_error=True`. The model sees the error message and can try again with corrected input.\n\n2. **Protocol errors**: The request itself is malformed. Raise an exception. The SDK converts it to a JSON-RPC error response.\n\n```python\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp.types import TextContent\n\nserver = FastMCP(\"robust-server\")\n\n@server.tool()\nasync def safe_query(sql: str) -> list:\n    \"\"\"Execute a database query with comprehensive error handling.\"\"\"\n    # Validate input\n    validation = validate_sql(sql)\n    if not validation.valid:\n        # Return error as tool result -- model can see it and retry\n        return [TextContent(\n            type=\"text\",\n            text=f\"Error: {validation.error}\\n\\n\"\n                 f\"Please fix the query and try again. \"\n                 f\"Only SELECT statements against these tables \"\n                 f\"are allowed: {', '.join(sorted(ALLOWED_TABLES))}\"\n        )]\n\n    try:\n        result = await execute_query(validation.sanitized_value)\n        return [TextContent(type=\"text\", text=format_result(result))]\n    except DatabaseConnectionError as e:\n        # Transient error -- tell the model to retry\n        return [TextContent(\n            type=\"text\",\n            text=f\"Database connection error: {e}. \"\n                 f\"This is a temporary issue. Please try again.\"\n        )]\n    except QueryTimeoutError as e:\n        # Query too complex -- suggest simplification\n        return [TextContent(\n            type=\"text\",\n            text=f\"Query timed out after {e.timeout}s. \"\n                 f\"Try simplifying the query: use LIMIT, \"\n                 f\"avoid subqueries, or filter with WHERE.\"\n        )]\n    except Exception as e:\n        # Unknown error -- log and return generic message\n        logger.exception(\"Unexpected error executing query\")\n        return [TextContent(\n            type=\"text\",\n            text=\"An unexpected error occurred. \"\n                 \"Please try a different query.\"\n        )]\n```\n\nThe pattern is: validate first, catch specific exceptions, provide actionable error messages that help the model recover. Never return a raw stack trace -- the model cannot do anything useful with it.\n\n### Testing Your Server Locally\n\nTesting MCP servers requires testing at two levels: unit tests for individual tool logic, and integration tests for the full MCP protocol flow.\n\n**Unit Testing Tool Logic**\n\nExtract your tool logic into pure functions that can be tested without the MCP framework:\n\n```python\n\"\"\"test_db_tools.py -- Unit tests for database tool logic.\"\"\"\n\nimport pytest\nfrom db_server import validate_sql, validate_table_name, ALLOWED_TABLES\n\n\nclass TestValidateSQL:\n    \"\"\"Tests for SQL validation.\"\"\"\n\n    def test_valid_select(self):\n        result = validate_sql(\"SELECT * FROM users\")\n        assert result.valid is True\n        assert result.sanitized_value == \"SELECT * FROM users\"\n\n    def test_rejects_empty(self):\n        result = validate_sql(\"\")\n        assert result.valid is False\n        assert \"empty\" in result.error.lower()\n\n    def test_rejects_drop(self):\n        result = validate_sql(\"DROP TABLE users\")\n        assert result.valid is False\n        assert \"DROP\" in result.error\n\n    def test_rejects_delete(self):\n        result = validate_sql(\"DELETE FROM users WHERE id = 1\")\n        assert result.valid is False\n\n    def test_rejects_multiple_statements(self):\n        result = validate_sql(\"SELECT 1; DROP TABLE users\")\n        assert result.valid is False\n        assert \"Multiple\" in result.error\n\n    def test_allows_trailing_semicolon(self):\n        result = validate_sql(\"SELECT * FROM users;\")\n        assert result.valid is True\n\n    def test_rejects_comments(self):\n        result = validate_sql(\"SELECT * FROM users -- drop table\")\n        assert result.valid is False\n\n    def test_case_insensitive_select(self):\n        result = validate_sql(\"select * from users\")\n        assert result.valid is True\n\n\nclass TestValidateTableName:\n    \"\"\"Tests for table name validation.\"\"\"\n\n    def test_valid_table(self):\n        result = validate_table_name(\"users\", ALLOWED_TABLES)\n        assert result.valid is True\n\n    def test_rejects_unknown_table(self):\n        result = validate_table_name(\"secrets\", ALLOWED_TABLES)\n        assert result.valid is False\n        assert \"not available\" in result.error\n\n    def test_rejects_sql_injection(self):\n        result = validate_table_name(\"users; DROP TABLE\", ALLOWED_TABLES)\n        assert result.valid is False\n\n    def test_strips_whitespace(self):\n        result = validate_table_name(\"  users  \", ALLOWED_TABLES)\n        assert result.valid is True\n        assert result.sanitized_value == \"users\"\n```\n\n**Integration Testing with the MCP Client**\n\nFor full protocol testing, use the SDK's client to connect to your server:\n\n```python\n\"\"\"test_integration.py -- Integration tests for the MCP server.\"\"\"\n\nimport asyncio\nimport pytest\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\n\n@pytest.fixture\nasync def session():\n    \"\"\"Create a client session connected to the test server.\"\"\"\n    params = StdioServerParameters(\n        command=\"python\",\n        args=[\"db_server.py\"],\n        env={\"DATABASE_URL\": \"sqlite:\u002F\u002F\u002Ftest.db\"},\n    )\n    async with stdio_client(params) as (read, write):\n        async with ClientSession(read, write) as session:\n            await session.initialize()\n            yield session\n\n\n@pytest.mark.asyncio\nasync def test_list_tools(session):\n    \"\"\"Server exposes the expected tools.\"\"\"\n    tools = await session.list_tools()\n    names = {t.name for t in tools.tools}\n    assert \"query_database\" in names\n    assert \"list_tables\" in names\n    assert \"describe_table\" in names\n\n\n@pytest.mark.asyncio\nasync def test_query_returns_results(session):\n    \"\"\"A valid query returns formatted results.\"\"\"\n    result = await session.call_tool(\n        \"query_database\",\n        {\"sql\": \"SELECT 1 as value\", \"format\": \"json\"},\n    )\n    assert len(result.content) > 0\n    assert \"value\" in result.content[0].text\n\n\n@pytest.mark.asyncio\nasync def test_dangerous_query_rejected(session):\n    \"\"\"A dangerous query returns an error, not a crash.\"\"\"\n    result = await session.call_tool(\n        \"query_database\",\n        {\"sql\": \"DROP TABLE users\"},\n    )\n    assert \"error\" in result.content[0].text.lower() or result.isError\n```\n\n---\n\n## Chapter 3: Advanced Server Patterns\n\n### Stateful Servers: Sessions and Context\n\nMany real-world MCP servers need to maintain state across tool calls. A database server needs a connection pool. A code execution server needs a sandbox with accumulated state. A workflow server needs to track which steps have been completed.\n\nMCP supports stateful servers through server-side session management. Each client connection gets a unique session. The server can store per-session state that persists across tool calls within that session.\n\n```python\n\"\"\"stateful_server.py -- MCP server with session state.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Any\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"workflow\")\n\n\n@dataclass\nclass WorkflowState:\n    \"\"\"Per-session workflow state.\"\"\"\n    steps_completed: list = field(default_factory=list)\n    variables: dict = field(default_factory=dict)\n    current_step: int = 0\n    total_steps: int = 0\n\n\n# Session state storage\n_sessions: dict[str, WorkflowState] = {}\n\n\ndef get_state(session_id: str) -> WorkflowState:\n    \"\"\"Get or create session state.\"\"\"\n    if session_id not in _sessions:\n        _sessions[session_id] = WorkflowState()\n    return _sessions[session_id]\n\n\n@server.tool()\nasync def start_workflow(name: str, steps: list[str]) -> str:\n    \"\"\"Start a new multi-step workflow.\n\n    Args:\n        name: Name of the workflow.\n        steps: List of step descriptions in order.\n    \"\"\"\n    ctx = server.request_context\n    state = get_state(ctx.session.session_id)\n    state.steps_completed = []\n    state.current_step = 0\n    state.total_steps = len(steps)\n    state.variables[\"workflow_name\"] = name\n    state.variables[\"steps\"] = steps\n    return (\n        f\"Workflow '{name}' started with {len(steps)} steps.\\n\"\n        f\"Next step: {steps[0]}\"\n    )\n\n\n@server.tool()\nasync def complete_step(result: str) -> str:\n    \"\"\"Mark the current workflow step as complete.\n\n    Args:\n        result: The result or output of the completed step.\n    \"\"\"\n    ctx = server.request_context\n    state = get_state(ctx.session.session_id)\n\n    if state.current_step >= state.total_steps:\n        return \"Error: No active workflow or all steps already completed.\"\n\n    steps = state.variables.get(\"steps\", [])\n    step_name = steps[state.current_step]\n    state.steps_completed.append({\n        \"step\": step_name,\n        \"result\": result,\n        \"index\": state.current_step,\n    })\n    state.current_step += 1\n\n    if state.current_step >= state.total_steps:\n        return (\n            f\"Step '{step_name}' completed. \"\n            f\"Workflow '{state.variables['workflow_name']}' is now finished. \"\n            f\"All {state.total_steps} steps completed.\"\n        )\n\n    next_step = steps[state.current_step]\n    return (\n        f\"Step '{step_name}' completed ({state.current_step}\u002F{state.total_steps}). \"\n        f\"Next step: {next_step}\"\n    )\n\n\n@server.tool()\nasync def get_workflow_status() -> str:\n    \"\"\"Get the current workflow progress and completed steps.\"\"\"\n    ctx = server.request_context\n    state = get_state(ctx.session.session_id)\n\n    if state.total_steps == 0:\n        return \"No active workflow. Use start_workflow to begin.\"\n\n    lines = [\n        f\"Workflow: {state.variables.get('workflow_name', 'Unknown')}\",\n        f\"Progress: {state.current_step}\u002F{state.total_steps}\",\n        \"\",\n        \"Completed steps:\",\n    ]\n    for step in state.steps_completed:\n        lines.append(f\"  [{step['index'] + 1}] {step['step']}: {step['result']}\")\n\n    if state.current_step \u003C state.total_steps:\n        remaining = state.variables[\"steps\"][state.current_step:]\n        lines.append(\"\")\n        lines.append(\"Remaining steps:\")\n        for i, step in enumerate(remaining):\n            lines.append(f\"  [{state.current_step + i + 1}] {step}\")\n\n    return \"\\n\".join(lines)\n```\n\n### Streaming Responses\n\nFor long-running operations, streaming progress updates to the client prevents timeouts and keeps the user informed. MCP supports streaming through progress notifications and logging.\n\n```python\n\"\"\"streaming_server.py -- MCP server with progress streaming.\"\"\"\n\nimport asyncio\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"data-processor\")\n\n\n@server.tool()\nasync def process_large_dataset(\n    source: str,\n    batch_size: int = 1000,\n) -> str:\n    \"\"\"Process a large dataset in batches with progress updates.\n\n    Args:\n        source: The data source identifier.\n        batch_size: Number of records per batch.\n    \"\"\"\n    ctx = server.request_context\n    total_records = await get_record_count(source)\n    processed = 0\n    errors = 0\n    batches = (total_records + batch_size - 1) \u002F\u002F batch_size\n\n    for batch_num in range(batches):\n        # Send progress notification\n        await ctx.report_progress(\n            progress=batch_num,\n            total=batches,\n        )\n\n        # Send log message for visibility\n        await ctx.info(\n            f\"Processing batch {batch_num + 1}\u002F{batches} \"\n            f\"({processed}\u002F{total_records} records)\"\n        )\n\n        # Process the batch\n        batch_result = await process_batch(source, batch_num, batch_size)\n        processed += batch_result[\"processed\"]\n        errors += batch_result[\"errors\"]\n\n        # Yield control to allow other requests\n        await asyncio.sleep(0)\n\n    return (\n        f\"Processing complete.\\n\"\n        f\"Total records: {total_records}\\n\"\n        f\"Processed: {processed}\\n\"\n        f\"Errors: {errors}\\n\"\n        f\"Batches: {batches}\"\n    )\n```\n\nThe `report_progress` method sends a `notifications\u002Fprogress` message that the client can use to display a progress bar. The `info` method sends a log message that appears in the client's log stream.\n\n### Rate Limiting and Quotas\n\nIf your MCP server wraps a paid API or a resource-constrained backend, you need rate limiting. Implement it as middleware that runs before every tool call.\n\n```python\n\"\"\"rate_limited_server.py -- MCP server with rate limiting.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"rate-limited-api\")\n\n\n@dataclass\nclass RateLimiter:\n    \"\"\"Token bucket rate limiter.\"\"\"\n    max_tokens: int = 60\n    refill_rate: float = 1.0  # tokens per second\n    _buckets: dict = field(default_factory=lambda: defaultdict(lambda: {\"tokens\": 60, \"last\": time.monotonic()}))\n\n    def allow(self, key: str) -> bool:\n        \"\"\"Check if a request is allowed and consume a token.\"\"\"\n        bucket = self._buckets[key]\n        now = time.monotonic()\n        elapsed = now - bucket[\"last\"]\n        bucket[\"tokens\"] = min(\n            self.max_tokens,\n            bucket[\"tokens\"] + elapsed * self.refill_rate,\n        )\n        bucket[\"last\"] = now\n\n        if bucket[\"tokens\"] >= 1:\n            bucket[\"tokens\"] -= 1\n            return True\n        return False\n\n    def tokens_remaining(self, key: str) -> int:\n        \"\"\"Return approximate tokens remaining.\"\"\"\n        bucket = self._buckets[key]\n        now = time.monotonic()\n        elapsed = now - bucket[\"last\"]\n        return int(min(\n            self.max_tokens,\n            bucket[\"tokens\"] + elapsed * self.refill_rate,\n        ))\n\n\n@dataclass\nclass QuotaTracker:\n    \"\"\"Track usage against daily quotas.\"\"\"\n    daily_limit: int = 10000\n    _usage: dict = field(default_factory=lambda: defaultdict(lambda: {\"count\": 0, \"day\": \"\"}))\n\n    def check_and_increment(self, key: str) -> tuple[bool, int]:\n        \"\"\"Check quota and increment usage. Returns (allowed, remaining).\"\"\"\n        today = time.strftime(\"%Y-%m-%d\")\n        record = self._usage[key]\n\n        # Reset on new day\n        if record[\"day\"] != today:\n            record[\"count\"] = 0\n            record[\"day\"] = today\n\n        if record[\"count\"] >= self.daily_limit:\n            return False, 0\n\n        record[\"count\"] += 1\n        remaining = self.daily_limit - record[\"count\"]\n        return True, remaining\n\n\nlimiter = RateLimiter(max_tokens=60, refill_rate=1.0)\nquota = QuotaTracker(daily_limit=10000)\n\n\ndef rate_limit_check(client_id: str) -> None:\n    \"\"\"Check rate limit and quota before processing.\"\"\"\n    if not limiter.allow(client_id):\n        remaining = limiter.tokens_remaining(client_id)\n        raise RuntimeError(\n            f\"Rate limit exceeded. {remaining} tokens remaining. \"\n            f\"Try again in a few seconds.\"\n        )\n\n    allowed, remaining = quota.check_and_increment(client_id)\n    if not allowed:\n        raise RuntimeError(\n            f\"Daily quota of {quota.daily_limit} requests exhausted. \"\n            f\"Resets at midnight UTC.\"\n        )\n\n\n@server.tool()\nasync def translate(text: str, target_language: str) -> str:\n    \"\"\"Translate text to the target language.\n\n    Args:\n        text: The text to translate.\n        target_language: ISO 639-1 language code (e.g., 'es', 'fr', 'de').\n    \"\"\"\n    ctx = server.request_context\n    client_id = ctx.session.session_id\n\n    rate_limit_check(client_id)\n\n    result = await call_translation_api(text, target_language)\n    return result\n```\n\n### Authentication: API Keys and OAuth\n\nRemote MCP servers need authentication. The MCP specification does not mandate a specific auth mechanism -- it relies on the transport layer. For HTTP-based transports, use standard HTTP authentication.\n\n**API Key Authentication**\n\n```python\n\"\"\"auth_server.py -- MCP server with API key authentication.\"\"\"\n\nimport hashlib\nimport os\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"authenticated-api\")\n\n# In production, store hashed keys in a database\nAPI_KEYS = {\n    hashlib.sha256(b\"ghx_key_test_12345\").hexdigest(): {\n        \"client_id\": \"client-1\",\n        \"tier\": \"pro\",\n        \"rate_limit\": 1000,\n    },\n    hashlib.sha256(b\"ghx_key_test_67890\").hexdigest(): {\n        \"client_id\": \"client-2\",\n        \"tier\": \"free\",\n        \"rate_limit\": 100,\n    },\n}\n\n\ndef authenticate(api_key: str) -> dict:\n    \"\"\"Validate an API key and return the client profile.\"\"\"\n    key_hash = hashlib.sha256(api_key.encode()).hexdigest()\n    client = API_KEYS.get(key_hash)\n    if not client:\n        raise PermissionError(\"Invalid API key\")\n    return client\n\n\ndef authorize(client: dict, required_tier: str) -> None:\n    \"\"\"Check if the client has the required tier.\"\"\"\n    tier_order = {\"free\": 0, \"basic\": 1, \"pro\": 2, \"enterprise\": 3}\n    if tier_order.get(client[\"tier\"], 0) \u003C tier_order.get(required_tier, 0):\n        raise PermissionError(\n            f\"This tool requires '{required_tier}' tier. \"\n            f\"Your tier: '{client['tier']}'. \"\n            f\"Upgrade at https:\u002F\u002Fexample.com\u002Fpricing\"\n        )\n```\n\n**OAuth 2.0 Integration**\n\nFor enterprise deployments, OAuth provides delegated authorization. The MCP specification added first-class OAuth support in 2025, allowing servers to act as OAuth resource servers.\n\n```python\n\"\"\"oauth_server.py -- MCP server with OAuth 2.0.\"\"\"\n\nimport httpx\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass OAuthConfig:\n    \"\"\"OAuth 2.0 configuration for the MCP server.\"\"\"\n    issuer: str\n    audience: str\n    jwks_uri: str\n    scopes_required: list[str]\n\n\nasync def validate_oauth_token(\n    token: str,\n    config: OAuthConfig,\n) -> dict:\n    \"\"\"Validate an OAuth 2.0 bearer token.\n\n    Returns the decoded token claims if valid.\n    Raises PermissionError if invalid.\n    \"\"\"\n    import jwt  # PyJWT library\n\n    # Fetch JWKS (in production, cache this)\n    async with httpx.AsyncClient() as client:\n        resp = await client.get(config.jwks_uri)\n        jwks = resp.json()\n\n    # Decode and validate the token\n    try:\n        claims = jwt.decode(\n            token,\n            jwt.PyJWKSet.from_dict(jwks),\n            algorithms=[\"RS256\"],\n            audience=config.audience,\n            issuer=config.issuer,\n        )\n    except jwt.InvalidTokenError as e:\n        raise PermissionError(f\"Invalid OAuth token: {e}\")\n\n    # Check required scopes\n    token_scopes = set(claims.get(\"scope\", \"\").split())\n    required = set(config.scopes_required)\n    missing = required - token_scopes\n    if missing:\n        raise PermissionError(\n            f\"Missing required scopes: {', '.join(missing)}. \"\n            f\"Token scopes: {', '.join(token_scopes)}\"\n        )\n\n    return claims\n```\n\n### Multi-Tool Servers\n\nProduction MCP servers typically expose 5 to 50 tools organized around a domain. The key to a well-designed multi-tool server is grouping related tools and providing discovery tools that help the model navigate the available capabilities.\n\n```python\n\"\"\"multi_tool_server.py -- A multi-tool MCP server for project management.\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"project-manager\")\n\n\n# --- Discovery Tools ---\n\n@server.tool()\nasync def list_capabilities() -> str:\n    \"\"\"List all available capabilities of this project management server.\n\n    Call this tool first to understand what operations are available.\n    \"\"\"\n    return \"\"\"Available capabilities:\n\n    PROJECT MANAGEMENT:\n    - create_project: Create a new project\n    - list_projects: List all projects\n    - get_project: Get project details\n\n    TASK MANAGEMENT:\n    - create_task: Create a task in a project\n    - update_task: Update task status\u002Fassignee\n    - list_tasks: List tasks with filters\n\n    TEAM MANAGEMENT:\n    - add_member: Add a team member to a project\n    - list_members: List project team members\n\n    REPORTING:\n    - project_summary: Get a project status summary\n    - burndown_data: Get sprint burndown data\n    \"\"\"\n\n\n# --- Project Tools ---\n\n@server.tool()\nasync def create_project(\n    name: str,\n    description: str,\n    owner: str,\n) -> str:\n    \"\"\"Create a new project.\n\n    Args:\n        name: Project name (must be unique).\n        description: What this project is about.\n        owner: The agent or person who owns the project.\n    \"\"\"\n    project = await db.create_project(name, description, owner)\n    return f\"Project created: {project['id']} ({name})\"\n\n\n@server.tool()\nasync def create_task(\n    project_id: str,\n    title: str,\n    description: str = \"\",\n    assignee: str = \"\",\n    priority: str = \"medium\",\n) -> str:\n    \"\"\"Create a task within a project.\n\n    Args:\n        project_id: The project to add the task to.\n        title: Short task title.\n        description: Detailed task description.\n        assignee: Who is responsible for this task.\n        priority: low, medium, high, or critical.\n    \"\"\"\n    if priority not in (\"low\", \"medium\", \"high\", \"critical\"):\n        raise ValueError(\n            f\"Invalid priority '{priority}'. \"\n            f\"Use: low, medium, high, or critical.\"\n        )\n    task = await db.create_task(\n        project_id, title, description, assignee, priority\n    )\n    return f\"Task created: {task['id']} ({title}) in project {project_id}\"\n```\n\n### Composing Servers: The Proxy Pattern\n\nSometimes you want to combine multiple MCP servers into one, or add cross-cutting concerns (logging, authentication, rate limiting) to an existing server. The proxy pattern wraps one or more upstream servers behind a single server that the client connects to.\n\n```python\n\"\"\"proxy_server.py -- MCP proxy that composes multiple upstream servers.\"\"\"\n\nimport json\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\nlogger = logging.getLogger(__name__)\n\nserver = FastMCP(\"mcp-proxy\")\n\n\n@dataclass\nclass UpstreamServer:\n    \"\"\"Configuration for an upstream MCP server.\"\"\"\n    name: str\n    command: str\n    args: list[str] = field(default_factory=list)\n    env: dict[str, str] = field(default_factory=dict)\n    tools: list[str] = field(default_factory=list)\n\n\n@dataclass\nclass ProxyRouter:\n    \"\"\"Routes tool calls to the appropriate upstream server.\"\"\"\n    upstreams: dict[str, UpstreamServer] = field(default_factory=dict)\n    tool_to_upstream: dict[str, str] = field(default_factory=dict)\n\n    def register_upstream(self, upstream: UpstreamServer) -> None:\n        \"\"\"Register an upstream server and its tool mappings.\"\"\"\n        self.upstreams[upstream.name] = upstream\n        for tool in upstream.tools:\n            self.tool_to_upstream[tool] = upstream.name\n\n    def get_upstream_for_tool(self, tool_name: str) -> Optional[str]:\n        \"\"\"Find which upstream server handles a given tool.\"\"\"\n        return self.tool_to_upstream.get(tool_name)\n\n    async def forward_call(\n        self,\n        tool_name: str,\n        arguments: dict,\n    ) -> dict:\n        \"\"\"Forward a tool call to the appropriate upstream.\"\"\"\n        upstream_name = self.get_upstream_for_tool(tool_name)\n        if not upstream_name:\n            raise ValueError(f\"No upstream server handles tool '{tool_name}'\")\n\n        upstream = self.upstreams[upstream_name]\n\n        # Log the forwarded call\n        logger.info(\n            \"Forwarding %s to %s with args: %s\",\n            tool_name, upstream_name, json.dumps(arguments)[:200],\n        )\n\n        # In production, maintain persistent sessions\n        params = StdioServerParameters(\n            command=upstream.command,\n            args=upstream.args,\n            env=upstream.env,\n        )\n        async with stdio_client(params) as (read, write):\n            async with ClientSession(read, write) as session:\n                await session.initialize()\n                result = await session.call_tool(tool_name, arguments)\n                return result\n\n\nrouter = ProxyRouter()\n\n# Register upstream servers\nrouter.register_upstream(UpstreamServer(\n    name=\"database\",\n    command=\"python\",\n    args=[\"db_server.py\"],\n    tools=[\"query_database\", \"list_tables\", \"describe_table\"],\n))\n\nrouter.register_upstream(UpstreamServer(\n    name=\"project-manager\",\n    command=\"python\",\n    args=[\"project_server.py\"],\n    tools=[\"create_project\", \"create_task\", \"list_tasks\"],\n))\n\n\n@server.tool()\nasync def route_tool(tool_name: str, arguments: str) -> str:\n    \"\"\"Route a tool call to the appropriate upstream server.\n\n    This is a meta-tool that forwards calls to specialized servers.\n\n    Args:\n        tool_name: The name of the tool to call.\n        arguments: JSON string of the tool arguments.\n    \"\"\"\n    args = json.loads(arguments)\n    result = await router.forward_call(tool_name, args)\n    return result.content[0].text if result.content else \"No result\"\n```\n\n---\n\n## Chapter 4: Publishing to the MCP Registry\n\n### The MCP Registry Ecosystem\n\nThe official MCP registry at registry.modelcontextprotocol.io is the central directory where developers publish and discover MCP servers. As of April 2026, it lists over 10,000 servers across categories like databases, APIs, developer tools, productivity, and AI\u002FML. Clients like Claude Desktop, Cursor, Windsurf, and VS Code with Copilot can install servers directly from the registry.\n\nPublishing to the registry makes your server discoverable. When a user asks an AI client \"Can you help me query my Postgres database?\", the client can search the registry for relevant servers, suggest installation, and connect automatically. This is the distribution channel for MCP servers.\n\n### The Server Manifest: .well-known\u002Fmcp\u002Fserver.json\n\nEvery published MCP server needs a manifest file that describes its capabilities, transport, authentication requirements, and metadata. The manifest follows a standard schema that registries and clients use for discovery and installation.\n\n```json\n{\n  \"schema_version\": \"1.0\",\n  \"server_info\": {\n    \"name\": \"analytics-db\",\n    \"version\": \"2.1.0\",\n    \"description\": \"Query your analytics database using natural language. Supports PostgreSQL, MySQL, and SQLite. Read-only access with SQL injection protection.\",\n    \"author\": {\n      \"name\": \"DataTools Inc\",\n      \"url\": \"https:\u002F\u002Fdatatools.example.com\",\n      \"email\": \"support@datatools.example.com\"\n    },\n    \"repository\": \"https:\u002F\u002Fgithub.com\u002Fdatatools\u002Fmcp-analytics-db\",\n    \"license\": \"MIT\",\n    \"homepage\": \"https:\u002F\u002Fdatatools.example.com\u002Fmcp-analytics-db\"\n  },\n  \"transport\": {\n    \"type\": \"stdio\",\n    \"command\": \"npx\",\n    \"args\": [\"-y\", \"@datatools\u002Fmcp-analytics-db\"]\n  },\n  \"capabilities\": {\n    \"tools\": [\n      {\n        \"name\": \"query_database\",\n        \"description\": \"Execute a read-only SQL query\"\n      },\n      {\n        \"name\": \"list_tables\",\n        \"description\": \"List available database tables\"\n      },\n      {\n        \"name\": \"describe_table\",\n        \"description\": \"Get the schema for a table\"\n      }\n    ],\n    \"resources\": [],\n    \"prompts\": []\n  },\n  \"configuration\": {\n    \"required\": [\n      {\n        \"name\": \"DATABASE_URL\",\n        \"description\": \"PostgreSQL connection string\",\n        \"type\": \"string\",\n        \"secret\": true\n      }\n    ],\n    \"optional\": [\n      {\n        \"name\": \"MAX_ROWS\",\n        \"description\": \"Maximum rows returned per query\",\n        \"type\": \"integer\",\n        \"default\": 100\n      }\n    ]\n  },\n  \"tags\": [\"database\", \"sql\", \"postgresql\", \"analytics\", \"query\"],\n  \"categories\": [\"databases\", \"analytics\"]\n}\n```\n\n### Metadata Requirements\n\nTo be accepted by the official registry, your manifest must include:\n\n1. **server_info.name**: Unique, lowercase, alphanumeric with hyphens. This becomes your server's identifier. Choose carefully -- it cannot be changed after publishing.\n\n2. **server_info.version**: Semantic versioning (MAJOR.MINOR.PATCH). Clients use this to detect updates and manage compatibility.\n\n3. **server_info.description**: Clear, concise description of what your server does. This is the primary text users see when searching. Front-load the most important information -- \"Query your analytics database using natural language\" is better than \"A comprehensive database querying solution.\"\n\n4. **transport**: How to run the server. For stdio servers distributed as npm packages, the standard pattern is `npx -y @scope\u002Fpackage-name`. For Python packages: `uvx package-name` or `pipx run package-name`. The registry validates that the specified command is available and the server starts correctly.\n\n5. **capabilities**: List of tools, resources, and prompts. Clients use this to show users what the server can do before installing it.\n\n6. **configuration**: Required and optional configuration parameters. Mark secrets (API keys, connection strings) with `\"secret\": true` so clients know to handle them securely.\n\n### Version Management\n\nSemantic versioning communicates the impact of changes:\n\n- **PATCH** (2.1.0 -> 2.1.1): Bug fixes. No tool signature changes. Clients can update automatically.\n- **MINOR** (2.1.0 -> 2.2.0): New tools added. Existing tools unchanged. Backward-compatible. Clients can update automatically.\n- **MAJOR** (2.1.0 -> 3.0.0): Breaking changes. Tool signatures changed, tools removed, or behavior altered. Clients should prompt the user before updating.\n\n```python\n\"\"\"version_management.py -- Semantic version management for MCP servers.\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass ServerVersion:\n    \"\"\"Represents a semantic version.\"\"\"\n    major: int\n    minor: int\n    patch: int\n    pre_release: Optional[str] = None\n\n    @classmethod\n    def parse(cls, version_str: str) -> \"ServerVersion\":\n        \"\"\"Parse a semantic version string.\"\"\"\n        parts = version_str.split(\"-\", 1)\n        pre = parts[1] if len(parts) > 1 else None\n        nums = parts[0].split(\".\")\n        if len(nums) != 3:\n            raise ValueError(f\"Invalid version: {version_str}\")\n        return cls(int(nums[0]), int(nums[1]), int(nums[2]), pre)\n\n    def __str__(self) -> str:\n        base = f\"{self.major}.{self.minor}.{self.patch}\"\n        return f\"{base}-{self.pre_release}\" if self.pre_release else base\n\n    def is_compatible_with(self, other: \"ServerVersion\") -> bool:\n        \"\"\"Check if this version is backward-compatible with another.\"\"\"\n        if self.major != other.major:\n            return False\n        if self.major == 0:\n            # Pre-1.0: minor version changes are breaking\n            return self.minor == other.minor\n        return True\n\n    def bump_patch(self) -> \"ServerVersion\":\n        return ServerVersion(self.major, self.minor, self.patch + 1)\n\n    def bump_minor(self) -> \"ServerVersion\":\n        return ServerVersion(self.major, self.minor + 1, 0)\n\n    def bump_major(self) -> \"ServerVersion\":\n        return ServerVersion(self.major + 1, 0, 0)\n```\n\n### Discovery and Search Optimization\n\nRegistry search considers these factors when ranking results:\n\n1. **Name match**: Exact and partial matches against the server name.\n2. **Description relevance**: Keyword matches in the description. Use specific, descriptive language.\n3. **Tags**: Exact tag matches are weighted heavily. Use 5-10 relevant tags.\n4. **Categories**: Placing your server in the right category ensures it appears in category browsing.\n5. **Install count**: More-installed servers rank higher. This creates a flywheel effect.\n6. **Recency**: Recently updated servers get a small boost.\n\nTips for optimizing discovery:\n\n- **Name your server for the problem, not the solution**: `mcp-postgres-query` is better than `mcp-sql-executor`. Users search for \"postgres\" not \"sql-executor.\"\n- **Front-load the description**: \"Query PostgreSQL databases with natural language\" beats \"A tool for executing SQL queries against various database backends including PostgreSQL.\"\n- **Use specific tags**: `postgresql` is better than `database`. Include the specific technologies your server supports.\n- **Publish frequently**: Regular updates (even small ones) signal an active project and boost ranking.\n\n### Publishing Workflow\n\n```bash\n# 1. Validate your manifest\nmcp validate server.json\n\n# 2. Test your server starts and responds to initialize\nmcp test server.json\n\n# 3. Authenticate with the registry\nmcp auth login\n\n# 4. Publish\nmcp publish\n\n# 5. Verify it appears\nmcp search your-server-name\n```\n\nFor npm-distributed servers, the common pattern is:\n\n```bash\n# Build and publish the npm package\nnpm publish\n\n# Then publish the MCP manifest to the registry\nmcp publish --manifest .well-known\u002Fmcp\u002Fserver.json\n```\n\nFor Python-distributed servers:\n\n```bash\n# Build and publish to PyPI\npython -m build\ntwine upload dist\u002F*\n\n# Then publish the MCP manifest\nmcp publish --manifest .well-known\u002Fmcp\u002Fserver.json\n```\n\n---\n\n## Chapter 5: Enterprise MCP Governance\n\n### Why Governance Matters\n\nWhen a single developer installs an MCP server on their laptop, security is a personal responsibility. When an enterprise deploys MCP servers across thousands of developer workstations, security becomes a governance challenge. Which servers are allowed? Who authorized them? What data can they access? What happens when a server is compromised? Enterprise MCP governance answers these questions.\n\nThe stakes are significant. An MCP server has the same access as the process it runs in. A malicious or compromised server can read local files, access environment variables (which often contain API keys and credentials), make network requests, and execute arbitrary code. In enterprise environments where developers work with proprietary code, customer data, and production credentials, ungoverned MCP servers are a data exfiltration risk.\n\n### SSO Integration for Server Access\n\nEnterprise MCP deployments should integrate with the organization's SSO provider (Okta, Azure AD, Google Workspace) so that server access is governed by the same identity and access management policies as every other tool.\n\n```python\n\"\"\"enterprise_auth.py -- Enterprise SSO integration for MCP servers.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport time\nimport secrets\n\n\n@dataclass\nclass SSOConfig:\n    \"\"\"SSO configuration for enterprise MCP deployment.\"\"\"\n    provider: str  # \"okta\", \"azure_ad\", \"google\"\n    tenant_id: str\n    client_id: str\n    client_secret: str\n    allowed_groups: list[str] = field(default_factory=list)\n    allowed_domains: list[str] = field(default_factory=list)\n    mfa_required: bool = True\n    session_timeout_minutes: int = 480  # 8 hours\n\n\n@dataclass\nclass AccessPolicy:\n    \"\"\"Define who can access which MCP servers.\"\"\"\n    server_name: str\n    allowed_groups: list[str]\n    allowed_roles: list[str]\n    requires_approval: bool = False\n    approval_group: str = \"\"\n    data_classification: str = \"internal\"\n    max_session_hours: int = 8\n\n\n@dataclass\nclass EnterpriseGateway:\n    \"\"\"Gateway that enforces SSO and access policies for MCP servers.\"\"\"\n    sso_config: SSOConfig\n    policies: dict[str, AccessPolicy] = field(default_factory=dict)\n    _active_sessions: dict[str, dict] = field(default_factory=dict)\n\n    def register_policy(self, policy: AccessPolicy) -> None:\n        \"\"\"Register an access policy for an MCP server.\"\"\"\n        self.policies[policy.server_name] = policy\n\n    def check_access(\n        self, user_id: str, user_groups: list[str],\n        user_roles: list[str], server_name: str,\n    ) -> dict:\n        \"\"\"Check if a user can access a specific MCP server.\"\"\"\n        policy = self.policies.get(server_name)\n        if not policy:\n            return {\n                \"allowed\": False,\n                \"reason\": f\"No access policy defined for server '{server_name}'\",\n            }\n\n        # Check group membership\n        user_group_set = set(user_groups)\n        allowed_group_set = set(policy.allowed_groups)\n        if not user_group_set.intersection(allowed_group_set):\n            return {\n                \"allowed\": False,\n                \"reason\": (\n                    f\"User is not a member of any allowed group. \"\n                    f\"Required: {policy.allowed_groups}\"\n                ),\n            }\n\n        # Check role\n        user_role_set = set(user_roles)\n        allowed_role_set = set(policy.allowed_roles)\n        if not user_role_set.intersection(allowed_role_set):\n            return {\n                \"allowed\": False,\n                \"reason\": (\n                    f\"User does not have a required role. \"\n                    f\"Required: {policy.allowed_roles}\"\n                ),\n            }\n\n        # Check if approval is needed\n        if policy.requires_approval:\n            return {\n                \"allowed\": False,\n                \"reason\": \"Access requires approval\",\n                \"approval_group\": policy.approval_group,\n                \"requires_approval\": True,\n            }\n\n        return {\"allowed\": True, \"data_classification\": policy.data_classification}\n\n    def create_session(self, user_id: str, server_name: str) -> dict:\n        \"\"\"Create an authenticated session for a user-server pair.\"\"\"\n        policy = self.policies.get(server_name)\n        max_hours = policy.max_session_hours if policy else 8\n        session_id = secrets.token_hex(16)\n\n        self._active_sessions[session_id] = {\n            \"user_id\": user_id,\n            \"server_name\": server_name,\n            \"created_at\": time.time(),\n            \"expires_at\": time.time() + (max_hours * 3600),\n            \"requests_count\": 0,\n        }\n        return {\"session_id\": session_id, \"expires_in_hours\": max_hours}\n\n    def validate_session(self, session_id: str) -> dict:\n        \"\"\"Validate that a session is still active.\"\"\"\n        session = self._active_sessions.get(session_id)\n        if not session:\n            return {\"valid\": False, \"reason\": \"Session not found\"}\n        if time.time() > session[\"expires_at\"]:\n            del self._active_sessions[session_id]\n            return {\"valid\": False, \"reason\": \"Session expired\"}\n        session[\"requests_count\"] += 1\n        return {\"valid\": True, \"user_id\": session[\"user_id\"]}\n```\n\n### Audit Logging\n\nEvery tool call through an enterprise MCP deployment should be logged with enough detail for security review, compliance, and incident response.\n\n```python\n\"\"\"audit_logging.py -- Structured audit logging for MCP servers.\"\"\"\n\nimport json\nimport time\nfrom dataclasses import dataclass, field, asdict\nfrom typing import Optional\n\n\n@dataclass\nclass AuditEvent:\n    \"\"\"A single audit event for an MCP tool call.\"\"\"\n    timestamp: float\n    event_type: str  # \"tool_call\", \"tool_result\", \"auth_failure\", \"policy_violation\"\n    user_id: str\n    server_name: str\n    tool_name: str\n    session_id: str\n    request_id: str\n    arguments_hash: str  # SHA-256 of the arguments (not the arguments themselves)\n    result_status: str  # \"success\", \"error\", \"denied\"\n    duration_ms: float = 0.0\n    error_message: Optional[str] = None\n    data_classification: str = \"internal\"\n    client_ip: str = \"\"\n    user_agent: str = \"\"\n\n\n@dataclass\nclass AuditLogger:\n    \"\"\"Structured audit logger that writes to multiple sinks.\"\"\"\n    sinks: list = field(default_factory=list)\n    _buffer: list = field(default_factory=list)\n    buffer_size: int = 100\n\n    def log(self, event: AuditEvent) -> None:\n        \"\"\"Log an audit event.\"\"\"\n        self._buffer.append(asdict(event))\n        if len(self._buffer) >= self.buffer_size:\n            self.flush()\n\n    def flush(self) -> None:\n        \"\"\"Flush buffered events to all sinks.\"\"\"\n        if not self._buffer:\n            return\n        events = list(self._buffer)\n        self._buffer.clear()\n        for sink in self.sinks:\n            sink.write(events)\n\n    def query(\n        self,\n        user_id: Optional[str] = None,\n        server_name: Optional[str] = None,\n        tool_name: Optional[str] = None,\n        start_time: Optional[float] = None,\n        end_time: Optional[float] = None,\n    ) -> list:\n        \"\"\"Query audit events with filters.\"\"\"\n        self.flush()\n        results = []\n        for sink in self.sinks:\n            if hasattr(sink, \"query\"):\n                results.extend(sink.query(\n                    user_id=user_id, server_name=server_name,\n                    tool_name=tool_name,\n                    start_time=start_time, end_time=end_time,\n                ))\n        return results\n```\n\n### Gateway Patterns\n\nEnterprise MCP gateways sit between AI clients and MCP servers. They enforce policies, add authentication, log activity, and control which servers are available.\n\n**The Central Gateway Model**\n\nAll MCP traffic flows through a central gateway service. Developers configure their AI clients to connect to the gateway instead of individual servers. The gateway authenticates the user, checks access policies, forwards the request to the appropriate server, logs the interaction, and returns the result.\n\n```\nDeveloper's AI Client\n    |\n    +-- connects to --> Enterprise MCP Gateway\n                            |\n                            +-- authenticates via SSO\n                            +-- checks access policy\n                            +-- forwards to --> MCP Server A\n                            +-- forwards to --> MCP Server B\n                            +-- logs to --> Audit Log\n```\n\nAdvantages: Central policy enforcement. Single point of audit logging. Easy to add or remove servers. Can cache responses, rate limit, and filter.\n\nDisadvantages: Single point of failure. Adds latency. Requires infrastructure.\n\n**The Sidecar Model**\n\nA lightweight policy agent runs alongside each MCP server on the developer's machine. The sidecar intercepts tool calls, checks policies against a central policy server, and logs activity.\n\nAdvantages: No central bottleneck. Works offline with cached policies. Lower latency.\n\nDisadvantages: Must be installed on every machine. Policy updates require propagation. Harder to audit in real time.\n\n### Policy Enforcement\n\nEnterprise policies for MCP servers typically cover four areas:\n\n1. **Server allowlist**: Only approved servers can be installed. Unapproved servers are blocked.\n2. **Tool restrictions**: Even within an approved server, certain tools may be restricted by team.\n3. **Data classification**: Tools that access confidential data require additional authorization.\n4. **Rate limits**: Per-user and per-team rate limits prevent runaway usage.\n\n```python\n\"\"\"policy_engine.py -- Policy enforcement for enterprise MCP governance.\"\"\"\n\nimport re\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass PolicyRule:\n    \"\"\"A single policy rule.\"\"\"\n    rule_id: str\n    description: str\n    action: str  # \"allow\", \"deny\", \"require_approval\"\n    server_pattern: str = \"*\"\n    tool_pattern: str = \"*\"\n    user_groups: list[str] = field(default_factory=list)\n    priority: int = 0\n\n\n@dataclass\nclass PolicyEngine:\n    \"\"\"Evaluate access policies for MCP tool calls.\"\"\"\n    rules: list[PolicyRule] = field(default_factory=list)\n\n    def add_rule(self, rule: PolicyRule) -> None:\n        \"\"\"Add a policy rule.\"\"\"\n        self.rules.append(rule)\n        self.rules.sort(key=lambda r: r.priority, reverse=True)\n\n    def evaluate(\n        self,\n        server_name: str,\n        tool_name: str,\n        user_groups: list[str],\n    ) -> dict:\n        \"\"\"Evaluate policies and return the access decision.\"\"\"\n        for rule in self.rules:\n            if not self._matches(rule.server_pattern, server_name):\n                continue\n            if not self._matches(rule.tool_pattern, tool_name):\n                continue\n            if rule.user_groups:\n                if not set(user_groups).intersection(set(rule.user_groups)):\n                    continue\n            return {\n                \"decision\": rule.action,\n                \"rule_id\": rule.rule_id,\n                \"description\": rule.description,\n            }\n\n        # Default deny\n        return {\n            \"decision\": \"deny\",\n            \"rule_id\": \"default\",\n            \"description\": \"No matching policy rule; default deny\",\n        }\n\n    @staticmethod\n    def _matches(pattern: str, value: str) -> bool:\n        \"\"\"Simple glob matching.\"\"\"\n        regex = pattern.replace(\".\", r\"\\.\").replace(\"*\", \".*\").replace(\"?\", \".\")\n        return bool(re.fullmatch(regex, value))\n```\n\n### Configuration Portability\n\nEnterprise teams need a standard way to share MCP server configurations. A centralized configuration service distributes approved server configs to developer machines.\n\n```python\n\"\"\"config_portability.py -- Portable MCP configuration management.\"\"\"\n\nimport json\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass MCPServerConfig:\n    \"\"\"Configuration for a single MCP server.\"\"\"\n    name: str\n    command: str\n    args: list[str] = field(default_factory=list)\n    env: dict[str, str] = field(default_factory=dict)\n    env_secrets: list[str] = field(default_factory=list)\n    enabled: bool = True\n    required_groups: list[str] = field(default_factory=list)\n\n\n@dataclass\nclass TeamConfig:\n    \"\"\"MCP configuration for a team.\"\"\"\n    team_name: str\n    servers: list[MCPServerConfig] = field(default_factory=list)\n    version: str = \"1.0.0\"\n\n    def to_claude_desktop_config(self) -> dict:\n        \"\"\"Export as Claude Desktop configuration format.\"\"\"\n        mcp_servers = {}\n        for s in self.servers:\n            if not s.enabled:\n                continue\n            config = {\"command\": s.command, \"args\": s.args}\n            if s.env:\n                config[\"env\"] = s.env\n            mcp_servers[s.name] = config\n        return {\"mcpServers\": mcp_servers}\n\n    def to_cursor_config(self) -> dict:\n        \"\"\"Export as Cursor IDE configuration format.\"\"\"\n        return {\n            \"mcp\": {\n                \"servers\": {\n                    s.name: {\n                        \"command\": s.command,\n                        \"args\": s.args,\n                        \"env\": s.env,\n                    }\n                    for s in self.servers if s.enabled\n                }\n            }\n        }\n\n    def to_json(self) -> str:\n        \"\"\"Serialize to portable JSON.\"\"\"\n        return json.dumps({\n            \"team\": self.team_name,\n            \"version\": self.version,\n            \"servers\": [\n                {\n                    \"name\": s.name,\n                    \"command\": s.command,\n                    \"args\": s.args,\n                    \"env\": {k: v for k, v in s.env.items()},\n                    \"env_secrets\": s.env_secrets,\n                    \"enabled\": s.enabled,\n                    \"required_groups\": s.required_groups,\n                }\n                for s in self.servers\n            ],\n        }, indent=2)\n```\n\n### Compliance Considerations\n\nEnterprise MCP deployments must address regulatory requirements:\n\n**Data Residency**: Some regulations require data to stay within specific geographic regions. MCP servers that access customer data must run in the same region as the data. Remote MCP servers (HTTP transport) must be deployed in compliant regions.\n\n**Access Reviews**: Periodic reviews of who has access to which MCP servers. The audit log provides the data; the governance team reviews it quarterly.\n\n**Data Loss Prevention**: MCP servers can exfiltrate data by including it in tool responses that flow to cloud-hosted AI models. DLP policies should scan tool responses for sensitive patterns (credit card numbers, SSNs, API keys) and redact them before they reach the model.\n\n**Retention**: Audit logs must be retained per the organization's data retention policy. Tool call arguments and results may contain sensitive data and should be stored with appropriate encryption and access controls.\n\n---\n\n## Chapter 6: Monetization Strategies\n\n### The MCP Server Business Landscape\n\nMCP servers are the new APIs. Every business model that works for APIs works for MCP servers -- with one advantage: MCP servers are discoverable by AI agents, which means your market is not just human developers but also autonomous systems that find, evaluate, and pay for tools at machine speed. This chapter covers six monetization strategies, from freemium to pay-per-use, with implementation details for each.\n\n### Strategy 1: Freemium (Basic Tools Free, Advanced Paid)\n\nThe most common model. Offer a set of basic tools for free to drive adoption, then gate advanced tools behind a paid tier. The free tier serves as a distribution mechanism -- every free user is a potential paid customer.\n\n```python\n\"\"\"freemium_server.py -- MCP server with tiered tool access.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"analytics-server\")\n\n\n@dataclass\nclass TierConfig:\n    \"\"\"Configuration for a pricing tier.\"\"\"\n    name: str\n    tools_allowed: set\n    monthly_price_usd: float\n    daily_call_limit: int\n    max_rows_per_query: int\n\n\nTIERS = {\n    \"free\": TierConfig(\n        name=\"Free\",\n        tools_allowed={\"query_database\", \"list_tables\", \"describe_table\"},\n        monthly_price_usd=0.0,\n        daily_call_limit=100,\n        max_rows_per_query=100,\n    ),\n    \"pro\": TierConfig(\n        name=\"Pro\",\n        tools_allowed={\n            \"query_database\", \"list_tables\", \"describe_table\",\n            \"create_dashboard\", \"schedule_report\", \"export_data\",\n            \"query_optimizer\", \"schema_diff\",\n        },\n        monthly_price_usd=29.0,\n        daily_call_limit=10000,\n        max_rows_per_query=10000,\n    ),\n    \"enterprise\": TierConfig(\n        name=\"Enterprise\",\n        tools_allowed={\n            \"query_database\", \"list_tables\", \"describe_table\",\n            \"create_dashboard\", \"schedule_report\", \"export_data\",\n            \"query_optimizer\", \"schema_diff\",\n            \"admin_create_user\", \"admin_audit_log\", \"admin_backup\",\n            \"custom_function\", \"cross_database_query\",\n        },\n        monthly_price_usd=199.0,\n        daily_call_limit=100000,\n        max_rows_per_query=1000000,\n    ),\n}\n\n\n@dataclass\nclass ClientProfile:\n    \"\"\"Tracks a client's tier and usage.\"\"\"\n    client_id: str\n    tier: str = \"free\"\n    daily_calls: int = 0\n    last_reset_day: str = \"\"\n\n\n_clients: dict[str, ClientProfile] = {}\n\n\ndef get_client(client_id: str) -> ClientProfile:\n    \"\"\"Get or create a client profile.\"\"\"\n    if client_id not in _clients:\n        _clients[client_id] = ClientProfile(client_id=client_id)\n    return _clients[client_id]\n\n\ndef check_tier_access(client_id: str, tool_name: str) -> None:\n    \"\"\"Verify the client's tier allows access to the tool.\"\"\"\n    import time\n    client = get_client(client_id)\n    tier = TIERS.get(client.tier)\n    if not tier:\n        raise PermissionError(f\"Unknown tier: {client.tier}\")\n\n    # Check tool access\n    if tool_name not in tier.tools_allowed:\n        available_in = [\n            t.name for t in TIERS.values()\n            if tool_name in t.tools_allowed\n        ]\n        raise PermissionError(\n            f\"Tool '{tool_name}' requires a {' or '.join(available_in)} plan. \"\n            f\"Your plan: {tier.name}. Upgrade at https:\u002F\u002Fexample.com\u002Fpricing\"\n        )\n\n    # Check daily limit\n    today = time.strftime(\"%Y-%m-%d\")\n    if client.last_reset_day != today:\n        client.daily_calls = 0\n        client.last_reset_day = today\n\n    if client.daily_calls >= tier.daily_call_limit:\n        raise PermissionError(\n            f\"Daily call limit of {tier.daily_call_limit} exceeded \"\n            f\"for {tier.name} plan. Resets at midnight UTC. \"\n            f\"Upgrade for higher limits.\"\n        )\n\n    client.daily_calls += 1\n```\n\n### Strategy 2: Usage-Based Billing (Per-Call Metering)\n\nCharge per tool call. This model aligns cost with value -- users pay only for what they use. It works well for high-volume, low-cost operations like API calls, translations, and data lookups.\n\n```python\n\"\"\"usage_billing.py -- Per-call usage metering for MCP servers.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom typing import Optional\n\n\n@dataclass\nclass UsageMeter:\n    \"\"\"Track per-call usage for billing.\"\"\"\n    _usage: dict = field(default_factory=lambda: defaultdict(list))\n\n    def record(\n        self,\n        client_id: str,\n        tool_name: str,\n        cost_usd: float,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Record a billable tool call.\"\"\"\n        event = {\n            \"timestamp\": time.time(),\n            \"tool_name\": tool_name,\n            \"cost_usd\": cost_usd,\n            \"metadata\": metadata or {},\n        }\n        self._usage[client_id].append(event)\n        return event\n\n    def get_current_bill(self, client_id: str) -> dict:\n        \"\"\"Calculate the current billing period total.\"\"\"\n        events = self._usage.get(client_id, [])\n        # Filter to current month\n        current_month = time.strftime(\"%Y-%m\")\n        month_events = [\n            e for e in events\n            if time.strftime(\"%Y-%m\", time.localtime(e[\"timestamp\"])) == current_month\n        ]\n        total = sum(e[\"cost_usd\"] for e in month_events)\n        by_tool = defaultdict(float)\n        for e in month_events:\n            by_tool[e[\"tool_name\"]] += e[\"cost_usd\"]\n\n        return {\n            \"client_id\": client_id,\n            \"period\": current_month,\n            \"total_usd\": round(total, 4),\n            \"call_count\": len(month_events),\n            \"by_tool\": dict(by_tool),\n        }\n\n    def get_usage_report(self, client_id: str, days: int = 30) -> dict:\n        \"\"\"Generate a usage report for the last N days.\"\"\"\n        events = self._usage.get(client_id, [])\n        cutoff = time.time() - (days * 86400)\n        recent = [e for e in events if e[\"timestamp\"] >= cutoff]\n\n        daily = defaultdict(lambda: {\"calls\": 0, \"cost\": 0.0})\n        for e in recent:\n            day = time.strftime(\"%Y-%m-%d\", time.localtime(e[\"timestamp\"]))\n            daily[day][\"calls\"] += 1\n            daily[day][\"cost\"] += e[\"cost_usd\"]\n\n        return {\n            \"client_id\": client_id,\n            \"period_days\": days,\n            \"total_calls\": len(recent),\n            \"total_cost_usd\": round(sum(e[\"cost_usd\"] for e in recent), 4),\n            \"daily_breakdown\": dict(daily),\n        }\n\n\n# Pricing per tool call\nTOOL_PRICING = {\n    \"translate\": 0.002,       # $0.002 per translation\n    \"summarize\": 0.005,       # $0.005 per summary\n    \"analyze_image\": 0.01,    # $0.01 per image analysis\n    \"generate_report\": 0.05,  # $0.05 per report\n    \"query_database\": 0.001,  # $0.001 per query\n}\n\nmeter = UsageMeter()\n```\n\n### Strategy 3: Enterprise Licensing\n\nSell annual or multi-year licenses to organizations. This model provides predictable revenue, higher deal sizes, and longer customer relationships. Enterprise customers typically need SSO integration, audit logging, SLA guarantees, and dedicated support.\n\nThe key differentiators for enterprise licensing:\n\n- **Unlimited usage** within the license (no per-call fees).\n- **SLA guarantees**: 99.9% uptime, response time commitments.\n- **Dedicated infrastructure**: Option for on-premise or private cloud deployment.\n- **SSO\u002FSCIM integration**: Automatic user provisioning.\n- **Priority support**: Dedicated Slack channel, guaranteed response times.\n- **Custom tools**: Build custom tools specific to the customer's domain.\n\nEnterprise pricing is typically based on the number of developer seats or the number of connected AI agents, ranging from $500 to $5,000 per seat per year depending on the domain.\n\n### Strategy 4: Marketplace Models\n\nList your MCP server on AI tool marketplaces and take a revenue share. As of April 2026, several marketplaces accept MCP server listings:\n\n- **The official MCP registry**: Free to list, no revenue share. You handle billing directly.\n- **AI client marketplaces**: Cursor, Windsurf, and other IDEs are building in-app marketplaces where developers can purchase premium MCP servers. Revenue share varies from 15% to 30%.\n- **Enterprise marketplaces**: Azure API Center and similar platforms list MCP servers for enterprise customers. Higher deal sizes but longer sales cycles.\n\n### Strategy 5: Combining MCP with x402 for Pay-Per-Use\n\nThe x402 protocol enables HTTP-native micropayments. By combining an MCP server with an x402-enabled endpoint, you can create a pay-per-use model where agent clients pay per tool call without needing a subscription or API key. This is especially powerful for agent-to-agent commerce where the calling agent discovers your MCP server and pays automatically.\n\n```python\n\"\"\"x402_integration.py -- Combine MCP server with x402 pay-per-use.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass X402PaymentGate:\n    \"\"\"Gate MCP tool calls behind x402 micropayments.\"\"\"\n    payment_address: str\n    tool_prices: dict = field(default_factory=dict)\n    _verified_payments: dict = field(default_factory=dict)\n\n    def set_price(self, tool_name: str, price_usd: float) -> None:\n        \"\"\"Set the price for a tool call.\"\"\"\n        self.tool_prices[tool_name] = price_usd\n\n    def generate_payment_request(self, tool_name: str) -> dict:\n        \"\"\"Generate an x402 payment request for a tool call.\"\"\"\n        price = self.tool_prices.get(tool_name, 0.01)\n        return {\n            \"status\": 402,\n            \"headers\": {\n                \"X-Payment-Amount\": str(price),\n                \"X-Payment-Currency\": \"USD\",\n                \"X-Payment-Methods\": \"x402\",\n                \"X-Payment-Address\": self.payment_address,\n                \"X-Payment-Description\": f\"MCP tool call: {tool_name}\",\n            },\n        }\n\n    def verify_payment(self, payment_token: str, tool_name: str) -> dict:\n        \"\"\"Verify an x402 payment token.\"\"\"\n        # In production, verify against the x402 facilitator\n        price = self.tool_prices.get(tool_name, 0.01)\n        return {\n            \"verified\": True,\n            \"amount_usd\": price,\n            \"token\": payment_token,\n            \"tool_name\": tool_name,\n        }\n\n    def check_and_charge(\n        self, tool_name: str, payment_token: Optional[str],\n    ) -> dict:\n        \"\"\"Check payment for a tool call. Returns payment status.\"\"\"\n        if tool_name not in self.tool_prices:\n            return {\"paid\": True, \"free\": True}\n\n        if not payment_token:\n            return {\n                \"paid\": False,\n                \"payment_required\": self.generate_payment_request(tool_name),\n            }\n\n        verification = self.verify_payment(payment_token, tool_name)\n        if not verification[\"verified\"]:\n            return {\"paid\": False, \"reason\": \"Payment verification failed\"}\n\n        return {\"paid\": True, \"amount_charged\": verification[\"amount_usd\"]}\n\n\n# Example: Gate MCP tools behind x402\ngate = X402PaymentGate(payment_address=\"ghx_pay_example\")\ngate.set_price(\"translate\", 0.002)\ngate.set_price(\"summarize\", 0.005)\ngate.set_price(\"analyze_image\", 0.01)\n```\n\n### Strategy 6: Revenue Tracking and Analytics\n\nRegardless of your monetization model, you need revenue tracking. Build it into your MCP server from day one.\n\n```python\n\"\"\"revenue_analytics.py -- Revenue tracking for MCP server monetization.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\n\n\n@dataclass\nclass RevenueTracker:\n    \"\"\"Track and analyze MCP server revenue.\"\"\"\n    _events: list = field(default_factory=list)\n\n    def record_revenue(\n        self,\n        client_id: str,\n        amount_usd: float,\n        source: str,\n        tool_name: str = \"\",\n    ) -> None:\n        \"\"\"Record a revenue event.\"\"\"\n        self._events.append({\n            \"timestamp\": time.time(),\n            \"client_id\": client_id,\n            \"amount_usd\": amount_usd,\n            \"source\": source,  # \"subscription\", \"usage\", \"enterprise\", \"x402\"\n            \"tool_name\": tool_name,\n        })\n\n    def monthly_recurring_revenue(self) -> float:\n        \"\"\"Calculate MRR from subscription events in the current month.\"\"\"\n        current_month = time.strftime(\"%Y-%m\")\n        return sum(\n            e[\"amount_usd\"] for e in self._events\n            if e[\"source\"] == \"subscription\"\n            and time.strftime(\"%Y-%m\", time.localtime(e[\"timestamp\"])) == current_month\n        )\n\n    def revenue_by_tool(self, days: int = 30) -> dict:\n        \"\"\"Break down revenue by tool for the last N days.\"\"\"\n        cutoff = time.time() - (days * 86400)\n        by_tool = defaultdict(float)\n        for e in self._events:\n            if e[\"timestamp\"] >= cutoff and e[\"tool_name\"]:\n                by_tool[e[\"tool_name\"]] += e[\"amount_usd\"]\n        return dict(by_tool)\n\n    def customer_lifetime_value(self, client_id: str) -> float:\n        \"\"\"Calculate total revenue from a single customer.\"\"\"\n        return sum(\n            e[\"amount_usd\"] for e in self._events\n            if e[\"client_id\"] == client_id\n        )\n\n    def churn_rate(self, period_days: int = 30) -> float:\n        \"\"\"Estimate churn rate based on active customers.\"\"\"\n        now = time.time()\n        current_cutoff = now - (period_days * 86400)\n        previous_cutoff = current_cutoff - (period_days * 86400)\n\n        current_clients = set(\n            e[\"client_id\"] for e in self._events\n            if e[\"timestamp\"] >= current_cutoff\n        )\n        previous_clients = set(\n            e[\"client_id\"] for e in self._events\n            if previous_cutoff \u003C= e[\"timestamp\"] \u003C current_cutoff\n        )\n\n        if not previous_clients:\n            return 0.0\n\n        churned = previous_clients - current_clients\n        return len(churned) \u002F len(previous_clients)\n```\n\n---\n\n## Chapter 7: Production Operations\n\n### Deployment Patterns\n\nMCP servers can be deployed in several ways, depending on whether they need to run locally or remotely, and whether they serve a single user or many.\n\n**Local stdio Deployment**\n\nThe simplest deployment. The AI client starts the server as a subprocess. No infrastructure needed. Suitable for personal tools and development.\n\n```json\n{\n  \"mcpServers\": {\n    \"my-tool\": {\n      \"command\": \"python\",\n      \"args\": [\"\u002Fopt\u002Fmcp-servers\u002Fmy-tool\u002Fserver.py\"],\n      \"env\": {\n        \"DATABASE_URL\": \"sqlite:\u002F\u002F\u002Fdata\u002Fanalytics.db\"\n      }\n    }\n  }\n}\n```\n\n**Docker Deployment**\n\nPackage your MCP server as a Docker container for consistent environments and easy distribution. Especially useful for servers with complex dependencies.\n\n```dockerfile\nFROM python:3.12-slim\n\nWORKDIR \u002Fapp\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . .\n\n# For stdio transport (used with docker run -i)\nCMD [\"python\", \"server.py\"]\n\n# For HTTP transport\n# EXPOSE 8080\n# CMD [\"python\", \"server.py\", \"--transport\", \"http\", \"--port\", \"8080\"]\n```\n\nFor stdio transport with Docker:\n\n```json\n{\n  \"mcpServers\": {\n    \"my-tool\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"my-mcp-server:latest\"]\n    }\n  }\n}\n```\n\n**Serverless Deployment**\n\nFor HTTP-based MCP servers with bursty traffic, serverless platforms (AWS Lambda, Google Cloud Functions, Cloudflare Workers) provide automatic scaling and pay-per-use pricing.\n\nThe key constraint with serverless is cold start latency. MCP's `initialize` handshake adds to the first-request latency. Mitigate with provisioned concurrency or by using the streamable HTTP transport (which allows stateless request-response without persistent connections).\n\n**Edge Deployment**\n\nFor latency-sensitive MCP servers, deploy at the edge using Cloudflare Workers, Deno Deploy, or AWS CloudFront Functions. Edge deployment puts your server within 50ms of most users globally.\n\n### Monitoring and Alerting\n\nProduction MCP servers need the same monitoring as any production service: health checks, latency tracking, error rates, and alerting.\n\n```python\n\"\"\"monitoring.py -- Monitoring for production MCP servers.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom typing import Optional\n\n\n@dataclass\nclass ToolMetrics:\n    \"\"\"Metrics for a single tool.\"\"\"\n    call_count: int = 0\n    error_count: int = 0\n    total_latency_ms: float = 0.0\n    max_latency_ms: float = 0.0\n    last_call_time: float = 0.0\n\n\n@dataclass\nclass ServerMonitor:\n    \"\"\"Monitor MCP server health and performance.\"\"\"\n    _tools: dict[str, ToolMetrics] = field(default_factory=lambda: defaultdict(ToolMetrics))\n    _alerts: list = field(default_factory=list)\n    error_rate_threshold: float = 0.05  # 5%\n    latency_threshold_ms: float = 5000.0  # 5 seconds\n\n    def record_call(\n        self,\n        tool_name: str,\n        latency_ms: float,\n        success: bool,\n    ) -> None:\n        \"\"\"Record a tool call for monitoring.\"\"\"\n        metrics = self._tools[tool_name]\n        metrics.call_count += 1\n        metrics.total_latency_ms += latency_ms\n        metrics.last_call_time = time.time()\n\n        if latency_ms > metrics.max_latency_ms:\n            metrics.max_latency_ms = latency_ms\n\n        if not success:\n            metrics.error_count += 1\n\n        # Check thresholds\n        self._check_alerts(tool_name, metrics, latency_ms, success)\n\n    def _check_alerts(\n        self,\n        tool_name: str,\n        metrics: ToolMetrics,\n        latency_ms: float,\n        success: bool,\n    ) -> None:\n        \"\"\"Check if any alert thresholds are exceeded.\"\"\"\n        # High error rate\n        if metrics.call_count >= 10:\n            error_rate = metrics.error_count \u002F metrics.call_count\n            if error_rate > self.error_rate_threshold:\n                self._alerts.append({\n                    \"type\": \"high_error_rate\",\n                    \"tool\": tool_name,\n                    \"error_rate\": round(error_rate, 3),\n                    \"threshold\": self.error_rate_threshold,\n                    \"timestamp\": time.time(),\n                })\n\n        # High latency\n        if latency_ms > self.latency_threshold_ms:\n            self._alerts.append({\n                \"type\": \"high_latency\",\n                \"tool\": tool_name,\n                \"latency_ms\": latency_ms,\n                \"threshold\": self.latency_threshold_ms,\n                \"timestamp\": time.time(),\n            })\n\n    def get_health(self) -> dict:\n        \"\"\"Get overall server health status.\"\"\"\n        total_calls = sum(m.call_count for m in self._tools.values())\n        total_errors = sum(m.error_count for m in self._tools.values())\n        error_rate = total_errors \u002F total_calls if total_calls > 0 else 0.0\n\n        return {\n            \"status\": \"healthy\" if error_rate \u003C self.error_rate_threshold else \"degraded\",\n            \"total_calls\": total_calls,\n            \"total_errors\": total_errors,\n            \"error_rate\": round(error_rate, 4),\n            \"tools\": {\n                name: {\n                    \"calls\": m.call_count,\n                    \"errors\": m.error_count,\n                    \"avg_latency_ms\": round(m.total_latency_ms \u002F m.call_count, 1) if m.call_count > 0 else 0,\n                    \"max_latency_ms\": round(m.max_latency_ms, 1),\n                }\n                for name, m in self._tools.items()\n            },\n            \"recent_alerts\": self._alerts[-10:],\n        }\n```\n\n### Scaling Strategies\n\n**Horizontal Scaling for HTTP Servers**\n\nFor HTTP-based MCP servers, scale horizontally behind a load balancer. Each instance is stateless (or uses shared state via Redis or a database).\n\n```\nLoad Balancer\n    |\n    +-- MCP Server Instance 1\n    +-- MCP Server Instance 2\n    +-- MCP Server Instance 3\n    |\n    +-- Shared State (Redis \u002F PostgreSQL)\n```\n\n**Connection Pooling for stdio Servers**\n\nstdio servers cannot be shared across clients, but they can be pooled. A pool manager maintains a set of pre-started server processes and assigns them to incoming client connections.\n\n**Caching**\n\nFor tools that return the same result for the same input (deterministic tools like schema lookups, format conversions, and reference data), implement response caching:\n\n```python\n\"\"\"caching.py -- Response caching for MCP tools.\"\"\"\n\nimport hashlib\nimport json\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass ToolCache:\n    \"\"\"LRU cache for deterministic MCP tool responses.\"\"\"\n    max_size: int = 1000\n    ttl_seconds: float = 300.0  # 5 minutes\n    _cache: dict = field(default_factory=dict)\n    _access_order: list = field(default_factory=list)\n\n    def _make_key(self, tool_name: str, arguments: dict) -> str:\n        \"\"\"Create a cache key from tool name and arguments.\"\"\"\n        canonical = json.dumps(\n            {\"tool\": tool_name, \"args\": arguments},\n            sort_keys=True, separators=(\",\", \":\"),\n        )\n        return hashlib.sha256(canonical.encode()).hexdigest()\n\n    def get(self, tool_name: str, arguments: dict) -> Optional[str]:\n        \"\"\"Get a cached result if available and not expired.\"\"\"\n        key = self._make_key(tool_name, arguments)\n        entry = self._cache.get(key)\n        if not entry:\n            return None\n        if time.time() - entry[\"timestamp\"] > self.ttl_seconds:\n            del self._cache[key]\n            return None\n        return entry[\"result\"]\n\n    def put(self, tool_name: str, arguments: dict, result: str) -> None:\n        \"\"\"Cache a tool result.\"\"\"\n        key = self._make_key(tool_name, arguments)\n        self._cache[key] = {\n            \"result\": result,\n            \"timestamp\": time.time(),\n        }\n        # Evict oldest if over max size\n        if len(self._cache) > self.max_size:\n            oldest_key = min(\n                self._cache, key=lambda k: self._cache[k][\"timestamp\"]\n            )\n            del self._cache[oldest_key]\n```\n\n### Version Upgrades Without Breaking Clients\n\nWhen upgrading your MCP server, maintain backward compatibility by following these rules:\n\n1. **Never remove tools** in a minor version. Deprecate them first (add \"DEPRECATED\" to the description), then remove in the next major version.\n2. **Never change tool input schemas** in a breaking way. Adding optional parameters is safe. Removing parameters or changing types is breaking.\n3. **Use feature flags** to roll out new tool behavior gradually.\n4. **Version your transport endpoint** (`\u002Fv1\u002Fmcp`, `\u002Fv2\u002Fmcp`) for HTTP servers.\n5. **Test against older clients** before releasing.\n\n### Security Hardening\n\nProduction MCP servers handle untrusted input from AI models. Apply defense-in-depth:\n\n1. **Input validation**: Validate every input against the schema and semantic constraints. Never trust model-generated input.\n2. **Sandboxing**: Run tool handlers in sandboxed environments when they execute user-provided code or queries.\n3. **Network isolation**: MCP servers should only have network access to the services they need. Use firewall rules to block everything else.\n4. **Secret management**: Never hardcode API keys or credentials. Use environment variables or a secret manager.\n5. **Dependency scanning**: Regularly scan your dependencies for known vulnerabilities.\n6. **Rate limiting**: Always implement rate limiting, even for internal servers. A compromised client can flood a server.\n\n---\n\n## Chapter 8: Case Studies\n\n### Case Study 1: Data Connector MCP Server (Database Access)\n\n**The Problem**: A data analytics company has 500 analysts who need to query 12 databases across three cloud providers. Each analyst has different access levels. The current workflow: write SQL in a notebook, run it, wait, copy-paste results into reports. AI assistants could automate this, but each database requires different connection logic, authentication, and query syntax.\n\n**The Solution**: A single MCP server that provides unified access to all 12 databases with role-based access control.\n\n```python\n\"\"\"data_connector.py -- Multi-database MCP server case study.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass DatabaseConfig:\n    \"\"\"Configuration for a single database connection.\"\"\"\n    name: str\n    engine: str  # \"postgresql\", \"mysql\", \"bigquery\", \"snowflake\"\n    connection_string: str\n    allowed_roles: list[str] = field(default_factory=list)\n    read_only: bool = True\n    max_rows: int = 10000\n    timeout_seconds: int = 30\n\n\n@dataclass\nclass DataConnector:\n    \"\"\"Multi-database connector with role-based access.\"\"\"\n    databases: dict[str, DatabaseConfig] = field(default_factory=dict)\n\n    def register_database(self, config: DatabaseConfig) -> None:\n        \"\"\"Register a database connection.\"\"\"\n        self.databases[config.name] = config\n\n    def list_databases(self, user_role: str) -> list:\n        \"\"\"List databases the user can access.\"\"\"\n        return [\n            {\n                \"name\": db.name,\n                \"engine\": db.engine,\n                \"read_only\": db.read_only,\n                \"max_rows\": db.max_rows,\n            }\n            for db in self.databases.values()\n            if user_role in db.allowed_roles or not db.allowed_roles\n        ]\n\n    def check_access(self, database_name: str, user_role: str) -> bool:\n        \"\"\"Check if a user role has access to a database.\"\"\"\n        db = self.databases.get(database_name)\n        if not db:\n            return False\n        return user_role in db.allowed_roles or not db.allowed_roles\n\n    def validate_query(self, database_name: str, sql: str) -> dict:\n        \"\"\"Validate a query against the database's constraints.\"\"\"\n        db = self.databases.get(database_name)\n        if not db:\n            return {\"valid\": False, \"error\": f\"Database '{database_name}' not found\"}\n\n        upper_sql = sql.strip().upper()\n\n        if db.read_only and not upper_sql.startswith(\"SELECT\"):\n            return {\"valid\": False, \"error\": \"Database is read-only. Only SELECT allowed.\"}\n\n        dangerous = [\"DROP\", \"DELETE\", \"TRUNCATE\", \"ALTER\"]\n        for keyword in dangerous:\n            if keyword in upper_sql:\n                return {\"valid\": False, \"error\": f\"Keyword '{keyword}' is not allowed\"}\n\n        return {\"valid\": True, \"database\": database_name, \"engine\": db.engine}\n```\n\n**Results**: Query time for analysts dropped 70% because the AI assistant handles SQL generation, connection routing, and result formatting. Access control incidents dropped to zero because the server enforces the same RBAC policies regardless of which AI client the analyst uses.\n\n### Case Study 2: API Wrapper MCP Server (Third-Party API)\n\n**The Problem**: A SaaS company's customer success team uses five different APIs (Salesforce, Zendesk, Stripe, Mixpanel, Intercom) to manage customer accounts. Each API has its own authentication, rate limits, and data model. Customer success managers spend 30 minutes per account review switching between tools.\n\n**The Solution**: An MCP server that wraps all five APIs behind unified tools that answer customer-centric questions.\n\n```python\n\"\"\"customer_360.py -- Unified customer data MCP server.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass APIEndpoint:\n    \"\"\"Configuration for a third-party API.\"\"\"\n    name: str\n    base_url: str\n    api_key: str\n    rate_limit_per_minute: int\n    timeout_seconds: int = 10\n\n\n@dataclass\nclass Customer360Server:\n    \"\"\"Unified customer view from multiple API sources.\"\"\"\n    apis: dict[str, APIEndpoint] = field(default_factory=dict)\n    _cache: dict = field(default_factory=dict)\n\n    def register_api(self, endpoint: APIEndpoint) -> None:\n        \"\"\"Register an API endpoint.\"\"\"\n        self.apis[endpoint.name] = endpoint\n\n    def get_customer_summary(self, customer_email: str) -> dict:\n        \"\"\"Build a 360-degree customer summary from all sources.\"\"\"\n        # In production, these would be actual API calls\n        return {\n            \"email\": customer_email,\n            \"crm\": self._get_crm_data(customer_email),\n            \"support\": self._get_support_data(customer_email),\n            \"billing\": self._get_billing_data(customer_email),\n            \"engagement\": self._get_engagement_data(customer_email),\n        }\n\n    def _get_crm_data(self, email: str) -> dict:\n        \"\"\"Get CRM data from Salesforce.\"\"\"\n        return {\n            \"source\": \"salesforce\",\n            \"account_status\": \"active\",\n            \"plan\": \"enterprise\",\n            \"mrr\": 5000.0,\n            \"renewal_date\": \"2026-09-15\",\n        }\n\n    def _get_support_data(self, email: str) -> dict:\n        \"\"\"Get support data from Zendesk.\"\"\"\n        return {\n            \"source\": \"zendesk\",\n            \"open_tickets\": 2,\n            \"avg_resolution_hours\": 4.2,\n            \"satisfaction_score\": 4.5,\n        }\n\n    def _get_billing_data(self, email: str) -> dict:\n        \"\"\"Get billing data from Stripe.\"\"\"\n        return {\n            \"source\": \"stripe\",\n            \"current_period_amount\": 5000.0,\n            \"payment_status\": \"current\",\n            \"last_payment_date\": \"2026-03-01\",\n        }\n\n    def _get_engagement_data(self, email: str) -> dict:\n        \"\"\"Get engagement data from Mixpanel.\"\"\"\n        return {\n            \"source\": \"mixpanel\",\n            \"dau_last_30\": 22,\n            \"feature_adoption\": 0.73,\n            \"last_active\": \"2026-04-06\",\n        }\n\n    def assess_health(self, summary: dict) -> dict:\n        \"\"\"Assess customer health from summary data. Pure logic.\"\"\"\n        score = 100\n        risks = []\n\n        # Support issues\n        open_tickets = summary.get(\"support\", {}).get(\"open_tickets\", 0)\n        if open_tickets > 3:\n            score -= 20\n            risks.append(f\"{open_tickets} open support tickets\")\n\n        # Engagement drop\n        dau = summary.get(\"engagement\", {}).get(\"dau_last_30\", 0)\n        if dau \u003C 5:\n            score -= 30\n            risks.append(f\"Low engagement: {dau} active days in last 30\")\n\n        # Payment issues\n        payment = summary.get(\"billing\", {}).get(\"payment_status\", \"\")\n        if payment != \"current\":\n            score -= 25\n            risks.append(f\"Payment status: {payment}\")\n\n        # Feature adoption\n        adoption = summary.get(\"engagement\", {}).get(\"feature_adoption\", 0)\n        if adoption \u003C 0.3:\n            score -= 15\n            risks.append(f\"Low feature adoption: {adoption:.0%}\")\n\n        health = \"healthy\" if score >= 70 else \"at_risk\" if score >= 40 else \"critical\"\n\n        return {\n            \"health_score\": max(0, score),\n            \"health_status\": health,\n            \"risks\": risks,\n            \"recommendation\": self._get_recommendation(health, risks),\n        }\n\n    @staticmethod\n    def _get_recommendation(health: str, risks: list) -> str:\n        \"\"\"Generate a recommendation based on health assessment.\"\"\"\n        if health == \"healthy\":\n            return \"No action needed. Consider upsell opportunity.\"\n        if health == \"at_risk\":\n            return f\"Schedule check-in to address: {'; '.join(risks)}\"\n        return f\"Immediate intervention required. Critical issues: {'; '.join(risks)}\"\n```\n\n**Results**: Account review time dropped from 30 minutes to 3 minutes. At-risk customers are identified automatically, and the AI assistant generates action plans. Net revenue retention improved 8 percentage points in the first quarter.\n\n### Case Study 3: Domain-Specific Tool Server (Specialized Computation)\n\n**The Problem**: A biotech company needs to perform protein structure predictions, molecular docking simulations, and drug interaction checks. These computations require specialized libraries (AlphaFold, RDKit, Open Babel) that are difficult to install and configure. Researchers want to access these tools through their AI assistant without managing the computational environment.\n\n**The Solution**: An MCP server that wraps the computational tools behind simple, well-documented tool interfaces, running on a GPU-equipped server.\n\n```python\n\"\"\"biotech_tools.py -- Biotech computation MCP server case study.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass ComputeJob:\n    \"\"\"A computational job submitted to the server.\"\"\"\n    job_id: str\n    job_type: str\n    status: str = \"pending\"  # pending, running, completed, failed\n    input_params: dict = field(default_factory=dict)\n    result: Optional[dict] = None\n    error: Optional[str] = None\n    submitted_at: float = 0.0\n    completed_at: float = 0.0\n    compute_seconds: float = 0.0\n\n\n@dataclass\nclass BiotechServer:\n    \"\"\"MCP server for biotech computations.\"\"\"\n    _jobs: dict[str, ComputeJob] = field(default_factory=dict)\n    max_concurrent_jobs: int = 4\n    _running_count: int = 0\n\n    def submit_structure_prediction(\n        self,\n        sequence: str,\n        model: str = \"alphafold2\",\n    ) -> dict:\n        \"\"\"Submit a protein structure prediction job.\"\"\"\n        # Validate sequence (amino acid letters only)\n        valid_aa = set(\"ACDEFGHIKLMNPQRSTVWY\")\n        invalid = set(sequence.upper()) - valid_aa\n        if invalid:\n            return {\n                \"error\": f\"Invalid amino acid characters: {invalid}. \"\n                         f\"Use standard single-letter codes.\"\n            }\n\n        if len(sequence) > 2000:\n            return {\n                \"error\": f\"Sequence too long ({len(sequence)} residues). \"\n                         f\"Maximum is 2000 residues.\"\n            }\n\n        if self._running_count >= self.max_concurrent_jobs:\n            return {\n                \"error\": f\"Server at capacity ({self.max_concurrent_jobs} jobs). \"\n                         f\"Try again in a few minutes.\"\n            }\n\n        import time, secrets\n        job_id = f\"sp_{secrets.token_hex(8)}\"\n        job = ComputeJob(\n            job_id=job_id,\n            job_type=\"structure_prediction\",\n            status=\"pending\",\n            input_params={\n                \"sequence\": sequence,\n                \"model\": model,\n                \"length\": len(sequence),\n            },\n            submitted_at=time.time(),\n        )\n        self._jobs[job_id] = job\n\n        return {\n            \"job_id\": job_id,\n            \"status\": \"submitted\",\n            \"estimated_time_seconds\": len(sequence) * 0.5,\n            \"message\": f\"Structure prediction submitted for {len(sequence)}-residue sequence\",\n        }\n\n    def check_drug_interaction(\n        self,\n        drug_a: str,\n        drug_b: str,\n    ) -> dict:\n        \"\"\"Check for known interactions between two drugs.\"\"\"\n        # In production, queries a drug interaction database\n        return {\n            \"drug_a\": drug_a,\n            \"drug_b\": drug_b,\n            \"interaction_found\": False,\n            \"severity\": \"none\",\n            \"evidence_level\": \"no_data\",\n            \"recommendation\": f\"No known interaction between {drug_a} and {drug_b}.\",\n            \"disclaimer\": \"This is a computational prediction. Consult a pharmacist.\",\n        }\n\n    def get_job_status(self, job_id: str) -> dict:\n        \"\"\"Get the status of a submitted computation job.\"\"\"\n        job = self._jobs.get(job_id)\n        if not job:\n            return {\"error\": f\"Job '{job_id}' not found\"}\n        return {\n            \"job_id\": job.job_id,\n            \"job_type\": job.job_type,\n            \"status\": job.status,\n            \"submitted_at\": job.submitted_at,\n            \"completed_at\": job.completed_at if job.completed_at else None,\n            \"compute_seconds\": job.compute_seconds if job.completed_at else None,\n            \"result\": job.result,\n            \"error\": job.error,\n        }\n```\n\n**Results**: Researchers can now ask their AI assistant \"What is the predicted structure of this 300-residue protein?\" and get results back in minutes without managing computational environments. The MCP server handles queueing, GPU allocation, and result formatting. The number of predictions run per week tripled because the barrier to entry dropped from \"install AlphaFold and configure GPU drivers\" to \"ask the AI.\"\n\n---\n\n## What's Next\n\nBuilding an MCP server is the first step. The market is early -- as of April 2026, the registry has 10,000 servers but millions of potential use cases remain uncovered. The developers who build the best MCP servers today will own the tool layer of the AI economy.\n\nStart with a domain you know well. Build a server that solves a real problem for you. Publish it. Iterate based on usage data. Monetize when you have traction. The MCP specification is stable, the SDKs are mature, and the client ecosystem (Claude, GPT, Cursor, VS Code) is actively integrating. The infrastructure is ready. The opportunity is now.\n\n","# MCP Server Development & Monetization Guide: Build, Publish, and Profit from the Tool Integration Standard\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nThe Model Context Protocol has become the standard interface between AI models and external tools. In under eighteen months, the ecosystem has grown from a single Anthropic specification to over 10,000 registered servers, adopted by every major AI platform -- Claude, GPT, Gemini, Copilot, and dozens of open-source frameworks. MCP servers are the new APIs. They are how AI agents read databases, call services, execute code, and interact with the physical world. If you can build an API, you can build an MCP server. If you can build an MCP server, you can monetize it. This guide covers both: the engineering of production-grade MCP servers and the business models that turn them into revenue. It starts with the protocol architecture, moves through implementation in Python and TypeScript, covers advanced patterns like authentication, streaming, and composition, then walks through registry publishing, enterprise governance, monetization strategies, and production operations. Every chapter includes working code. By the end, you will have the knowledge to build, publish, and profit from MCP servers.\n1. [MCP Architecture Deep Dive](#chapter-1-mcp-architecture-deep-dive)\n2. [Building Your First MCP Server](#chapter-2-building-your-first-mcp-server)\n\n## What You'll Learn\n- Chapter 1: MCP Architecture Deep Dive\n- Chapter 2: Building Your First MCP Server\n- Chapter 3: Advanced Server Patterns\n- Chapter 4: Publishing to the MCP Registry\n- Chapter 5: Enterprise MCP Governance\n- Chapter 6: Monetization Strategies\n- Chapter 7: Production Operations\n- Chapter 8: Case Studies\n- What's Next\n\n## Full Guide\n\n# MCP Server Development & Monetization Guide: Build, Publish, and Profit from the Tool Integration Standard\n\nThe Model Context Protocol has become the standard interface between AI models and external tools. In under eighteen months, the ecosystem has grown from a single Anthropic specification to over 10,000 registered servers, adopted by every major AI platform -- Claude, GPT, Gemini, Copilot, and dozens of open-source frameworks. MCP servers are the new APIs. They are how AI agents read databases, call services, execute code, and interact with the physical world. If you can build an API, you can build an MCP server. If you can build an MCP server, you can monetize it. This guide covers both: the engineering of production-grade MCP servers and the business models that turn them into revenue. It starts with the protocol architecture, moves through implementation in Python and TypeScript, covers advanced patterns like authentication, streaming, and composition, then walks through registry publishing, enterprise governance, monetization strategies, and production operations. Every chapter includes working code. By the end, you will have the knowledge to build, publish, and profit from MCP servers.\n\n---\n\n## Table of Contents\n\n1. [MCP Architecture Deep Dive](#chapter-1-mcp-architecture-deep-dive)\n2. [Building Your First MCP Server](#chapter-2-building-your-first-mcp-server)\n3. [Advanced Server Patterns](#chapter-3-advanced-server-patterns)\n4. [Publishing to the MCP Registry](#chapter-4-publishing-to-the-mcp-registry)\n5. [Enterprise MCP Governance](#chapter-5-enterprise-mcp-governance)\n6. [Monetization Strategies](#chapter-6-monetization-strategies)\n7. [Production Operations](#chapter-7-production-operations)\n8. [Case Studies](#chapter-8-case-studies)\n\n---\n\n## Chapter 1: MCP Architecture Deep Dive\n\n### What MCP Actually Is\n\nThe Model Context Protocol is a client-server protocol that standardizes how AI models interact with external data sources and tools. Before MCP, every AI platform had its own way of defining tool interfaces. OpenAI used function calling with JSON Schema. Anthropic used tool use with a similar but incompatible schema. LangChain had its own tool abstraction. Every integration was bespoke. MCP replaces this fragmentation with a single protocol that any client can speak to any server.\n\nThe protocol has three roles:\n\n- **Host**: The application that contains the AI model. Claude Desktop, VS Code with Copilot, a custom LangChain app -- these are hosts. The host manages the lifecycle of MCP connections and mediates between the model and the servers.\n- **Client**: A protocol client that lives inside the host. Each client maintains a one-to-one connection with a single MCP server. The client handles capability negotiation, request routing, and response marshaling.\n- **Server**: A lightweight program that exposes tools, resources, and prompts through the MCP protocol. This is what you build. A server might wrap a database, an API, a file system, a computation engine, or any other capability that an AI model needs to access.\n\nThe separation between host and client matters for security. The host controls which servers the model can access, what permissions each server has, and whether to require human approval for sensitive operations. The client is a protocol implementation detail -- you rarely interact with it directly.\n\n### The Transport Layer\n\nMCP is transport-agnostic. The protocol defines the message format and semantics; the transport defines how those messages move between client and server. Three transports are in common use as of April 2026.\n\n**stdio (Standard Input\u002FOutput)**\n\nThe simplest transport. The host launches the server as a subprocess. Messages flow over stdin and stdout as newline-delimited JSON. stderr is reserved for logging. This is how most local MCP servers work -- Claude Desktop, for example, spawns each configured server as a child process and communicates over pipes.\n\n```\nHost Process\n    |\n    +-- spawns --> Server Process\n    |                  |\n    stdin  \u003C---------> stdout  (JSON-RPC messages)\n    stderr ----------> (logging)\n```\n\nAdvantages: Zero network configuration. No ports to open. No TLS to configure. The operating system handles the IPC. Process isolation is automatic -- if the server crashes, the host detects the broken pipe and can restart it.\n\nDisadvantages: Only works for local servers. Cannot be shared across machines. Cannot be load-balanced. Each host-server pair requires a separate process.\n\nWhen to use: Local development. Personal tools. Servers that access local files or databases. Servers where latency must be minimal (no network hop).\n\n**HTTP with Server-Sent Events (SSE)**\n\nThe original remote transport in the MCP specification. The client connects to the server over HTTP. The server uses Server-Sent Events (SSE) to push notifications and responses back to the client. This transport enables remote servers, shared servers, and server-to-client notifications.\n\nThe connection flow:\n\n1. Client sends HTTP GET to the server's SSE endpoint (typically `\u002Fsse`).\n2. Server responds with `Content-Type: text\u002Fevent-stream` and keeps the connection open.\n3. Server sends an `endpoint` event containing a URL for the client to POST requests to.\n4. Client sends JSON-RPC requests via HTTP POST to that endpoint.\n5. Server sends JSON-RPC responses and notifications via the SSE stream.\n\n```python\n# Simplified SSE transport flow\n# Server side\n@app.get(\"\u002Fsse\")\nasync def sse_endpoint():\n    async def event_stream():\n        yield f\"event: endpoint\\ndata: \u002Fmessages\u002F{session_id}\\n\\n\"\n        while True:\n            message = await outgoing_queue.get()\n            yield f\"event: message\\ndata: {json.dumps(message)}\\n\\n\"\n    return StreamingResponse(event_stream(), media_type=\"text\u002Fevent-stream\")\n\n@app.post(\"\u002Fmessages\u002F{session_id}\")\nasync def handle_message(session_id: str, request: Request):\n    body = await request.json()\n    # Process JSON-RPC request, put response on outgoing_queue\n```\n\nAdvantages: Works over the network. Supports server-to-client push. Compatible with existing HTTP infrastructure (load balancers, proxies, CDNs).\n\nDisadvantages: SSE is unidirectional (server-to-client only), so the client must use a separate HTTP POST channel for requests. This creates two connections per session. Some proxies and firewalls struggle with long-lived SSE connections. Connection resumption after network interruption requires custom logic.\n\nWhen to use: Remote servers behind a web server. Servers that need to push updates. Production deployments where you already have HTTP infrastructure.\n\n**Streamable HTTP**\n\nThe newest transport, introduced in the MCP specification revision of March 2026. Streamable HTTP simplifies the SSE transport by using a single HTTP endpoint for both requests and responses. The client sends a POST request. The server can respond with either a regular JSON response (for simple request-response patterns) or upgrade to SSE for streaming responses and follow-up notifications.\n\n```\nClient                              Server\n  |                                    |\n  |  POST \u002Fmcp                         |\n  |  {\"jsonrpc\":\"2.0\",\"method\":\"...\"}  |\n  |----------------------------------->|\n  |                                    |\n  |  200 OK                            |\n  |  Content-Type: text\u002Fevent-stream   |\n  |  (or application\u002Fjson for simple)  |\n  |\u003C-----------------------------------|\n```\n\nAdvantages: Single endpoint. Backward-compatible with simple HTTP clients. Supports streaming when needed. Easier to deploy behind reverse proxies. No persistent connection required for basic operations.\n\nDisadvantages: Newer, so not all clients support it yet. Streaming mode still has the SSE proxy compatibility issues.\n\nWhen to use: New remote deployments. Servers that need to work with both streaming-capable and simple HTTP clients.\n\n### The Message Format: JSON-RPC 2.0\n\nEvery MCP message is a JSON-RPC 2.0 message. This is not a custom format -- it is the same JSON-RPC used by Ethereum, Language Server Protocol, and dozens of other systems. The format has three message types.\n\n**Request**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"tools\u002Fcall\",\n  \"params\": {\n    \"name\": \"query_database\",\n    \"arguments\": {\n      \"sql\": \"SELECT count(*) FROM users\"\n    }\n  }\n}\n```\n\nThe `id` field correlates requests with responses. The `method` field identifies the operation. The `params` field carries the operation-specific data.\n\n**Response**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"result\": {\n    \"content\": [\n      {\n        \"type\": \"text\",\n        \"text\": \"Query returned 42,531 rows.\"\n      }\n    ]\n  }\n}\n```\n\n**Error Response**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"error\": {\n    \"code\": -32602,\n    \"message\": \"Invalid params\",\n    \"data\": \"Column 'nonexistent' does not exist in table 'users'\"\n  }\n}\n```\n\nStandard JSON-RPC error codes apply: -32700 (parse error), -32600 (invalid request), -32601 (method not found), -32602 (invalid params), -32603 (internal error). MCP adds no custom error codes -- use the standard codes plus descriptive messages and data fields.\n\n**Notification**\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"method\": \"notifications\u002Ftools\u002Flist_changed\"\n}\n```\n\nNotifications have no `id` field and expect no response. They are fire-and-forget messages used for events like \"the tool list has changed\" or \"a resource has been updated.\"\n\n### Capabilities Negotiation\n\nWhen a client connects to a server, the first message exchange is capabilities negotiation via the `initialize` method. The client sends its capabilities; the server responds with its own.\n\n```json\n\u002F\u002F Client -> Server\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"initialize\",\n  \"params\": {\n    \"protocolVersion\": \"2025-03-26\",\n    \"capabilities\": {\n      \"roots\": { \"listChanged\": true },\n      \"sampling\": {}\n    },\n    \"clientInfo\": {\n      \"name\": \"claude-desktop\",\n      \"version\": \"1.5.0\"\n    }\n  }\n}\n\n\u002F\u002F Server -> Client\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"result\": {\n    \"protocolVersion\": \"2025-03-26\",\n    \"capabilities\": {\n      \"tools\": { \"listChanged\": true },\n      \"resources\": { \"subscribe\": true, \"listChanged\": true },\n      \"prompts\": { \"listChanged\": true },\n      \"logging\": {}\n    },\n    \"serverInfo\": {\n      \"name\": \"database-server\",\n      \"version\": \"2.1.0\"\n    }\n  }\n}\n```\n\nAfter the server responds, the client sends an `initialized` notification to confirm the handshake is complete. Only then can the client call tools, read resources, or use prompts.\n\nKey fields in the server capabilities:\n\n- `tools`: The server exposes callable tools. `listChanged` means the server will notify the client if the tool list changes at runtime.\n- `resources`: The server exposes readable resources (files, database records, API responses). `subscribe` means the client can subscribe to resource change notifications.\n- `prompts`: The server exposes prompt templates that the model can use.\n- `logging`: The server supports structured logging that the client can consume.\n\nCapabilities negotiation is important because it allows both sides to adapt. A server that exposes only tools does not need to handle resource subscriptions. A client that does not support sampling will never receive sampling requests from the server.\n\n### The Three Primitives: Tools, Resources, and Prompts\n\nMCP servers expose capabilities through three primitives. Understanding which primitive to use for which purpose is the most important design decision you will make.\n\n**Tools**\n\nTools are functions that the AI model can call. They take structured input, perform an action, and return a result. Tools are the most common primitive and the one you will use most often.\n\nA tool has:\n- A name (string, unique within the server)\n- A description (string, used by the model to decide when to call the tool)\n- An input schema (JSON Schema, validated before execution)\n- A handler function (your code that executes when the tool is called)\n\n```python\n@server.tool()\nasync def query_database(sql: str) -> str:\n    \"\"\"Execute a read-only SQL query against the analytics database.\n\n    Use this tool when the user asks about data, metrics, counts,\n    or any question that can be answered with a database query.\n    Only SELECT statements are allowed.\n    \"\"\"\n    if not sql.strip().upper().startswith(\"SELECT\"):\n        raise ValueError(\"Only SELECT queries are allowed\")\n    result = await db.execute(sql)\n    return format_result(result)\n```\n\nTools are model-controlled -- the AI model decides when to call them based on the description and the current conversation context. The host may require human approval before executing a tool call (this is configurable per-server and per-tool).\n\nWhen to use tools: Any operation that has side effects (creating records, sending emails, modifying state). Any computation that the model cannot do itself (database queries, API calls, mathematical operations). Any action where the model needs to act on behalf of the user.\n\n**Resources**\n\nResources are data that the AI model can read. They are identified by URIs and return content in a structured format. Resources are like GET endpoints in a REST API -- they retrieve data without modifying anything.\n\nA resource has:\n- A URI (string, following the `scheme:\u002F\u002Fpath` pattern)\n- A name (string, human-readable)\n- A description (string, optional)\n- A MIME type (string, optional)\n- Content (text or binary, returned when the resource is read)\n\n```python\n@server.resource(\"config:\u002F\u002Fapp\u002Fsettings\")\nasync def get_app_settings() -> str:\n    \"\"\"Current application configuration settings.\"\"\"\n    settings = await load_settings()\n    return json.dumps(settings, indent=2)\n```\n\nResources can also be dynamic using URI templates:\n\n```python\n@server.resource(\"db:\u002F\u002Ftables\u002F{table_name}\u002Fschema\")\nasync def get_table_schema(table_name: str) -> str:\n    \"\"\"Schema definition for a database table.\"\"\"\n    schema = await db.get_schema(table_name)\n    return json.dumps(schema, indent=2)\n```\n\nResources are application-controlled -- the host application decides when to expose them to the model, often by attaching them to the conversation context. The model does not call resources directly; instead, the host includes resource content in the model's context window.\n\nWhen to use resources: Configuration data. Reference documentation. Database schemas. File contents. Anything the model needs to read but should not modify.\n\n**Prompts**\n\nPrompts are reusable templates that the AI model or the user can invoke. They generate structured message sequences that set up the model's context for a specific task.\n\nA prompt has:\n- A name (string, unique within the server)\n- A description (string, explains what the prompt does)\n- Arguments (list of named parameters, some required, some optional)\n- A handler that returns a list of messages\n\n```python\n@server.prompt()\nasync def analyze_table(table_name: str, question: str) -> list:\n    \"\"\"Analyze a database table to answer a specific question.\"\"\"\n    schema = await db.get_schema(table_name)\n    sample = await db.execute(f\"SELECT * FROM {table_name} LIMIT 5\")\n    return [\n        {\n            \"role\": \"user\",\n            \"content\": f\"Here is the schema for {table_name}:\\n{schema}\\n\\n\"\n                       f\"Sample data:\\n{sample}\\n\\n\"\n                       f\"Question: {question}\"\n        }\n    ]\n```\n\nPrompts are user-controlled -- the user explicitly selects them (like choosing a slash command). They are useful for workflows that require a specific context setup.\n\nWhen to use prompts: Complex workflows that need specific context. Onboarding sequences. Analysis templates where the model needs schema + sample data + instructions.\n\n### Server Lifecycle\n\nAn MCP server goes through a defined lifecycle:\n\n1. **Initialization**: Client sends `initialize` with its capabilities. Server responds with its capabilities and info. Client sends `initialized` notification.\n2. **Operation**: Client and server exchange requests, responses, and notifications. The client can call tools, read resources, and invoke prompts. The server can send logging messages and change notifications.\n3. **Shutdown**: Client sends a shutdown request or closes the transport. The server cleans up resources and exits.\n\nFor stdio servers, the lifecycle is tied to the process lifetime. When the host terminates the subprocess, the server is gone. For HTTP servers, sessions can persist across multiple HTTP connections, and the server process can serve multiple clients simultaneously.\n\nThe lifecycle matters for resource management. If your server opens database connections, file handles, or network sockets during initialization, it must close them during shutdown. The Python and TypeScript SDKs provide lifecycle hooks for this purpose.\n\n```python\nfrom contextlib import asynccontextmanager\nfrom mcp.server import Server\n\n@asynccontextmanager\nasync def server_lifespan(server: Server):\n    # Startup: open connections\n    db = await create_db_pool()\n    server.state[\"db\"] = db\n    try:\n        yield\n    finally:\n        # Shutdown: close connections\n        await db.close()\n```\n\n---\n\n## Chapter 2: Building Your First MCP Server\n\n### Environment Setup\n\nYou need Python 3.10 or later for the Python SDK, or Node.js 18 or later for the TypeScript SDK. Both SDKs are actively maintained and track the latest protocol specification.\n\n**Python**\n\n```bash\npip install mcp\n```\n\nThe `mcp` package includes the server framework, all three transports (stdio, SSE, streamable HTTP), and the client library for testing. It pulls in `pydantic` for schema validation and `httpx` for HTTP transport.\n\n**TypeScript**\n\n```bash\nnpm install @modelcontextprotocol\u002Fsdk\n```\n\nThe TypeScript SDK includes the same server framework, transports, and client library.\n\n### A Minimal Python MCP Server\n\nHere is the simplest possible MCP server -- a single tool that adds two numbers:\n\n```python\n\"\"\"minimal_server.py -- A minimal MCP server with one tool.\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"calculator\")\n\n@server.tool()\nasync def add(a: float, b: float) -> str:\n    \"\"\"Add two numbers together.\n\n    Use this tool when the user asks you to add, sum, or total\n    two numeric values.\n    \"\"\"\n    result = a + b\n    return str(result)\n\nif __name__ == \"__main__\":\n    server.run(transport=\"stdio\")\n```\n\nThat is 15 lines of code. Let us break down what each part does.\n\n`FastMCP(\"calculator\")` creates a server instance with the name \"calculator\". This name appears in capabilities negotiation and helps the client identify the server.\n\n`@server.tool()` registers the decorated function as a tool. The function name becomes the tool name. The docstring becomes the tool description. The function signature is automatically converted to a JSON Schema input schema -- `a: float, b: float` becomes:\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"a\": { \"type\": \"number\" },\n    \"b\": { \"type\": \"number\" }\n  },\n  \"required\": [\"a\", \"b\"]\n}\n```\n\nThe return type `str` means the tool returns text content. MCP tools always return content blocks -- text, images, or embedded resources. The SDK handles wrapping your string return value into the proper content block format.\n\n`server.run(transport=\"stdio\")` starts the server using the stdio transport. It reads JSON-RPC messages from stdin and writes responses to stdout.\n\n### Running and Testing Locally\n\n**With Claude Desktop**\n\nAdd the server to your Claude Desktop configuration file (`claude_desktop_config.json`):\n\n```json\n{\n  \"mcpServers\": {\n    \"calculator\": {\n      \"command\": \"python\",\n      \"args\": [\"\u002Fpath\u002Fto\u002Fminimal_server.py\"]\n    }\n  }\n}\n```\n\nRestart Claude Desktop. The calculator tool will appear in the tools list. Ask Claude \"What is 17.5 plus 23.8?\" and it will call the `add` tool.\n\n**With the MCP Inspector**\n\nThe MCP Inspector is a web-based debugging tool that connects to your server and lets you interact with it directly:\n\n```bash\nnpx @modelcontextprotocol\u002Finspector python minimal_server.py\n```\n\nThis opens a browser interface where you can see the server's capabilities, call tools manually, browse resources, and view the raw JSON-RPC messages.\n\n**With the Python Client Library**\n\nFor automated testing, use the MCP client library:\n\n```python\n\"\"\"test_minimal_server.py -- Test the calculator server.\"\"\"\n\nimport asyncio\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\nasync def test_add():\n    server_params = StdioServerParameters(\n        command=\"python\",\n        args=[\"minimal_server.py\"],\n    )\n    async with stdio_client(server_params) as (read, write):\n        async with ClientSession(read, write) as session:\n            await session.initialize()\n\n            # List tools\n            tools = await session.list_tools()\n            assert len(tools.tools) == 1\n            assert tools.tools[0].name == \"add\"\n\n            # Call the add tool\n            result = await session.call_tool(\"add\", {\"a\": 17.5, \"b\": 23.8})\n            assert result.content[0].text == \"41.3\"\n\nasyncio.run(test_add())\n```\n\n### A TypeScript MCP Server\n\nThe equivalent server in TypeScript:\n\n```typescript\n\u002F\u002F minimal_server.ts -- A minimal MCP server with one tool.\n\nimport { McpServer } from \"@modelcontextprotocol\u002Fsdk\u002Fserver\u002Fmcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol\u002Fsdk\u002Fserver\u002Fstdio.js\";\nimport { z } from \"zod\";\n\nconst server = new McpServer({\n  name: \"calculator\",\n  version: \"1.0.0\",\n});\n\nserver.tool(\n  \"add\",\n  \"Add two numbers together. Use this tool when the user asks you to add, sum, or total two numeric values.\",\n  {\n    a: z.number().describe(\"First number\"),\n    b: z.number().describe(\"Second number\"),\n  },\n  async ({ a, b }) => ({\n    content: [{ type: \"text\", text: String(a + b) }],\n  })\n);\n\nasync function main() {\n  const transport = new StdioServerTransport();\n  await server.connect(transport);\n}\n\nmain();\n```\n\nThe TypeScript SDK uses Zod for schema definition instead of Python type hints. The structure is the same: create a server, register tools, connect a transport.\n\n### Defining Tools with Schemas\n\nReal tools need more sophisticated input schemas. Here is a database query tool with proper validation:\n\n```python\n\"\"\"db_server.py -- MCP server for database access.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"database\")\n\n# Allowed tables for security\nALLOWED_TABLES = {\"users\", \"orders\", \"products\", \"analytics\"}\n\n# Maximum rows to return\nMAX_ROWS = 1000\n\n@server.tool()\nasync def query_database(\n    sql: str,\n    max_rows: int = 100,\n    format: str = \"table\",\n) -> str:\n    \"\"\"Execute a read-only SQL query against the analytics database.\n\n    Use this tool to answer questions about users, orders, products,\n    or analytics data. Only SELECT statements are allowed.\n    Dangerous operations (DROP, DELETE, UPDATE, INSERT) are blocked.\n\n    Args:\n        sql: The SQL query to execute. Must be a SELECT statement.\n        max_rows: Maximum number of rows to return (1-1000, default 100).\n        format: Output format -- \"table\" for ASCII table, \"csv\" for CSV,\n                \"json\" for JSON array.\n    \"\"\"\n    # Validate SQL\n    normalized = sql.strip().upper()\n    if not normalized.startswith(\"SELECT\"):\n        raise ValueError(\"Only SELECT queries are allowed\")\n\n    dangerous = [\"DROP\", \"DELETE\", \"UPDATE\", \"INSERT\", \"ALTER\", \"TRUNCATE\"]\n    for keyword in dangerous:\n        if keyword in normalized:\n            raise ValueError(f\"Dangerous keyword '{keyword}' is not allowed\")\n\n    # Validate max_rows\n    max_rows = min(max(1, max_rows), MAX_ROWS)\n\n    # Validate format\n    if format not in (\"table\", \"csv\", \"json\"):\n        raise ValueError(f\"Invalid format '{format}'. Use table, csv, or json.\")\n\n    # Execute query (using your database connection)\n    result = await execute_query(sql, limit=max_rows)\n\n    # Format output\n    if format == \"json\":\n        return json.dumps(result, indent=2, default=str)\n    elif format == \"csv\":\n        return format_as_csv(result)\n    else:\n        return format_as_table(result)\n\n\n@server.tool()\nasync def list_tables() -> str:\n    \"\"\"List all available database tables and their row counts.\n\n    Use this tool to discover what data is available before\n    writing a query.\n    \"\"\"\n    tables = []\n    for table in sorted(ALLOWED_TABLES):\n        count = await get_row_count(table)\n        tables.append(f\"  {table}: {count:,} rows\")\n    return \"Available tables:\\n\" + \"\\n\".join(tables)\n\n\n@server.tool()\nasync def describe_table(table_name: str) -> str:\n    \"\"\"Get the schema (columns, types, constraints) for a database table.\n\n    Use this tool to understand a table's structure before\n    writing a query against it.\n\n    Args:\n        table_name: The name of the table to describe.\n    \"\"\"\n    if table_name not in ALLOWED_TABLES:\n        raise ValueError(\n            f\"Table '{table_name}' is not available. \"\n            f\"Available tables: {', '.join(sorted(ALLOWED_TABLES))}\"\n        )\n    schema = await get_table_schema(table_name)\n    return format_schema(schema)\n```\n\nKey patterns to notice:\n\n1. **Descriptive docstrings**: The model reads these to decide when to call each tool. Be specific about what the tool does and when to use it. Include examples of the kinds of questions each tool can answer.\n\n2. **Input validation**: Validate every input before using it. MCP validates the JSON Schema types, but you must validate semantic constraints (allowed tables, safe SQL, value ranges).\n\n3. **Default values**: Use sensible defaults so the model does not need to specify every parameter. `max_rows=100` and `format=\"table\"` cover the common case.\n\n4. **Error messages**: Raise `ValueError` with clear messages. The error text is sent back to the model, which can use it to correct its tool call. \"Table 'nonexistent' is not available. Available tables: users, orders, products, analytics\" is much more useful than \"Invalid table.\"\n\n5. **Discovery tools**: Always provide tools that help the model discover what is available. `list_tables` and `describe_table` let the model explore the database schema before writing queries. Without these, the model has to guess table and column names.\n\n### Input Validation Deep Dive\n\nMCP servers receive input from AI models, which means the input is generated, not typed by a human. Models make mistakes -- they hallucinate column names, invent parameters, and sometimes pass the wrong types despite the schema. Robust input validation is not optional.\n\nThe Python SDK validates JSON Schema types automatically. If your tool expects `a: float` and the model sends `\"hello\"`, the SDK returns an error before your code runs. But type validation is just the first layer.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\nimport re\n\n\n@dataclass\nclass ValidationResult:\n    \"\"\"Result of input validation.\"\"\"\n    valid: bool\n    error: Optional[str] = None\n    sanitized_value: Optional[str] = None\n\n\ndef validate_sql(sql: str) -> ValidationResult:\n    \"\"\"Validate a SQL query for safety and correctness.\"\"\"\n    if not sql or not sql.strip():\n        return ValidationResult(False, \"SQL query cannot be empty\")\n\n    normalized = sql.strip()\n    upper = normalized.upper()\n\n    # Must start with SELECT\n    if not upper.startswith(\"SELECT\"):\n        return ValidationResult(False, \"Only SELECT queries are allowed\")\n\n    # Block dangerous keywords\n    dangerous_patterns = [\n        r\"\\bDROP\\b\", r\"\\bDELETE\\b\", r\"\\bUPDATE\\b\", r\"\\bINSERT\\b\",\n        r\"\\bALTER\\b\", r\"\\bTRUNCATE\\b\", r\"\\bEXEC\\b\", r\"\\bEXECUTE\\b\",\n        r\"\\bCREATE\\b\", r\"\\bGRANT\\b\", r\"\\bREVOKE\\b\",\n    ]\n    for pattern in dangerous_patterns:\n        if re.search(pattern, upper):\n            keyword = re.search(pattern, upper).group()\n            return ValidationResult(\n                False, f\"Dangerous keyword '{keyword}' is not allowed\"\n            )\n\n    # Block multiple statements (SQL injection via semicolons)\n    if \";\" in normalized[:-1]:  # Allow trailing semicolon\n        return ValidationResult(\n            False, \"Multiple SQL statements are not allowed\"\n        )\n\n    # Block comments (potential injection vector)\n    if \"--\" in normalized or \"\u002F*\" in normalized:\n        return ValidationResult(False, \"SQL comments are not allowed\")\n\n    return ValidationResult(True, sanitized_value=normalized.rstrip(\";\"))\n\n\ndef validate_table_name(name: str, allowed: set) -> ValidationResult:\n    \"\"\"Validate a table name against an allowlist.\"\"\"\n    if not name or not name.strip():\n        return ValidationResult(False, \"Table name cannot be empty\")\n\n    cleaned = name.strip().lower()\n\n    # Only allow alphanumeric and underscores\n    if not re.match(r\"^[a-z][a-z0-9_]*$\", cleaned):\n        return ValidationResult(\n            False,\n            f\"Invalid table name '{cleaned}'. \"\n            \"Use only lowercase letters, numbers, and underscores.\"\n        )\n\n    if cleaned not in allowed:\n        return ValidationResult(\n            False,\n            f\"Table '{cleaned}' is not available. \"\n            f\"Available: {', '.join(sorted(allowed))}\"\n        )\n\n    return ValidationResult(True, sanitized_value=cleaned)\n```\n\n### Error Handling Patterns\n\nMCP tools should return errors in a way that helps the model recover. There are two kinds of errors:\n\n1. **Tool errors**: The tool executed but the operation failed. Return an error result with `is_error=True`. The model sees the error message and can try again with corrected input.\n\n2. **Protocol errors**: The request itself is malformed. Raise an exception. The SDK converts it to a JSON-RPC error response.\n\n```python\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp.types import TextContent\n\nserver = FastMCP(\"robust-server\")\n\n@server.tool()\nasync def safe_query(sql: str) -> list:\n    \"\"\"Execute a database query with comprehensive error handling.\"\"\"\n    # Validate input\n    validation = validate_sql(sql)\n    if not validation.valid:\n        # Return error as tool result -- model can see it and retry\n        return [TextContent(\n            type=\"text\",\n            text=f\"Error: {validation.error}\\n\\n\"\n                 f\"Please fix the query and try again. \"\n                 f\"Only SELECT statements against these tables \"\n                 f\"are allowed: {', '.join(sorted(ALLOWED_TABLES))}\"\n        )]\n\n    try:\n        result = await execute_query(validation.sanitized_value)\n        return [TextContent(type=\"text\", text=format_result(result))]\n    except DatabaseConnectionError as e:\n        # Transient error -- tell the model to retry\n        return [TextContent(\n            type=\"text\",\n            text=f\"Database connection error: {e}. \"\n                 f\"This is a temporary issue. Please try again.\"\n        )]\n    except QueryTimeoutError as e:\n        # Query too complex -- suggest simplification\n        return [TextContent(\n            type=\"text\",\n            text=f\"Query timed out after {e.timeout}s. \"\n                 f\"Try simplifying the query: use LIMIT, \"\n                 f\"avoid subqueries, or filter with WHERE.\"\n        )]\n    except Exception as e:\n        # Unknown error -- log and return generic message\n        logger.exception(\"Unexpected error executing query\")\n        return [TextContent(\n            type=\"text\",\n            text=\"An unexpected error occurred. \"\n                 \"Please try a different query.\"\n        )]\n```\n\nThe pattern is: validate first, catch specific exceptions, provide actionable error messages that help the model recover. Never return a raw stack trace -- the model cannot do anything useful with it.\n\n### Testing Your Server Locally\n\nTesting MCP servers requires testing at two levels: unit tests for individual tool logic, and integration tests for the full MCP protocol flow.\n\n**Unit Testing Tool Logic**\n\nExtract your tool logic into pure functions that can be tested without the MCP framework:\n\n```python\n\"\"\"test_db_tools.py -- Unit tests for database tool logic.\"\"\"\n\nimport pytest\nfrom db_server import validate_sql, validate_table_name, ALLOWED_TABLES\n\n\nclass TestValidateSQL:\n    \"\"\"Tests for SQL validation.\"\"\"\n\n    def test_valid_select(self):\n        result = validate_sql(\"SELECT * FROM users\")\n        assert result.valid is True\n        assert result.sanitized_value == \"SELECT * FROM users\"\n\n    def test_rejects_empty(self):\n        result = validate_sql(\"\")\n        assert result.valid is False\n        assert \"empty\" in result.error.lower()\n\n    def test_rejects_drop(self):\n        result = validate_sql(\"DROP TABLE users\")\n        assert result.valid is False\n        assert \"DROP\" in result.error\n\n    def test_rejects_delete(self):\n        result = validate_sql(\"DELETE FROM users WHERE id = 1\")\n        assert result.valid is False\n\n    def test_rejects_multiple_statements(self):\n        result = validate_sql(\"SELECT 1; DROP TABLE users\")\n        assert result.valid is False\n        assert \"Multiple\" in result.error\n\n    def test_allows_trailing_semicolon(self):\n        result = validate_sql(\"SELECT * FROM users;\")\n        assert result.valid is True\n\n    def test_rejects_comments(self):\n        result = validate_sql(\"SELECT * FROM users -- drop table\")\n        assert result.valid is False\n\n    def test_case_insensitive_select(self):\n        result = validate_sql(\"select * from users\")\n        assert result.valid is True\n\n\nclass TestValidateTableName:\n    \"\"\"Tests for table name validation.\"\"\"\n\n    def test_valid_table(self):\n        result = validate_table_name(\"users\", ALLOWED_TABLES)\n        assert result.valid is True\n\n    def test_rejects_unknown_table(self):\n        result = validate_table_name(\"secrets\", ALLOWED_TABLES)\n        assert result.valid is False\n        assert \"not available\" in result.error\n\n    def test_rejects_sql_injection(self):\n        result = validate_table_name(\"users; DROP TABLE\", ALLOWED_TABLES)\n        assert result.valid is False\n\n    def test_strips_whitespace(self):\n        result = validate_table_name(\"  users  \", ALLOWED_TABLES)\n        assert result.valid is True\n        assert result.sanitized_value == \"users\"\n```\n\n**Integration Testing with the MCP Client**\n\nFor full protocol testing, use the SDK's client to connect to your server:\n\n```python\n\"\"\"test_integration.py -- Integration tests for the MCP server.\"\"\"\n\nimport asyncio\nimport pytest\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\n\n@pytest.fixture\nasync def session():\n    \"\"\"Create a client session connected to the test server.\"\"\"\n    params = StdioServerParameters(\n        command=\"python\",\n        args=[\"db_server.py\"],\n        env={\"DATABASE_URL\": \"sqlite:\u002F\u002F\u002Ftest.db\"},\n    )\n    async with stdio_client(params) as (read, write):\n        async with ClientSession(read, write) as session:\n            await session.initialize()\n            yield session\n\n\n@pytest.mark.asyncio\nasync def test_list_tools(session):\n    \"\"\"Server exposes the expected tools.\"\"\"\n    tools = await session.list_tools()\n    names = {t.name for t in tools.tools}\n    assert \"query_database\" in names\n    assert \"list_tables\" in names\n    assert \"describe_table\" in names\n\n\n@pytest.mark.asyncio\nasync def test_query_returns_results(session):\n    \"\"\"A valid query returns formatted results.\"\"\"\n    result = await session.call_tool(\n        \"query_database\",\n        {\"sql\": \"SELECT 1 as value\", \"format\": \"json\"},\n    )\n    assert len(result.content) > 0\n    assert \"value\" in result.content[0].text\n\n\n@pytest.mark.asyncio\nasync def test_dangerous_query_rejected(session):\n    \"\"\"A dangerous query returns an error, not a crash.\"\"\"\n    result = await session.call_tool(\n        \"query_database\",\n        {\"sql\": \"DROP TABLE users\"},\n    )\n    assert \"error\" in result.content[0].text.lower() or result.isError\n```\n\n---\n\n## Chapter 3: Advanced Server Patterns\n\n### Stateful Servers: Sessions and Context\n\nMany real-world MCP servers need to maintain state across tool calls. A database server needs a connection pool. A code execution server needs a sandbox with accumulated state. A workflow server needs to track which steps have been completed.\n\nMCP supports stateful servers through server-side session management. Each client connection gets a unique session. The server can store per-session state that persists across tool calls within that session.\n\n```python\n\"\"\"stateful_server.py -- MCP server with session state.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Any\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"workflow\")\n\n\n@dataclass\nclass WorkflowState:\n    \"\"\"Per-session workflow state.\"\"\"\n    steps_completed: list = field(default_factory=list)\n    variables: dict = field(default_factory=dict)\n    current_step: int = 0\n    total_steps: int = 0\n\n\n# Session state storage\n_sessions: dict[str, WorkflowState] = {}\n\n\ndef get_state(session_id: str) -> WorkflowState:\n    \"\"\"Get or create session state.\"\"\"\n    if session_id not in _sessions:\n        _sessions[session_id] = WorkflowState()\n    return _sessions[session_id]\n\n\n@server.tool()\nasync def start_workflow(name: str, steps: list[str]) -> str:\n    \"\"\"Start a new multi-step workflow.\n\n    Args:\n        name: Name of the workflow.\n        steps: List of step descriptions in order.\n    \"\"\"\n    ctx = server.request_context\n    state = get_state(ctx.session.session_id)\n    state.steps_completed = []\n    state.current_step = 0\n    state.total_steps = len(steps)\n    state.variables[\"workflow_name\"] = name\n    state.variables[\"steps\"] = steps\n    return (\n        f\"Workflow '{name}' started with {len(steps)} steps.\\n\"\n        f\"Next step: {steps[0]}\"\n    )\n\n\n@server.tool()\nasync def complete_step(result: str) -> str:\n    \"\"\"Mark the current workflow step as complete.\n\n    Args:\n        result: The result or output of the completed step.\n    \"\"\"\n    ctx = server.request_context\n    state = get_state(ctx.session.session_id)\n\n    if state.current_step >= state.total_steps:\n        return \"Error: No active workflow or all steps already completed.\"\n\n    steps = state.variables.get(\"steps\", [])\n    step_name = steps[state.current_step]\n    state.steps_completed.append({\n        \"step\": step_name,\n        \"result\": result,\n        \"index\": state.current_step,\n    })\n    state.current_step += 1\n\n    if state.current_step >= state.total_steps:\n        return (\n            f\"Step '{step_name}' completed. \"\n            f\"Workflow '{state.variables['workflow_name']}' is now finished. \"\n            f\"All {state.total_steps} steps completed.\"\n        )\n\n    next_step = steps[state.current_step]\n    return (\n        f\"Step '{step_name}' completed ({state.current_step}\u002F{state.total_steps}). \"\n        f\"Next step: {next_step}\"\n    )\n\n\n@server.tool()\nasync def get_workflow_status() -> str:\n    \"\"\"Get the current workflow progress and completed steps.\"\"\"\n    ctx = server.request_context\n    state = get_state(ctx.session.session_id)\n\n    if state.total_steps == 0:\n        return \"No active workflow. Use start_workflow to begin.\"\n\n    lines = [\n        f\"Workflow: {state.variables.get('workflow_name', 'Unknown')}\",\n        f\"Progress: {state.current_step}\u002F{state.total_steps}\",\n        \"\",\n        \"Completed steps:\",\n    ]\n    for step in state.steps_completed:\n        lines.append(f\"  [{step['index'] + 1}] {step['step']}: {step['result']}\")\n\n    if state.current_step \u003C state.total_steps:\n        remaining = state.variables[\"steps\"][state.current_step:]\n        lines.append(\"\")\n        lines.append(\"Remaining steps:\")\n        for i, step in enumerate(remaining):\n            lines.append(f\"  [{state.current_step + i + 1}] {step}\")\n\n    return \"\\n\".join(lines)\n```\n\n### Streaming Responses\n\nFor long-running operations, streaming progress updates to the client prevents timeouts and keeps the user informed. MCP supports streaming through progress notifications and logging.\n\n```python\n\"\"\"streaming_server.py -- MCP server with progress streaming.\"\"\"\n\nimport asyncio\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"data-processor\")\n\n\n@server.tool()\nasync def process_large_dataset(\n    source: str,\n    batch_size: int = 1000,\n) -> str:\n    \"\"\"Process a large dataset in batches with progress updates.\n\n    Args:\n        source: The data source identifier.\n        batch_size: Number of records per batch.\n    \"\"\"\n    ctx = server.request_context\n    total_records = await get_record_count(source)\n    processed = 0\n    errors = 0\n    batches = (total_records + batch_size - 1) \u002F\u002F batch_size\n\n    for batch_num in range(batches):\n        # Send progress notification\n        await ctx.report_progress(\n            progress=batch_num,\n            total=batches,\n        )\n\n        # Send log message for visibility\n        await ctx.info(\n            f\"Processing batch {batch_num + 1}\u002F{batches} \"\n            f\"({processed}\u002F{total_records} records)\"\n        )\n\n        # Process the batch\n        batch_result = await process_batch(source, batch_num, batch_size)\n        processed += batch_result[\"processed\"]\n        errors += batch_result[\"errors\"]\n\n        # Yield control to allow other requests\n        await asyncio.sleep(0)\n\n    return (\n        f\"Processing complete.\\n\"\n        f\"Total records: {total_records}\\n\"\n        f\"Processed: {processed}\\n\"\n        f\"Errors: {errors}\\n\"\n        f\"Batches: {batches}\"\n    )\n```\n\nThe `report_progress` method sends a `notifications\u002Fprogress` message that the client can use to display a progress bar. The `info` method sends a log message that appears in the client's log stream.\n\n### Rate Limiting and Quotas\n\nIf your MCP server wraps a paid API or a resource-constrained backend, you need rate limiting. Implement it as middleware that runs before every tool call.\n\n```python\n\"\"\"rate_limited_server.py -- MCP server with rate limiting.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"rate-limited-api\")\n\n\n@dataclass\nclass RateLimiter:\n    \"\"\"Token bucket rate limiter.\"\"\"\n    max_tokens: int = 60\n    refill_rate: float = 1.0  # tokens per second\n    _buckets: dict = field(default_factory=lambda: defaultdict(lambda: {\"tokens\": 60, \"last\": time.monotonic()}))\n\n    def allow(self, key: str) -> bool:\n        \"\"\"Check if a request is allowed and consume a token.\"\"\"\n        bucket = self._buckets[key]\n        now = time.monotonic()\n        elapsed = now - bucket[\"last\"]\n        bucket[\"tokens\"] = min(\n            self.max_tokens,\n            bucket[\"tokens\"] + elapsed * self.refill_rate,\n        )\n        bucket[\"last\"] = now\n\n        if bucket[\"tokens\"] >= 1:\n            bucket[\"tokens\"] -= 1\n            return True\n        return False\n\n    def tokens_remaining(self, key: str) -> int:\n        \"\"\"Return approximate tokens remaining.\"\"\"\n        bucket = self._buckets[key]\n        now = time.monotonic()\n        elapsed = now - bucket[\"last\"]\n        return int(min(\n            self.max_tokens,\n            bucket[\"tokens\"] + elapsed * self.refill_rate,\n        ))\n\n\n@dataclass\nclass QuotaTracker:\n    \"\"\"Track usage against daily quotas.\"\"\"\n    daily_limit: int = 10000\n    _usage: dict = field(default_factory=lambda: defaultdict(lambda: {\"count\": 0, \"day\": \"\"}))\n\n    def check_and_increment(self, key: str) -> tuple[bool, int]:\n        \"\"\"Check quota and increment usage. Returns (allowed, remaining).\"\"\"\n        today = time.strftime(\"%Y-%m-%d\")\n        record = self._usage[key]\n\n        # Reset on new day\n        if record[\"day\"] != today:\n            record[\"count\"] = 0\n            record[\"day\"] = today\n\n        if record[\"count\"] >= self.daily_limit:\n            return False, 0\n\n        record[\"count\"] += 1\n        remaining = self.daily_limit - record[\"count\"]\n        return True, remaining\n\n\nlimiter = RateLimiter(max_tokens=60, refill_rate=1.0)\nquota = QuotaTracker(daily_limit=10000)\n\n\ndef rate_limit_check(client_id: str) -> None:\n    \"\"\"Check rate limit and quota before processing.\"\"\"\n    if not limiter.allow(client_id):\n        remaining = limiter.tokens_remaining(client_id)\n        raise RuntimeError(\n            f\"Rate limit exceeded. {remaining} tokens remaining. \"\n            f\"Try again in a few seconds.\"\n        )\n\n    allowed, remaining = quota.check_and_increment(client_id)\n    if not allowed:\n        raise RuntimeError(\n            f\"Daily quota of {quota.daily_limit} requests exhausted. \"\n            f\"Resets at midnight UTC.\"\n        )\n\n\n@server.tool()\nasync def translate(text: str, target_language: str) -> str:\n    \"\"\"Translate text to the target language.\n\n    Args:\n        text: The text to translate.\n        target_language: ISO 639-1 language code (e.g., 'es', 'fr', 'de').\n    \"\"\"\n    ctx = server.request_context\n    client_id = ctx.session.session_id\n\n    rate_limit_check(client_id)\n\n    result = await call_translation_api(text, target_language)\n    return result\n```\n\n### Authentication: API Keys and OAuth\n\nRemote MCP servers need authentication. The MCP specification does not mandate a specific auth mechanism -- it relies on the transport layer. For HTTP-based transports, use standard HTTP authentication.\n\n**API Key Authentication**\n\n```python\n\"\"\"auth_server.py -- MCP server with API key authentication.\"\"\"\n\nimport hashlib\nimport os\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"authenticated-api\")\n\n# In production, store hashed keys in a database\nAPI_KEYS = {\n    hashlib.sha256(b\"ghx_key_test_12345\").hexdigest(): {\n        \"client_id\": \"client-1\",\n        \"tier\": \"pro\",\n        \"rate_limit\": 1000,\n    },\n    hashlib.sha256(b\"ghx_key_test_67890\").hexdigest(): {\n        \"client_id\": \"client-2\",\n        \"tier\": \"free\",\n        \"rate_limit\": 100,\n    },\n}\n\n\ndef authenticate(api_key: str) -> dict:\n    \"\"\"Validate an API key and return the client profile.\"\"\"\n    key_hash = hashlib.sha256(api_key.encode()).hexdigest()\n    client = API_KEYS.get(key_hash)\n    if not client:\n        raise PermissionError(\"Invalid API key\")\n    return client\n\n\ndef authorize(client: dict, required_tier: str) -> None:\n    \"\"\"Check if the client has the required tier.\"\"\"\n    tier_order = {\"free\": 0, \"basic\": 1, \"pro\": 2, \"enterprise\": 3}\n    if tier_order.get(client[\"tier\"], 0) \u003C tier_order.get(required_tier, 0):\n        raise PermissionError(\n            f\"This tool requires '{required_tier}' tier. \"\n            f\"Your tier: '{client['tier']}'. \"\n            f\"Upgrade at https:\u002F\u002Fexample.com\u002Fpricing\"\n        )\n```\n\n**OAuth 2.0 Integration**\n\nFor enterprise deployments, OAuth provides delegated authorization. The MCP specification added first-class OAuth support in 2025, allowing servers to act as OAuth resource servers.\n\n```python\n\"\"\"oauth_server.py -- MCP server with OAuth 2.0.\"\"\"\n\nimport httpx\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass OAuthConfig:\n    \"\"\"OAuth 2.0 configuration for the MCP server.\"\"\"\n    issuer: str\n    audience: str\n    jwks_uri: str\n    scopes_required: list[str]\n\n\nasync def validate_oauth_token(\n    token: str,\n    config: OAuthConfig,\n) -> dict:\n    \"\"\"Validate an OAuth 2.0 bearer token.\n\n    Returns the decoded token claims if valid.\n    Raises PermissionError if invalid.\n    \"\"\"\n    import jwt  # PyJWT library\n\n    # Fetch JWKS (in production, cache this)\n    async with httpx.AsyncClient() as client:\n        resp = await client.get(config.jwks_uri)\n        jwks = resp.json()\n\n    # Decode and validate the token\n    try:\n        claims = jwt.decode(\n            token,\n            jwt.PyJWKSet.from_dict(jwks),\n            algorithms=[\"RS256\"],\n            audience=config.audience,\n            issuer=config.issuer,\n        )\n    except jwt.InvalidTokenError as e:\n        raise PermissionError(f\"Invalid OAuth token: {e}\")\n\n    # Check required scopes\n    token_scopes = set(claims.get(\"scope\", \"\").split())\n    required = set(config.scopes_required)\n    missing = required - token_scopes\n    if missing:\n        raise PermissionError(\n            f\"Missing required scopes: {', '.join(missing)}. \"\n            f\"Token scopes: {', '.join(token_scopes)}\"\n        )\n\n    return claims\n```\n\n### Multi-Tool Servers\n\nProduction MCP servers typically expose 5 to 50 tools organized around a domain. The key to a well-designed multi-tool server is grouping related tools and providing discovery tools that help the model navigate the available capabilities.\n\n```python\n\"\"\"multi_tool_server.py -- A multi-tool MCP server for project management.\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"project-manager\")\n\n\n# --- Discovery Tools ---\n\n@server.tool()\nasync def list_capabilities() -> str:\n    \"\"\"List all available capabilities of this project management server.\n\n    Call this tool first to understand what operations are available.\n    \"\"\"\n    return \"\"\"Available capabilities:\n\n    PROJECT MANAGEMENT:\n    - create_project: Create a new project\n    - list_projects: List all projects\n    - get_project: Get project details\n\n    TASK MANAGEMENT:\n    - create_task: Create a task in a project\n    - update_task: Update task status\u002Fassignee\n    - list_tasks: List tasks with filters\n\n    TEAM MANAGEMENT:\n    - add_member: Add a team member to a project\n    - list_members: List project team members\n\n    REPORTING:\n    - project_summary: Get a project status summary\n    - burndown_data: Get sprint burndown data\n    \"\"\"\n\n\n# --- Project Tools ---\n\n@server.tool()\nasync def create_project(\n    name: str,\n    description: str,\n    owner: str,\n) -> str:\n    \"\"\"Create a new project.\n\n    Args:\n        name: Project name (must be unique).\n        description: What this project is about.\n        owner: The agent or person who owns the project.\n    \"\"\"\n    project = await db.create_project(name, description, owner)\n    return f\"Project created: {project['id']} ({name})\"\n\n\n@server.tool()\nasync def create_task(\n    project_id: str,\n    title: str,\n    description: str = \"\",\n    assignee: str = \"\",\n    priority: str = \"medium\",\n) -> str:\n    \"\"\"Create a task within a project.\n\n    Args:\n        project_id: The project to add the task to.\n        title: Short task title.\n        description: Detailed task description.\n        assignee: Who is responsible for this task.\n        priority: low, medium, high, or critical.\n    \"\"\"\n    if priority not in (\"low\", \"medium\", \"high\", \"critical\"):\n        raise ValueError(\n            f\"Invalid priority '{priority}'. \"\n            f\"Use: low, medium, high, or critical.\"\n        )\n    task = await db.create_task(\n        project_id, title, description, assignee, priority\n    )\n    return f\"Task created: {task['id']} ({title}) in project {project_id}\"\n```\n\n### Composing Servers: The Proxy Pattern\n\nSometimes you want to combine multiple MCP servers into one, or add cross-cutting concerns (logging, authentication, rate limiting) to an existing server. The proxy pattern wraps one or more upstream servers behind a single server that the client connects to.\n\n```python\n\"\"\"proxy_server.py -- MCP proxy that composes multiple upstream servers.\"\"\"\n\nimport json\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\nlogger = logging.getLogger(__name__)\n\nserver = FastMCP(\"mcp-proxy\")\n\n\n@dataclass\nclass UpstreamServer:\n    \"\"\"Configuration for an upstream MCP server.\"\"\"\n    name: str\n    command: str\n    args: list[str] = field(default_factory=list)\n    env: dict[str, str] = field(default_factory=dict)\n    tools: list[str] = field(default_factory=list)\n\n\n@dataclass\nclass ProxyRouter:\n    \"\"\"Routes tool calls to the appropriate upstream server.\"\"\"\n    upstreams: dict[str, UpstreamServer] = field(default_factory=dict)\n    tool_to_upstream: dict[str, str] = field(default_factory=dict)\n\n    def register_upstream(self, upstream: UpstreamServer) -> None:\n        \"\"\"Register an upstream server and its tool mappings.\"\"\"\n        self.upstreams[upstream.name] = upstream\n        for tool in upstream.tools:\n            self.tool_to_upstream[tool] = upstream.name\n\n    def get_upstream_for_tool(self, tool_name: str) -> Optional[str]:\n        \"\"\"Find which upstream server handles a given tool.\"\"\"\n        return self.tool_to_upstream.get(tool_name)\n\n    async def forward_call(\n        self,\n        tool_name: str,\n        arguments: dict,\n    ) -> dict:\n        \"\"\"Forward a tool call to the appropriate upstream.\"\"\"\n        upstream_name = self.get_upstream_for_tool(tool_name)\n        if not upstream_name:\n            raise ValueError(f\"No upstream server handles tool '{tool_name}'\")\n\n        upstream = self.upstreams[upstream_name]\n\n        # Log the forwarded call\n        logger.info(\n            \"Forwarding %s to %s with args: %s\",\n            tool_name, upstream_name, json.dumps(arguments)[:200],\n        )\n\n        # In production, maintain persistent sessions\n        params = StdioServerParameters(\n            command=upstream.command,\n            args=upstream.args,\n            env=upstream.env,\n        )\n        async with stdio_client(params) as (read, write):\n            async with ClientSession(read, write) as session:\n                await session.initialize()\n                result = await session.call_tool(tool_name, arguments)\n                return result\n\n\nrouter = ProxyRouter()\n\n# Register upstream servers\nrouter.register_upstream(UpstreamServer(\n    name=\"database\",\n    command=\"python\",\n    args=[\"db_server.py\"],\n    tools=[\"query_database\", \"list_tables\", \"describe_table\"],\n))\n\nrouter.register_upstream(UpstreamServer(\n    name=\"project-manager\",\n    command=\"python\",\n    args=[\"project_server.py\"],\n    tools=[\"create_project\", \"create_task\", \"list_tasks\"],\n))\n\n\n@server.tool()\nasync def route_tool(tool_name: str, arguments: str) -> str:\n    \"\"\"Route a tool call to the appropriate upstream server.\n\n    This is a meta-tool that forwards calls to specialized servers.\n\n    Args:\n        tool_name: The name of the tool to call.\n        arguments: JSON string of the tool arguments.\n    \"\"\"\n    args = json.loads(arguments)\n    result = await router.forward_call(tool_name, args)\n    return result.content[0].text if result.content else \"No result\"\n```\n\n---\n\n## Chapter 4: Publishing to the MCP Registry\n\n### The MCP Registry Ecosystem\n\nThe official MCP registry at registry.modelcontextprotocol.io is the central directory where developers publish and discover MCP servers. As of April 2026, it lists over 10,000 servers across categories like databases, APIs, developer tools, productivity, and AI\u002FML. Clients like Claude Desktop, Cursor, Windsurf, and VS Code with Copilot can install servers directly from the registry.\n\nPublishing to the registry makes your server discoverable. When a user asks an AI client \"Can you help me query my Postgres database?\", the client can search the registry for relevant servers, suggest installation, and connect automatically. This is the distribution channel for MCP servers.\n\n### The Server Manifest: .well-known\u002Fmcp\u002Fserver.json\n\nEvery published MCP server needs a manifest file that describes its capabilities, transport, authentication requirements, and metadata. The manifest follows a standard schema that registries and clients use for discovery and installation.\n\n```json\n{\n  \"schema_version\": \"1.0\",\n  \"server_info\": {\n    \"name\": \"analytics-db\",\n    \"version\": \"2.1.0\",\n    \"description\": \"Query your analytics database using natural language. Supports PostgreSQL, MySQL, and SQLite. Read-only access with SQL injection protection.\",\n    \"author\": {\n      \"name\": \"DataTools Inc\",\n      \"url\": \"https:\u002F\u002Fdatatools.example.com\",\n      \"email\": \"support@datatools.example.com\"\n    },\n    \"repository\": \"https:\u002F\u002Fgithub.com\u002Fdatatools\u002Fmcp-analytics-db\",\n    \"license\": \"MIT\",\n    \"homepage\": \"https:\u002F\u002Fdatatools.example.com\u002Fmcp-analytics-db\"\n  },\n  \"transport\": {\n    \"type\": \"stdio\",\n    \"command\": \"npx\",\n    \"args\": [\"-y\", \"@datatools\u002Fmcp-analytics-db\"]\n  },\n  \"capabilities\": {\n    \"tools\": [\n      {\n        \"name\": \"query_database\",\n        \"description\": \"Execute a read-only SQL query\"\n      },\n      {\n        \"name\": \"list_tables\",\n        \"description\": \"List available database tables\"\n      },\n      {\n        \"name\": \"describe_table\",\n        \"description\": \"Get the schema for a table\"\n      }\n    ],\n    \"resources\": [],\n    \"prompts\": []\n  },\n  \"configuration\": {\n    \"required\": [\n      {\n        \"name\": \"DATABASE_URL\",\n        \"description\": \"PostgreSQL connection string\",\n        \"type\": \"string\",\n        \"secret\": true\n      }\n    ],\n    \"optional\": [\n      {\n        \"name\": \"MAX_ROWS\",\n        \"description\": \"Maximum rows returned per query\",\n        \"type\": \"integer\",\n        \"default\": 100\n      }\n    ]\n  },\n  \"tags\": [\"database\", \"sql\", \"postgresql\", \"analytics\", \"query\"],\n  \"categories\": [\"databases\", \"analytics\"]\n}\n```\n\n### Metadata Requirements\n\nTo be accepted by the official registry, your manifest must include:\n\n1. **server_info.name**: Unique, lowercase, alphanumeric with hyphens. This becomes your server's identifier. Choose carefully -- it cannot be changed after publishing.\n\n2. **server_info.version**: Semantic versioning (MAJOR.MINOR.PATCH). Clients use this to detect updates and manage compatibility.\n\n3. **server_info.description**: Clear, concise description of what your server does. This is the primary text users see when searching. Front-load the most important information -- \"Query your analytics database using natural language\" is better than \"A comprehensive database querying solution.\"\n\n4. **transport**: How to run the server. For stdio servers distributed as npm packages, the standard pattern is `npx -y @scope\u002Fpackage-name`. For Python packages: `uvx package-name` or `pipx run package-name`. The registry validates that the specified command is available and the server starts correctly.\n\n5. **capabilities**: List of tools, resources, and prompts. Clients use this to show users what the server can do before installing it.\n\n6. **configuration**: Required and optional configuration parameters. Mark secrets (API keys, connection strings) with `\"secret\": true` so clients know to handle them securely.\n\n### Version Management\n\nSemantic versioning communicates the impact of changes:\n\n- **PATCH** (2.1.0 -> 2.1.1): Bug fixes. No tool signature changes. Clients can update automatically.\n- **MINOR** (2.1.0 -> 2.2.0): New tools added. Existing tools unchanged. Backward-compatible. Clients can update automatically.\n- **MAJOR** (2.1.0 -> 3.0.0): Breaking changes. Tool signatures changed, tools removed, or behavior altered. Clients should prompt the user before updating.\n\n```python\n\"\"\"version_management.py -- Semantic version management for MCP servers.\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass ServerVersion:\n    \"\"\"Represents a semantic version.\"\"\"\n    major: int\n    minor: int\n    patch: int\n    pre_release: Optional[str] = None\n\n    @classmethod\n    def parse(cls, version_str: str) -> \"ServerVersion\":\n        \"\"\"Parse a semantic version string.\"\"\"\n        parts = version_str.split(\"-\", 1)\n        pre = parts[1] if len(parts) > 1 else None\n        nums = parts[0].split(\".\")\n        if len(nums) != 3:\n            raise ValueError(f\"Invalid version: {version_str}\")\n        return cls(int(nums[0]), int(nums[1]), int(nums[2]), pre)\n\n    def __str__(self) -> str:\n        base = f\"{self.major}.{self.minor}.{self.patch}\"\n        return f\"{base}-{self.pre_release}\" if self.pre_release else base\n\n    def is_compatible_with(self, other: \"ServerVersion\") -> bool:\n        \"\"\"Check if this version is backward-compatible with another.\"\"\"\n        if self.major != other.major:\n            return False\n        if self.major == 0:\n            # Pre-1.0: minor version changes are breaking\n            return self.minor == other.minor\n        return True\n\n    def bump_patch(self) -> \"ServerVersion\":\n        return ServerVersion(self.major, self.minor, self.patch + 1)\n\n    def bump_minor(self) -> \"ServerVersion\":\n        return ServerVersion(self.major, self.minor + 1, 0)\n\n    def bump_major(self) -> \"ServerVersion\":\n        return ServerVersion(self.major + 1, 0, 0)\n```\n\n### Discovery and Search Optimization\n\nRegistry search considers these factors when ranking results:\n\n1. **Name match**: Exact and partial matches against the server name.\n2. **Description relevance**: Keyword matches in the description. Use specific, descriptive language.\n3. **Tags**: Exact tag matches are weighted heavily. Use 5-10 relevant tags.\n4. **Categories**: Placing your server in the right category ensures it appears in category browsing.\n5. **Install count**: More-installed servers rank higher. This creates a flywheel effect.\n6. **Recency**: Recently updated servers get a small boost.\n\nTips for optimizing discovery:\n\n- **Name your server for the problem, not the solution**: `mcp-postgres-query` is better than `mcp-sql-executor`. Users search for \"postgres\" not \"sql-executor.\"\n- **Front-load the description**: \"Query PostgreSQL databases with natural language\" beats \"A tool for executing SQL queries against various database backends including PostgreSQL.\"\n- **Use specific tags**: `postgresql` is better than `database`. Include the specific technologies your server supports.\n- **Publish frequently**: Regular updates (even small ones) signal an active project and boost ranking.\n\n### Publishing Workflow\n\n```bash\n# 1. Validate your manifest\nmcp validate server.json\n\n# 2. Test your server starts and responds to initialize\nmcp test server.json\n\n# 3. Authenticate with the registry\nmcp auth login\n\n# 4. Publish\nmcp publish\n\n# 5. Verify it appears\nmcp search your-server-name\n```\n\nFor npm-distributed servers, the common pattern is:\n\n```bash\n# Build and publish the npm package\nnpm publish\n\n# Then publish the MCP manifest to the registry\nmcp publish --manifest .well-known\u002Fmcp\u002Fserver.json\n```\n\nFor Python-distributed servers:\n\n```bash\n# Build and publish to PyPI\npython -m build\ntwine upload dist\u002F*\n\n# Then publish the MCP manifest\nmcp publish --manifest .well-known\u002Fmcp\u002Fserver.json\n```\n\n---\n\n## Chapter 5: Enterprise MCP Governance\n\n### Why Governance Matters\n\nWhen a single developer installs an MCP server on their laptop, security is a personal responsibility. When an enterprise deploys MCP servers across thousands of developer workstations, security becomes a governance challenge. Which servers are allowed? Who authorized them? What data can they access? What happens when a server is compromised? Enterprise MCP governance answers these questions.\n\nThe stakes are significant. An MCP server has the same access as the process it runs in. A malicious or compromised server can read local files, access environment variables (which often contain API keys and credentials), make network requests, and execute arbitrary code. In enterprise environments where developers work with proprietary code, customer data, and production credentials, ungoverned MCP servers are a data exfiltration risk.\n\n### SSO Integration for Server Access\n\nEnterprise MCP deployments should integrate with the organization's SSO provider (Okta, Azure AD, Google Workspace) so that server access is governed by the same identity and access management policies as every other tool.\n\n```python\n\"\"\"enterprise_auth.py -- Enterprise SSO integration for MCP servers.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport time\nimport secrets\n\n\n@dataclass\nclass SSOConfig:\n    \"\"\"SSO configuration for enterprise MCP deployment.\"\"\"\n    provider: str  # \"okta\", \"azure_ad\", \"google\"\n    tenant_id: str\n    client_id: str\n    client_secret: str\n    allowed_groups: list[str] = field(default_factory=list)\n    allowed_domains: list[str] = field(default_factory=list)\n    mfa_required: bool = True\n    session_timeout_minutes: int = 480  # 8 hours\n\n\n@dataclass\nclass AccessPolicy:\n    \"\"\"Define who can access which MCP servers.\"\"\"\n    server_name: str\n    allowed_groups: list[str]\n    allowed_roles: list[str]\n    requires_approval: bool = False\n    approval_group: str = \"\"\n    data_classification: str = \"internal\"\n    max_session_hours: int = 8\n\n\n@dataclass\nclass EnterpriseGateway:\n    \"\"\"Gateway that enforces SSO and access policies for MCP servers.\"\"\"\n    sso_config: SSOConfig\n    policies: dict[str, AccessPolicy] = field(default_factory=dict)\n    _active_sessions: dict[str, dict] = field(default_factory=dict)\n\n    def register_policy(self, policy: AccessPolicy) -> None:\n        \"\"\"Register an access policy for an MCP server.\"\"\"\n        self.policies[policy.server_name] = policy\n\n    def check_access(\n        self, user_id: str, user_groups: list[str],\n        user_roles: list[str], server_name: str,\n    ) -> dict:\n        \"\"\"Check if a user can access a specific MCP server.\"\"\"\n        policy = self.policies.get(server_name)\n        if not policy:\n            return {\n                \"allowed\": False,\n                \"reason\": f\"No access policy defined for server '{server_name}'\",\n            }\n\n        # Check group membership\n        user_group_set = set(user_groups)\n        allowed_group_set = set(policy.allowed_groups)\n        if not user_group_set.intersection(allowed_group_set):\n            return {\n                \"allowed\": False,\n                \"reason\": (\n                    f\"User is not a member of any allowed group. \"\n                    f\"Required: {policy.allowed_groups}\"\n                ),\n            }\n\n        # Check role\n        user_role_set = set(user_roles)\n        allowed_role_set = set(policy.allowed_roles)\n        if not user_role_set.intersection(allowed_role_set):\n            return {\n                \"allowed\": False,\n                \"reason\": (\n                    f\"User does not have a required role. \"\n                    f\"Required: {policy.allowed_roles}\"\n                ),\n            }\n\n        # Check if approval is needed\n        if policy.requires_approval:\n            return {\n                \"allowed\": False,\n                \"reason\": \"Access requires approval\",\n                \"approval_group\": policy.approval_group,\n                \"requires_approval\": True,\n            }\n\n        return {\"allowed\": True, \"data_classification\": policy.data_classification}\n\n    def create_session(self, user_id: str, server_name: str) -> dict:\n        \"\"\"Create an authenticated session for a user-server pair.\"\"\"\n        policy = self.policies.get(server_name)\n        max_hours = policy.max_session_hours if policy else 8\n        session_id = secrets.token_hex(16)\n\n        self._active_sessions[session_id] = {\n            \"user_id\": user_id,\n            \"server_name\": server_name,\n            \"created_at\": time.time(),\n            \"expires_at\": time.time() + (max_hours * 3600),\n            \"requests_count\": 0,\n        }\n        return {\"session_id\": session_id, \"expires_in_hours\": max_hours}\n\n    def validate_session(self, session_id: str) -> dict:\n        \"\"\"Validate that a session is still active.\"\"\"\n        session = self._active_sessions.get(session_id)\n        if not session:\n            return {\"valid\": False, \"reason\": \"Session not found\"}\n        if time.time() > session[\"expires_at\"]:\n            del self._active_sessions[session_id]\n            return {\"valid\": False, \"reason\": \"Session expired\"}\n        session[\"requests_count\"] += 1\n        return {\"valid\": True, \"user_id\": session[\"user_id\"]}\n```\n\n### Audit Logging\n\nEvery tool call through an enterprise MCP deployment should be logged with enough detail for security review, compliance, and incident response.\n\n```python\n\"\"\"audit_logging.py -- Structured audit logging for MCP servers.\"\"\"\n\nimport json\nimport time\nfrom dataclasses import dataclass, field, asdict\nfrom typing import Optional\n\n\n@dataclass\nclass AuditEvent:\n    \"\"\"A single audit event for an MCP tool call.\"\"\"\n    timestamp: float\n    event_type: str  # \"tool_call\", \"tool_result\", \"auth_failure\", \"policy_violation\"\n    user_id: str\n    server_name: str\n    tool_name: str\n    session_id: str\n    request_id: str\n    arguments_hash: str  # SHA-256 of the arguments (not the arguments themselves)\n    result_status: str  # \"success\", \"error\", \"denied\"\n    duration_ms: float = 0.0\n    error_message: Optional[str] = None\n    data_classification: str = \"internal\"\n    client_ip: str = \"\"\n    user_agent: str = \"\"\n\n\n@dataclass\nclass AuditLogger:\n    \"\"\"Structured audit logger that writes to multiple sinks.\"\"\"\n    sinks: list = field(default_factory=list)\n    _buffer: list = field(default_factory=list)\n    buffer_size: int = 100\n\n    def log(self, event: AuditEvent) -> None:\n        \"\"\"Log an audit event.\"\"\"\n        self._buffer.append(asdict(event))\n        if len(self._buffer) >= self.buffer_size:\n            self.flush()\n\n    def flush(self) -> None:\n        \"\"\"Flush buffered events to all sinks.\"\"\"\n        if not self._buffer:\n            return\n        events = list(self._buffer)\n        self._buffer.clear()\n        for sink in self.sinks:\n            sink.write(events)\n\n    def query(\n        self,\n        user_id: Optional[str] = None,\n        server_name: Optional[str] = None,\n        tool_name: Optional[str] = None,\n        start_time: Optional[float] = None,\n        end_time: Optional[float] = None,\n    ) -> list:\n        \"\"\"Query audit events with filters.\"\"\"\n        self.flush()\n        results = []\n        for sink in self.sinks:\n            if hasattr(sink, \"query\"):\n                results.extend(sink.query(\n                    user_id=user_id, server_name=server_name,\n                    tool_name=tool_name,\n                    start_time=start_time, end_time=end_time,\n                ))\n        return results\n```\n\n### Gateway Patterns\n\nEnterprise MCP gateways sit between AI clients and MCP servers. They enforce policies, add authentication, log activity, and control which servers are available.\n\n**The Central Gateway Model**\n\nAll MCP traffic flows through a central gateway service. Developers configure their AI clients to connect to the gateway instead of individual servers. The gateway authenticates the user, checks access policies, forwards the request to the appropriate server, logs the interaction, and returns the result.\n\n```\nDeveloper's AI Client\n    |\n    +-- connects to --> Enterprise MCP Gateway\n                            |\n                            +-- authenticates via SSO\n                            +-- checks access policy\n                            +-- forwards to --> MCP Server A\n                            +-- forwards to --> MCP Server B\n                            +-- logs to --> Audit Log\n```\n\nAdvantages: Central policy enforcement. Single point of audit logging. Easy to add or remove servers. Can cache responses, rate limit, and filter.\n\nDisadvantages: Single point of failure. Adds latency. Requires infrastructure.\n\n**The Sidecar Model**\n\nA lightweight policy agent runs alongside each MCP server on the developer's machine. The sidecar intercepts tool calls, checks policies against a central policy server, and logs activity.\n\nAdvantages: No central bottleneck. Works offline with cached policies. Lower latency.\n\nDisadvantages: Must be installed on every machine. Policy updates require propagation. Harder to audit in real time.\n\n### Policy Enforcement\n\nEnterprise policies for MCP servers typically cover four areas:\n\n1. **Server allowlist**: Only approved servers can be installed. Unapproved servers are blocked.\n2. **Tool restrictions**: Even within an approved server, certain tools may be restricted by team.\n3. **Data classification**: Tools that access confidential data require additional authorization.\n4. **Rate limits**: Per-user and per-team rate limits prevent runaway usage.\n\n```python\n\"\"\"policy_engine.py -- Policy enforcement for enterprise MCP governance.\"\"\"\n\nimport re\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass PolicyRule:\n    \"\"\"A single policy rule.\"\"\"\n    rule_id: str\n    description: str\n    action: str  # \"allow\", \"deny\", \"require_approval\"\n    server_pattern: str = \"*\"\n    tool_pattern: str = \"*\"\n    user_groups: list[str] = field(default_factory=list)\n    priority: int = 0\n\n\n@dataclass\nclass PolicyEngine:\n    \"\"\"Evaluate access policies for MCP tool calls.\"\"\"\n    rules: list[PolicyRule] = field(default_factory=list)\n\n    def add_rule(self, rule: PolicyRule) -> None:\n        \"\"\"Add a policy rule.\"\"\"\n        self.rules.append(rule)\n        self.rules.sort(key=lambda r: r.priority, reverse=True)\n\n    def evaluate(\n        self,\n        server_name: str,\n        tool_name: str,\n        user_groups: list[str],\n    ) -> dict:\n        \"\"\"Evaluate policies and return the access decision.\"\"\"\n        for rule in self.rules:\n            if not self._matches(rule.server_pattern, server_name):\n                continue\n            if not self._matches(rule.tool_pattern, tool_name):\n                continue\n            if rule.user_groups:\n                if not set(user_groups).intersection(set(rule.user_groups)):\n                    continue\n            return {\n                \"decision\": rule.action,\n                \"rule_id\": rule.rule_id,\n                \"description\": rule.description,\n            }\n\n        # Default deny\n        return {\n            \"decision\": \"deny\",\n            \"rule_id\": \"default\",\n            \"description\": \"No matching policy rule; default deny\",\n        }\n\n    @staticmethod\n    def _matches(pattern: str, value: str) -> bool:\n        \"\"\"Simple glob matching.\"\"\"\n        regex = pattern.replace(\".\", r\"\\.\").replace(\"*\", \".*\").replace(\"?\", \".\")\n        return bool(re.fullmatch(regex, value))\n```\n\n### Configuration Portability\n\nEnterprise teams need a standard way to share MCP server configurations. A centralized configuration service distributes approved server configs to developer machines.\n\n```python\n\"\"\"config_portability.py -- Portable MCP configuration management.\"\"\"\n\nimport json\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass MCPServerConfig:\n    \"\"\"Configuration for a single MCP server.\"\"\"\n    name: str\n    command: str\n    args: list[str] = field(default_factory=list)\n    env: dict[str, str] = field(default_factory=dict)\n    env_secrets: list[str] = field(default_factory=list)\n    enabled: bool = True\n    required_groups: list[str] = field(default_factory=list)\n\n\n@dataclass\nclass TeamConfig:\n    \"\"\"MCP configuration for a team.\"\"\"\n    team_name: str\n    servers: list[MCPServerConfig] = field(default_factory=list)\n    version: str = \"1.0.0\"\n\n    def to_claude_desktop_config(self) -> dict:\n        \"\"\"Export as Claude Desktop configuration format.\"\"\"\n        mcp_servers = {}\n        for s in self.servers:\n            if not s.enabled:\n                continue\n            config = {\"command\": s.command, \"args\": s.args}\n            if s.env:\n                config[\"env\"] = s.env\n            mcp_servers[s.name] = config\n        return {\"mcpServers\": mcp_servers}\n\n    def to_cursor_config(self) -> dict:\n        \"\"\"Export as Cursor IDE configuration format.\"\"\"\n        return {\n            \"mcp\": {\n                \"servers\": {\n                    s.name: {\n                        \"command\": s.command,\n                        \"args\": s.args,\n                        \"env\": s.env,\n                    }\n                    for s in self.servers if s.enabled\n                }\n            }\n        }\n\n    def to_json(self) -> str:\n        \"\"\"Serialize to portable JSON.\"\"\"\n        return json.dumps({\n            \"team\": self.team_name,\n            \"version\": self.version,\n            \"servers\": [\n                {\n                    \"name\": s.name,\n                    \"command\": s.command,\n                    \"args\": s.args,\n                    \"env\": {k: v for k, v in s.env.items()},\n                    \"env_secrets\": s.env_secrets,\n                    \"enabled\": s.enabled,\n                    \"required_groups\": s.required_groups,\n                }\n                for s in self.servers\n            ],\n        }, indent=2)\n```\n\n### Compliance Considerations\n\nEnterprise MCP deployments must address regulatory requirements:\n\n**Data Residency**: Some regulations require data to stay within specific geographic regions. MCP servers that access customer data must run in the same region as the data. Remote MCP servers (HTTP transport) must be deployed in compliant regions.\n\n**Access Reviews**: Periodic reviews of who has access to which MCP servers. The audit log provides the data; the governance team reviews it quarterly.\n\n**Data Loss Prevention**: MCP servers can exfiltrate data by including it in tool responses that flow to cloud-hosted AI models. DLP policies should scan tool responses for sensitive patterns (credit card numbers, SSNs, API keys) and redact them before they reach the model.\n\n**Retention**: Audit logs must be retained per the organization's data retention policy. Tool call arguments and results may contain sensitive data and should be stored with appropriate encryption and access controls.\n\n---\n\n## Chapter 6: Monetization Strategies\n\n### The MCP Server Business Landscape\n\nMCP servers are the new APIs. Every business model that works for APIs works for MCP servers -- with one advantage: MCP servers are discoverable by AI agents, which means your market is not just human developers but also autonomous systems that find, evaluate, and pay for tools at machine speed. This chapter covers six monetization strategies, from freemium to pay-per-use, with implementation details for each.\n\n### Strategy 1: Freemium (Basic Tools Free, Advanced Paid)\n\nThe most common model. Offer a set of basic tools for free to drive adoption, then gate advanced tools behind a paid tier. The free tier serves as a distribution mechanism -- every free user is a potential paid customer.\n\n```python\n\"\"\"freemium_server.py -- MCP server with tiered tool access.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nfrom mcp.server.fastmcp import FastMCP\n\nserver = FastMCP(\"analytics-server\")\n\n\n@dataclass\nclass TierConfig:\n    \"\"\"Configuration for a pricing tier.\"\"\"\n    name: str\n    tools_allowed: set\n    monthly_price_usd: float\n    daily_call_limit: int\n    max_rows_per_query: int\n\n\nTIERS = {\n    \"free\": TierConfig(\n        name=\"Free\",\n        tools_allowed={\"query_database\", \"list_tables\", \"describe_table\"},\n        monthly_price_usd=0.0,\n        daily_call_limit=100,\n        max_rows_per_query=100,\n    ),\n    \"pro\": TierConfig(\n        name=\"Pro\",\n        tools_allowed={\n            \"query_database\", \"list_tables\", \"describe_table\",\n            \"create_dashboard\", \"schedule_report\", \"export_data\",\n            \"query_optimizer\", \"schema_diff\",\n        },\n        monthly_price_usd=29.0,\n        daily_call_limit=10000,\n        max_rows_per_query=10000,\n    ),\n    \"enterprise\": TierConfig(\n        name=\"Enterprise\",\n        tools_allowed={\n            \"query_database\", \"list_tables\", \"describe_table\",\n            \"create_dashboard\", \"schedule_report\", \"export_data\",\n            \"query_optimizer\", \"schema_diff\",\n            \"admin_create_user\", \"admin_audit_log\", \"admin_backup\",\n            \"custom_function\", \"cross_database_query\",\n        },\n        monthly_price_usd=199.0,\n        daily_call_limit=100000,\n        max_rows_per_query=1000000,\n    ),\n}\n\n\n@dataclass\nclass ClientProfile:\n    \"\"\"Tracks a client's tier and usage.\"\"\"\n    client_id: str\n    tier: str = \"free\"\n    daily_calls: int = 0\n    last_reset_day: str = \"\"\n\n\n_clients: dict[str, ClientProfile] = {}\n\n\ndef get_client(client_id: str) -> ClientProfile:\n    \"\"\"Get or create a client profile.\"\"\"\n    if client_id not in _clients:\n        _clients[client_id] = ClientProfile(client_id=client_id)\n    return _clients[client_id]\n\n\ndef check_tier_access(client_id: str, tool_name: str) -> None:\n    \"\"\"Verify the client's tier allows access to the tool.\"\"\"\n    import time\n    client = get_client(client_id)\n    tier = TIERS.get(client.tier)\n    if not tier:\n        raise PermissionError(f\"Unknown tier: {client.tier}\")\n\n    # Check tool access\n    if tool_name not in tier.tools_allowed:\n        available_in = [\n            t.name for t in TIERS.values()\n            if tool_name in t.tools_allowed\n        ]\n        raise PermissionError(\n            f\"Tool '{tool_name}' requires a {' or '.join(available_in)} plan. \"\n            f\"Your plan: {tier.name}. Upgrade at https:\u002F\u002Fexample.com\u002Fpricing\"\n        )\n\n    # Check daily limit\n    today = time.strftime(\"%Y-%m-%d\")\n    if client.last_reset_day != today:\n        client.daily_calls = 0\n        client.last_reset_day = today\n\n    if client.daily_calls >= tier.daily_call_limit:\n        raise PermissionError(\n            f\"Daily call limit of {tier.daily_call_limit} exceeded \"\n            f\"for {tier.name} plan. Resets at midnight UTC. \"\n            f\"Upgrade for higher limits.\"\n        )\n\n    client.daily_calls += 1\n```\n\n### Strategy 2: Usage-Based Billing (Per-Call Metering)\n\nCharge per tool call. This model aligns cost with value -- users pay only for what they use. It works well for high-volume, low-cost operations like API calls, translations, and data lookups.\n\n```python\n\"\"\"usage_billing.py -- Per-call usage metering for MCP servers.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom typing import Optional\n\n\n@dataclass\nclass UsageMeter:\n    \"\"\"Track per-call usage for billing.\"\"\"\n    _usage: dict = field(default_factory=lambda: defaultdict(list))\n\n    def record(\n        self,\n        client_id: str,\n        tool_name: str,\n        cost_usd: float,\n        metadata: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Record a billable tool call.\"\"\"\n        event = {\n            \"timestamp\": time.time(),\n            \"tool_name\": tool_name,\n            \"cost_usd\": cost_usd,\n            \"metadata\": metadata or {},\n        }\n        self._usage[client_id].append(event)\n        return event\n\n    def get_current_bill(self, client_id: str) -> dict:\n        \"\"\"Calculate the current billing period total.\"\"\"\n        events = self._usage.get(client_id, [])\n        # Filter to current month\n        current_month = time.strftime(\"%Y-%m\")\n        month_events = [\n            e for e in events\n            if time.strftime(\"%Y-%m\", time.localtime(e[\"timestamp\"])) == current_month\n        ]\n        total = sum(e[\"cost_usd\"] for e in month_events)\n        by_tool = defaultdict(float)\n        for e in month_events:\n            by_tool[e[\"tool_name\"]] += e[\"cost_usd\"]\n\n        return {\n            \"client_id\": client_id,\n            \"period\": current_month,\n            \"total_usd\": round(total, 4),\n            \"call_count\": len(month_events),\n            \"by_tool\": dict(by_tool),\n        }\n\n    def get_usage_report(self, client_id: str, days: int = 30) -> dict:\n        \"\"\"Generate a usage report for the last N days.\"\"\"\n        events = self._usage.get(client_id, [])\n        cutoff = time.time() - (days * 86400)\n        recent = [e for e in events if e[\"timestamp\"] >= cutoff]\n\n        daily = defaultdict(lambda: {\"calls\": 0, \"cost\": 0.0})\n        for e in recent:\n            day = time.strftime(\"%Y-%m-%d\", time.localtime(e[\"timestamp\"]))\n            daily[day][\"calls\"] += 1\n            daily[day][\"cost\"] += e[\"cost_usd\"]\n\n        return {\n            \"client_id\": client_id,\n            \"period_days\": days,\n            \"total_calls\": len(recent),\n            \"total_cost_usd\": round(sum(e[\"cost_usd\"] for e in recent), 4),\n            \"daily_breakdown\": dict(daily),\n        }\n\n\n# Pricing per tool call\nTOOL_PRICING = {\n    \"translate\": 0.002,       # $0.002 per translation\n    \"summarize\": 0.005,       # $0.005 per summary\n    \"analyze_image\": 0.01,    # $0.01 per image analysis\n    \"generate_report\": 0.05,  # $0.05 per report\n    \"query_database\": 0.001,  # $0.001 per query\n}\n\nmeter = UsageMeter()\n```\n\n### Strategy 3: Enterprise Licensing\n\nSell annual or multi-year licenses to organizations. This model provides predictable revenue, higher deal sizes, and longer customer relationships. Enterprise customers typically need SSO integration, audit logging, SLA guarantees, and dedicated support.\n\nThe key differentiators for enterprise licensing:\n\n- **Unlimited usage** within the license (no per-call fees).\n- **SLA guarantees**: 99.9% uptime, response time commitments.\n- **Dedicated infrastructure**: Option for on-premise or private cloud deployment.\n- **SSO\u002FSCIM integration**: Automatic user provisioning.\n- **Priority support**: Dedicated Slack channel, guaranteed response times.\n- **Custom tools**: Build custom tools specific to the customer's domain.\n\nEnterprise pricing is typically based on the number of developer seats or the number of connected AI agents, ranging from $500 to $5,000 per seat per year depending on the domain.\n\n### Strategy 4: Marketplace Models\n\nList your MCP server on AI tool marketplaces and take a revenue share. As of April 2026, several marketplaces accept MCP server listings:\n\n- **The official MCP registry**: Free to list, no revenue share. You handle billing directly.\n- **AI client marketplaces**: Cursor, Windsurf, and other IDEs are building in-app marketplaces where developers can purchase premium MCP servers. Revenue share varies from 15% to 30%.\n- **Enterprise marketplaces**: Azure API Center and similar platforms list MCP servers for enterprise customers. Higher deal sizes but longer sales cycles.\n\n### Strategy 5: Combining MCP with x402 for Pay-Per-Use\n\nThe x402 protocol enables HTTP-native micropayments. By combining an MCP server with an x402-enabled endpoint, you can create a pay-per-use model where agent clients pay per tool call without needing a subscription or API key. This is especially powerful for agent-to-agent commerce where the calling agent discovers your MCP server and pays automatically.\n\n```python\n\"\"\"x402_integration.py -- Combine MCP server with x402 pay-per-use.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass X402PaymentGate:\n    \"\"\"Gate MCP tool calls behind x402 micropayments.\"\"\"\n    payment_address: str\n    tool_prices: dict = field(default_factory=dict)\n    _verified_payments: dict = field(default_factory=dict)\n\n    def set_price(self, tool_name: str, price_usd: float) -> None:\n        \"\"\"Set the price for a tool call.\"\"\"\n        self.tool_prices[tool_name] = price_usd\n\n    def generate_payment_request(self, tool_name: str) -> dict:\n        \"\"\"Generate an x402 payment request for a tool call.\"\"\"\n        price = self.tool_prices.get(tool_name, 0.01)\n        return {\n            \"status\": 402,\n            \"headers\": {\n                \"X-Payment-Amount\": str(price),\n                \"X-Payment-Currency\": \"USD\",\n                \"X-Payment-Methods\": \"x402\",\n                \"X-Payment-Address\": self.payment_address,\n                \"X-Payment-Description\": f\"MCP tool call: {tool_name}\",\n            },\n        }\n\n    def verify_payment(self, payment_token: str, tool_name: str) -> dict:\n        \"\"\"Verify an x402 payment token.\"\"\"\n        # In production, verify against the x402 facilitator\n        price = self.tool_prices.get(tool_name, 0.01)\n        return {\n            \"verified\": True,\n            \"amount_usd\": price,\n            \"token\": payment_token,\n            \"tool_name\": tool_name,\n        }\n\n    def check_and_charge(\n        self, tool_name: str, payment_token: Optional[str],\n    ) -> dict:\n        \"\"\"Check payment for a tool call. Returns payment status.\"\"\"\n        if tool_name not in self.tool_prices:\n            return {\"paid\": True, \"free\": True}\n\n        if not payment_token:\n            return {\n                \"paid\": False,\n                \"payment_required\": self.generate_payment_request(tool_name),\n            }\n\n        verification = self.verify_payment(payment_token, tool_name)\n        if not verification[\"verified\"]:\n            return {\"paid\": False, \"reason\": \"Payment verification failed\"}\n\n        return {\"paid\": True, \"amount_charged\": verification[\"amount_usd\"]}\n\n\n# Example: Gate MCP tools behind x402\ngate = X402PaymentGate(payment_address=\"ghx_pay_example\")\ngate.set_price(\"translate\", 0.002)\ngate.set_price(\"summarize\", 0.005)\ngate.set_price(\"analyze_image\", 0.01)\n```\n\n### Strategy 6: Revenue Tracking and Analytics\n\nRegardless of your monetization model, you need revenue tracking. Build it into your MCP server from day one.\n\n```python\n\"\"\"revenue_analytics.py -- Revenue tracking for MCP server monetization.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\n\n\n@dataclass\nclass RevenueTracker:\n    \"\"\"Track and analyze MCP server revenue.\"\"\"\n    _events: list = field(default_factory=list)\n\n    def record_revenue(\n        self,\n        client_id: str,\n        amount_usd: float,\n        source: str,\n        tool_name: str = \"\",\n    ) -> None:\n        \"\"\"Record a revenue event.\"\"\"\n        self._events.append({\n            \"timestamp\": time.time(),\n            \"client_id\": client_id,\n            \"amount_usd\": amount_usd,\n            \"source\": source,  # \"subscription\", \"usage\", \"enterprise\", \"x402\"\n            \"tool_name\": tool_name,\n        })\n\n    def monthly_recurring_revenue(self) -> float:\n        \"\"\"Calculate MRR from subscription events in the current month.\"\"\"\n        current_month = time.strftime(\"%Y-%m\")\n        return sum(\n            e[\"amount_usd\"] for e in self._events\n            if e[\"source\"] == \"subscription\"\n            and time.strftime(\"%Y-%m\", time.localtime(e[\"timestamp\"])) == current_month\n        )\n\n    def revenue_by_tool(self, days: int = 30) -> dict:\n        \"\"\"Break down revenue by tool for the last N days.\"\"\"\n        cutoff = time.time() - (days * 86400)\n        by_tool = defaultdict(float)\n        for e in self._events:\n            if e[\"timestamp\"] >= cutoff and e[\"tool_name\"]:\n                by_tool[e[\"tool_name\"]] += e[\"amount_usd\"]\n        return dict(by_tool)\n\n    def customer_lifetime_value(self, client_id: str) -> float:\n        \"\"\"Calculate total revenue from a single customer.\"\"\"\n        return sum(\n            e[\"amount_usd\"] for e in self._events\n            if e[\"client_id\"] == client_id\n        )\n\n    def churn_rate(self, period_days: int = 30) -> float:\n        \"\"\"Estimate churn rate based on active customers.\"\"\"\n        now = time.time()\n        current_cutoff = now - (period_days * 86400)\n        previous_cutoff = current_cutoff - (period_days * 86400)\n\n        current_clients = set(\n            e[\"client_id\"] for e in self._events\n            if e[\"timestamp\"] >= current_cutoff\n        )\n        previous_clients = set(\n            e[\"client_id\"] for e in self._events\n            if previous_cutoff \u003C= e[\"timestamp\"] \u003C current_cutoff\n        )\n\n        if not previous_clients:\n            return 0.0\n\n        churned = previous_clients - current_clients\n        return len(churned) \u002F len(previous_clients)\n```\n\n---\n\n## Chapter 7: Production Operations\n\n### Deployment Patterns\n\nMCP servers can be deployed in several ways, depending on whether they need to run locally or remotely, and whether they serve a single user or many.\n\n**Local stdio Deployment**\n\nThe simplest deployment. The AI client starts the server as a subprocess. No infrastructure needed. Suitable for personal tools and development.\n\n```json\n{\n  \"mcpServers\": {\n    \"my-tool\": {\n      \"command\": \"python\",\n      \"args\": [\"\u002Fopt\u002Fmcp-servers\u002Fmy-tool\u002Fserver.py\"],\n      \"env\": {\n        \"DATABASE_URL\": \"sqlite:\u002F\u002F\u002Fdata\u002Fanalytics.db\"\n      }\n    }\n  }\n}\n```\n\n**Docker Deployment**\n\nPackage your MCP server as a Docker container for consistent environments and easy distribution. Especially useful for servers with complex dependencies.\n\n```dockerfile\nFROM python:3.12-slim\n\nWORKDIR \u002Fapp\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . .\n\n# For stdio transport (used with docker run -i)\nCMD [\"python\", \"server.py\"]\n\n# For HTTP transport\n# EXPOSE 8080\n# CMD [\"python\", \"server.py\", \"--transport\", \"http\", \"--port\", \"8080\"]\n```\n\nFor stdio transport with Docker:\n\n```json\n{\n  \"mcpServers\": {\n    \"my-tool\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"my-mcp-server:latest\"]\n    }\n  }\n}\n```\n\n**Serverless Deployment**\n\nFor HTTP-based MCP servers with bursty traffic, serverless platforms (AWS Lambda, Google Cloud Functions, Cloudflare Workers) provide automatic scaling and pay-per-use pricing.\n\nThe key constraint with serverless is cold start latency. MCP's `initialize` handshake adds to the first-request latency. Mitigate with provisioned concurrency or by using the streamable HTTP transport (which allows stateless request-response without persistent connections).\n\n**Edge Deployment**\n\nFor latency-sensitive MCP servers, deploy at the edge using Cloudflare Workers, Deno Deploy, or AWS CloudFront Functions. Edge deployment puts your server within 50ms of most users globally.\n\n### Monitoring and Alerting\n\nProduction MCP servers need the same monitoring as any production service: health checks, latency tracking, error rates, and alerting.\n\n```python\n\"\"\"monitoring.py -- Monitoring for production MCP servers.\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom typing import Optional\n\n\n@dataclass\nclass ToolMetrics:\n    \"\"\"Metrics for a single tool.\"\"\"\n    call_count: int = 0\n    error_count: int = 0\n    total_latency_ms: float = 0.0\n    max_latency_ms: float = 0.0\n    last_call_time: float = 0.0\n\n\n@dataclass\nclass ServerMonitor:\n    \"\"\"Monitor MCP server health and performance.\"\"\"\n    _tools: dict[str, ToolMetrics] = field(default_factory=lambda: defaultdict(ToolMetrics))\n    _alerts: list = field(default_factory=list)\n    error_rate_threshold: float = 0.05  # 5%\n    latency_threshold_ms: float = 5000.0  # 5 seconds\n\n    def record_call(\n        self,\n        tool_name: str,\n        latency_ms: float,\n        success: bool,\n    ) -> None:\n        \"\"\"Record a tool call for monitoring.\"\"\"\n        metrics = self._tools[tool_name]\n        metrics.call_count += 1\n        metrics.total_latency_ms += latency_ms\n        metrics.last_call_time = time.time()\n\n        if latency_ms > metrics.max_latency_ms:\n            metrics.max_latency_ms = latency_ms\n\n        if not success:\n            metrics.error_count += 1\n\n        # Check thresholds\n        self._check_alerts(tool_name, metrics, latency_ms, success)\n\n    def _check_alerts(\n        self,\n        tool_name: str,\n        metrics: ToolMetrics,\n        latency_ms: float,\n        success: bool,\n    ) -> None:\n        \"\"\"Check if any alert thresholds are exceeded.\"\"\"\n        # High error rate\n        if metrics.call_count >= 10:\n            error_rate = metrics.error_count \u002F metrics.call_count\n            if error_rate > self.error_rate_threshold:\n                self._alerts.append({\n                    \"type\": \"high_error_rate\",\n                    \"tool\": tool_name,\n                    \"error_rate\": round(error_rate, 3),\n                    \"threshold\": self.error_rate_threshold,\n                    \"timestamp\": time.time(),\n                })\n\n        # High latency\n        if latency_ms > self.latency_threshold_ms:\n            self._alerts.append({\n                \"type\": \"high_latency\",\n                \"tool\": tool_name,\n                \"latency_ms\": latency_ms,\n                \"threshold\": self.latency_threshold_ms,\n                \"timestamp\": time.time(),\n            })\n\n    def get_health(self) -> dict:\n        \"\"\"Get overall server health status.\"\"\"\n        total_calls = sum(m.call_count for m in self._tools.values())\n        total_errors = sum(m.error_count for m in self._tools.values())\n        error_rate = total_errors \u002F total_calls if total_calls > 0 else 0.0\n\n        return {\n            \"status\": \"healthy\" if error_rate \u003C self.error_rate_threshold else \"degraded\",\n            \"total_calls\": total_calls,\n            \"total_errors\": total_errors,\n            \"error_rate\": round(error_rate, 4),\n            \"tools\": {\n                name: {\n                    \"calls\": m.call_count,\n                    \"errors\": m.error_count,\n                    \"avg_latency_ms\": round(m.total_latency_ms \u002F m.call_count, 1) if m.call_count > 0 else 0,\n                    \"max_latency_ms\": round(m.max_latency_ms, 1),\n                }\n                for name, m in self._tools.items()\n            },\n            \"recent_alerts\": self._alerts[-10:],\n        }\n```\n\n### Scaling Strategies\n\n**Horizontal Scaling for HTTP Servers**\n\nFor HTTP-based MCP servers, scale horizontally behind a load balancer. Each instance is stateless (or uses shared state via Redis or a database).\n\n```\nLoad Balancer\n    |\n    +-- MCP Server Instance 1\n    +-- MCP Server Instance 2\n    +-- MCP Server Instance 3\n    |\n    +-- Shared State (Redis \u002F PostgreSQL)\n```\n\n**Connection Pooling for stdio Servers**\n\nstdio servers cannot be shared across clients, but they can be pooled. A pool manager maintains a set of pre-started server processes and assigns them to incoming client connections.\n\n**Caching**\n\nFor tools that return the same result for the same input (deterministic tools like schema lookups, format conversions, and reference data), implement response caching:\n\n```python\n\"\"\"caching.py -- Response caching for MCP tools.\"\"\"\n\nimport hashlib\nimport json\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass ToolCache:\n    \"\"\"LRU cache for deterministic MCP tool responses.\"\"\"\n    max_size: int = 1000\n    ttl_seconds: float = 300.0  # 5 minutes\n    _cache: dict = field(default_factory=dict)\n    _access_order: list = field(default_factory=list)\n\n    def _make_key(self, tool_name: str, arguments: dict) -> str:\n        \"\"\"Create a cache key from tool name and arguments.\"\"\"\n        canonical = json.dumps(\n            {\"tool\": tool_name, \"args\": arguments},\n            sort_keys=True, separators=(\",\", \":\"),\n        )\n        return hashlib.sha256(canonical.encode()).hexdigest()\n\n    def get(self, tool_name: str, arguments: dict) -> Optional[str]:\n        \"\"\"Get a cached result if available and not expired.\"\"\"\n        key = self._make_key(tool_name, arguments)\n        entry = self._cache.get(key)\n        if not entry:\n            return None\n        if time.time() - entry[\"timestamp\"] > self.ttl_seconds:\n            del self._cache[key]\n            return None\n        return entry[\"result\"]\n\n    def put(self, tool_name: str, arguments: dict, result: str) -> None:\n        \"\"\"Cache a tool result.\"\"\"\n        key = self._make_key(tool_name, arguments)\n        self._cache[key] = {\n            \"result\": result,\n            \"timestamp\": time.time(),\n        }\n        # Evict oldest if over max size\n        if len(self._cache) > self.max_size:\n            oldest_key = min(\n                self._cache, key=lambda k: self._cache[k][\"timestamp\"]\n            )\n            del self._cache[oldest_key]\n```\n\n### Version Upgrades Without Breaking Clients\n\nWhen upgrading your MCP server, maintain backward compatibility by following these rules:\n\n1. **Never remove tools** in a minor version. Deprecate them first (add \"DEPRECATED\" to the description), then remove in the next major version.\n2. **Never change tool input schemas** in a breaking way. Adding optional parameters is safe. Removing parameters or changing types is breaking.\n3. **Use feature flags** to roll out new tool behavior gradually.\n4. **Version your transport endpoint** (`\u002Fv1\u002Fmcp`, `\u002Fv2\u002Fmcp`) for HTTP servers.\n5. **Test against older clients** before releasing.\n\n### Security Hardening\n\nProduction MCP servers handle untrusted input from AI models. Apply defense-in-depth:\n\n1. **Input validation**: Validate every input against the schema and semantic constraints. Never trust model-generated input.\n2. **Sandboxing**: Run tool handlers in sandboxed environments when they execute user-provided code or queries.\n3. **Network isolation**: MCP servers should only have network access to the services they need. Use firewall rules to block everything else.\n4. **Secret management**: Never hardcode API keys or credentials. Use environment variables or a secret manager.\n5. **Dependency scanning**: Regularly scan your dependencies for known vulnerabilities.\n6. **Rate limiting**: Always implement rate limiting, even for internal servers. A compromised client can flood a server.\n\n---\n\n## Chapter 8: Case Studies\n\n### Case Study 1: Data Connector MCP Server (Database Access)\n\n**The Problem**: A data analytics company has 500 analysts who need to query 12 databases across three cloud providers. Each analyst has different access levels. The current workflow: write SQL in a notebook, run it, wait, copy-paste results into reports. AI assistants could automate this, but each database requires different connection logic, authentication, and query syntax.\n\n**The Solution**: A single MCP server that provides unified access to all 12 databases with role-based access control.\n\n```python\n\"\"\"data_connector.py -- Multi-database MCP server case study.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass DatabaseConfig:\n    \"\"\"Configuration for a single database connection.\"\"\"\n    name: str\n    engine: str  # \"postgresql\", \"mysql\", \"bigquery\", \"snowflake\"\n    connection_string: str\n    allowed_roles: list[str] = field(default_factory=list)\n    read_only: bool = True\n    max_rows: int = 10000\n    timeout_seconds: int = 30\n\n\n@dataclass\nclass DataConnector:\n    \"\"\"Multi-database connector with role-based access.\"\"\"\n    databases: dict[str, DatabaseConfig] = field(default_factory=dict)\n\n    def register_database(self, config: DatabaseConfig) -> None:\n        \"\"\"Register a database connection.\"\"\"\n        self.databases[config.name] = config\n\n    def list_databases(self, user_role: str) -> list:\n        \"\"\"List databases the user can access.\"\"\"\n        return [\n            {\n                \"name\": db.name,\n                \"engine\": db.engine,\n                \"read_only\": db.read_only,\n                \"max_rows\": db.max_rows,\n            }\n            for db in self.databases.values()\n            if user_role in db.allowed_roles or not db.allowed_roles\n        ]\n\n    def check_access(self, database_name: str, user_role: str) -> bool:\n        \"\"\"Check if a user role has access to a database.\"\"\"\n        db = self.databases.get(database_name)\n        if not db:\n            return False\n        return user_role in db.allowed_roles or not db.allowed_roles\n\n    def validate_query(self, database_name: str, sql: str) -> dict:\n        \"\"\"Validate a query against the database's constraints.\"\"\"\n        db = self.databases.get(database_name)\n        if not db:\n            return {\"valid\": False, \"error\": f\"Database '{database_name}' not found\"}\n\n        upper_sql = sql.strip().upper()\n\n        if db.read_only and not upper_sql.startswith(\"SELECT\"):\n            return {\"valid\": False, \"error\": \"Database is read-only. Only SELECT allowed.\"}\n\n        dangerous = [\"DROP\", \"DELETE\", \"TRUNCATE\", \"ALTER\"]\n        for keyword in dangerous:\n            if keyword in upper_sql:\n                return {\"valid\": False, \"error\": f\"Keyword '{keyword}' is not allowed\"}\n\n        return {\"valid\": True, \"database\": database_name, \"engine\": db.engine}\n```\n\n**Results**: Query time for analysts dropped 70% because the AI assistant handles SQL generation, connection routing, and result formatting. Access control incidents dropped to zero because the server enforces the same RBAC policies regardless of which AI client the analyst uses.\n\n### Case Study 2: API Wrapper MCP Server (Third-Party API)\n\n**The Problem**: A SaaS company's customer success team uses five different APIs (Salesforce, Zendesk, Stripe, Mixpanel, Intercom) to manage customer accounts. Each API has its own authentication, rate limits, and data model. Customer success managers spend 30 minutes per account review switching between tools.\n\n**The Solution**: An MCP server that wraps all five APIs behind unified tools that answer customer-centric questions.\n\n```python\n\"\"\"customer_360.py -- Unified customer data MCP server.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass APIEndpoint:\n    \"\"\"Configuration for a third-party API.\"\"\"\n    name: str\n    base_url: str\n    api_key: str\n    rate_limit_per_minute: int\n    timeout_seconds: int = 10\n\n\n@dataclass\nclass Customer360Server:\n    \"\"\"Unified customer view from multiple API sources.\"\"\"\n    apis: dict[str, APIEndpoint] = field(default_factory=dict)\n    _cache: dict = field(default_factory=dict)\n\n    def register_api(self, endpoint: APIEndpoint) -> None:\n        \"\"\"Register an API endpoint.\"\"\"\n        self.apis[endpoint.name] = endpoint\n\n    def get_customer_summary(self, customer_email: str) -> dict:\n        \"\"\"Build a 360-degree customer summary from all sources.\"\"\"\n        # In production, these would be actual API calls\n        return {\n            \"email\": customer_email,\n            \"crm\": self._get_crm_data(customer_email),\n            \"support\": self._get_support_data(customer_email),\n            \"billing\": self._get_billing_data(customer_email),\n            \"engagement\": self._get_engagement_data(customer_email),\n        }\n\n    def _get_crm_data(self, email: str) -> dict:\n        \"\"\"Get CRM data from Salesforce.\"\"\"\n        return {\n            \"source\": \"salesforce\",\n            \"account_status\": \"active\",\n            \"plan\": \"enterprise\",\n            \"mrr\": 5000.0,\n            \"renewal_date\": \"2026-09-15\",\n        }\n\n    def _get_support_data(self, email: str) -> dict:\n        \"\"\"Get support data from Zendesk.\"\"\"\n        return {\n            \"source\": \"zendesk\",\n            \"open_tickets\": 2,\n            \"avg_resolution_hours\": 4.2,\n            \"satisfaction_score\": 4.5,\n        }\n\n    def _get_billing_data(self, email: str) -> dict:\n        \"\"\"Get billing data from Stripe.\"\"\"\n        return {\n            \"source\": \"stripe\",\n            \"current_period_amount\": 5000.0,\n            \"payment_status\": \"current\",\n            \"last_payment_date\": \"2026-03-01\",\n        }\n\n    def _get_engagement_data(self, email: str) -> dict:\n        \"\"\"Get engagement data from Mixpanel.\"\"\"\n        return {\n            \"source\": \"mixpanel\",\n            \"dau_last_30\": 22,\n            \"feature_adoption\": 0.73,\n            \"last_active\": \"2026-04-06\",\n        }\n\n    def assess_health(self, summary: dict) -> dict:\n        \"\"\"Assess customer health from summary data. Pure logic.\"\"\"\n        score = 100\n        risks = []\n\n        # Support issues\n        open_tickets = summary.get(\"support\", {}).get(\"open_tickets\", 0)\n        if open_tickets > 3:\n            score -= 20\n            risks.append(f\"{open_tickets} open support tickets\")\n\n        # Engagement drop\n        dau = summary.get(\"engagement\", {}).get(\"dau_last_30\", 0)\n        if dau \u003C 5:\n            score -= 30\n            risks.append(f\"Low engagement: {dau} active days in last 30\")\n\n        # Payment issues\n        payment = summary.get(\"billing\", {}).get(\"payment_status\", \"\")\n        if payment != \"current\":\n            score -= 25\n            risks.append(f\"Payment status: {payment}\")\n\n        # Feature adoption\n        adoption = summary.get(\"engagement\", {}).get(\"feature_adoption\", 0)\n        if adoption \u003C 0.3:\n            score -= 15\n            risks.append(f\"Low feature adoption: {adoption:.0%}\")\n\n        health = \"healthy\" if score >= 70 else \"at_risk\" if score >= 40 else \"critical\"\n\n        return {\n            \"health_score\": max(0, score),\n            \"health_status\": health,\n            \"risks\": risks,\n            \"recommendation\": self._get_recommendation(health, risks),\n        }\n\n    @staticmethod\n    def _get_recommendation(health: str, risks: list) -> str:\n        \"\"\"Generate a recommendation based on health assessment.\"\"\"\n        if health == \"healthy\":\n            return \"No action needed. Consider upsell opportunity.\"\n        if health == \"at_risk\":\n            return f\"Schedule check-in to address: {'; '.join(risks)}\"\n        return f\"Immediate intervention required. Critical issues: {'; '.join(risks)}\"\n```\n\n**Results**: Account review time dropped from 30 minutes to 3 minutes. At-risk customers are identified automatically, and the AI assistant generates action plans. Net revenue retention improved 8 percentage points in the first quarter.\n\n### Case Study 3: Domain-Specific Tool Server (Specialized Computation)\n\n**The Problem**: A biotech company needs to perform protein structure predictions, molecular docking simulations, and drug interaction checks. These computations require specialized libraries (AlphaFold, RDKit, Open Babel) that are difficult to install and configure. Researchers want to access these tools through their AI assistant without managing the computational environment.\n\n**The Solution**: An MCP server that wraps the computational tools behind simple, well-documented tool interfaces, running on a GPU-equipped server.\n\n```python\n\"\"\"biotech_tools.py -- Biotech computation MCP server case study.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n\n@dataclass\nclass ComputeJob:\n    \"\"\"A computational job submitted to the server.\"\"\"\n    job_id: str\n    job_type: str\n    status: str = \"pending\"  # pending, running, completed, failed\n    input_params: dict = field(default_factory=dict)\n    result: Optional[dict] = None\n    error: Optional[str] = None\n    submitted_at: float = 0.0\n    completed_at: float = 0.0\n    compute_seconds: float = 0.0\n\n\n@dataclass\nclass BiotechServer:\n    \"\"\"MCP server for biotech computations.\"\"\"\n    _jobs: dict[str, ComputeJob] = field(default_factory=dict)\n    max_concurrent_jobs: int = 4\n    _running_count: int = 0\n\n    def submit_structure_prediction(\n        self,\n        sequence: str,\n        model: str = \"alphafold2\",\n    ) -> dict:\n        \"\"\"Submit a protein structure prediction job.\"\"\"\n        # Validate sequence (amino acid letters only)\n        valid_aa = set(\"ACDEFGHIKLMNPQRSTVWY\")\n        invalid = set(sequence.upper()) - valid_aa\n        if invalid:\n            return {\n                \"error\": f\"Invalid amino acid characters: {invalid}. \"\n                         f\"Use standard single-letter codes.\"\n            }\n\n        if len(sequence) > 2000:\n            return {\n                \"error\": f\"Sequence too long ({len(sequence)} residues). \"\n                         f\"Maximum is 2000 residues.\"\n            }\n\n        if self._running_count >= self.max_concurrent_jobs:\n            return {\n                \"error\": f\"Server at capacity ({self.max_concurrent_jobs} jobs). \"\n                         f\"Try again in a few minutes.\"\n            }\n\n        import time, secrets\n        job_id = f\"sp_{secrets.token_hex(8)}\"\n        job = ComputeJob(\n            job_id=job_id,\n            job_type=\"structure_prediction\",\n            status=\"pending\",\n            input_params={\n                \"sequence\": sequence,\n                \"model\": model,\n                \"length\": len(sequence),\n            },\n            submitted_at=time.time(),\n        )\n        self._jobs[job_id] = job\n\n        return {\n            \"job_id\": job_id,\n            \"status\": \"submitted\",\n            \"estimated_time_seconds\": len(sequence) * 0.5,\n            \"message\": f\"Structure prediction submitted for {len(sequence)}-residue sequence\",\n        }\n\n    def check_drug_interaction(\n        self,\n        drug_a: str,\n        drug_b: str,\n    ) -> dict:\n        \"\"\"Check for known interactions between two drugs.\"\"\"\n        # In production, queries a drug interaction database\n        return {\n            \"drug_a\": drug_a,\n            \"drug_b\": drug_b,\n            \"interaction_found\": False,\n            \"severity\": \"none\",\n            \"evidence_level\": \"no_data\",\n            \"recommendation\": f\"No known interaction between {drug_a} and {drug_b}.\",\n            \"disclaimer\": \"This is a computational prediction. Consult a pharmacist.\",\n        }\n\n    def get_job_status(self, job_id: str) -> dict:\n        \"\"\"Get the status of a submitted computation job.\"\"\"\n        job = self._jobs.get(job_id)\n        if not job:\n            return {\"error\": f\"Job '{job_id}' not found\"}\n        return {\n            \"job_id\": job.job_id,\n            \"job_type\": job.job_type,\n            \"status\": job.status,\n            \"submitted_at\": job.submitted_at,\n            \"completed_at\": job.completed_at if job.completed_at else None,\n            \"compute_seconds\": job.compute_seconds if job.completed_at else None,\n            \"result\": job.result,\n            \"error\": job.error,\n        }\n```\n\n**Results**: Researchers can now ask their AI assistant \"What is the predicted structure of this 300-residue protein?\" and get results back in minutes without managing computational environments. The MCP server handles queueing, GPU allocation, and result formatting. The number of predictions run per week tripled because the barrier to entry dropped from \"install AlphaFold and configure GPU drivers\" to \"ask the AI.\"\n\n---\n\n## What's Next\n\nBuilding an MCP server is the first step. The market is early -- as of April 2026, the registry has 10,000 servers but millions of potential use cases remain uncovered. The developers who build the best MCP servers today will own the tool layer of the AI economy.\n\nStart with a domain you know well. Build a server that solves a real problem for you. Publish it. Iterate based on usage data. Monetize when you have traction. The MCP specification is stable, the SDKs are mature, and the client ecosystem (Claude, GPT, Cursor, VS Code) is actively integrating. The infrastructure is ready. The opportunity is now.\n\n",{"name":5,"tags":24,"type":33,"author":34,"install":35,"license":15,"version":36,"metadata":37,"price_usd":42,"executable":20,"credentials":43,"description":7,"content_type":44,"compatibility":45},[25,26,27,28,29,30,31,32,33],"mcp","model-context-protocol","tool-integration","agent-infrastructure","monetization","greenhelix","openclaw","ai-agent","guide","felix-agent","none","1.3.1",{"openclaw":38},{"requires":39,"primaryEnv":41},{"env":40},[41],"STRIPE_API_KEY",49,[41],"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-mcp-server-development",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-mcp-server-development",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-mcp-server-development",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-mcp-server-development","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-mcp-server-development\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]