// Why this matters
Building MCP servers in Python for SRE work is worth it because the same two chores recur forever: turning a ticket into a Terraform pull request, and answering "is this service healthier or worse than last week". Both are procedural, both are boring, and both are safe to automate if the automation is bounded.
MCP matters because it decouples the tool from the orchestrator. We use a workflow engine for scheduled and chat-triggered flows, and an IDE assistant for interactive work. Writing each tool once as an MCP server means both use the same code and the same guardrails.
The principle throughout is that agents propose and humans dispose. See Vault Access via Directory Groups, Requested by an Agent, Approved by a Human for the same principle applied to access.
// The problem
Change chores are repetitive: read the ticket, create a branch with the right name, make the edit, write a conventional commit message, push, open a PR with the template filled in. Each step is trivial and each is a place for inconsistency, like a branch named differently each time or a PR body missing its checklist.
Health checks are similar. Someone opens a dashboard, eyeballs a few charts and decides it looks fine. The judgement is hard to repeat, impossible to compare across weeks and leaves no record.
Naively pointing a language model at a shell to do these things works in a demo and is unsafe in production: unbounded tools, free-text output that cannot be compared, and no stopping point before merge.
// The solution
Each agent is a small Python module whose functions are exposed as MCP tools with typed arguments and docstrings the model can read. The change agent offers start_change, commit_and_push and open_pr; the analyst offers compare_weeks, check_quotas and query_timeseries. Nothing else is exposed, so there is no "run arbitrary command" tool to misuse.
Outputs are structured. Every analyst tool returns JSON with a numeric change, a severity (ok, warning, critical) computed by fixed thresholds and a one-line verdict. A model can narrate the result, but the classification is code, so a Monday report and a Friday report are directly comparable.
Orchestration is deliberately thin. The workflow engine (self-hosted) calls the MCP tools over HTTP or stdio for scheduled reports and chat requests; the IDE assistant calls the same servers locally for interactive edits. I rejected embedding logic in workflow nodes because it would fork the behaviour of the two front ends.
The hard boundary is that the change agent opens a PR and stops. It holds a token that can push branches and open PRs, nothing more. Review, CI plan and merge are the existing human path, which is the point: automation reduces typing, not accountability.
- Ticket intakeID and description arrive via chat or workflow
- Start changeagent creates a ticket-named branch
- Edithuman or Copilot makes the Terraform change
- Commit and pushconventional message and templated PR body
- Open PR gatestandard review and CI plan apply
- Observability branchanalyst compares week-over-week metrics
- Reportseverity, percentage change and verdict
// Before you start
- Python 3.10+ and the
fastmcppackage (or the official MCP Python SDK) - git and the GitHub CLI authenticated with a token limited to branches and pull requests
- A cloud monitoring API with read access to metrics (the example uses Google Cloud Monitoring)
- A workflow engine that can act as an MCP client (n8n in our case) and/or an IDE assistant with MCP support
- A Terraform repository with a PR template and CI plan on pull requests
// Step-by-step implementation
01 Scaffold an MCP server with FastMCP
Start with the smallest possible server and run it over stdio, which is what most IDE assistants expect. Silence banner output: anything extra on stdout corrupts the protocol stream, which is the most common reason a new server "does not connect".
Docstrings are part of the interface. The model chooses tools by reading them, so write them for it: what the tool does, each argument and what comes back.
02 Write the change agent: ticket to branch
Derive the branch from the ticket ID so there is exactly one correct name. Validate the ticket against a pattern before touching git, fetch main, and branch from
origin/mainrather than whatever is checked out.Return structured results, including the branch name and the working tree status, so the caller does not parse prose.
03 Commit, push and open the PR from a template
Commit messages follow a convention: ticket, imperative summary. Reject a commit on
mainand reject an empty diff. The PR body comes from a template with a changes section, a test-plan section and a rollback line, so reviewers always find the same shape.Return the PR URL and nothing else is possible: there is no merge tool. That absence is the control.
04 Build the metrics analyst: week-over-week comparison
Query the same window for this week and the previous week, aggregate each to a single number (mean or p95, depending on the metric), compute the percentage change and classify it. The classification is plain thresholds in code.
Always align windows to the same weekday and hours. Comparing a Monday morning to the weekend is a classic source of false alarms.
05 Add quota and raw time-series tools
A quota tool answers a different question: how close are we to a limit. Read the usage and the limit metrics for a service and return utilisation with the same severity scale, so the report format is uniform.
Keep a raw
query_timeseriestool for follow-up questions, but cap the number of points it returns. An unbounded tool is how a model fills its own context window with numbers.06 Run it over HTTP and connect the workflow engine
Orchestrators usually reach MCP servers over HTTP, so run the same module with the HTTP transport behind an internal-only listener and an auth header. The workflow engine then lists tools, and a schedule node calls
compare_weeksfor each service on Monday morning.Run the engine in a container with its data volume persisted, and give it only the network paths it needs. The engine holds the schedule and the chat integration; it does not hold the logic.
07 Render a weekly report with a fixed template
The report is produced from the structured results, not written freehand. Sort by severity, show the numbers, and put the verdict line first. A model can add a sentence of context, but the table is generated, which keeps it stable.
Post it to the team channel on a schedule. The value is the habit: the same report, same format, every Monday, and the trend becomes visible by comparison.
// How to verify it works
- Run
python -m sre_mcp.change_serverunder an MCP inspector: the tool list must show exactly start_change, commit_and_push and open_pr. - Call
start_changewith a malformed ticket ID: it must return an error and leave git untouched. - Call
commit_and_pushwhile on main: it must refuse. - Call
compare_weekson a metric with known data: the result must contain severity and a verdict, and rerunning it must give the same classification. - Open the PR the agent created: the body must match the template and CI must have started a plan.
// Design decisions and trade-offs
- Agents stop at PR creation; humans merge.
- MCP makes tools reusable across orchestrators.
- Outputs are structured and templated so they are comparable run to run.
// Pitfalls and lessons learned
- Stray prints or banners on stdout corrupt a stdio MCP stream. Log to stderr and silence library banners.
- A tool that returns prose forces the caller to parse it. Return JSON with fixed keys and let the model narrate.
- Unbounded tools exhaust the model context. Cap points, rows and lengths in the tool, not in the prompt.
- Comparing windows that start at different weekday hours creates false alarms. Align by the same offset.
- Giving the change agent a broad token defeats the design. Scope it to branches and pull requests only.
- Dirty working trees cause surprising branches. Refuse to start a change unless the tree is clean.
// Frequently asked questions
How do I build an MCP server in Python?
Install fastmcp, create FastMCP("name"), decorate typed functions with @mcp.tool(), give them clear docstrings and call mcp.run(). It speaks stdio by default.
Can n8n call MCP tools?
Yes, through its MCP client node or by calling an HTTP-transport server, so scheduled flows and chat triggers can use the same tools as your IDE assistant.
Why should the agent not merge?
Merge is the accountability point. If the agent can only open a PR, a human always reviews the plan before anything changes.
How do I keep AI health reports consistent?
Compute severity and verdict in code from fixed thresholds and return structured JSON. Let the model only add commentary.
How do I compare metrics week over week in Cloud Monitoring?
Query two windows of equal length offset by seven days with the same aligner, reduce each to a mean or percentile and compute the percentage change.
// The outcome
Three analyst tools and a change agent behind one protocol.
// Where to take it next
- Add a read-only Terraform plan-summary tool so the assistant can explain CI results.
- Expose the access validator from Vault Access via Directory Groups, Requested by an Agent, Approved by a Human as a third tool.
- Store weekly results to build a trend instead of a single comparison.
- Look at Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys for the delivery metrics that complement these health checks.