All writing

The Complete Guide to Model Context Protocol (MCP) in Python

By Bronson Dunbar ·

Updated November 2026: rewritten for version 2 of the official Python SDK, where FastMCP became MCPServer. The first version of this post imported classes that don't exist and used a JavaScript client package that was never published. Every example below has been run.

The Model Context Protocol (MCP) is an open standard for giving AI applications access to tools and data. You write an MCP server once, and any MCP-capable app (Claude Desktop, Claude Code, Cursor, VS Code and many more) can use it. If you're new to the idea, start with MCP explained.

In this guide we'll build a small notes server in Python, call it from a Python client, test it with the MCP Inspector, plug it into Claude Desktop and Claude Code, and finally hand its tools to Claude from our own code.

How the pieces fit

  • Server: exposes capabilities. Ours will be a Python process.
  • Client: connects to one server and speaks the protocol. Apps like Claude Desktop create one client per server.
  • Transport: how they talk. stdio runs the server as a child process and is what you'll use locally. Streamable HTTP is for remote servers.

A server can offer three kinds of capability:

Capability What it is Who decides to use it
Tools Functions the model can call, like "search notes" The model
Resources Data the app can read, addressed by URI The app or user
Prompts Reusable prompt templates The user

Set up the project

You need Python 3.10 or newer.

mkdir mcp-notes && cd mcp-notes
python -m venv .venv
source .venv/bin/activate
pip install "mcp>=2"

If you're following an older tutorial that does from mcp.server.fastmcp import FastMCP, it was written for version 1. In version 2 that import fails with a message pointing you to MCPServer. The migration guide covers the other changes.

Build the server

Create notes_server.py. Type hints and docstrings do most of the work: the SDK builds each tool's schema from the function signature and uses the docstring as its description.

from mcp.server.mcpserver import MCPServer

mcp = MCPServer("notes")

# A real server would use a database. A dict keeps the example focused on MCP.
notes: dict[int, str] = {}


@mcp.tool()
def add_note(text: str) -> str:
    """Save a note and return its ID."""
    note_id = len(notes) + 1
    notes[note_id] = text
    return f"Saved note {note_id}"


@mcp.tool()
def search_notes(query: str) -> list[str]:
    """Return every note that contains the query (case-insensitive)."""
    return [text for text in notes.values() if query.lower() in text.lower()]


@mcp.resource("notes://{note_id}")
def get_note(note_id: int) -> str:
    """Read a single note by ID."""
    return notes.get(note_id, "No note with that ID.")


@mcp.prompt()
def summarise_notes() -> str:
    """Ask the model to summarise everything saved so far."""
    joined = "\n".join(f"- {text}" for text in notes.values()) or "(no notes yet)"
    return f"Summarise these notes in three bullet points:\n\n{joined}"


if __name__ == "__main__":
    mcp.run()  # stdio by default
  • @mcp.tool() registers a tool. Because search_notes returns list[str], clients also receive the result as structured data.
  • @mcp.resource("notes://{note_id}") registers a resource template. The {note_id} placeholder becomes an argument, converted to int from the type hint.
  • @mcp.prompt() registers a prompt template that clients can offer to users.
  • Never print() in a stdio server. stdout carries the protocol, so a stray print corrupts it. Log to stderr instead.

Write a client

Create client.py. Client launches the server as a subprocess and closes it when the async with block ends:

import asyncio
import sys

from mcp import Client, StdioServerParameters

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


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

        await client.call_tool("add_note", {"text": "Ship the MCP post on Friday"})
        await client.call_tool("add_note", {"text": "Record the Friday devlog video"})

        result = await client.call_tool("search_notes", {"query": "friday"})
        print("Search:", result.structured_content)

        note = await client.read_resource("notes://1")
        print("Resource:", note.contents[0].text)

        prompt = await client.get_prompt("summarise_notes")
        print("Prompt:", prompt.messages[0].content.text)


asyncio.run(main())
python client.py
Tools: ['add_note', 'search_notes']
Search: {'result': ['Ship the MCP post on Friday', 'Record the Friday devlog video']}
Resource: Ship the MCP post on Friday
Prompt: Summarise these notes in three bullet points: ...

Client also accepts a URL for remote servers over Streamable HTTP, and in tests you can pass the MCPServer instance itself to connect in-process without starting a subprocess.

Test with the MCP Inspector

The MCP Inspector is a browser UI for poking at a server by hand. It needs Node.js:

npx @modelcontextprotocol/inspector python notes_server.py

Use it from Claude Desktop and Claude Code

To add the server to Claude Desktop, open Settings → Developer → Edit Config and add it to claude_desktop_config.json. Use absolute paths, and point at the Python inside your virtual environment so the mcp package is available:

{
  "mcpServers": {
    "notes": {
      "command": "/absolute/path/to/mcp-notes/.venv/bin/python",
      "args": ["/absolute/path/to/mcp-notes/notes_server.py"]
    }
  }
}

In Claude Code it's one command:

claude mcp add notes -- /absolute/path/to/mcp-notes/.venv/bin/python /absolute/path/to/mcp-notes/notes_server.py

Give the tools to Claude in your own app

MCP tool definitions map almost one-to-one onto the Claude API's tool format, so connecting them takes a short loop: send the tools, run whatever Claude asks for through MCP, send the results back, and repeat until Claude answers.

pip install anthropic
export ANTHROPIC_API_KEY="sk-ant-..."

Create agent.py:

import asyncio
import json
import sys

import anthropic
from mcp import Client, StdioServerParameters

claude = anthropic.AsyncAnthropic()
server = StdioServerParameters(command=sys.executable, args=["notes_server.py"])


async def main() -> None:
    async with Client(server) as mcp:
        # MCP tool definitions map almost one-to-one onto Claude's tool format.
        listed = await mcp.list_tools()
        tools = [
            {"name": t.name, "description": t.description or "", "input_schema": t.input_schema}
            for t in listed.tools
        ]

        await mcp.call_tool("add_note", {"text": "Ship the MCP post on Friday"})

        messages = [{"role": "user", "content": "What have I got planned for Friday? Check my notes."}]

        # Keep going until Claude stops asking for tools.
        while True:
            response = await claude.messages.create(
                model="claude-opus-5-5",
                max_tokens=4096,
                tools=tools,
                messages=messages,
            )
            messages.append({"role": "assistant", "content": response.content})

            if response.stop_reason != "tool_use":
                print("".join(b.text for b in response.content if b.type == "text"))
                break

            # Run every tool Claude asked for and send all the results back in one message.
            results = []
            for block in response.content:
                if block.type != "tool_use":
                    continue
                result = await mcp.call_tool(block.name, block.input)
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": json.dumps([c.model_dump() for c in result.content]),
                    "is_error": result.is_error,
                })
            messages.append({"role": "user", "content": results})


asyncio.run(main())

Two rules to keep: return all the tool results from one turn in a single user message, and pass failures back with is_error rather than dropping them, so Claude can recover. If the Claude API is new to you, read getting started with the Claude API in Python first.

Going further

  • Remote servers. mcp.run(transport="streamable-http") serves the same server over HTTP. Remote servers need authentication, and the spec uses OAuth 2.1 for that.
  • Security. Tools run with your server's permissions. Validate inputs, keep destructive tools behind user approval with annotations like destructiveHint, and remember that text from tools (web pages, emails, files) can contain prompt injection.
  • Reuse before you build. Check the official MCP Registry and the reference servers first.

Resources