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:
- Refactor your existing code for better quality.
- Automatically insert MCP integration using the fastapi_mcp library.
- 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