entry
No. 9
date

updated
filed under
mcp, tool use, agents
checked against
11 sources

Build an MCP Server in Python: A Working 60-Line Example

To build an MCP server in Python, install the official mcp package, create an MCPServer, and turn plain functions into tools with the @mcp.tool() decorator. The SDK reads each function's name, docstring and type hints and turns them into the tool's name, description and JSON Schema, so you write no protocol code. Call mcp.run() and any MCP host, such as Claude Code or Claude Desktop, can launch the file and call your tools.

This post builds a complete server in about 60 lines: two tools that let an agent search and read a folder of Markdown docs, plus a resource and a prompt. Every snippet here was run against version 2.3.0 of the SDK, the latest release on PyPI at the time of writing.

What an MCP server is

The Model Context Protocol (MCP) is a standard way for an AI application to reach outside data and actions. The application (the host) runs an MCP client, and your server answers it. A server can offer three kinds of things, and the specification separates them by who decides to use them:

  • Tools are model-controlled: functions the model can call to take an action or fetch information.
  • Resources are application-controlled: data, such as file contents, that the client attaches as context.
  • Prompts are user-controlled: templates the user picks, often shown as slash commands.

Most agent work happens through tools, so this post spends most of its time there. If you have built tools for a model API directly, the ideas carry over. The difference is that one MCP server works with every host that speaks the protocol, instead of being wired into one app.

Version notes before you copy older tutorials

Two changes mean many MCP tutorials no longer run as written.

First, the protocol itself. The current specification, revision 2026-07-28, removed the initialize handshake. Every request now carries its protocol version and client capabilities in _meta, and servers must implement a new server/discover method. The same revision deprecated the Roots, Sampling and Logging features and suggests logging to stderr or using OpenTelemetry instead.

Second, the Python SDK. Version 2 implements the 2026-07-28 revision and still serves older 2025-era clients. It also renamed FastMCP to MCPServer, imported from mcp.server, and removed the old mcp.server.fastmcp import path rather than deprecating it. If a tutorial starts with from mcp.server.fastmcp import FastMCP, it was written for version 1. The SDK's What's new page suggests pinning mcp>=1.28,<2 if you need to stay on 1.x for now.

The SDK needs Python 3.10 or later. Install it with the CLI extra, which adds the mcp command used below:

pip install "mcp[cli]"

The server

The example gives an agent read access to a folder of Markdown files, the kind of internal docs an agent needs before it answers a policy question. Save this as server.py, next to a docs/ folder with a few .md files in it:

"""A small MCP server that lets an agent search and read a folder of Markdown docs."""
import os
from pathlib import Path
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

DOCS_DIR = Path(os.environ.get("DOCS_DIR", Path(__file__).parent / "docs")).resolve()
mcp = MCPServer("Docs", instructions="Search the team docs before answering policy questions.")


class Hit(BaseModel):
    name: str
    line: str


def _doc_path(name: str) -> Path:
    path = (DOCS_DIR / name).resolve()
    if path.parent != DOCS_DIR or path.suffix != ".md" or not path.is_file():
        raise ToolError(f"No doc named {name!r}. Call search_docs to find valid names.")
    return path


@mcp.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def search_docs(
    query: Annotated[str, Field(description="Word or phrase to look for, case-insensitive.")],
    limit: Annotated[int, Field(ge=1, le=20)] = 5,
) -> list[Hit]:
    """Find lines in the docs that contain the query. Returns doc names to pass to read_doc."""
    hits = []
    for path in sorted(DOCS_DIR.glob("*.md")):
        for line in path.read_text(encoding="utf-8").splitlines():
            if query.lower() in line.lower():
                hits.append(Hit(name=path.name, line=line.strip()))
    return hits[:limit]


@mcp.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def read_doc(name: Annotated[str, Field(description="A file name from search_docs, e.g. refunds.md")]) -> str:
    """Return the full text of one doc."""
    return _doc_path(name).read_text(encoding="utf-8")


@mcp.resource("docs://{name}")
def doc_resource(name: str) -> str:
    """One doc, for clients that let the user attach it as context."""
    return _doc_path(name).read_text(encoding="utf-8")


@mcp.prompt()
def answer_from_docs(question: str) -> str:
    """Ask a question that must be answered from the docs only."""
    return f"Use search_docs and read_doc to answer: {question}\nCite the doc names you used."


if __name__ == "__main__":
    mcp.run()

Here is what each part does.

