Tag: mcp

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.
What is Claude Code? (And Why It’s Not Just Another Chatbot)

What is Claude Code? (And Why It’s Not Just Another Chatbot)

Let’s be real: most AI coding assistants are glorified autocomplete engines that require you to copy-paste code like it’s 2005. Claude Code is different. It’s an agentic coding tool that lives in your terminal, understands your actual codebase, executes commands, and—here is the kicker—does the work for you.

It doesn’t just suggest a function; it writes the function, runs the tests, fixes the inevitable “oops,” and commits the result.

The “Must-Know” Workflow: Explore → Plan → Code → Commit
If you jump straight to asking Claude to “write code,” you’re setting yourself up for a chaotic debugging session. Instead, embrace the Explore → Plan → Code → Commit rhythm:

Explore & Plan: Use Plan Mode (Shift + Tab). Claude reads your files (read-only!) and builds a map. It’s like giving your GPS a destination before you start driving.

Code: Once the plan is approved, Claude executes. It’s your pair programmer—but the kind that doesn’t complain about your coffee habits.

Commit: Use built-in subagents to review your work before you push. It’s like having a senior dev check your PR without the existential dread of a code review meeting.


Supercharging Your Workflow (Without Killing Your Context)

The biggest challenge with any agent is the Context Window. You have a finite amount of space in Claude’s “brain,” and if you fill it with irrelevant garbage, Claude gets “dumb.” Here is how to keep it sharp:

1. Skills > MCP

Think of Skills as your AI’s muscle memory. Whether it’s a specific TDD workflow or a custom PR template, Skills only load the heavy instructions when they are needed.

Pro-tip: Don’t overuse MCP servers. They load tool definitions into context permanently. If a tool has a CLI equivalent (like gh for GitHub), use the CLI—it’s way more efficient. Try to keep your MCP footprint under 10% of your context window, or Claude will start struggling.

2. Deterministic Power: Hooks

If you want something to happen every single time, don’t ask Claude to remember it in a prompt (it’ll eventually forget). Use Hooks.

  • PostToolUse: Perfect for auto-formatting (e.g., running Prettier after every edit).
  • PreToolUse: Your “Do Not Touch” switch. Block rm -rf or production file edits.
  • Humor Note: Treat these hooks like your stern office manager—they don’t care about your “intent,” they just enforce the rules.

3. The Holy Grail: CLAUDE.md

If your project feels like it’s suffering from amnesia, create a CLAUDE.md file. It’s the “Onboarding Guide” for your agent. If you find yourself correcting Claude twice on the same thing, tell it to “save this rule to CLAUDE.md.” It’s basically teaching your AI to grow up.

Final Thoughts

Claude Code is essentially a super-powered intern that never sleeps. By managing your context, relying on deterministic Hooks for safety, and using Skills for reusable workflows, you stop fighting the tool and start shipping code.

Now, go forth, run claude, and try not to let the AI take too much credit for your genius.

Beyond Infrastructure as Code: Why MCP is the Next Evolution of Your DevOps (AI) Stack

Beyond Infrastructure as Code: Why MCP is the Next Evolution of Your DevOps (AI) Stack

If you’ve spent the last 25 years navigating the evolution of software engineering—from bare-metal servers to the complexity of Kubernetes clusters and multi-cloud architectures—you know that the “dev” in DevOps has always been about abstraction.

We moved from manual scripts to Terraform (IaC), from manual deployments to GitOps (ArgoCD), and from siloed monitoring to observability stacks. Every step was about making our systems more predictable, repeatable, and scalable.

Today, we are hitting the next wall: The “Context Gap.” Even with the best AI coding assistants, there is a disconnect between the LLM’s general knowledge and the specific, idiosyncratic realities of your internal platforms, APIs, and business data.

Enter the Model Context Protocol (MCP). If you’ve spent your career building pipelines to get code into production, think of MCP as the pipeline to get intelligence into your development workflow.

