How I Built an MCP Server in 50 Lines of Python (Auto-Generated from OpenAPI)

Ever wished you could connect your existing APIs to AI assistants like Claude or Cursor without writing a ton of boilerplate? This article shows you how to build an MCP (Model Context Protocol) server...

How I Built an MCP Server in 50 Lines of Python (Auto-Generated from OpenAPI)
Photo by Rubaitul Azad / Unsplash

Ever wished you could connect your existing APIs to AI assistants like Claude or Cursor without writing a ton of boilerplate? This article shows you how to build an MCP (Model Context Protocol) server that does just that, automatically generating tools from an OpenAPI specification in under 50 lines of Python! The key is using FastMCP, a framework designed for this purpose, along with FastAPI for production-ready features.

The process involves several clever tricks. First, the code uses `contextvars` to manage API keys on a per-request basis, ensuring thread safety. Then, `httpx` is leveraged with event hooks to inject the API key into the `Authorization` header of every outgoing request. The heart of the solution is `FastMCP.from_openapi()`, which magically transforms your OpenAPI spec into a set of MCP tools, complete with parameter validation and descriptions. Finally, FastAPI provides health check endpoints and middleware for API key extraction, making the server production-ready. The resulting architecture allows AI assistants to seamlessly execute tasks like posting comments or fetching profiles through your API.

The beauty of this approach is its simplicity and power. Zero duplication of tool definitions, instant AI integration, and production-ready features like health checks and asynchronous handling. Plus, it's client-agnostic, working with Claude Desktop, Cursor, or any MCP-compatible client. The article even provides a complete, copy-paste-able code block to get you started. With this pattern, you can quickly unlock a new world of AI-powered interactions with your existing APIs and focus on building valuable features.


📰 Original article: https://dev.to/durgaprasadbudhwani/how-i-built-an-mcp-server-in-50-lines-of-python-auto-generated-from-openapi-5apb

This content has been curated and summarized for Code Crafts readers.