The tool schema comes from the type hints. For search_docs, the SDK generates an input schema in which query is a required string with the description from Field, and limit is an optional integer with a default of 5, a minimum of 1 and a maximum of 20. The docstring becomes the tool description. Write it for the model: the line "Returns doc names to pass to read_doc" tells it how the two tools fit together.

Bad arguments never reach your function. The SDK checks arguments against the type hints and constraints before it calls the tool. Calling search_docs with limit set to 99 returns an error result that includes Input should be less than or equal to 20. Sending "two" for limit returns Input should be a valid integer. The model reads that message and can retry with a valid value.

Return types become structured output. Because search_docs returns list[Hit], the SDK publishes an output schema and sends the hits as structured_content, wrapped in a result key. The model still gets the results as text in content.

ToolError is for mistakes the model can fix. When read_doc gets a name that isn't a doc, it raises ToolError with a message that says what to do next. The call comes back as a result with is_error set to true, and the model sees the message. The SDK docs also cover the other cases. Raise MCPError for protocol-level failures the model can't fix; those fail the whole request as a JSON-RPC error. Any other exception is treated as a crash: the client gets a generic Error executing tool message, and the exception text stays in your server's logs. Why your agent calls the wrong tool has more on writing errors that point the model at the fix.

_doc_path is the security boundary. The MCP specification says servers must validate all tool inputs, implement access controls, rate limit tool invocations and sanitize tool outputs. Here, resolving the path and checking that its parent is the docs folder stops a call like read_doc("../server.py") from reading anything outside it.

Annotations are hints, not guarantees. read_only_hint=True tells the client that the tool changes nothing, and open_world_hint=False says it works on a closed set of data rather than the open web. Clients can use these to decide when to ask the user for confirmation; human-in-the-loop approval for agents covers how to build that step. The specification says clients must treat annotations as untrusted unless they come from trusted servers, so they are no substitute for the checks in your code.

The __main__ guard matters. mcp.run() starts a stdio server by default. The mcp command-line tool and your tests import the file, and the guard keeps an import from starting a server.

Keep stdout clean

On the stdio transport, the host launches your server as a subprocess and exchanges newline-delimited JSON-RPC messages over stdin and stdout. The specification says the server must not write anything to stdout that is not a valid MCP message, and that it may write logs to stderr.

The SDK helps: output flushed to stdout while the server is running is redirected to stderr. But output written before serving starts, or a buffered print() that is flushed at exit, can still reach the wire and break the connection. Use the logging module for diagnostics, as the SDK docs recommend.

Test it without a host

The SDK's Client can connect to the server object directly, with no subprocess, port or transport, which makes tests fast. With pytest installed, save this as test_server.py next to server.py:

import pytest

from mcp import Client

from server import mcp


@pytest.mark.anyio
async def test_search_finds_refund_policy() -> None:
    async with Client(mcp) as client:
        result = await client.call_tool("search_docs", {"query": "refund"})
        names = [hit["name"] for hit in result.structured_content["result"]]
        assert names == ["refunds.md", "refunds.md"]


@pytest.mark.anyio
async def test_read_doc_rejects_paths_outside_docs() -> None:
    async with Client(mcp) as client:
        result = await client.call_tool("read_doc", {"name": "../server.py"})
        assert result.is_error

With a docs/refunds.md whose heading and body both mention refunds, both tests pass. The anyio marker comes from the pytest plugin in anyio, which the SDK already depends on.

To test the real stdio path, point Client at a command instead. It launches the server as a subprocess, the way a host would:

import asyncio
import sys

from mcp import Client, StdioServerParameters

server = StdioServerParameters(command=sys.executable, args=["server.py"])


async def main() -> None:
    async with Client(server) as client:
        tools = await client.list_tools()
        print([t.name for t in tools.tools])

        result = await client.call_tool("search_docs", {"query": "return"})
        print(result.structured_content)


asyncio.run(main())

With two docs, one saying refunds are issued within 14 days of a return and one saying returns use a prepaid label, it prints:

['search_docs', 'read_doc']
{'result': [{'name': 'refunds.md', 'line': 'Refunds are issued within 14 days of a return.'}, {'name': 'shipping.md', 'line': 'Orders ship in 2 business days. Returns use the prepaid label.'}]}

For clicking through tools by hand, mcp dev server.py opens the server in the MCP Inspector. The Inspector is a Node.js app, so npx must be on your PATH.

Connect it to a real host

Hosts start your server from their own working directory with a minimal PATH, so use absolute paths. That is also why DOCS_DIR defaults to a folder next to server.py rather than one relative to the current directory. The SDK docs give one launch command that works for any host:

