# MCP Server Python Boilerplate: Free Tested Starter

> Free MCP server Python boilerplate on the 2.x SDK: two tools, a resource, a prompt and a smoke test over stdio. Run it with uv and connect to Claude Code.

URL: https://www.matthewswong.com/en/toolkit/mcp-server-python-starter/

- Author: Matthews Wong (https://www.matthewswong.com/en/about/)
- Updated: 13 November 2026
- Checked against: mcp 2.3.0 (Python SDK)

> **Key takeaway:** A small MCP server in one Python file that you can run in two commands and reshape into your own. It registers two tools, one resource and one prompt on the 2.x SDK, serves them over stdio, and ships a smoke test that connects as a real client, so you know it works before you point Claude Code at it.

- Type: MCP starter
- Works with: Claude Code, Claude Desktop, Any MCP client, Python 3.10+
- Download: [mcp-server-python-starter.zip](https://www.matthewswong.com/downloads/toolkit/mcp-server-python-starter.zip) (8.2 KB)
- License: Free to use, change and share, at work too.

## The files

Exactly what the download contains. Read it first, then copy or download.

### server.py

```python
"""A minimal MCP server over stdio.

A client such as Claude Code starts this file as a child process and talks
to it over stdin and stdout. stdout carries the protocol, so never print()
here: one stray line corrupts the stream. Log to stderr instead.
"""

import json
import logging
import re
import sys

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger("starter")

mcp = MCPServer("starter", version="0.1.0")

# Replace this with your real data source: a database, an API, a file.
NOTES: dict[str, str] = {
    "welcome": "This note ships with the starter. Replace NOTES with real data.",
}

NOTE_ID = re.compile(r"^[a-z0-9-]{1,40}$")
MAX_NOTE_CHARS = 2000


@mcp.tool()
def search_notes(query: str) -> str:
    """Find notes whose id or text contains the query (case-insensitive).

    Returns matching ids with their text. Use before add_note to avoid
    duplicates.
    """
    needle = query.lower()
    matches = [
        {"id": note_id, "text": text}
        for note_id, text in NOTES.items()
        if needle in f"{note_id} {text}".lower()
    ]
    return json.dumps(matches, indent=2)


@mcp.tool()
def add_note(id: str, text: str) -> str:
    """Store a new note under a short id. Fails if the id is already taken.

    The id is lowercase letters, digits and hyphens, at most 40 characters.
    """
    # ToolError is for a failure you saw coming: the model receives the
    # message and can recover. Any other exception counts as a crash, and
    # the model is told only that the tool failed.
    if not NOTE_ID.match(id):
        raise ToolError("id must match ^[a-z0-9-]{1,40}$")
    if not text or len(text) > MAX_NOTE_CHARS:
        raise ToolError(f"text must be 1 to {MAX_NOTE_CHARS} characters")
    if id in NOTES:
        raise ToolError(f'A note with id "{id}" already exists.')
    NOTES[id] = text
    return f'Saved note "{id}".'


@mcp.resource("notes://index", mime_type="text/plain")
def notes_index() -> str:
    """The id of every stored note, one per line."""
    return "\n".join(NOTES)


@mcp.prompt()
def summarize_notes(topic: str) -> str:
    """Ask for a short summary of every note on one topic."""
    return (
        f'Search the notes for "{topic}" and summarize what they say in five '
        "bullet points. Name the note id behind each point."
    )


if __name__ == "__main__":
    log.info("MCP server ready on stdio")
    mcp.run()
```

### .gitignore

```
.venv/
__pycache__/
.env
```

### .mcp.json.example

```
{
  "mcpServers": {
    "starter": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/absolute/path/to/this/folder",
        "python",
        "server.py"
      ]
    }
  }
}
```

### LICENSE

```
MIT License

Copyright (c) 2026 Matthews Wong

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

### README.md

````markdown
# MCP server starter (Python)

A minimal Model Context Protocol server over stdio: two tools, one resource,
one prompt, and a smoke test that talks to it the way a real client does.

Built on the official `mcp` package, 2.x, where the high-level server class
is `MCPServer` (it was `FastMCP` in 1.x). Needs Python 3.10 or newer and
[uv](https://docs.astral.sh/uv/).

## Run it

```bash
uv sync
uv run python smoke.py    # starts the server, lists its tools, calls one
```

`ok: 2 tools, search and duplicate check passed` means the server works.

## Connect it to Claude Code

Register the server with the absolute path to this folder, because the client
starts the server from its own working directory.

```bash
claude mcp add starter -- uv run --directory /absolute/path/to/this/folder python server.py
claude mcp list
```

To share the server with everyone who clones a repository, copy
`.mcp.json.example` to `.mcp.json` at that repository's root and fix the path.

Then ask Claude: "search my notes for welcome".

## What is where

| File        | What it does                                                 |
| ----------- | ------------------------------------------------------------ |
| `server.py` | The tools, the resource and the prompt, served over stdio    |
| `smoke.py`  | Starts the server as a client would and checks what it finds |

## Make it yours

1. Replace the `NOTES` dict in `server.py` with your real data source.
2. Rename the tools and rewrite their docstrings. The docstring becomes the
   tool description, which is what the model reads to decide whether to call
   it, so say what it returns and when to use it.
3. Type every parameter. The type hints become the input schema.
4. Update `smoke.py` to the new tool names and run it again.

## Rules that save an afternoon

- **Never print to stdout.** stdout carries the protocol. Log to stderr.
- **Raise `ToolError` for failures you expect.** The model receives your
  message and can recover. Any other exception is treated as a crash, and the
  model is told only that the tool failed.
- **Validate every input.** The schema is the only thing between the model's
  guess and your data.
- **Keep secrets in the environment**, never in the code or in `.mcp.json`.

## License

MIT. See `LICENSE`.
````

### pyproject.toml

```toml
[project]
name = "mcp-server-starter"
version = "0.1.0"
description = "A minimal MCP server over stdio: two tools, one resource, one prompt, and a smoke test."
requires-python = ">=3.10"
dependencies = ["mcp>=2.3,<3"]
```

### smoke.py

```python
"""Smoke test: start the server the way a real client does, list what it
offers and call one tool. Exits non-zero when anything is off.

    uv run python smoke.py
"""

import asyncio
import sys

from mcp import Client, StdioServerParameters


async def main() -> None:
    server = StdioServerParameters(command=sys.executable, args=["server.py"])
    async with Client(server) as client:
        tools = await client.list_tools()
        names = sorted(tool.name for tool in tools.tools)
        assert names == ["add_note", "search_notes"], names

        found = await client.call_tool("search_notes", {"query": "welcome"})
        assert not found.is_error
        assert "welcome" in found.content[0].text

        duplicate = await client.call_tool(
            "add_note", {"id": "welcome", "text": "again"}
        )
        assert duplicate.is_error
        assert "already exists" in duplicate.content[0].text

        print(f"ok: {len(names)} tools, search and duplicate check passed")


if __name__ == "__main__":
    asyncio.run(main())
```

## Use it when

- You want Claude to reach your own data or API from Python and need a server that already runs.
- You know FastMCP from the 1.x SDK and want a working example of the 2.x imports.
- You are teaching MCP and need a server short enough to read in one sitting.

## From download to working

1. **Install and run the smoke test.** Unzip, then run uv sync and uv run python smoke.py. The script starts the server as a child process, lists its tools, calls one and checks that a duplicate id is refused. A line starting with ok means the server works on your machine.
2. **Register it with Claude Code.** Run claude mcp add starter -- uv run --directory followed by the absolute path to the folder, then python server.py. Use the absolute path because the client starts the server from its own working directory. claude mcp list shows whether it connected.
3. **Call a tool from a conversation.** Ask Claude to search your notes for welcome. Claude calls search_notes and reads the JSON the tool returns.
4. **Replace the sample data.** Swap the NOTES dict in server.py for your database or API, rename the tools, rewrite their docstrings, and update smoke.py to match. Run the smoke test after every change.
5. **Share it through a repository.** Copy .mcp.json.example to .mcp.json at the root of a repository and fix the path. Everyone who clones the repository is then asked to approve the same server.

## Why it is written this way

- **One file, on the 2.x imports.** server.py imports MCPServer from mcp.server.mcpserver, the 2.x name for the class that 1.x called FastMCP. Tools, the resource and the prompt are plain functions under a decorator, and mcp.run() serves them over stdio by default.
- **The docstring and the type hints are the contract.** The docstring becomes the tool description, which is what the model reads to decide whether to call it. The type hints become the input schema. So each docstring says what the tool returns and when to use it.
- **Expected failures raise ToolError.** add_note raises ToolError for a bad id, an empty text or a duplicate. The client receives an error result with that message, so the model sees why the call failed and can choose another id. Any other exception counts as a crash, and the model is told only that the tool failed.
- **Logging goes to stderr.** stdout carries the protocol, so the starter configures logging to write to stderr and never calls print. One stray line on stdout corrupts the stream.
- **A smoke test that acts like a client.** smoke.py uses Client and StdioServerParameters from the same mcp package to start server.py over stdio, so it exercises the path a real client takes. It is the fastest way to tell a broken server from a broken client config.

## What goes wrong

- Anything printed to stdout breaks the connection, because stdout carries the protocol. Log to stderr, in tools too.
- This starter targets mcp 2.x. Examples that import FastMCP from mcp.server.fastmcp are written for 1.x, and that import raises ModuleNotFoundError on 2.x.
- The notes live in memory and vanish when the process exits. That is deliberate for a starter; connect real storage before you rely on it.
- It has no authentication, which is fine for a local stdio process. Do not expose it over a network as it is.

## FAQ

### What is the difference between FastMCP and MCPServer in the Python SDK?

They are the same high-level server class under two names. In mcp 1.x it was FastMCP, imported from mcp.server.fastmcp. In 2.x it is MCPServer, imported from mcp.server.mcpserver, and the old import path raises ModuleNotFoundError with a pointer to the migration guide.

### Do I need an API key or an account to run it?

No. The server and its smoke test run locally with Python 3.10 or newer and uv, with no model in the loop. You only need Claude Code or another MCP client when you want a model to call the tools.

### Why raise ToolError instead of a normal Python exception?

ToolError turns into an error result whose message the model can read, so it can correct the arguments and try again. Any other exception is treated as a crash, and the model is told only that the tool failed. The MCP specification draws the same line: tool execution errors carry feedback the model can act on.

### Can I use it as the base for a production server?

As a base, yes: the structure, the typed inputs and the error handling carry over. Before production you still need real storage, authentication if it leaves your machine, and tools scoped to the least access the job needs.

## Learn what this file packages

- Free lesson: [What Is an MCP Server? How One Tool Call Travels](https://www.matthewswong.com/en/learn/ai-agents-mcp/what-is-mcp-how-a-tool-call-travels/)
- Free lesson: [MCP Server Least Privilege: Read-Only Mode and Toolsets](https://www.matthewswong.com/en/learn/ai-agents-mcp/scope-an-mcp-server-read-only-toolsets/)
- Free lesson: [Add an MCP Server to Claude Code: Scopes and Permissions](https://www.matthewswong.com/en/learn/claude-code-tips/add-mcp-server-claude-code/)
- [Building an MCP Server from Scratch: A Practical Developer Guide](https://www.matthewswong.com/en/blog/mcp-server-development-guide/)
- [MCP Primitives: Tools, Resources, and Prompts](https://www.matthewswong.com/en/blog/mcp-tools-resources-prompts-primitives/)
- [MCP Transports: stdio vs Streamable HTTP](https://www.matthewswong.com/en/blog/mcp-transports-stdio-vs-http/)
- [MCP Server Security Checklist for Developers](https://www.matthewswong.com/en/blog/mcp-server-security-checklist/)

## Sources

- [MCP Python SDK: migration guide, v1 to v2](https://py.sdk.modelcontextprotocol.io/v2/migration/)
- [Model Context Protocol specification 2026-07-28: tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)
- [Claude Code docs: connect Claude Code to tools via MCP](https://code.claude.com/docs/en/mcp)

[All toolkit items](https://www.matthewswong.com/en/toolkit/)

---

- HTML version: https://www.matthewswong.com/en/toolkit/mcp-server-python-starter/
- Bahasa Indonesia: https://www.matthewswong.com/id/toolkit/mcp-server-python-starter/
- Site index for agents: https://www.matthewswong.com/llms.txt
- Sitemap: https://www.matthewswong.com/sitemap.xml
- API description (OpenAPI): https://www.matthewswong.com/openapi.json
