Creating an MCP Server from Any FastAPI URL with One Prompt

In the rapidly evolving landscape of AI-assisted development, the Model Context Protocol (MCP) has emerged as a game-changer. But what if you want to connect your AI assistants to existing FastAPI applications without modifying their code? Today, I’ll show you how to create an automatic MCP server from any FastAPI URL using just one prompt in Cursor.

The Power of FastAPI’s OpenAPI Documentation

FastAPI automatically generates comprehensive OpenAPI (formerly Swagger) documentation for all endpoints. This documentation contains everything needed to understand and interact with the API:

  • Endpoint paths and HTTP methods
  • Request parameters and body schemas
  • Response formats and status codes
  • Detailed descriptions and examples

This rich metadata is exactly what we need to create an MCP server that can proxy requests to the original API.

The One-Prompt Solution

Copy and paste this prompt into Cursor to generate a complete, ready-to-run MCP server that connects to any FastAPI application:

Create a complete Python script that generates an MCP server from the FastAPI application running at {URL}. The script should:

1. Fetch the OpenAPI/Swagger documentation from {URL}/openapi.json
2. Analyze all endpoints, parameters, request bodies, and response models
3. Create a new FastAPI application that:
- Mirrors all the endpoints from the original API
- Forwards requests to the original API
- Returns responses from the original API
4. Add MCP server functionality using the fastapi_mcp library
5. Include proper error handling for:
- Connection issues
- Authentication failures
- Invalid responses

The final script should be a single, self-contained Python file that:
- Takes command line arguments for customization (port, authentication, etc.)
- Includes detailed comments explaining how it works
- Can be run directly with "python script.py" to start the MCP server
- Automatically connects to {URL} and creates an MCP server at http://localhost:8000/mcp

Replace {URL} with the actual URL of the FastAPI application, for example https://api.example.com.

The output should be ONLY the complete Python script, ready to run, with no explanations before or after the code.

How to Use This Prompt

  1. Replace {URL} with the actual URL of the FastAPI application you want to connect to
  • For example: https://api.example.com or http://localhost:8000
  1. Paste the prompt into Cursor or another AI coding assistant
  2. Copy the generated Python script and save it as mcp_bridge.py
  3. Run the script with Python:

python mcp_bridge.py

  1. Connect your AI assistant to the MCP server at http://localhost:8000/mcp

That’s it! No manual coding, no configuration files, no complex setup. Just one prompt and you have a fully functional MCP server that connects to any FastAPI application.

What Makes This Approach Special

This solution is unique because:

  1. It requires zero knowledge of MCP or FastAPI – the AI does all the work
  2. It works with any FastAPI application that has OpenAPI documentation enabled
  3. It preserves all the original API’s functionality including parameters, schemas, and documentation
  4. It creates a production-ready MCP server with proper error handling and logging
  5. It’s completely automated – no manual intervention required

Real-World Applications

This approach opens up exciting possibilities:

  • Connect AI assistants to your company’s internal APIs without modifying them
  • Create MCP bridges to public APIs that use FastAPI
  • Test MCP functionality before implementing it directly in your codebase
  • Provide AI access to legacy systems through a FastAPI proxy

Conclusion

The ability to create MCP servers from existing FastAPI URLs with just one prompt is a game-changer for AI-assisted development. You can now connect your favorite AI assistants to any FastAPI application in minutes, without writing a single line of code yourself.

Try this approach today and experience the power of combining FastAPI’s excellent documentation with the flexibility of the Model Context Protocol!

Loic Baconnier

Automate MCP Integration in Your FastAPI App with a Single Copy/Paste

Modern APIs need more than just endpoints—they require robust documentation, strong typing, and seamless integration with advanced AI assistants. In our fast-paced development environment, every minute counts. That’s why today we’re exploring how to leverage a single, well-crafted Cursor prompt to automatically refactor an existing FastAPI application and integrate the Model Context Protocol (MCP) with zero extra manual adjustments.

What Is MCP and Why Does It Matter?

MCP (Model Context Protocol) is a lightweight framework that enables AI assistants to interact with your APIs. By converting your API endpoints into well-documented, standardized MCP tools, AI models (like those running in Cursor or Claude 3.7 Sonnet) can automatically discover and call your API functions. This not only enhances interoperability but also allows for dynamic, natural-language-driven interactions with your app.

Why Improve Your FastAPI Code First?

Before unlocking the power of MCP, your API needs to be in top shape. This means:

  • Comprehensive docstrings for each endpoint.
  • Detailed type hints and Pydantic models for requests and responses.
  • Robust error handling with proper HTTP exceptions.
  • Clear descriptions for every route so that MCP can easily « discover » and interpret them.

