To build an MCP server, install an official SDK (for Python, pip install "mcp[cli]"), write each capability as a typed function with a clear docstring, and run it over stdio for local use or Streamable HTTP for remote use. Test it in MCP Inspector, then register it with a host such as Claude Code, Claude Desktop, VS Code or ChatGPT. A first working server is about 40 lines of Python. Most of the effort goes into choosing a few tools a model can use well and deciding what those tools are allowed to touch.
Two changes in mid-2026 put a lot of tutorials out of date. The current protocol revision, 2026-07-28, removed the initialize handshake and protocol-level sessions, so every request now carries its own protocol version and capabilities. And the Python SDK's 2.0 release renamed FastMCP to MCPServer: code that imports mcp.server.fastmcp fails with ModuleNotFoundError on mcp 2.x. (Tutorials that import from fastmcp use PrefectHQ's FastMCP, a separate project with its own API.) The code below was run against mcp 2.3.0, the current release on PyPI in October 2026.
We're building an MCP server for a property-search platform in Finland that we develop (the client stays anonymous). It isn't finished yet, so what follows is the method and checklist we're working from.
What an MCP server is
MCP (Model Context Protocol) is an open protocol for connecting AI applications to outside tools and data. Anthropic published it in November 2024 and in December 2025 donated it to the Agentic AI Foundation, a fund under the Linux Foundation that Anthropic co-founded with Block and OpenAI.
There are three roles. The host is the AI application the user works in: Claude Desktop, Claude Code, an IDE, ChatGPT. Inside it, a client holds the connection to one server, which is your program. Server and client exchange JSON-RPC 2.0 messages, and a server can offer three kinds of things:
- Tools are functions the model decides to call, such as "search rentals in Tampere".
- Resources are data, addressed by URI, that the application can read and show to the model.
- Prompts are reusable templates the user picks, often surfaced as slash commands.
Many servers offer only tools, and that's a sensible place to start.
People often ask how this relates to function calling. Function calling is how a model asks for a tool to be run. MCP is how the host learns which tools exist and calls them when they live in another process or on another machine. The host reads your server's tool list and hands those definitions to the model through the model's own function-calling interface, so the two work together.
When you don't need to build one
First check whether the vendor already runs a server. GitHub, Notion and Stripe have official remote MCP servers, and the official MCP Registry at registry.modelcontextprotocol.io lists many more. Wrapping a SaaS product yourself when its maker ships a server means maintaining something you'll eventually throw away.
If you own the application and the model calls, and the tools live in the same codebase, plain function calling inside your app is less work. A server earns its keep when the same tools should work from several hosts (your team in Claude Code, customers in ChatGPT, an agent you run yourself) or when another team owns the system you're exposing.
Also skip the idea of mirroring your REST API with one tool per endpoint. Models pick badly from long lists of similar tools, which we come back to below.
Step 1: choose an SDK and a transport
There are official SDKs for TypeScript, Python, C#, Go, Rust and Ruby (all Tier 1 in the project's own ranking), Java (Tier 2), and Swift, PHP and Kotlin (Tier 3). Python and TypeScript have the most examples. If you use TypeScript, note that v2 replaced the single @modelcontextprotocol/sdk package; server code now installs from @modelcontextprotocol/server.
The transport depends on where the server will run.
With stdio, the host starts your server as a subprocess and talks to it over stdin and stdout. Use it for anything that runs on the user's machine. Credentials come from environment variables, and the spec says stdio servers shouldn't use the OAuth flow at all. One rule catches nearly everyone once: nothing except MCP messages may go to stdout. A stray print() corrupts the stream, so log to stderr.
With Streamable HTTP, one endpoint, usually /mcp, accepts POST requests and answers each one with JSON or a short SSE stream scoped to that request. Use it when the server runs somewhere else and many users connect. Since the 2026-07-28 revision there are no protocol sessions, so the server can sit behind an ordinary load balancer without sticky routing. There's a catch while hosts upgrade: a host still on 2025-11-25 or older connects with the old handshake, and the Python SDK opens a session for it unless you start the server with stateless_http=True.
The older HTTP+SSE transport from 2024 is deprecated. Don't start anything new on it.
Step 2: write the server
This is a complete stdio server with one read-only tool. The LISTINGS list is a stand-in: in a real server that line is a database query or an internal API call. It's a toy written for this post; none of it comes from the Finland project.
from typing import Annotated
from pydantic import BaseModel, Field
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
mcp = MCPServer("rentals")
LISTINGS = [ # stand-in for your database or internal API
{"id": "hel-101", "city": "Helsinki", "rooms": 2, "rent_eur": 1150},
{"id": "hel-102", "city": "Helsinki", "rooms": 1, "rent_eur": 890},
{"id": "tre-201", "city": "Tampere", "rooms": 3, "rent_eur": 1240},
]
class Listing(BaseModel):
id: str
city: str
rooms: int
rent_eur: int
@mcp.tool(annotations=ToolAnnotations(read_only_hint=True))
def search_rentals(
city: Annotated[str, Field(description="City name, e.g. 'Helsinki'")],
max_rent_eur: Annotated[int | None, Field(description="Monthly rent ceiling in euros")] = None,
limit: Annotated[int, Field(ge=1, le=20)] = 10,
) -> list[Listing]:
"""Search apartments for rent in one city, cheapest first.
Use when the user asks what is available to rent. Returns at most `limit` rows.
"""
rows = [r for r in LISTINGS if r["city"].lower() == city.lower()]
if not rows:
known = ", ".join(sorted({r["city"] for r in LISTINGS}))
raise ToolError(f"No listings in '{city}'. Cities with listings: {known}.")
if max_rent_eur is not None:
rows = [r for r in rows if r["rent_eur"] <= max_rent_eur]
rows.sort(key=lambda r: r["rent_eur"])
return [Listing(**r) for r in rows[:limit]]
if __name__ == "__main__":
mcp.run() # stdio by defaultSave it as server.py in a virtual environment with mcp[cli] installed (Python 3.10 or newer). A few of those lines do more than they appear to.
The type hints become the tool's inputSchema. Because of Field(ge=1, le=20), a call with limit: 50 is rejected before your function runs, and the model gets the validation message back.
The docstring becomes the tool's description. Together with the name and the parameter schema, it's all the model has to go on when deciding whether to call the tool, so write it for the model.
The list[Listing] return type gives the tool an outputSchema. Results arrive as structuredContent, plus a JSON text copy for older clients.
ToolError produces a normal result with isError: true and your message. The tools spec separates these tool execution errors, which a model can read and act on, from protocol errors. Any other exception reaches the model only as "Error executing tool search_rentals", so raise ToolError for every failure you can foresee.
read_only_hint=True tells hosts the tool changes nothing, which they can use when deciding whether to ask the user first. It's only a hint. The spec tells clients to treat annotations from untrusted servers as untrusted, so permissions still have to be enforced in your code.
Step 3: test it before a host sees it
mcp dev server.py starts the server inside MCP Inspector, a browser UI that lists your tools with their generated schemas and lets you call them by hand. It needs two things installed: Node.js 22.19 or newer, because the Inspector runs through npx, and uv, because mcp dev launches your server with uv run. If you set the project up with pip and don't have uv, start the Inspector yourself with the interpreter from your virtual environment:
npx @modelcontextprotocol/inspector .venv/bin/python server.pyCheck three things in the Inspector: the description makes sense with no other context, a bad argument produces a message the model could act on, and the output is short.
For regression tests, the SDK's client can talk to the server in memory, with no subprocess or port:
import pytest
from mcp import Client
from server import mcp
@pytest.mark.anyio
async def test_unknown_city_is_a_tool_error():
async with Client(mcp) as client:
result = await client.call_tool("search_rentals", {"city": "Oulu"})
assert result.is_error
assert "Helsinki" in result.content[0].textThe anyio marker comes from the pytest plugin that ships with anyio, which the SDK already depends on.
Step 4: connect it to a host
In Claude Code, everything after -- is the command that starts your server. Use the interpreter from the virtual environment that has mcp installed:
claude mcp add rentals -- /absolute/path/to/.venv/bin/python /absolute/path/to/server.py
claude mcp listAdding --scope project writes the entry to .mcp.json so the whole team gets it. Remote servers are added with claude mcp add --transport http <name> <url>.
For Claude Desktop, put the same command under mcpServers in claude_desktop_config.json (on macOS in ~/Library/Application Support/Claude/, on Windows in %APPDATA%\Claude), then quit and reopen the app:
{
"mcpServers": {
"rentals": {
"command": "/absolute/path/to/.venv/bin/python",
"args": ["/absolute/path/to/server.py"]
}
}
}If the server doesn't show up, open mcp-server-rentals.log in ~/Library/Logs/Claude/ (on Windows, %APPDATA%\Claude\logs). That file is your server's stderr, and it usually names the problem: a relative path, the wrong interpreter, a missing package.
ChatGPT and OpenAI's Responses API run in OpenAI's cloud, so they can't start a process on your machine. They connect over HTTP (Streamable HTTP or the older HTTP/SSE transport), or reach a private server through OpenAI's Secure MCP Tunnel without exposing it to the internet. For an HTTP endpoint, change the last line to mcp.run(transport="streamable-http"), which serves http://127.0.0.1:8000/mcp by default. Read the authorization section before that endpoint leaves your laptop.
Designing tools a model picks correctly
The model sees a name, a description and a JSON Schema. Nothing else. Compare these two sketches. With the first, the model has to guess what "search" covers and what q means; the second says what it finds, when to use it and what comes back.
def search(q: str) -> str:
"""Searches the database."""
...
def search_rentals(city: str, max_rent_eur: int | None = None, limit: int = 10) -> list[Listing]:
"""Search apartments for rent in one city, cheapest first.
Use when the user asks what is available to rent. Returns at most `limit` rows.
"""
...The rules we work from:
- Fewer tools, shaped like tasks. "Find rentals under a budget" is one tool even if it touches three tables. Name tools specifically, too: a host that connects several servers can end up with two tools called
search, and the spec leaves the clash for the client to sort out. - Keep results small. Claude Code warns when one tool result passes 10,000 tokens, and above its default limit of 25,000 it saves the result to a file and gives the model only the path. Return IDs and the few fields the task needs, paginate, and offer a separate details tool.
- Write errors as instructions. "No listings in 'Oulu'. Cities with listings: Helsinki, Tampere." lets the model retry correctly. A stack trace doesn't.
- Carry state in arguments. With no sessions in the current spec, a multi-step flow (a basket, a draft, a search the user keeps refining) returns a handle from its first tool and takes it as an argument in the next. Generate handles randomly and check on every call that the handle belongs to the caller.
- Review descriptions like code. They are prompts, and editing one changes model behaviour as much as a code change does. Most of what we wrote about prompt engineering applies to them.
Going remote: Streamable HTTP and authorization
A local stdio server runs with the user's own permissions on the user's own machine. A remote one is a public API driven by a language model, so it needs everything a public API needs, plus a few rules from the MCP authorization spec:
- Your server is an OAuth 2.1 resource server. It publishes Protected Resource Metadata (RFC 9728) naming its authorization server, and answers unauthenticated requests with
401and aWWW-Authenticateheader that points to that metadata. - You don't have to write an authorization server. Point the metadata at an identity provider you already run, provided it supports what the spec requires.
- Accept only tokens issued for your server. Clients send a
resourceparameter (RFC 8707) so tokens are bound to one server, and you check the audience on every request. - Never forward the user's token to a downstream API. The spec forbids this "token passthrough". If your server calls another API, it uses its own credentials for that API.
- Start with narrow scopes and ask for more when a privileged tool is first used (the spec's step-up flow) instead of requesting everything at sign-in.
- For client registration, the 2026-07-28 revision prefers Client ID Metadata Documents and marks Dynamic Client Registration as deprecated, kept for older authorization servers.
- Validate the
Originheader to block DNS rebinding, and bind to 127.0.0.1 when running locally.
Check two Python SDK details before you deploy. DNS rebinding protection switches on by itself only when the server binds to localhost; bind to 0.0.0.0 in a container and it stays off until you pass transport_security=TransportSecuritySettings(...) with your own allowed_hosts and allowed_origins. And for bearer tokens, MCPServer takes a token_verifier plus auth=AuthSettings(issuer_url=..., resource_server_url=...), but it doesn't check the token's audience unless you set validate_token_resource=True or do that check in your verifier. Rate limits, timeouts and audit logs apply as they would to any API; the tools spec says servers must validate inputs, enforce access control, rate-limit calls and sanitize outputs. Our OWASP Top 10 notes cover the general hardening.
Threats that are specific to MCP
Tool poisoning
In April 2025, Invariant Labs showed that instructions hidden in a tool description, which users rarely read and models always do, could make an agent read private files and leak them. In their demo, a harmless-looking add tool got Cursor to send the user's SSH private key and ~/.cursor/mcp.json, which holds credentials for other MCP servers, to the attacker inside a tool argument. A variant they called a "rug pull" changes the description after the user has approved the server. If you build servers, your descriptions are part of your attack surface. If you install other people's servers, pin versions and read what you're installing: a local server runs with your permissions.
Prompt injection through tool results
Whatever a tool returns lands in the model's context, where it can read like an instruction. On a property site, a listing description is text written by whoever posted the listing. Return structured fields where you can, cap free text, and be most careful when one agent has both a tool that reads untrusted content and a tool that can send data out (email, HTTP calls, writes to shared systems).
Actions the user didn't intend
The spec says hosts should keep a human in the loop, and most ask before running a tool. Don't make that your only safeguard. Put destructive operations behind an explicit argument such as confirm: true, make them idempotent where you can, check permissions per user on the server, and log who called which tool with which arguments.
One more point that's easy to miss: everything a tool returns goes to whichever model the host uses, often a provider in another country. Return only the fields the task needs, and mask personal data such as phone numbers, national ID numbers and health details inside the server, before it reaches the model.
Frequently asked questions
Is MCP a replacement for function calling?
No. Hosts turn MCP tools into function-calling definitions for whichever model they use. MCP standardizes the part between the host and your code.
Which apps can use my server?
Anthropic's December 2025 announcement lists ChatGPT, Cursor, Gemini, Microsoft Copilot and VS Code among the products that support MCP, alongside Claude's own apps. Local stdio servers work in desktop apps and IDEs. ChatGPT and OpenAI's API need an HTTP endpoint, or OpenAI's Secure MCP Tunnel for a server you don't want on the public internet.
Python or TypeScript?
Whichever your team and the system you're wrapping already use. Both are Tier 1 SDKs whose v2 releases implement the 2026-07-28 revision. The Python SDK 2.x still speaks the older handshake-based revisions back to 2024-11-05, so older hosts can connect.
Do I need OAuth for a local server?
No. For stdio, the spec says to read credentials from the environment, for example an API key passed with --env in claude mcp add. OAuth is for HTTP servers.
Can one codebase serve both local and remote users?
Yes, the tool code is the same on both transports and only the last line changes. In practice a remote deployment needs authentication and per-user permissions that the local version doesn't, so budget for that code rather than treating it as a flag.
If you're planning an MCP server for your own product and want a second opinion on the tool design or the auth setup, that's part of our data and AI work.
Related Articles
MLOps Guide: What to Set Up First, and What Can Wait
MLOps gets a model into production and keeps it useful there. Here is the order we'd set it up in, with current MLflow and DVC examples, and what changes for LLM features.
Read More: MLOps Guide: What to Set Up First, and What Can WaitComputer Vision Applications: Where It Works and Where It Struggles
Where computer vision works today, from inspection lines to invoices and medical scans, what makes some applications hard, and when a general vision model saves you training your own.
Read More: Computer Vision Applications: Where It Works and Where It StrugglesAI Agent Development: When You Need One and How to Build It
An AI agent is a language model working in a loop with tools. When you need one, the loop in Python, choosing a framework, keeping it safe, and what each run costs.
Read More: AI Agent Development: When You Need One and How to Build It
