How to Build an MCP Server (Step by Step)
A hands-on tutorial for building a Model Context Protocol server that exposes tools, resources, and prompts to any LLM host.
Key takeaways
- Install the official Python SDK with pip install "mcp[cli]", create an MCPServer, and decorate typed functions with @mcp.tool(), @mcp.resource() and @mcp.prompt().
- Test it with the MCP Inspector, run it over stdio for local hosts, and switch to Streamable HTTP with OAuth 2.1 token validation only when you need remote clients.
On this page
To build an MCP server, install the official SDK (pip install "mcp[cli]"), create an MCPServer, and decorate typed Python functions as tools, resources and prompts. The SDK derives the schemas from your type hints. Test it in the MCP Inspector, run it over stdio for local hosts, and add Streamable HTTP plus OAuth only for remote clients.
Verified against
MCP Python SDK 2.3.0 (mcp on PyPI, Python 3.10+) and MCP specification 2026-07-28, against the SDK README and v2 migration guide and the modelcontextprotocol.io transports and authorization pages. Checked October 2026.
Write a capability once as an MCP server and any MCP client, whether Claude, Cursor, or your own agent, can use it. For the wider context, read what is the Model Context Protocol; for where servers fit in a larger system, see the building AI agents guide. One warning: if a tutorial still imports FastMCP, it predates SDK v2.
Prerequisites
You need Python 3.10+ (or the TypeScript SDK, npm install @modelcontextprotocol/sdk) and a host to test against. Claude Desktop is the easiest local target because it spawns your server for you.
$ python -m venv .venv && source .venv/bin/activate
$ pip install "mcp[cli]"
The cli extra gives you the mcp dev and mcp run commands used below.
The three primitives: tools, resources, prompts
- Tools are functions the model executes: query a database, file a ticket, send a request. They have side effects and typed inputs.
- Resources are read-only context addressed by a URI. They inform, they do not act.
- Prompts are templated messages the user invokes deliberately, like a slash command.
The common beginner mistake is modeling everything as a tool. If the model only needs to read something, make it a resource.
Define a tool, a resource and a prompt
MCPServer derives each tool's input schema from your type hints and handles JSON-RPC and transport plumbing, so your effort goes into tool design and safety.
# server.py
import logging
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("weather-mcp")
SERVER_VERSION = "1.2.0"
mcp = MCPServer("weather-mcp")
def get_forecast(city: str, days: int = 3) -> dict:
"""Return a short forecast for a city. days must be 1-7."""
if not city.strip():
raise ToolError("city must not be empty")
if not 1 <= days <= 7:
raise ToolError("days must be between 1 and 7")
log.info("get_forecast city=%s days=%s", city, days)
return {"city": city, "days": days, "summary": f"Clear skies in {city}"}
def units() -> str:
"""Expose the unit system as a readable resource."""
return "metric"
def trip_check(city: str) -> str:
"""Reusable prompt template for a packing suggestion."""
return f"Given the forecast for {city}, suggest what to pack."
if __name__ == "__main__":
mcp.run(transport="stdio")
Dict, list, scalar and Pydantic model returns are wrapped into both text content and structured_content, so clients can validate the shape. Return structured data, not prose: it also makes the server testable, because you assert on fields instead of wording.
Write tool descriptions for a model, not a human
An LLM chooses tools from their names, descriptions, and parameter docs, so vague descriptions produce wrong tool choices and hallucinated arguments. State what the tool does, when to use it, when not to, and what it returns.
def search_orders(customer_email: str, status: str = "any") -> list[dict]:
"""Search a customer's orders by email address.
Use this when the user asks about the status or history of their orders.
Do NOT use it for product catalog questions; use search_catalog instead.
status is one of "any", "open", "shipped", "cancelled".
Returns orders with id, status, total, and placed_at.
"""
...
Handle errors so the model can recover
The model needs to understand a failure to recover from it. In SDK v2, raise ToolError (or return a CallToolResult with is_error=True) for failures the model should see. A protocol-level MCPError becomes a JSON-RPC error instead, which typical clients raise as an exception, so the model never reads it. For expected, recoverable cases, return an actionable message:
def refund_order(order_id: str) -> dict:
"""Issue a refund for an order. Returns {ok, message}."""
order = db.fetch_order(order_id)
if order is None:
return {"ok": False, "message": f"No order {order_id}. Ask the user to confirm the ID."}
if order["status"] == "refunded":
return {"ok": False, "message": "Order is already refunded; no action taken."}
db.refund(order_id)
return {"ok": True, "message": f"Refunded order {order_id}."}
Never leak stack traces or secrets in error text; it goes back to the model and into logs.
Choose a transport
The 2026-07-28 spec defines two standard transports.
stdio: the host launches your server as a subprocess and they exchange newline-delimited JSON-RPC over stdin and stdout. This is the right default for local development and desktop clients: no ports, no network surface, and the trust boundary of the user who launched it.
Streamable HTTP: each message is an HTTP POST to a single MCP endpoint, and replies come back as JSON or a request-scoped SSE stream. Use it for remote or shared deployments and anything behind a load balancer. In v2, host and port are arguments to run():
mcp.run(transport="streamable-http", host="0.0.0.0", port=8000)
Same handlers, different threat model: a Streamable HTTP server is a network service anyone who finds the URL can reach.
Test with the Inspector, then connect a host
Don't debug a server through an LLM; that mixes two sources of error. The MCP Inspector connects directly:
$ uv run mcp dev server.py
(npx @modelcontextprotocol/inspector launches the same Inspector without the SDK CLI.) Once schemas and error cases look right, add the server to Claude Desktop's claude_desktop_config.json (on macOS under ~/Library/Application Support/Claude/) and restart the app:
{
"mcpServers": {
"weather": {
"command": "/path/to/.venv/bin/python",
"args": ["/path/to/server.py"]
}
}
}
Secure remote servers with OAuth 2.1
The spec's authorization section applies to HTTP transports; stdio servers should take credentials from the environment instead. A protected MCP server acts as an OAuth 2.1 resource server. It must validate every access token, confirm the token was issued for it as the audience (RFC 8707), return 401 for invalid or expired tokens, and never pass client tokens through to downstream APIs.
from mcp.server import MCPServer
from mcp.server.auth.settings import AuthSettings
mcp = MCPServer(
"orders",
token_verifier=MyTokenVerifier(), # your JWT or introspection check
auth=AuthSettings(
issuer_url="https://auth.example.com",
resource_server_url="https://mcp.example.com",
required_scopes=["orders:read"],
),
)
Scope tools to least privilege: a read-only integration should never hold a token that can issue refunds.
Guard against MCP-specific attacks
An autonomous model is the caller, so treat every tool argument as untrusted. For the broader picture, see prompt injection defense.
- Tool poisoning: returned data can carry instructions that hijack the agent. Treat tool output as untrusted.
- Confused deputy: your server acts with its own credentials for a possibly malicious user. Authorize every call against the end user's scopes, not just the server's.
- Over-broad tools: a single
run_sql(query)hands the model your whole database. Keep tools narrow. - Destructive actions: for irreversible operations, return a plan and require an explicit
confirm=Truere-call instead of acting immediately.
Going to production
Tag every tool call with a correlation id. Log SERVER_VERSION and a hash of each tool's schema at startup, so when a host reports weird behavior you know in seconds whether you both see the same tool definition. Renaming a tool or its arguments breaks every host bound to it, so treat the tool list like a public API. Ship remote servers like any other service: containerized, TLS-terminated, health-checked, rate-limited.
Questions people ask
What is the difference between FastMCP and MCPServer?
They are the same high-level server class under two names. Version 2 of the official Python SDK renamed FastMCP to MCPServer, importable from mcp.server, and the old mcp.server.fastmcp path now fails with ModuleNotFoundError. The decorators (@mcp.tool(), @mcp.resource(), @mcp.prompt()) work the same way, but transport settings such as host and port moved from the constructor to run().
Should my MCP server use stdio or Streamable HTTP?
Use stdio for local servers that a desktop host or IDE launches as a subprocess: there is no network surface and no auth to build. Use Streamable HTTP when several remote clients share one server, or it sits behind a load balancer. The spec's OAuth 2.1 authorization applies to HTTP transports, so adopting HTTP means running token validation from day one.
How do I test an MCP server without an LLM?
Run uv run mcp dev server.py, or npx @modelcontextprotocol/inspector, to open the MCP Inspector. It connects straight to your server, lists every tool, resource and prompt, and lets you call them with hand-written inputs while showing the raw responses. Fix schema and error-message problems there first, then connect Claude Desktop or Cursor, so model behavior is the only remaining variable.
The call we'd make
Start on stdio with a single tool and a real host. Get the description and validation right before you add a second tool, because a vague description costs more than a missing feature. Move to Streamable HTTP only when you actually need remote access, and add OAuth in the same change, not later. Ship the correlation ids and schema hash on day one; they're cheap now and priceless during an incident.
Sources
Cite this article
Kiril Urbonas (2026). How to Build an MCP Server (Step by Step). DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/how-to-build-an-mcp-server
[How to Build an MCP Server (Step by Step)](https://www.devopsness.com/blog/how-to-build-an-mcp-server) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from AI
Explore more articles in this category
vLLM vs SGLang vs TGI vs TensorRT-LLM: Which LLM Server in 2026
Hugging Face TGI is archived and read-only, so the real 2026 choice is vLLM, SGLang or TensorRT-LLM. A feature table, a launch command for each, and the one we default to.
Monitoring ML Models in Production: Data, Concept and Prediction Drift, With Code
Three kinds of drift, two tests that catch most of it, one Prometheus exporter, and the alert rules that do not page you every Monday morning.
MLOps Tools in 2026: 7 Platforms Compared, and the Stack We'd Pick
MLflow, Kubeflow, Weights & Biases, SageMaker, Vertex AI, ZenML and Metaflow compared on tracking, registry, pipelines, serving, self-hosting and pricing, with a default stack for each team size.
You might have missed
Evergreen posts worth revisiting.