GyaanStack. Blog

Articles / mcpagentspython

MCP from zero: write a server and call it

A minimal MCP server in Python with two tools and one resource, plus a client that lists and calls them over stdio. Tested with mcp 2.3.0.

By Raghunath · · 8 min read

MCP (Model Context Protocol) is a standard way for an app that uses an LLM to discover and call tools that live in another program. You write the tools once, as an MCP server, and any MCP client can use them: Claude Desktop, Claude Code, an IDE, or your own Python script.

In this post I write a small notes server with two tools and one resource, then a client that connects to it, lists what it offers and calls it. There is no LLM in either script. Leaving the model out makes it clear which parts MCP handles and which it does not.

Tested with Python 3.15.2, mcp 2.3.0, pydantic 2.14.4 and anyio 4.16.0.

What MCP is, and what it is not#

An MCP server is a program that answers a few kinds of request over JSON-RPC:

  • tools: functions the client can call with arguments, like search_notes(query).
  • resources: data the client can read by URI, like notes://index.
  • prompts: reusable prompt templates. I skip these here.

The client asks the server what it has (tools/list, resources/list), gets names, descriptions and JSON schemas back, and calls things by name (tools/call, resources/read).

MCP does not decide when to call a tool. That is the model's job, inside the host app. MCP is not an agent framework either. It has no planning, no memory and no loop. It only covers how tools get described and called. If you have used function calling, an MCP server is a way to keep those functions in their own process, behind a standard interface, so you don't rewrite them for every app.

The transport here is stdio. The client starts the server as a subprocess and they exchange JSON messages over stdin and stdout. For a server other people reach over the network, MCP also has an HTTP transport. Stdio is the simplest place to start and is what desktop apps use for local servers.

Setup#

python -m venv .venv
source .venv/bin/activate
pip install mcp

A note on versions: many tutorials you will find use from mcp.server.fastmcp import FastMCP. That is the 1.x SDK. In 2.x the class is called MCPServer, and the old import fails with an error that points to the migration guide. The code below is for 2.x. If you are stuck on 1.x, pin mcp<2 and use FastMCP with the same decorators. The 1.x client also uses camelCase field names (inputSchema, isError), so the client below needs small edits there. I tested only 2.3.0.

The server#

# notes_server.py
from mcp.server.mcpserver import MCPServer

server = MCPServer("notes")

NOTES: dict[str, str] = {
    "mcp": "MCP is a protocol for exposing tools and data to LLM apps.",
}


@server.tool()
def add_note(title: str, body: str) -> str:
    """Save a note under a short title. Overwrites an existing note."""
    NOTES[title.lower()] = body
    return f"saved '{title.lower()}' ({len(NOTES)} notes total)"


@server.tool()
def search_notes(query: str) -> list[str]:
    """Return titles of notes whose title or body contains the query."""
    q = query.lower()
    return [t for t, b in NOTES.items() if q in t or q in b.lower()]


@server.resource("notes://index", mime_type="text/plain")
def notes_index() -> str:
    """One line per note: title and the first 40 characters of the body."""
    return "\n".join(f"{t}: {b[:40]}" for t, b in sorted(NOTES.items()))


if __name__ == "__main__":
    server.run()  # stdio by default

That is the whole server. The SDK reads three things from each function:

  1. The name becomes the tool name.
  2. The type hints become a JSON schema for the arguments. title: str, body: str turns into an object with two required string fields.
  3. The docstring becomes the description. A model reads this text when it decides whether to call the tool, so write it for that reader: what the tool does, what it returns, and anything surprising, like "overwrites an existing note".

search_notes returns list[str], so the SDK also sends a structured result the client can read as data, not only as text.

The notes live in a dict, so they disappear when the server stops. In a real server this would be a database or files on disk. Nothing else in the code would change.

Don't run this file directly to "test" it. It will sit there waiting for JSON on stdin, which looks like a hang. The client starts it for you.

The client#

# client.py
import asyncio
import sys

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

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


