Tag: Model Context Protocol

Turning a REST API into an MCP Server: From Quick Prototype to Production-Ready

Connecting existing REST APIs to Large Language Models (LLMs) used to mean dumping massive OpenAPI specifications into a prompt and hoping the AI formatted its HTTP requests properly. With the Model Context Protocol (MCP), you can build a lightweight wrapper around your API that exposes clean, typed Tools that AI clients—like Claude Desktop, Cursor, or VS Code—can reliably discover and execute.

In this guide, we will take the classic Swagger Petstore REST API, build a working Python MCP prototype in minutes, and then harden it for real-world security.

Part 1: The Rapid Prototype

To get started quickly, we will use Python along with the official mcp SDK (FastMCP) and httpx for making asynchronous HTTP requests.

1. Project Setup

Initialize a new project and install the required dependencies:

uv init petstore-mcp
cd petstore-mcp
uv add "mcp[cli]" httpx

2. Building the Basic Server (server.py)

When writing MCP tools, type hints and docstrings do the heavy lifting. The AI reads them to understand what each tool does and which parameters to pass.

import httpx
from mcp.server.fastmcp import FastMCP
# Initialize the MCP server
mcp = FastMCP("Petstore")
BASE_URL = "https://petstore3.swagger.io/api/v3"
@mcp.tool()
async def find_pets_by_status(status: str = "available") -> list[dict]:
"""
Find pets in the store filtered by their current status.
Valid status values: 'available', 'pending', or 'sold'.
"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"{BASE_URL}/pet/findByStatus",
params={"status": status},
)
response.raise_for_status()
# Trim large responses so we don't flood the AI's context window
pets = response.json()
return [
{"id": p.get("id"), "name": p.get("name"), "status": p.get("status")}
for p in pets[:20]
]
@mcp.tool()
async def get_pet_by_id(pet_id: int) -> dict:
"""Retrieve full details for a single pet using its numeric ID."""
async with httpx.AsyncClient() as client:
response = await client.get(f"{BASE_URL}/pet/{pet_id}")
response.raise_for_status()
return response.json()
@mcp.tool()
async def add_pet(name: str, category: str = "Dogs", status: str = "available") -> dict:
"""Add a new pet to the store inventory."""
payload = {
"name": name,
"category": {"name": category},
"photoUrls": [],
"status": status,
}
async with httpx.AsyncClient() as client:
response = await client.post(f"{BASE_URL}/pet", json=payload)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
# Runs over standard input/output (stdio) for local AI clients
mcp.run(transport="stdio")

3. Testing Locally

You can test your tools interactively in your browser before connecting an AI client by running the built-in MCP Inspector:

uv run mcp dev server.py

Once verified, register the server in your AI client’s MCP configuration file (such as claude_desktop_config.json or .cursor/mcp.json):

{
"mcpServers": {
"petstore": {
"command": "uv",
"args": [
"--directory",
"/absolute/path/to/petstore-mcp",
"run",
"server.py"
]
}
}
}

Part 2: Why the Prototype Isn’t Ready for Production

While the prototype works great on your laptop, exposing it to real data or wider teams introduces several security risks:

  1. Hardcoded Configuration & Missing Auth: The base URL is hardcoded, and there is no API key authentication.
  2. Loose Input Validation: status: str allows an LLM (or a prompt injection attack) to pass arbitrary strings or path-traversal attempts instead of strict enum values.
  3. Leaky Error Messages: Calling response.raise_for_status() directly throws raw exceptions that can expose internal URLs, headers, and stack traces to the LLM.
  4. No Network Timeouts: A hanging upstream API call can stall the entire MCP server indefinitely.
  5. Unrestricted Mutating Actions: Write operations like add_pet lack tool annotations warning the host client that the action modifies state.

Part 3: The Hardened, Production-Ready Version

Let’s refactor server.py to fix these vulnerabilities using environment variables, Pydantic validation, structured error handling, and MCP tool annotations.

import logging
import os
import sys
from typing import Literal
import httpx
from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations
from pydantic import Field
# Configure logging strictly to stderr (stdout is reserved for JSON-RPC messages)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("petstore-mcp")
# 1. Externalize configuration & fail fast if secrets are missing
BASE_URL = os.environ.get("PETSTORE_BASE_URL", "https://petstore3.swagger.io/api/v3")
API_KEY = os.environ.get("PETSTORE_API_KEY")
if not API_KEY:
raise RuntimeError("PETSTORE_API_KEY environment variable must be set.")
mcp = FastMCP("Petstore-Secure")
# 2. Reuse a single HTTP client with strict timeouts and auth headers
http_client = httpx.AsyncClient(
base_url=BASE_URL,
headers={"api_key": API_KEY, "Accept": "application/json"},
timeout=httpx.Timeout(10.0, connect=5.0),
)
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def find_pets_by_status(
# 3. Enforce strict enum values at the schema level
status: Literal["available", "pending", "sold"] = "available",
) -> list[dict] | dict:
"""
Find pets in the store filtered by their current status.
Valid status values: 'available', 'pending', or 'sold'.
"""
try:
response = await http_client.get("/pet/findByStatus", params={"status": status})
response.raise_for_status()
pets = response.json()
# 4. Minimize returned fields to reduce token usage & prompt-injection surface
return [
{
"id": p.get("id"),
"name": str(p.get("name", ""))[:50], # Truncate untrusted strings
"status": p.get("status"),
}
for p in pets[:20]
]
except httpx.HTTPStatusError as exc:
logger.error("Upstream HTTP %s on find_pets_by_status", exc.response.status_code)
return {"error": "Failed to fetch pets from the store API."}
except httpx.RequestError as exc:
logger.error("Network error on find_pets_by_status: %s", exc)
return {"error": "Petstore service is currently unreachable."}
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
async def get_pet_by_id(
# Constrain ID to positive integers only
pet_id: int = Field(gt=0, description="Positive numeric ID of the pet"),
) -> dict:
"""Retrieve details for a single pet using its numeric ID."""
try:
response = await http_client.get(f"/pet/{pet_id}")
response.raise_for_status()
data = response.json()
return {
"id": data.get("id"),
"name": str(data.get("name", ""))[:50],
"category": data.get("category", {}).get("name"),
"status": data.get("status"),
}
except httpx.HTTPStatusError as exc:
logger.error("Upstream HTTP %s for pet_id=%s", exc.response.status_code, pet_id)
if exc.response.status_code == 404:
return {"error": f"Pet with ID {pet_id} was not found."}
return {"error": "Failed to retrieve pet details."}
except httpx.RequestError as exc:
logger.error("Network error on get_pet_by_id: %s", exc)
return {"error": "Petstore service is currently unreachable."}
# 5. Mark mutating tools explicitly so AI hosts can prompt for user approval
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False))
async def add_pet(
name: str = Field(min_length=1, max_length=50, description="Name of the pet"),
category: Literal["Dogs", "Cats", "Birds", "Other"] = "Dogs",
status: Literal["available", "pending", "sold"] = "available",
) -> dict:
"""Add a new pet to the store inventory."""
payload = {
"name": name.strip(),
"category": {"name": category},
"photoUrls": [],
"status": status,
}
try:
response = await http_client.post("/pet", json=payload)
response.raise_for_status()
created = response.json()
return {
"id": created.get("id"),
"name": created.get("name"),
"status": created.get("status"),
}
except httpx.HTTPStatusError as exc:
logger.error("Upstream HTTP %s on add_pet", exc.response.status_code)
return {"error": "Unable to add pet to the store."}
except httpx.RequestError as exc:
logger.error("Network error on add_pet: %s", exc)
return {"error": "Petstore service is currently unreachable."}
if __name__ == "__main__":
mcp.run(transport="stdio")

Updated Client Configuration

Pass the API key cleanly via the env block in your MCP host configuration rather than storing it in your codebase:
TIP: You can do better by sandboxing the container and running Proxy Injection at the edge to inject the keys into the payload.

{
"mcpServers": {
"petstore": {
"command": "uv",
"args": [
"--directory",
"/absolute/path/to/petstore-mcp",
"run",
"server.py"
],
"env": {
"PETSTORE_API_KEY": "your-secret-api-key-here",
"PETSTORE_BASE_URL": "https://petstore3.swagger.io/api/v3"
}
}
}
}

PROXY Injection Pattern
[ AI Agent ] ──(MCP)──> [ MCP Server ] ──(No API Key)──> 
[ Egress Edge Proxy ] ──(+ API Key Header)──> [ Upstream REST API ]

Summary of Security Best Practices

  • Validate everything at the schema boundary: Use Literal and Pydantic Field constraints so invalid arguments never reach your HTTP client.
  • Sanitize outputs against prompt injection: Untrusted database fields (like pet names or user comments) can carry hidden instructions. Strip unnecessary fields and truncate free-text strings before returning data to the LLM.
  • Separate logs from protocol traffic: Always log diagnostic details to stderr so stdout stays strictly reserved for MCP JSON-RPC communication.
  • Secure remote deployments: If you move from local stdio to streamable-http for shared team access, always enforce OAuth 2.1 / Bearer token authentication, run behind TLS (HTTPS), and deploy inside a locked-down, non-root container.