Skip to content
Mia Automation
NLEN Sign in Put Mia to workGet started

How to Build an MCP Server: A Tested Python and Node Example

To build an MCP server, you write a few typed functions and register them as tools with the official SDK. Then you test them with a plain client and connect the server to an AI app such as Claude Code or Claude Desktop. We built the same notes server twice, in Python (73 lines) and in Node (45 lines), and tested it four ways. Below is the full code, the order we test in, and the errors we ran into, including one that breaks most tutorials written before the 2.0 SDK.

AI agents and agentic workUpdated 7 min read

Tested by us on 11 November 2026.

What you'll build

A small server that gives an AI app three tools for plain-text notes: list_notes, read_note and add_note. It's deliberately boring, because the interesting parts are the ones tutorials skip: a name check so the AI can't write outside its folder, a rule that it never overwrites, and an audit line for every call. Swap the notes folder for your own data and the pattern stays the same.

Animated diagram of four stages lighting up in turn: write the tools, test with a plain client and no model, inspect in MCP Inspector, connect to an AI app, with what each check showed.
The order we build and test in. Each stage catches a different kind of mistake.

Before you start

  • Python route: Python 3.10 or newer and uv, a fast Python package manager. The official guide requires MCP Python SDK 2.0.0 or higher.
  • Node route: Node.js 20 or newer. We tested with Node 20 on Linux and Node 22 on Windows.
  • An MCP host to connect to: Claude Code, Claude Desktop, VS Code or another app that supports MCP. For testing you can use MCP Inspector, the official debugging tool, which runs with npx.
  • No API key or paid plan is needed to build and inspect the server. You only need one when an AI app starts calling it.

Build the server in Python, step by step

  1. Create the project

    Make a folder and add the official SDK with uv. On our machine uv add finished in under a second because the packages were cached.

    bash
    uv init notes
    cd notes
    uv add "mcp[cli]"
  2. Write the server

    Save this as notes.py. Each function with a type-hinted signature and a docstring becomes a tool. The docstring is what the model reads to decide when to use it, so write it for the model, not for yourself.

    python
    """A small MCP server for plain-text notes.
    
    Three tools: list_notes and read_note only read; add_note writes a new file.
    Every call is appended to audit.jsonl, and add_note never overwrites a file.
    Tested with the official Python SDK (mcp 2.3.0), protocol 2026-07-28.
    """
    import json
    import re
    import time
    from pathlib import Path
    
    from mcp.server import MCPServer
    
    NOTES_DIR = Path(__file__).parent / "notes"
    AUDIT_LOG = Path(__file__).parent / "audit.jsonl"
    NOTES_DIR.mkdir(exist_ok=True)
    
    mcp = MCPServer("notes")
    
    
    def audit(tool: str, **args) -> None:
        """Append one line per tool call, so you can see what the AI did."""
        with AUDIT_LOG.open("a", encoding="utf-8") as f:
            f.write(json.dumps({"t": time.strftime("%Y-%m-%dT%H:%M:%S"), "tool": tool, "args": args}) + "\n")
    
    
    def safe_name(name: str) -> str:
        """Allow letters, digits and dashes only, so a note can never escape the folder."""
        slug = re.sub(r"[^a-z0-9-]+", "-", name.lower()).strip("-")
        if not slug:
            raise ValueError("Note name needs at least one letter or digit.")
        return slug
    
    
    @mcp.tool()
    def list_notes() -> list[str]:
        """List the names of all saved notes."""
        audit("list_notes")
        return sorted(p.stem for p in NOTES_DIR.glob("*.md"))
    
    
    @mcp.tool()
    def read_note(name: str) -> str:
        """Read one note.
    
        Args:
            name: The note name as returned by list_notes.
        """
        audit("read_note", name=name)
        path = NOTES_DIR / f"{safe_name(name)}.md"
        if not path.exists():
            return f"No note called '{name}'."
        return path.read_text(encoding="utf-8")
    
    
    @mcp.tool()
    def add_note(name: str, text: str) -> str:
        """Save a new note. Refuses to overwrite an existing note.
    
        Args:
            name: Short name, letters, digits and dashes.
            text: The note itself, plain text or Markdown.
        """
        audit("add_note", name=name, chars=len(text))
        path = NOTES_DIR / f"{safe_name(name)}.md"
        if path.exists():
            return f"A note called '{path.stem}' already exists. Pick another name."
        path.write_text(text, encoding="utf-8")
        return f"Saved note '{path.stem}' ({len(text)} characters)."
    
    
    if __name__ == "__main__":
        mcp.run(transport="stdio")
  3. Test it without a model

    Before any AI touches it, call every tool from a plain MCP client. Ours tries the happy path and two attacks: a duplicate name and a path that tries to escape the folder. Run it with uv run test_client.py.

    python
    """Talk to notes.py over stdio without any AI model in between."""
    import asyncio
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client
    
    async def main():
        params = StdioServerParameters(command="uv", args=["run", "notes.py"])
        async with stdio_client(params) as (read, write):
            async with ClientSession(read, write) as s:
                await s.initialize()
                tools = await s.list_tools()
                print("tools:", [t.name for t in tools.tools])
                for name, args in [("add_note", {"name": "Offerte bakkerij", "text": "Call back Friday."}),
                                   ("add_note", {"name": "bakery quote", "text": "second try"}),
                                   ("list_notes", {}),
                                   ("read_note", {"name": "../../etc/passwd"}),
                                   ("read_note", {"name": "bakery-quote"})]:
                    r = await s.call_tool(name, args)
                    print(name, "->", [c.text for c in r.content])
    
    asyncio.run(main())
  4. Check the output

    You should see three tools, a saved note, a refusal for the duplicate, and "No note called '../../etc/passwd'" instead of file contents. That last line is the check doing its job: the name is cleaned before it becomes a path. The audit file now has one line per call.

    text
    tools: ['list_notes', 'read_note', 'add_note']
    add_note -> ["Saved note 'bakery-quote' (17 characters)."]
    add_note -> ["A note called 'bakery-quote' already exists. Pick another name."]
    list_notes -> ['bakery-quote']
    read_note -> ["No note called '../../etc/passwd'."]
    read_note -> ['Call back Friday.']

