Library

Volume 2 · MCP (Model Context Protocol) & Skills

Notebook
Sign in

Section 44

Building Custom MCP Servers

466 words · about 2 min

44.1 Full Python SDK Example

from mcp.server import Server
from mcp.types import Resource, Tool

server = Server("enterprise-knowledge-base")

@server.list_tools()
async def list_tools():
    return [
        Tool(
            name="search_knowledge_base",
            description="Search enterprise documents by semantic similarity",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "department": {"type": "string",
                                   "enum": ["hr", "legal", "engineering"]},
                    "top_k": {"type": "integer", "default": 5}
                },
                "required": ["query"]
            }
        ),
        Tool(
            name="get_document",
            description="Retrieve a specific document by ID",
            inputSchema={
                "type": "object",
                "properties": {"document_id": {"type": "string"}},
                "required": ["document_id"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "search_knowledge_base":
        results = await vector_db.search(
            query=arguments["query"],
            filter={"department": arguments.get("department")},
            top_k=arguments.get("top_k", 5)
        )
        return format_results(results)
    elif name == "get_document":
        doc = await document_store.get(arguments["document_id"])
        return doc.content
    raise ValueError(f"Unknown tool: {name}")

# Run the server over stdio
async def main():
    async with server.run_stdio() as streams:
        await streams.wait_closed()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

44.2 Transport Options

Transport Protocol Use Case Latency
stdio Process pipes Local servers, CLI tools, same-machine hosts Lowest
HTTP + SSE HTTP/Server-Sent Events Remote servers, cloud deployment Medium
Streamable HTTP HTTP streaming Modern remote servers, better proxy/load-balancer compatibility Medium

Section 44 — Interview Q&A

Q1: Walk through the minimum components required to stand up a production-grade custom MCP server. A list_tools handler that returns each tool’s name, description, and JSON Schema input definition (the description quality directly drives whether the model calls the tool correctly); a call_tool handler that dispatches by tool name, validates arguments against the declared schema before touching any backend system, and returns structured results/errors; a transport choice (stdio for local/same-host, HTTP+SSE or streamable HTTP for remote); and — beyond the SDK basics — auth/consent enforcement, rate limiting, and audit logging wrapped around every tool call (covered in Section 47).

Q2: How do you choose between stdio and HTTP+SSE transport for a new MCP server? stdio when the server runs on the same machine as the host (a local CLI tool, a desktop-client integration) — lowest latency, simplest deployment, no network/auth surface to secure. HTTP+SSE (or streamable HTTP) when the server needs to be reachable remotely — multiple hosts sharing one server instance, cloud-hosted enterprise integrations, or anywhere the server needs independent scaling and lifecycle from any single host. Remote transports also require you to add the authentication and network-security layer that stdio gets “for free” from process-level isolation.