MCP server Python tutorial: build one to expose your operations runbooks

MCP server Python tutorial with the official SDK: expose your operations runbooks read-only, with resources, a search tool and an investigation prompt.
Créer un serveur MCP Python pour exposer vos runbooks d'exploitation

Building an MCP server in Python is now one of the fastest ways to make internal knowledge available to an AI assistant. Operations runbooks are particularly well suited: they are written down, structured, often scattered across a wiki or a Git repository, and valuable at exactly the moment when nobody has time to look for them. The ingredients for this first MCP server: Python, the official SDK and a directory of runbooks.

The goal of this tutorial is modest and deliberately cautious: expose runbooks read-only, let the assistant search and read them, and offer a reusable investigation prompt. No action is run against production. It is the right starting point before considering tools that take action.

We use the official Python SDK for the Model Context Protocol. Its API changed with version 2 (the v1 FastMCP class is now called MCPServer): if you are following an older tutorial, adapt the imports.

Why build an MCP server in Python for your runbooks?

An MCP server exposes three types of capability: tools, resources and prompts (our Model Context Protocol guide covers them in detail). Runbooks map naturally onto all three:

  • each runbook becomes a resource, addressed by a URI such as runbook://redemarrage-api;
  • keyword search becomes a tool, which the model calls when it is looking for a procedure;
  • the investigation approach becomes a prompt, which the user triggers explicitly.

The advantage over simply copying and pasting into the conversation: the source stays single, up to date and versioned, and the assistant reads only what it needs.

Prepare the MCP server Python environment

The SDK requires Python 3.10 or later. It is installed from PyPI under the name mcp; the cli extra adds the mcp command, which is useful for testing:

python3 -m venv .venv
. .venv/bin/activate
pip install "mcp[cli]"

The project also recommends uv for managing the environment. Refer to the Python SDK documentation for the current method.

For the content, assume a directory of Markdown files, one per runbook:

/opt/runbooks/
  redemarrage-api.md
  saturation-disque.md
  certificat-expire.md

In practice

Step 1 — Declare the server and the resources

The server fits in a single file. Start with the server object and a parameterised resource that reads a runbook by name. The function is only called when a client actually reads the resource.

import logging
import os
import re
from pathlib import Path

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

RUNBOOKS_DIR = Path(os.environ.get("RUNBOOKS_DIR", "/opt/runbooks")).resolve()
NOM_VALIDE = re.compile(r"^[a-z0-9-]{1,64}$")

log = logging.getLogger("runbooks")
mcp = MCPServer("runbooks-ops")


def chemin_runbook(nom: str) -> Path:
    """Validate the name and prevent any escape from the directory."""
    if not NOM_VALIDE.match(nom):
        raise ResourceNotFoundError("Invalid runbook name.")
    chemin = (RUNBOOKS_DIR / f"{nom}.md").resolve()
    if chemin.parent != RUNBOOKS_DIR or not chemin.is_file():
        raise ResourceNotFoundError(f"Runbook not found: {nom}")
    return chemin


@mcp.resource("runbook://{nom}")
def lire_runbook(nom: str) -> str:
    """Full content of an operations runbook."""
    return chemin_runbook(nom).read_text(encoding="utf-8")

Two details matter. Validating the name with a regular expression, then checking the resolved path, blocks attempts such as ../../etc/passwd. And the error messages stay terse: they do not reveal the server’s directory tree.

Step 2 — Add a search tool

The model does not know your file names. A search tool lets it find the right runbook from a symptom:

@mcp.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def chercher_runbooks(mots_cles: str) -> list[str]:
    """Search for runbooks whose content contains all the keywords.
    Returns at most 10 names, to be read afterwards via runbook://{nom}."""
    termes = [t.lower() for t in mots_cles.split()][:5]
    if not termes:
        raise ToolError("Provide at least one keyword.")
    resultats = []
    for fichier in sorted(RUNBOOKS_DIR.glob("*.md")):
        texte = fichier.read_text(encoding="utf-8").lower()
        if all(t in texte for t in termes):
            resultats.append(fichier.stem)
    log.info("search %s: %d result(s)", termes, len(resultats))
    return resultats[:10]

The docstring is not decorative: it is the description the model reads to decide when to call the tool. The annotations tell the client that the tool changes nothing, but they are only hints; security relies on the code itself.

Step 3 — Offer an investigation prompt

A prompt guides the user towards a consistent approach:

@mcp.prompt()
def investiguer(symptome: str) -> str:
    """Start an investigation from a symptom."""
    return (
        f"Observed symptom: {symptome}\n"
        "1. Search for relevant runbooks with chercher_runbooks.\n"
        "2. Read the most suitable one and summarise the checks to perform.\n"
        "3. Do not propose any destructive action without explicit approval."
    )


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    mcp.run()

With no argument, mcp.run() uses the stdio transport. Standard output is then used by the protocol: go through the logging module, which writes to standard error, rather than using print().

Step 4 — Test with the Inspector

The command provided by the cli extra launches the server under MCP Inspector, a web test interface (it requires Node.js):

mcp dev serveur_runbooks.py

Test the search with real keywords, read a resource, then deliberately try invalid names to check that they are refused.

Step 5 — Declare the server in your assistant

Most hosts accept a launch command in their configuration. Use the virtual environment’s Python to be sure you have the right dependencies:

{
  "mcpServers": {
    "runbooks": {
      "command": "/opt/runbooks-mcp/.venv/bin/python",
      "args": ["/opt/runbooks-mcp/serveur_runbooks.py"],
      "env": { "RUNBOOKS_DIR": "/opt/runbooks" }
    }
  }
}

For a server shared by the team, the SDK can also serve over HTTP with mcp.run(transport="streamable-http"), which listens on the local interface by default. Before opening it to the network, add authentication and reread our guide to securing an MCP server.

Best practices

  • Start read-only; add action tools only with human approval.
  • Validate every argument on the server side: allow-lists, lengths, formats.
  • Write precise docstrings: they guide the model’s choice.
  • Raise an explicit tool error rather than returning error text as if it were a result.
  • Log to standard error, never to standard output with stdio.
  • Version runbooks in Git and review them like code: they become instructions read by an agent.

Frequently asked questions

Should I use FastMCP or MCPServer?

In version 2 of the official SDK, FastMCP was renamed MCPServer. The SDK migration guide details how the imports map.

Is my server observable?

SDK v2 emits OpenTelemetry spans for every message processed; you just need to install an SDK and an exporter. See observing MCP agents with OpenTelemetry.

Yes, by combining its runbooks with an observability server in the same assistant. Our guides such as common incidents on a Managed cluster are good candidates to turn into runbooks.

Conclusion

Building an MCP server in Python takes little code; the care goes elsewhere: input validation, clear descriptions, explicit errors and a read-only scope. This small runbook server already delivers real value during on-call shifts, and it is a sound basis for going further.

span.observer is an independent community blog, not affiliated with Dynatrace LLC or the projects mentioned. The trademarks mentioned belong to their respective owners. Tools evolve quickly: check commands and options in their official documentation.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
Sécuriser serveur MCP : tokens, moindre privilège, injection de prompt et validation humaine

A secure MCP server: tokens, least privilege, prompt injection and human approval

Next Post
Observer les agents MCP avec OpenTelemetry : spans d'appels d'outils, attributs, latence et erreurs

How to monitor MCP agents with OpenTelemetry: tool call spans, attributes, latency and errors

Related Posts