The same server in Node

The Node SDK has the same shape: npm install @modelcontextprotocol/server zod, a createServer() function that registers tools with a zod schema, and serveStdio(createServer) to start it. Our version is 45 lines. One rule matters more in Node than in Python: never write to stdout with console.log in a stdio server. Stdout carries the protocol messages, so a stray log line corrupts them. Use console.error for logging.

javascript
server.registerTool("add_note", {
  description: "Save a new note. Refuses to overwrite an existing note.",
  inputSchema: z.object({ name: z.string(), text: z.string() }),
}, async ({ name, text: body }) => {
  audit("add_note", { name, chars: body.length });
  const slug = safeName(name), f = path.join(DIR, slug + ".md");
  if (fs.existsSync(f)) return text(`A note called '${slug}' already exists.`);
  fs.writeFileSync(f, body, "utf8");
  return text(`Saved note '${slug}' (${body.length} characters).`);
});

The add_note tool in Node, with the same name check and no-overwrite rule as the Python version.

Inspect it in MCP Inspector

MCP Inspector shows every tool, lets you fill in the inputs by hand and logs each protocol message. Start it next to your server; it opens a page on http://127.0.0.1:6274. Flip the switch to connect, open Tools, pick a tool, fill in the fields and click Execute Tool.

bash
npx -y @modelcontextprotocol/inspector node notes.mjs
MCP Inspector on Windows with the notes server connected: three tools listed, add_note selected, the result Saved note bakery-quote (44 characters), and a tools/call message that took 25 ms. (opens at full size)
Our Node server in MCP Inspector 2.13.0 on a Windows 10 PC: the tool call and its result, with the protocol log on the right.
MCP Inspector showing the result of a second add_note call with the name Bakery Quote: A note called bakery-quote already exists. Pick another name. (opens at full size)
Same name in different capitals: the server cleaned it to bakery-quote and refused to overwrite.

Two things we noticed. Inspector 2.13.0 connected using protocol version 2025-11-25 and labeled the log "legacy", although the server also speaks 2026-07-28; the SDK handles both, so this needs no action. And the refusal above is the behavior you want to see before an AI ever gets the tool: "Bakery Quote" and "bakery quote" map to the same file, and the server says no instead of silently replacing a note.

Connect it to an AI app

In Claude Code, one command adds the server. Everything after the double dash is the start command. With --scope project the entry goes into .mcp.json in your project, which you can commit for your team.

bash
claude mcp add --scope project notes -- uv run --directory /path/to/notes notes.py
claude mcp list

Claude Desktop and most other hosts read the same structure from a JSON file under mcpServers:

json
{
  "mcpServers": {
    "notes": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/notes", "notes.py"]
    }
  }
}

We asked Claude Code in plain English to save a note, list all notes and read it back. It took 8 seconds and five turns, picked the tools on its own, and mentioned that the server had cleaned up the name.

If it doesn't work

The first three we hit ourselves on November 11, 2026; the fourth is the official guide's main warning for stdio servers.
What you seeCauseFix
No module named 'mcp.server.fastmcp'Tutorial written for SDK 1.xImport MCPServer from mcp.server
Pending approval (run claude to approve) in claude mcp listServers from a shared .mcp.json stay off until approvedStart claude once in the project and approve the server
Claude Code says it needs permission and nothing is savedIn non-interactive mode, tools must be allowedApprove the tool when asked, or pass --allowedTools mcp__notes__add_note
Garbled messages or a server that disconnects at onceSomething writes to stdout in a stdio serverLog to stderr (console.error, or Python's logging to stderr)

Checklist before you let an AI use it

  1. Every input that becomes a path, query or command is cleaned or validated in the server.
  2. Write tools refuse to overwrite or delete unless that's their explicit job.
  3. Every call is logged with the tool name and its inputs.
  4. Read-only tools and write tools are separate, so a host can allow one without the other.
  5. Secrets come from environment variables, never from the code or a committed config file.

Questions

How long does it take to build an MCP server?

Not long for a small one: the code is short and the official SDKs do the protocol work. Our notes server is 73 lines of Python or 45 lines of Node, including the safety checks.

Python or Node for an MCP server?

Pick the language your data access already lives in. Both official SDKs register tools the same way; Python uses type hints and docstrings, Node uses zod schemas.

Do I need Claude to test an MCP server?

No. Test with a plain MCP client or MCP Inspector first. No model, no API key and no cost are involved until you connect an AI app.

What is a local MCP server?

A server that runs on your own machine and talks to the AI app over stdio. A remote server runs elsewhere and is reached over Streamable HTTP, usually with OAuth sign-in.

Sources