How to Build Your First MCP Server in Python (and Test It Without an AI App)

Write a small MCP server in Python with two tools, test it without any AI app, inspect it with MCP Inspector and connect it to your editor or assistant.

Reviewed by Mindloop Editorial on . Every link in the Sources section at the end was re-checked that day.

Graphic of a small server box connected to a chat bubble and a code editor, for a guide to building an MCP server in Python

Most Model Context Protocol (MCP) guides show you how to install a server someone else wrote. This one shows you how to build your own MCP server in Python: a small server with two tools that any MCP-capable AI app can call. You’ll build it, test it without any AI app, inspect it with the official MCP Inspector, and then connect it to an editor or assistant.

Key takeaways

  • The official MCP Python SDK 2.x renamed the server class to MCPServer, so many older tutorials no longer run as written.
  • Decorating a function with @mcp.tool() makes it a tool; its name, description and input schema come from your code.
  • Test the server in memory with the SDK’s Client class, then over stdio with the official MCP Inspector.
  • Connect it to Cursor, VS Code or Claude Desktop by giving the app a uv launch command with an absolute path.

As of 15 November 2026 the official Python SDK is at version 2.3.0 (released 2 October 2026) and MCP Inspector is at 2.15.0 (released 12 November 2026). SDK 2.x renamed the main server class, so many older tutorials no longer run as written. The project, test and Inspector commands below were run against those versions.

What an MCP server is

MCP is an open-source standard for connecting AI applications to external systems. Three terms from the SDK docs are enough to follow along:

  • A host is the AI app you talk to, such as a chat assistant or a code editor.
  • A client lives inside the host and speaks MCP.
  • A server is what you build. It can offer tools (functions the model calls), resources (data the app loads) and prompts (templates the user picks).

This guide sticks to tools. The two you’ll write, a word counter and a date calculator, do exact work that is better handled by code than by a model’s estimate.

Video: The Model Context Protocol (MCP) (Anthropic)

What you need

  • uv, the Python project manager used in the official MCP tutorial. It downloads Python for you if a suitable version is missing. The SDK needs Python 3.10 or newer.
  • Node.js, only for the Inspector in Step 4. Inspector 2.15.0 requires Node ^22.23.4 || ^24.22.1 || >=26.12.1.
  • An MCP-capable app for Step 5 (optional).

Install uv on macOS or Linux:

Terminal
curl -LsSf https://astral.sh/uv/install.sh | sh

On Windows, in PowerShell:

Code
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Restart your terminal afterwards so the uv command is found.

By the numbers

2.3.0Python SDK version used

2.15.0MCP Inspector version used

3.10minimum Python version

Step 1: Create the project

Terminal
uv init --bare handy-tools
cd handy-tools
uv add "mcp[cli]"

--bare creates only a pyproject.toml, which is all this project needs. The cli extra adds the mcp command-line tool. Confirm the install:

Terminal
uv run mcp version

Expected output:

Code
MCP version 2.3.0

Step 2: Write the server

Create a file named server.py in the project folder:

Code
from datetime import date

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

mcp = MCPServer("Handy Tools")


@mcp.tool()
def count_words(text: str) -> int:
    """Count the words in a piece of text."""
    return len(text.split())


@mcp.tool()
def days_between(start: str, end: str) -> int:
    """Count the days from one date to another. Dates use YYYY-MM-DD format."""
    try:
        first = date.fromisoformat(start)
        second = date.fromisoformat(end)
    except ValueError:
        raise ToolError("Dates must look like 2026-11-15 (YYYY-MM-DD).")
    return (second - first).days


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

What each part does:

  • MCPServer("Handy Tools") creates the server. In SDK 2.x you import it from mcp.server.
  • @mcp.tool() turns a function into a tool. The SDK reads the tool’s name from the function name, its description from the docstring, and its input schema from the type hints. You write no JSON.
  • ToolError sends a readable message back to the model, so it can fix its arguments and try again.
  • mcp.run() with no arguments starts the server over stdio: the host launches your file as a subprocess and talks to it through stdin and stdout.
