Velamuvi AIAcademy

Lesson 5 of 9 · Building

Build an MCP Server in Python

Build an MCP server in Python with the official SDK: typed tools, a resource template, a prompt, readable errors and testing with the MCP Inspector.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Create an MCP server with the official Python SDK
  • Add tools, a resource template and a prompt with decorators
  • Return errors the model can read, and validate arguments automatically
  • Test a server in memory and with the MCP Inspector

What the SDK does for you

The official Python SDK (the mcp package) turns ordinary Python functions into MCP features. You write a function with type hints and a docstring; the SDK builds the tool definition, validates arguments, handles the protocol and runs the transport. Here is the core idea in miniature:

Try it yourselfPython
import inspect
import json

# A tiny imitation of what MCPServer's @mcp.tool() decorator does for you
class TinyServer:
    TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}

    def __init__(self, name):
        self.name = name
        self.tools = {}

    def tool(self):
        def register(fn):
            params = inspect.signature(fn).parameters
            self.tools[fn.__name__] = {
                "fn": fn,
                "definition": {
                    "name": fn.__name__,
                    "description": inspect.getdoc(fn),
                    "inputSchema": {
                        "type": "object",
                        "properties": {n: {"type": self.TYPES[p.annotation]} for n, p in params.items()},
                        "required": [n for n, p in params.items() if p.default is inspect.Parameter.empty],
                    },
                },
            }
            return fn
        return register

    def handle(self, method, params=None):
        if method == "tools/list":
            return {"tools": [t["definition"] for t in self.tools.values()], "resultType": "complete"}
        if method == "tools/call":
            try:
                value = self.tools[params["name"]]["fn"](**params["arguments"])
                return {"content": [{"type": "text", "text": str(value)}], "isError": False, "resultType": "complete"}
            except Exception as e:
                return {"content": [{"type": "text", "text": f"Error: {e}"}], "isError": True, "resultType": "complete"}

mcp = TinyServer("Converter")

@mcp.tool()
def km_to_miles(km: float) -> float:
    """Convert kilometres to miles."""
    return round(km * 0.621371, 2)

@mcp.tool()
def shout(text: str, times: int = 1) -> str:
    """Repeat text in capitals."""
    return " ".join([text.upper()] * times)

print(json.dumps(mcp.handle("tools/list")["tools"][1]))
print(mcp.handle("tools/call", {"name": "km_to_miles", "arguments": {"km": 42.195}}))
print(mcp.handle("tools/call", {"name": "shout", "arguments": {"text": "hi", "times": 3}}))

The decorator read the function's name, docstring and type hints, and built the definition a client receives from tools/list. times has a default, so it isn't required. The real SDK does the same, plus validation, structured output, resources, prompts and every transport.

The notes server

Install the SDK on your computer (pip install "mcp[cli]", Python 3.10 or newer) and save this as notes_server.py:

"""notes_server.py: an MCP server that lets AI apps search, read and add your notes."""
from pathlib import Path
from typing import Annotated

from pydantic import Field

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

NOTES_DIR = Path(__file__).parent / "notes"
NOTES_DIR.mkdir(exist_ok=True)

mcp = MCPServer("Notes", instructions="Personal notes stored as Markdown files.")


@mcp.tool()
def search_notes(query: Annotated[str, Field(description="Word or phrase to look for, e.g. 'Lisbon'")]) -> list[str]:
    """Search all notes for a word or phrase. Returns the names of matching notes."""
    q = query.lower()
    return sorted(p.stem for p in NOTES_DIR.glob("*.md") if q in p.read_text(encoding="utf-8").lower())