By improving your code according to these best practices, you’re ensuring that the MCP integration can accurately reflect your API’s capabilities, leading to smarter, reliable interactions for AI assistants.

Automating Everything with a Cursor Prompt

Imagine being able to improve your code—and add a whole new MCP interface—to your FastAPI project by simply pasting one prompt into Cursor. No more manual tweaks or back-and-forth adjustments. The idea is to use a precise instruction that tells the AI exactly how to:

  1. Refactor your existing code for better quality.
  2. Automatically insert MCP integration using the fastapi_mcp library.
  3. Generate the final, runnable code along with testing and configuration instructions.

Here’s why this approach is so powerful:

  • It removes the need for manual intervention.
  • It standardizes your API transformation process.
  • It sparks creativity by letting the AI fill in the boilerplate, making your API production-ready with minimal hassle.
  • It works with non-perfect AI systems by laying out each necessary step, ensuring no detail is lost.

The Final Cursor Prompt

Copy and paste the following prompt directly into Cursor. This instruction tells the AI to first improve your existing FastAPI code with best practices and then add the MCP route using the fastapi_mcp library—all in one go:

I have an existing FastAPI application that is functional but not optimized. Your job is to improve the code and integrate MCP (Model Context Protocol) using the fastapi_mcp library. Follow these steps carefully:

### Step 1: Improve the Existing FastAPI Code
1. **Docstrings**: Add detailed docstrings to all endpoints. Each docstring should include:
- A brief description of what the endpoint does.
- Parameters with their types and descriptions.
- The response format, including success and error cases.
- HTTP status codes used by the endpoint.
2. **Type Hints**: Ensure all functions have proper type hints for parameters and return values.
3. **Pydantic Models**:
- Define Pydantic models for request bodies (if any).
- Use Pydantic models for response validation (`response_model` in FastAPI).
4. **Error Handling**:
- Use `HTTPException` with appropriate status codes for errors.
- Handle edge cases gracefully with meaningful error messages.
5. **Endpoint Descriptions**: Add a `description` parameter to each route decorator to describe what the endpoint does.

### Step 2: Integrate MCP
1. Install the `fastapi_mcp` library:
```
pip install fastapi_mcp
```
2. Import the necessary function:
```
from fastapi_mcp import add_mcp_server
```
3. Add MCP functionality to the FastAPI app:
- After initializing your `FastAPI` app, call `add_mcp_server()`.
- Mount the MCP server at `/mcp`.
- Use a descriptive name for your MCP server (e.g., "My API MCP").
4. Ensure that all existing endpoints remain functional after adding the MCP server.

### Step 3: Provide Testing Instructions
1. Generate a JSON configuration snippet to connect this MCP server in Cursor:
```
{
"mcpServers": {
"My API MCP": {
"url": "http://127.0.0.1:8000/mcp"
}
}
}
```
2. Provide a sample `curl` command to test the `/mcp` endpoint:
```
curl -X POST http://127.0.0.1:8000/mcp/tools
```

### Input Example
Here is an example of my current FastAPI code (simplified):
```
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/items")
def get_items():
return {"items": []}

@app.get("/items/{item_id}")
def get_item(item_id: int):
if item_id == 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
```

### Output Requirements
- Refactor the above code to follow best practices (as outlined in Step 1).
- Add MCP integration (as described in Step 2).
- Provide a complete, runnable code block with comments explaining each change.
- Include testing instructions (as described in Step 3).

The final output should look like this:
1. The improved and MCP-integrated code.
2. A JSON snippet for connecting this API as an MCP server in Cursor.
3. A sample `curl` command to test the `/mcp` route.

DO NOT skip any steps or provide vague explanations—output only complete, ready-to-use code.

How This Works

By pasting the above prompt into Cursor, you delegate the entire transformation process to the AI assistant. It will:

  • Refactor your code to meet professional standards.
  • Automatically insert the MCP integration using fastapi_mcp.
  • Produce a self-contained code snippet with detailed comments and testing instructions.

This means you can convert an imperfect API into a fully MCP-compliant service without directly writing additional code!

Conclusion

This method not only accelerates your development process but also minimizes human error by standardizing integration tasks. With one thoughtfully constructed prompt, you can harness the power of AI to bring your FastAPI application up to production level—complete with modern documentation and remote AI assistant compatibility via the MCP protocol.

Try it out in your next project and experience a new level of automation that allows you to focus on what matters most: building innovative features while letting the AI take care of the boilerplate.

Loic Baconnier