uv run --with "mcp[cli]" mcp run /absolute/path/to/server.py

Claude Code: register it with claude mcp add, then run /mcp in a session to check that it connected:

claude mcp add docs -- uv run --with "mcp[cli]" mcp run /absolute/path/to/server.py

Claude Desktop: mcp install server.py writes the entry into Claude Desktop's config file for you. Add -v DOCS_DIR=/absolute/path/to/docs to store an environment variable in the entry. Fully quit and reopen the app after any change. If the server doesn't show up, Claude Desktop writes each server's stderr to a log file named mcp-server-<NAME>.log, in ~/Library/Logs/Claude on macOS. For spawn npx ENOENT and the other common launch errors, see MCP server not showing up in Claude Desktop.

Before you edit any config, run the launch command yourself. A working stdio server prints nothing and waits. A traceback or an immediate exit is the real error.

Serve it over HTTP

stdio is for a server on the same machine as the host. To share a server, run it over Streamable HTTP instead:

if __name__ == "__main__":
    mcp.run(transport="streamable-http", port=3001)

Clients then connect to http://127.0.0.1:3001/mcp, and Client("http://127.0.0.1:3001/mcp") works the same way as the stdio client above. The defaults are host 127.0.0.1, port 8000 and path /mcp, so the server is only reachable from your machine until you change host. Before you expose it further, read the SDK's deployment and authorization docs; the defaults are not a security setup. Older tutorials use the SSE transport, which the specification has reclassified as deprecated in favor of Streamable HTTP. Over HTTP there is also no session to hold state between calls; if a tool needs to remember something, return a handle from a create tool, as in stateless MCP servers with explicit handles.

Design tools for the model, not the API

An MCP server is a set of tool definitions, and the model only knows your tools through their names, descriptions, schemas and results. The same rules apply as for any agent tool:

  • Build fewer tools around tasks rather than one per endpoint.
  • Keep results small. A tool that returns a whole database fills the model's context; see context engineering for agents for why that hurts.
  • Return errors that say how to fix the call, so the agent doesn't repeat the same call in a loop.
  • Keep tool names unique and in a stable order. The specification recommends deterministic ordering from tools/list, partly so hosts get better prompt cache hits.

Checklist

  • Install mcp 2.x and import MCPServer from mcp.server, not FastMCP.
  • Type-hint every parameter and add Field descriptions and limits.
  • Write each docstring for the model, including how tools fit together.
  • Raise ToolError for mistakes the model can fix, with a next step in the message.
  • Check every path, ID and query against what the tool should be allowed to reach.
  • Send logs to stderr with logging, never print() to stdout.
  • Test with Client(mcp) in pytest, then once over stdio.
  • Use absolute paths in host configs.
  • Keep HTTP servers on 127.0.0.1 until you have read the deployment and auth docs.

FAQ

What is FastMCP in the MCP Python SDK?

In version 1 of the SDK, FastMCP was the high-level server class. Version 2 renamed it to MCPServer, imported from mcp.server, and removed the old import path. Code that imports FastMCP from mcp.server.fastmcp needs version 1.

Should I use stdio or Streamable HTTP?

Use stdio for a server that runs on the same machine as the host; it is the default for mcp.run(). Use Streamable HTTP when other people or remote hosts need to reach the server.

Why does my MCP server disconnect right away?

On stdio, anything written to stdout that is not an MCP message can break the connection, and a stray print() is the usual cause. Also check that the host config uses absolute paths, and run the launch command by hand to see any traceback.

Does the MCP Python SDK validate tool arguments?

Yes, for tools registered with MCPServer. Arguments are checked against the type hints and Field constraints before your function runs, and a failure comes back to the model as an error result it can read and correct.

What MCP protocol version does the Python SDK use?

Version 2 of the SDK implements the 2026-07-28 revision of the specification and still serves clients that use 2025-era versions.

Sources

Server not starting? Paste your config into the MCP config checker to find the usual causes.

Next in the notebook

  1. No. 26Stateless MCP Server: Keep State With Explicit Handles

    MCP 2026-07-28 removed sessions and Mcp-Session-Id. Keep state across tool calls with server-minted handles: tested Python code, auth, expiry and errors.

  2. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  3. No. 6Structured Outputs vs Function Calling: Which to Use When

    Structured outputs vs function calling: use tools when the model must act, a JSON schema when you need the answer in a fixed shape, and strict mode for both.