Diagram listing the parts of a minimal Python MCP server file and what each one does

Step 3: Test it from Python

The SDK includes a Client class that can connect to your server object in memory, with no subprocess, no port and no AI. Create check.py next to server.py:

Code
import asyncio

from mcp import Client

from server import mcp


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

        result = await client.call_tool("count_words", {"text": "the quick brown fox"})
        print(result.structured_content)

        result = await client.call_tool("days_between", {"start": "2026-11-15", "end": "2027-01-01"})
        print(result.structured_content)

        result = await client.call_tool("days_between", {"start": "tomorrow", "end": "2027-01-01"})
        print(result.is_error, result.content[0].text)


asyncio.run(main())

Run it:

Terminal
uv run check.py

Expected output:

Code
['count_words', 'days_between']
{'result': 4}
{'result': 47}
True Error executing tool days_between: Dates must look like 2026-11-15 (YYYY-MM-DD).

You’ll also see an INFO log line about the failed call, which is the server logging the ToolError. Notice that the bad date didn’t raise an exception in the client: a failed tool call comes back as a normal result with is_error set to True.

Did you know?

A failed tool call does not raise an exception in the client. It comes back as a normal result with is_error set to True, carrying the ToolError message.

Step 4: Inspect it with MCP Inspector

MCP Inspector is the MCP project’s own testing tool. Its CLI mode launches your server the way a real host would and prints what comes back. From the project folder:

Terminal
npx @modelcontextprotocol/inspector --cli uv run server.py --method tools/list

The first run asks permission to download the package. You should then see JSON that lists count_words and days_between, each with the input schema the SDK generated from your type hints.

Now call a tool:

Terminal
npx @modelcontextprotocol/inspector --cli uv run server.py \
  --method tools/call --tool-name days_between \
  --tool-args-json '{"start":"2026-11-15","end":"2027-01-01"}'

Expected output:

Code
{
  "content": [
    {
      "type": "text",
      "text": "47"
    }
  ],
  "structuredContent": {
    "result": 47
  },
  "isError": false
}

The SDK can also start the Inspector’s web interface:

Terminal
uv run mcp dev server.py

It prints a local address such as http://127.0.0.1:6274?MCP_INSPECTOR_API_TOKEN=... and opens it in your browser. On the Servers screen, turn on the connect switch next to your server, open Tools, pick count_words, type some text and click Execute Tool. Press Ctrl+C in the terminal when you’re done.

Step 5: Connect it to an AI app

Connecting to a host means telling it the command that starts your server. For this project that command is:

Terminal
uv --directory /ABSOLUTE/PATH/TO/handy-tools run server.py

Run pwd inside the project folder to get the real path. Try the command yourself first. Nothing prints and it doesn’t return, which is correct: the server is waiting for a host to speak. Press Ctrl+C to stop it.

Many apps accept the same JSON block for that command:

Code
{
  "mcpServers": {
    "handy-tools": {
      "command": "uv",
      "args": ["--directory", "/ABSOLUTE/PATH/TO/handy-tools", "run", "server.py"]
    }
  }
}

Where it goes depends on the app:

  • Cursor: save it as .cursor/mcp.json in a project, or ~/.cursor/mcp.json to use it everywhere, per Cursor’s MCP docs. Those docs also list a "type": "stdio" field for local servers, though their own examples omit it.
  • VS Code: run MCP: Add Server from the Command Palette, choose Command (stdio) and enter the launch command, per the VS Code docs.
  • Claude Desktop: run uv run mcp install server.py, which writes the entry for you. It’s the only host the SDK configures automatically.

Restart the app, then ask something like:

Code
Use the days_between tool: how many days from 2026-11-15 to 2027-01-01?