@mcp.tool()
def add_note(
    name: Annotated[str, Field(description="Short name using letters, digits and hyphens, e.g. 'trip-ideas'")],
    text: Annotated[str, Field(description="The note's content in Markdown")],
) -> str:
    """Save a new note. Fails if a note with that name already exists. Returns a confirmation."""
    if not name.replace("-", "").isalnum():
        raise ToolError("Use only letters, digits and hyphens in the note name.")
    path = NOTES_DIR / f"{name}.md"
    if path.exists():
        raise ToolError(f"A note called {name!r} already exists. Choose another name.")
    path.write_text(text, encoding="utf-8")
    return f"Saved note {name!r}."


@mcp.resource("notes://{name}", mime_type="text/markdown")
def read_note(name: str) -> str:
    """The full text of one note."""
    path = NOTES_DIR / f"{name}.md"
    if not path.exists():
        raise ResourceNotFoundError(f"No note called {name!r}.")
    return path.read_text(encoding="utf-8")


@mcp.prompt()
def summarise_note(name: str) -> str:
    """Summarise a note in three bullet points."""
    return f"Read the note notes://{name} and summarise it in three short bullet points."


if __name__ == "__main__":
    mcp.run()          # stdio by default: the AI app starts this script and talks to it

What each part does:

  • MCPServer("Notes", instructions=...) creates the server; the instructions tell the host's model what it's for.
  • @mcp.tool() turns a function into a tool. Annotated[str, Field(description=...)] adds a description to an argument, which ends up in the tool's input schema.
  • raise ToolError(...) returns a readable error to the model (isError: true). Any other exception is treated as a crash: the model sees only a generic message, so internal details don't leak.
  • @mcp.resource("notes://{name}") creates a resource template; {name} becomes the function's argument. ResourceNotFoundError reports a missing resource properly.
  • @mcp.prompt() creates a prompt the user can pick.
  • mcp.run() serves over stdio, ready for a host to launch.

Test it without an AI app

The SDK's Client can connect to a server object directly, in memory, which makes testing quick:

# test_notes.py: call the server's tools in memory, no AI app needed
import anyio
from mcp import Client

from notes_server import mcp


async def main():
    async with Client(mcp) as client:
        tools = await client.list_tools()
        print("Tools:", [t.name for t in tools.tools])

        result = await client.call_tool("add_note", {"name": "packing", "text": "Umbrella, adapter, tram card."})
        print(result.content[0].text)

        result = await client.call_tool("add_note", {"name": "bad name!", "text": "x"})
        print("Error?", result.is_error, "-", result.content[0].text)

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

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


anyio.run(main)
Output
Tools: ['search_notes', 'add_note']
Saved note 'packing'.
Error? True - Error executing tool add_note: Use only letters, digits and hyphens in the note name.
Found: {'result': ['packing']}
Resource: Umbrella, adapter, tram card.

Notice the structured result {'result': ['packing']}: because search_notes declares -> list[str], the SDK also generated an output schema and returned the list as structured data alongside the text.

For clicking through a server by hand, run mcp dev notes_server.py. It starts the MCP Inspector, a web page where you can list tools, call them with arguments and read resources.

Common mistakes

Practice exercise

Write a function in the shape MCP SDKs turn into a tool: type hints, a docstring and a return value.

Your solutionPython
import inspect

# MCP SDKs build a tool's schema from its type hints and docstring.
# Rewrite c_to_f with the type hints (celsius: float) -> float, the docstring
# "Convert degrees Celsius to Fahrenheit." and the body: return celsius * 9 / 5 + 32
def c_to_f(celsius):
    pass

print(inspect.signature(c_to_f))
print(inspect.getdoc(c_to_f))
print(c_to_f(100))
Knowledge check

In the MCP Python SDK, where does a tool's input schema come from?

Summary

  • The MCP Python SDK turns typed, documented functions into tools, resources and prompts with decorators.
  • Use Annotated[..., Field(...)] for argument descriptions and limits; validation is automatic.
  • Raise ToolError for failures the model should read; other exceptions are hidden as crashes.
  • Test with the in-memory Client and explore with the MCP Inspector (mcp dev).

Next: connecting your server to real AI apps.

Finished reading? Tick it off to track your progress.