Skip to main content
Text ready — video coming soon

Build a local MCP server

You can now follow a class, a decorator and an awaited call. In the last lesson, those pieces were still ordinary Python. Here we will use them to expose a small function through MCP, the Model Context Protocol.

Our server will answer one question: how many lessons are in a named public chapter? You will:

  • Identify the host, client and server responsibilities.
  • Discover the server's registered tool.
  • Call it through a real local connection and inspect the result.

A language model is not required for those checks. This lets you verify the tool itself before adding model decisions around it.

Identify the three roles around a tool call​

MCP gives applications a shared way to discover and use capabilities from servers. A host is the application coordinating the experience, such as an assistant application. Its client manages a connection to an MCP server. The server exposes capabilities on the other side of that connection.

A tool is an operation the server exposes with a name, a description and an input shape. Discovery tells a client what is available; a call requests that an operation actually run. These are separate events.

The protocol does not make a function correct, select your access policy or turn every result into trusted instructions. Those decisions still belong to the solution around it.

Choose the exact library used by the example​

This walkthrough uses the standalone FastMCP 4.1.3 distribution, imported with from fastmcp import FastMCP. It is different from the independently versioned official mcp Python SDK and its historical bundled helper. Do not combine imports and examples from those distributions as though their versions were interchangeable.

The examples were checked with Python 3.12.10. In the book-work folder that already has your uv configuration, add:

uv add "fastmcp==4.1.3"

The pin identifies the version for this walkthrough. Keep the resulting dependency and lockfile changes reviewable. When updating a version, repeat the tool-discovery and call checks rather than assuming an import with a familiar name means the same API.

Give the server a deliberately small capability​

Save this complete file as book_server.py:

from fastmcp import FastMCP

CHAPTERS = {
"Python and Roots": 7,
"Python and Branches": 8,
}

mcp = FastMCP("Book chapters")

@mcp.tool
def chapter_lessons(title: str) -> str:
"""Return the lesson count for a published chapter title."""
if title not in CHAPTERS:
return f"Not found: no chapter titled {title!r} in this table."
return f"{title}: {CHAPTERS[title]} lessons"

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

Most of this file is Python you already know. The dictionary holds the approved public information. The function checks membership and returns a string. In an f-string, !r uses a representation of the value, which makes quotes and unusual characters more visible in a diagnostic result.

FastMCP supplies the new parts. FastMCP(...) creates the server object. @mcp.tool registers the function as a tool. The function name becomes its default tool name, its documentation supplies a description, and its annotated parameters describe inputs.

The main-name guard keeps importing the file from starting the server accidentally. mcp.run starts it when the file is deliberately executed.

The caller supplies a title. The table determines which titles receive a lesson count; other titles receive an explicit not-found response. The title argument cannot select an arbitrary file, run a shell command or choose a network address. That narrow responsibility makes the result much easier to verify.

Start the server through its client​

Standard input/output, usually shortened to stdio, lets the client and its server subprocess exchange protocol messages through process streams. It does not need a public listening port for this example.

Save the following beside the server as book_client.py:

import asyncio
import sys
from pathlib import Path

from fastmcp import Client
from fastmcp.client.transports import StdioTransport

SERVER = Path(__file__).with_name("book_server.py")

async def main():
transport = StdioTransport(
command=sys.executable,
args=[str(SERVER)],
)
async with Client(transport, timeout=5, init_timeout=10) as client:
tools = await client.list_tools()
for tool in tools:
print(tool.name)
result = await client.call_tool(
"chapter_lessons",
{"title": "Python and Roots"},
)
print(result.content[0].text)

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

__file__ identifies the current script. with_name selects the server filename beside it. sys.executable selects the interpreter running this client, keeping it in the same environment. Those are trusted configuration choices in the code, not values supplied by the tool caller.

The client options set a five-second default request timeout and a ten-second initialisation timeout. They give this local walkthrough explicit waiting limits. A timeout reports that a wait failed; it does not prove that work elsewhere was undone. The FastMCP client guide describes the connection lifecycle.

The client launches the server subprocess itself. Run:

uv run python book_client.py

Expect a discovered tool named chapter_lessons and the text Python and Roots: 7 lessons. Server startup messages may also appear through its diagnostic stream.

async with keeps the connection lifetime around the operations that need it. list_tools discovers descriptions. call_tool requests execution. The result's content is a list of content blocks; our server returns a string represented in a text block, so this particular client reads its first block's text. A tool returning images or a structured result would need a matching output check.

Break the call at a known boundary​

Replace the title with "Unknown chapter". The expected result is the explicit not-found text, not a guessed count. Change the tool name to one the server does not expose, and expect a reported tool error rather than a chapter answer.

Also inspect wrong-type inputs and extra fields. Generated schemas and framework defaults do not necessarily implement every strict rule you might want. A future client that requires rejection of all undeclared fields must enforce and test that policy explicitly; we will do that at the LangChain boundary in the final lesson.

Safety floor

The stdio server's standard output carries protocol messages. Put diagnostic logs on standard error, not arbitrary prints on standard output. Treat the executable, arguments and server location as trusted configuration. A tool request must not be allowed to replace them. Add independent permission checks before exposing private information or write operations.

The FastMCP tool documentation, client transport documentation and MCP architecture overview support this walkthrough.

Trace the complete local run​

Without looking at the code:

  1. Which operation discovers a tool, and which operation executes it?
  2. What starts the server subprocess in this example?
  3. Why does a print inside the client differ from an arbitrary print inside the stdio server?
  4. Which approved data determines the answer for a title?
  5. What would you need to check before replacing the public table with private records?
Compare after your attempt

list_tools discovers; call_tool executes. The client's stdio transport launches the configured Python interpreter and server file. Client output is local display, whereas server stdout is part of the protocol connection. The fixed public dictionary supplies the answer. Private records need trusted identity, enforced resource permissions and suitable result/log handling in addition to input validation.

In the LangChain lesson, you will follow a different framework's blocks. The final lesson then connects a LangChain tool to this same real MCP server.