The answer should be 47. Keep in mind that tools run on your computer with your account’s permissions, so only expose actions you’re happy for a model to trigger. For an example of a larger ready-made server, see our guide to Chrome DevTools MCP.

Flow diagram of building, testing, inspecting and connecting a Python MCP server to an AI app

Common errors and fixes

  • ModuleNotFoundError: No module named 'mcp.server.fastmcp': the code was written for SDK 1.x. In 2.x the class is MCPServer, imported with from mcp.server import MCPServer. Update the import, or pin mcp<2 to keep running old code.
  • TypeError: The @tool decorator was used incorrectly: you wrote @mcp.tool without parentheses. Use @mcp.tool().
  • The app doesn’t show your server: the usual cause is a relative path. Use the absolute path to the project, and if the app can’t find uv, replace uv with the full path from which uv (macOS and Linux) or where uv (Windows). Fully quit and reopen the app after editing its config.
  • The connection drops or the tool list is empty: over stdio, stdout carries the protocol itself. A stray print() can corrupt it. Use Python’s logging module, which writes to stderr.
  • npm warn deprecated @modelcontextprotocol/inspector@0.15.0: v1 is deprecated, or a tool call fails with Field required: your Node.js is too old for Inspector 2.x. In a test on Node 20, npx quietly installed the old 0.15.0 release, which ignores --tool-args-json. Check node --version and upgrade to a supported release.
  • npx not found when running mcp dev: the Inspector is a Node.js app. Install Node.js first.
  • Error executing tool <name> with no message: the tool crashed with an exception you didn’t plan for. The traceback is in the server’s log, not in the result.

Did you know?

Over stdio, stdout carries the protocol itself, so a stray print() in your server can corrupt the connection. Python’s logging module writes to stderr instead.

Wrap-up

A working MCP server is a Python file with a few decorated functions. Write the tool, check it in memory with Client(mcp), confirm it over stdio with the Inspector, then hand any host the launch command. From here you can add resources and prompts, or serve the same code over HTTP with mcp.run(transport="streamable-http"). If your agent needs written instructions more than new functions, our guide to agent skills in Claude Code covers that side.

Frequently asked questions

What is the difference between an MCP host, client and server?

The host is the AI app you talk to, such as a chat assistant or code editor. The client lives inside the host and speaks MCP. The server is what you build, and it can offer tools, resources and prompts.

Why do I get No module named mcp.server.fastmcp?

That code was written for SDK 1.x. In 2.x the class is MCPServer, imported with from mcp.server import MCPServer. Update the import, or pin mcp<2 to keep running old code.

Can I test an MCP server without an AI app?

Yes. The SDK’s Client class connects to your server object in memory, with no subprocess, port or AI. MCP Inspector’s CLI mode then launches the server over stdio the way a real host would.

Which Node.js version does MCP Inspector need?

Inspector 2.15.0 requires Node ^22.23.4, ^24.22.1 or >=26.12.1. On older Node, npx may quietly install the old 0.15.0 release, which ignores –tool-args-json.

Quick quiz

In SDK 2.x, which class creates an MCP server?

  • FastMCP
  • ToolError
  • MCPServer

SDK 2.x renamed the main server class to MCPServer, imported from mcp.server.

What can a stray print() do to a stdio MCP server?

  • Corrupt the protocol stream
  • Nothing, output is ignored
  • Restart the server

Over stdio, stdout carries the protocol itself, so extra output can corrupt it.

Where does the SDK get a tool’s input schema?

  • A JSON file you write
  • The function’s type hints
  • The host’s config file

The SDK reads the input schema from the type hints, so you write no JSON.

Sources

Links last checked on 15 November 2026.

Written by Mindloop Editorial

The Mindloop Experience editorial team writes clear, carefully sourced explainers and how-tos on AI and technology, software and the business of tech, for anyone who likes to know how things actually work.

Meet the editorial team

Responses

Write a response

More from Mindloop Experience

See all from Mindloop Experience

You can clap up to 50 times.