MCP (Model Context Protocol) is an open-source standard for connecting AI applications to external systems.Using MCP, AI applications like Claude or ChatGPT can connect to data sources (e.g. local files, databases), tools (e.g. search engines, calculators) and workflows (e.g. specialized prompts)—enabling them to access key information and perform tasks.Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect electronic devices, MCP provides a standardized way to connect AI applications to external systems.

  • Agents can access your Google Calendar, acting as a more personalized AI assistant.
  • Claude Code can generate an entire web app using a Figma design.
  • Enterprise chatbots can connect to multiple databases across an organization, empowering users to analyze data using chat.
  • AI models can create 3D designs on Blender and print them out using a 3D printer.

Why MCP Matters to the Modern Platform Manager

As a Platform Manager, you’re already managing complexity. MCP isn’t just another library; it’s an open standard that allows your local IDE or AI assistant (like Claude) to “plug in” to your specific internal tools.

Instead of copying and pasting logs into a chatbot or manually checking API statuses, you build an MCP server that grants your AI the “eyes” and “hands” to interact with your services directly—with your explicit, human-in-the-loop approval.

  • Developers: MCP reduces development time and complexity when building, or integrating with, an AI application or agent.
  • AI applications or agents: MCP provides access to an ecosystem of data sources, tools and apps which will enhance capabilities and improve the end-user experience.
  • End-users: MCP results in more capable AI applications or agents which can access your data and take actions on your behalf when necessary.

Building Your First MCP Server: A Practical Approach

To see how this fits into your existing ecosystem, let’s look at a simple implementation. We’ll build a Weather MCP Server. While simple, it mirrors the same pattern you would use to build a “Production Status” or “Cluster Inventory” server that your team could use to query infrastructure health in natural language.

1. The Architecture

MCP servers communicate via JSON-RPC, usually over standard I/O (stdio). This is the “connector” that allows the AI client to execute code defined in your server.

2. The Code (Pythonic Simplicity)

Using the FastMCP library, the boilerplate is minimal. You focus on the business logic—defining Tools that the AI can trigger.

from mcp.server.fastmcp import FastMCP
import httpx
# Initialize the server
mcp = FastMCP("weather-server")
@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
"""Get the weather forecast for a specific coordinate."""
# Logic to interface with NWS API
...

The magic here is in the docstrings and type hints. The MCP SDK automatically introspects your code, telling the AI exactly what arguments are required (e.g., latitude, longitude), which significantly reduces hallucination and schema errors.

3. Connecting to the “Host”

In a DevOps context, the “Host” is the client—like Claude for Desktop, or perhaps a custom CLI tool your team uses. You register the server by updating a configuration file (like claude_desktop_config.json):

{
"mcpServers": {
"weather": {
"command": "uv",
"args": ["run", "/path/to/weather.py"]
}
}
}

The “DevOps” Mindset Applied to MCP

If you want to take this to the next level, stop thinking about weather data and start thinking about your Platform Interface:

  • Observability via MCP: Create a tool that queries your Prometheus/Grafana instances. Ask your AI: “What are the current error rates for the checkout service in prod?”
  • GitOps via MCP: Create a tool that wraps the argocd CLI. Ask your AI: “What is the current sync status of our core microservices in the Sydney region?”
  • Infrastructure Auditing: Create a tool that uses boto3 or Azure SDKs to audit security group rules. Ask: “Find any S3 buckets in the dev environment that are currently public.”

Final Thoughts: The New Infrastructure

We’ve spent decades optimizing the delivery of software. Now, the bottleneck is the interaction with the systems we’ve built. MCP is the bridge. It turns your documentation and APIs into living, conversational interfaces.

For those of us who have lived through the rise of Coding manually, Kubernetes and the transition to GitOps, this feels like the logical next step: making our internal platforms as discoverable and usable as the software we build on top of them.

Ready to start? Check out the official MCP Quickstart Guide to get your environment set up.