async def main() -> None:
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            init = await session.initialize()
            print("connected to:", init.server_info.name)

            tools = await session.list_tools()
            for tool in tools.tools:
                print("tool:", tool.name, "-", tool.description)
                print("  input schema:", tool.input_schema)

            resources = await session.list_resources()
            for res in resources.resources:
                print("resource:", res.uri)

            result = await session.call_tool(
                "add_note", {"title": "RAG", "body": "Retrieve first, then generate."}
            )
            print("add_note ->", result.content[0].text)

            result = await session.call_tool("search_notes", {"query": "generate"})
            print("search_notes ->", result.structured_content)

            index = await session.read_resource("notes://index")
            print("notes://index ->")
            print(index.contents[0].text)


asyncio.run(main())

Step by step:

  • StdioServerParameters says how to start the server. sys.executable is the Python running the client, so the server uses the same virtual environment.
  • stdio_client starts the subprocess and gives back a pair of streams. ClientSession speaks MCP over them.
  • initialize() is the handshake. Client and server agree on a protocol version and say what they support. Nothing else works before this call.
  • Then we list tools and resources, call both tools and read the resource.

Running it#

python client.py

Output:

connected to: notes
tool: add_note - Save a note under a short title. Overwrites an existing note.
  input schema: {'properties': {'title': {'title': 'Title', 'type': 'string'}, 'body': {'title': 'Body', 'type': 'string'}}, 'required': ['title', 'body'], 'type': 'object', 'title': 'add_noteArguments'}
tool: search_notes - Return titles of notes whose title or body contains the query.
  input schema: {'properties': {'query': {'title': 'Query', 'type': 'string'}}, 'required': ['query'], 'type': 'object', 'title': 'search_notesArguments'}
resource: notes://index
add_note -> saved 'rag' (2 notes total)
search_notes -> {'result': ['rag']}
notes://index ->
mcp: MCP is a protocol for exposing tools and
rag: Retrieve first, then generate.

The input schema lines are what a host app hands to the model as the tool definition. I never wrote a schema; the SDK built it from the type hints. If a model picks the wrong tool or passes odd arguments, look at these lines and the docstrings first.

What happens with bad arguments#

Models get arguments wrong, so it helps to see what a client receives when that happens. This call leaves out body:

# bad_call.py
import asyncio, sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

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

async def main() -> None:
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.call_tool("add_note", {"title": "no body"})
            print("is_error:", result.is_error)
            print(result.content[0].text[:200])

asyncio.run(main())
Tool 'add_note' rejected arguments: ['body']
is_error: True
Error executing tool add_note: 1 validation error for add_noteArguments
body
  Field required [type=missing, input_value={'title': 'no body'}, input_type=dict]
    For further information visit https:

The first line is a log message the client prints to stderr. The call itself does not raise. It comes back with is_error: True and the validation message as text. A host app passes that text back to the model, which can usually fix the call on the next try. Your own client code should check is_error instead of assuming every call worked.

Using the server from a real host#

The same notes_server.py works in any MCP host without changes. Each host needs the same two facts: the command to run and its arguments. In Claude Code, for example:

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

Use full paths. The host starts the server from its own working directory, and a relative path is the most common reason a local server "does not show up".

Once it is added, the model sees add_note and search_notes with the descriptions from the docstrings and decides on its own when to call them. That decision is the part this post left out on purpose. Everything below it, from schemas to calls, results and errors, is what you just ran.

Where to go next#

  • Add a template resource with a parameter in the URI, like notes://{title}, so a client can read one note directly.
  • Put the notes in SQLite so they survive restarts.
  • Write an eval for the server: a list of tool calls with expected results, run through this same client on every change.
  • Read the protocol spec at modelcontextprotocol.io once you have run this. It reads much faster after you have seen the messages work.

MCP itself is small. You describe a tool with a name, a schema and a description, then call it by name and read back a result or an error. The harder work is in the tools themselves and in writing descriptions a model can act on.