Day 12: Tool calling, the agent loop and MCP –
ops-agent
Goal: Provide Python functions as tools for an LLM, build an agent loop with stop conditions and guardrails, and offer the same tools as an MCP server · Duration: approx. 150 min · Prerequisite: Day 11
Briefing
- Tool calling: You send the model JSON schemas of
your functions. It answers not with text but with “call
disk_usage(path="/")”. - You execute, not the model. Your code decides what is allowed (guardrails).
- Agent loop: Send the result back to the model until it answers – or a limit kicks in (steps, calls, time).
- MCP (Model Context Protocol): a standard for offering tools to any client (Claude, IDEs, your own agents). Write once, use everywhere.
- Everything is read-only today: an agent that may only read can’t break much.
ops-agent "query" ─> run_agent ─(tools=schemas)─> ministral-3:3b
▲ │ tool_calls
└── result ◄─── run_tool ◄───┘ (allowlist, pydantic)
tools.py ──────────────────────────> mcp_server.py ──stdio──> MCP client
Drill 1: Create the project
cd ~/py-lab
uv init -q --package --name ops-agent tag12-ops-agent
cd tag12-ops-agent
uv add -q openai pydantic typer mcp
uv add -q --dev pytest ruff
cat >> pyproject.toml <<'EOF'
[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM"]
[tool.pytest.ini_options]
testpaths = ["tests"]
EOF
uv tree --depth 1 | grep -E 'mcp|openai'
ls srcExpected (versions may differ):
├── mcp v2.3.0
├── openai v3.28.0
ops_agent
Warning: The
mcpSDK was restructured in version 2:FastMCPis now calledMCPServer(from mcp.server.mcpserver import MCPServer), and there is a high-level classmcp.Client. Older tutorials usingfrom mcp.server.fastmcp import FastMCPonly work withmcp<2.
Save your progress? Sign up for free
Drill 2: Read-only tools with type hints
The signature is the contract:
Annotated[int, Field(ge=1, le=20)] later becomes the JSON
schema and the validation – for the LLM as well as for
MCP.
cat > src/ops_agent/tools.py <<'EOF'
"""Read-only System-Tools – genutzt vom Agenten und vom MCP-Server."""
import os
import shutil
import subprocess
from collections.abc import Callable
from typing import Annotated, Any
from openai.types.chat import ChatCompletionFunctionToolParam
from pydantic import Field, TypeAdapter
GB = 1024**3
def disk_usage(
path: Annotated[
str, Field(description="Absoluter Pfad, z. B. / oder /Users")
] = "/",
) -> dict[str, float]:
"""Belegung des Dateisystems, auf dem PATH liegt, in GB und Prozent."""
if not os.path.isabs(path):
raise ValueError("path muss absolut sein")
total, used, free = shutil.disk_usage(path)
return {
"total_gb": round(total / GB, 1),
"used_gb": round(used / GB, 1),
"free_gb": round(free / GB, 1),
"percent": round(used / total * 100, 1),
}
def load_average() -> dict[str, float]:
"""Systemlast der letzten 1, 5 und 15 Minuten und Anzahl der CPUs."""
one, five, fifteen = os.getloadavg()
return {
"load_1m": round(one, 2),
"load_5m": round(five, 2),
"load_15m": round(fifteen, 2),
"cpus": os.cpu_count() or 1,
}
def top_processes(
n: Annotated[int, Field(ge=1, le=20, description="Anzahl Prozesse")] = 5,
) -> list[dict[str, Any]]:
"""Die N Prozesse mit der höchsten CPU-Last."""
out = subprocess.run(
["ps", "-Ao", "pid=,pcpu=,comm="],
capture_output=True,
text=True,
check=True,
timeout=5,
env={**os.environ, "LC_ALL": "C"}, # sonst "0,5" statt "0.5"
).stdout
rows: list[dict[str, Any]] = []
for line in out.splitlines():
pid, cpu, cmd = line.split(None, 2)
rows.append({"pid": int(pid), "cpu": float(cpu), "cmd": cmd.rsplit("/")[-1]})
return sorted(rows, key=lambda r: r["cpu"], reverse=True)[:n]
TOOLS: dict[str, Callable[..., Any]] = {
f.__name__: f for f in (disk_usage, load_average, top_processes)
}
def openai_tools() -> list[ChatCompletionFunctionToolParam]:
"""Beschreibt alle Tools im Format der Chat-Completions-API."""
return [
{
"type": "function",
"function": {
"name": name,
"description": fn.__doc__ or "",
# TypeAdapter reads the signature; mypy only knows types as argument
"parameters": TypeAdapter(fn).json_schema(), # type: ignore[arg-type]
},
}
for name, fn in TOOLS.items()
]
EOF
uv run python -c "
from ops_agent.tools import TOOLS
print(TOOLS['disk_usage']('/'))
print(TOOLS['load_average']())
print(TOOLS['top_processes'](3))
"Expected (values from your machine, abridged):
{'total_gb': 228.3, 'used_gb': 213.4, 'free_gb': 14.9, 'percent': 93.5}
{'load_1m': 7.83, 'load_5m': 11.22, 'load_15m': 9.51, 'cpus': 10}
[{'pid': 59263, 'cpu': 122.8, 'cmd': 'com.apple.Virtualization.VirtualMachine'},
{'pid': 40972, 'cpu': 56.6, 'cmd': 'Python'}, ...]
Why LC_ALL=C? On a Mac with a German locale,
ps writes 0,5 instead of 0.5, and
float() crashes. subprocess.run gets a
fixed argument list without a shell – no model text
ever ends up in a command. The docstring becomes the tool description
that the model reads: write it for the model.
Save your progress? Sign up for free
Drill 3: The model picks a tool
uv run python -c "
import json
from ops_agent.tools import openai_tools
print(json.dumps(openai_tools()[2]['function']['parameters']))
"
uv run python - <<'EOF'
from openai import OpenAI
from ops_agent.tools import openai_tools
client = OpenAI(base_url="http://127.0.0.1:11434/v1", api_key="ollama")
resp = client.chat.completions.create(
model="ministral-3:3b",
tools=openai_tools(),
temperature=0,
messages=[{"role": "user", "content": "Wie voll ist /System/Volumes/Data?"}],
)
print(resp.choices[0].finish_reason)
for call in resp.choices[0].message.tool_calls or []:
print(call.function.name, call.function.arguments)
EOFExpected:
{"additionalProperties": false, "properties": {"n": {"default": 5, "description":
"Anzahl Prozesse", "maximum": 20, "minimum": 1, "title": "N", "type": "integer"}},
"type": "object"}
tool_calls
disk_usage {"path":"/System/Volumes/Data"}
Why finish_reason: tool_calls? The model did not answer;
it delivered a function call as data.
arguments is a JSON string generated by
the model – in other words, unvalidated input.
Save your progress? Sign up for free
Drill 4: Guardrails – only allowed tools, only valid arguments
cat > src/ops_agent/agent.py <<'EOF'
"""Agenten-Schleife: Das LLM wählt Tools, Python führt sie aus – mit Grenzen."""
import json
import logging
import os
import time
from dataclasses import dataclass
from typing import Any
from openai import OpenAI
from pydantic import ValidationError, validate_call
from ops_agent.tools import TOOLS, openai_tools
log = logging.getLogger("ops_agent")
BASE_URL = os.environ.get("OPS_AGENT_BASE_URL", "http://127.0.0.1:11434/v1")
MODEL = os.environ.get("OPS_AGENT_MODEL", "ministral-3:3b")
SYSTEM = (
"Du bist ein Ops-Assistent für diesen Rechner. Hole Fakten mit den Tools, "
"statt zu raten. Antworte auf Deutsch in max. 4 Sätzen mit konkreten Zahlen."
)
MAX_RESULT_CHARS = 2000
@dataclass(frozen=True)
class Limits:
max_steps: int = 5
max_tool_calls: int = 8
timeout_s: float = 120.0
class AgentError(RuntimeError):
"""Der Agent hat eine Grenze erreicht."""
def make_client() -> OpenAI:
key = os.environ.get("OPS_AGENT_API_KEY", "ollama")
return OpenAI(base_url=BASE_URL, api_key=key, timeout=120, max_retries=1)
def run_tool(name: str, arguments: str) -> str:
"""Führt ein Tool aus. Fehler gehen als Text zurück ans Modell."""
if name not in TOOLS:
return f"Fehler: unbekanntes Tool {name!r}. Erlaubt: {', '.join(TOOLS)}"
try:
args = json.loads(arguments or "{}")
result = validate_call(TOOLS[name])(**args)
except (ValueError, TypeError, OSError, ValidationError) as exc:
return f"Fehler: {type(exc).__name__}: {exc}"[:500]
return json.dumps(result, ensure_ascii=False)[:MAX_RESULT_CHARS]
EOF
uv run python -c "
from ops_agent.agent import run_tool
print(run_tool('rm_rf', '{}'))
print(run_tool('top_processes', '{\"n\": 99}')[:88])
print(run_tool('disk_usage', '{\"path\": \"etc\"}'))
print(run_tool('disk_usage', '{}'))
"Expected:
Fehler: unbekanntes Tool 'rm_rf'. Erlaubt: disk_usage, load_average, top_processes
Fehler: ValidationError: 1 validation error for top_processes
n
Input should be less t
Fehler: ValueError: path muss absolut sein
{"total_gb": 228.3, "used_gb": 213.4, "free_gb": 14.9, "percent": 93.5}
Why errors as text instead of an exception? The model reads the
message in the next step and can correct itself (“n=20 instead of 99”).
Three layers protect you: the allowlist
(TOOLS), validation
(validate_call checks against the type hints) and a
size limit (MAX_RESULT_CHARS), so that a
tool cannot flood the context window.
Save your progress? Sign up for free
Drill 5: The agent loop
cat >> src/ops_agent/agent.py <<'EOF'
def run_agent(client: OpenAI, question: str, limits: Limits | None = None) -> str:
limits = limits or Limits()
messages: list[Any] = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question},
]
calls = 0
deadline = time.monotonic() + limits.timeout_s
for step in range(1, limits.max_steps + 1):
if time.monotonic() > deadline:
raise AgentError(f"Zeitbudget von {limits.timeout_s:.0f}s überschritten")
resp = client.chat.completions.create(
model=MODEL, messages=messages, tools=openai_tools(), temperature=0
)
msg = resp.choices[0].message
if not msg.tool_calls:
return msg.content or ""
messages.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
if call.type != "function":
continue
calls += 1
if calls > limits.max_tool_calls:
raise AgentError(f"Mehr als {limits.max_tool_calls} Tool-Aufrufe")
fn = call.function
result = run_tool(fn.name, fn.arguments)
log.info("Schritt %d: %s(%s) -> %.40s", step, fn.name, fn.arguments, result)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)
raise AgentError(f"Keine Antwort nach {limits.max_steps} Schritten")
EOF
uv run ruff check srcExpected:
All checks passed!
Why three limits? max_steps stops endless loops (“one
more tool, and another”), max_tool_calls stops models that
send ten calls per step, and timeout_s caps the total time.
An agent without a stop condition is a cost leak. The assistant message
with the tool_calls must come before the tool
replies in the history, otherwise the model cannot match up the results
(tool_call_id).
Save your progress? Sign up for free
Drill 6: The CLI
cat > src/ops_agent/cli.py <<'EOF'
"""ops-agent – beantwortet Fragen über diesen Rechner mit read-only Tools."""
import logging
from typing import Annotated
import openai
import typer
from ops_agent.agent import AgentError, Limits, make_client, run_agent
app = typer.Typer(add_completion=False)
@app.command()
def main(
question: str,
verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
max_steps: Annotated[int, typer.Option(min=1, max=10)] = 5,
) -> None:
"""Stellt QUESTION an den Agenten. -v zeigt jeden Tool-Aufruf."""
logging.basicConfig(format=" %(message)s", level=logging.WARNING)
if verbose:
logging.getLogger("ops_agent").setLevel(logging.INFO)
try:
answer = run_agent(make_client(), question, Limits(max_steps=max_steps))
except AgentError as exc:
typer.secho(f"Abbruch: {exc}", fg="red", err=True)
raise typer.Exit(code=1) from exc
except openai.APIConnectionError:
typer.secho("Fehler: LLM nicht erreichbar (läuft Ollama?)", fg="red", err=True)
raise typer.Exit(code=1) from None
typer.echo(answer)
EOF
cat > src/ops_agent/__init__.py <<'EOF'
"""ops-agent – Fragen über diesen Rechner, beantwortet mit read-only Tools."""
from ops_agent.cli import app
def main() -> None:
app()
EOF
cat > src/ops_agent/__main__.py <<'EOF'
from ops_agent import main
main()
EOF
uv run ops-agent -v "Wie voll ist meine Festplatte und wie hoch ist die Last?"
uv run ops-agent --max-steps 1 "Welche Prozesse fressen CPU?"; echo "exit=$?"Expected (values and text vary):
Schritt 1: load_average({}) -> {"load_1m": 6.91, "load_5m": 8.35, "load
Schritt 1: disk_usage({"path":"/"}) -> {"total_gb": 228.3, "used_gb": 213.7, "f
Deine Festplatte ist mit **93,6 %** voll (ca. **213,7 GB aus 228,3 GB**). Die
CPU-Last liegt bei **6,9 pro Minute** und es sind **10 CPUs** verfügbar. Die
aktuelle Systemlast ist hoch.
Abbruch: Keine Antwort nach 1 Schritten
exit=1
Why two tools in step 1? Parallel tool calls: one
response may contain several calls, and run_agent works
through them in order. The wording matters: with “Platte” instead of
“Festplatte” (both mean “disk”), the 3B model at
temperature=0 only calls load_average and
drops half the question. And “6,9 pro Minute” (6.9 per minute) is a
misreading – load is an average of waiting processes, not a rate. The
numbers are right; you check the interpretations yourself.
Security: Tool results are unchecked input for the model. If a tool reads log files or web pages, they may contain “Ignore all rules and …” (prompt injection). That is why you use read-only tools, an allowlist and no tools that build commands from model text.
Save your progress? Sign up for free
Drill 7: The same tools as an MCP server
The MCP server reads the type hints just like
openai_tools() – you only register the functions.
cat > src/ops_agent/mcp_server.py <<'EOF'
"""MCP-Server: dieselben read-only Tools für Claude, IDEs und andere Agenten."""
from mcp.server.mcpserver import MCPServer
from mcp.types import ToolAnnotations
from ops_agent.tools import TOOLS
server = MCPServer("ops-tools", instructions="Read-only Infos über diesen Rechner.")
for fn in TOOLS.values():
server.add_tool(fn, annotations=ToolAnnotations(read_only_hint=True))
def main() -> None:
server.run() # Standard-Transport: stdio
EOF
perl -pi -e 's/^(ops-agent = .*)$/$1\nops-mcp = "ops_agent.mcp_server:main"/' \
pyproject.toml
grep -A2 'project.scripts' pyproject.tomlExpected:
[project.scripts]
ops-agent = "ops_agent:main"
ops-mcp = "ops_agent.mcp_server:main"
An MCP server over stdio speaks JSON-RPC on stdin/stdout – in the terminal you see none of it. Test it with the client from the SDK, which starts the server as a subprocess:
cat > mcp_check.py <<'EOF'
"""Startet den MCP-Server per stdio und ruft seine Tools wie ein Client auf."""
import asyncio
from mcp import Client, StdioServerParameters
from mcp.types import TextContent
async def main() -> None:
params = StdioServerParameters(command="uv", args=["run", "-q", "ops-mcp"])
async with Client(params) as client:
listing = await client.list_tools()
for tool in listing.tools:
ro = tool.annotations.read_only_hint if tool.annotations else None
print(f"{tool.name:14} read_only={ro} {(tool.description or '')[:40]}")
ok = await client.call_tool("disk_usage", {"path": "/"})
print("disk_usage:", ok.structured_content)
bad = await client.call_tool("top_processes", {"n": 99})
block = bad.content[0]
text = block.text if isinstance(block, TextContent) else ""
print("Fehlerfall:", bad.is_error, text[:60])
asyncio.run(main())
EOF
uv run python mcp_check.py 2>/dev/nullExpected (values abridged):
disk_usage read_only=True Belegung des Dateisystems, auf dem PATH
load_average read_only=True Systemlast der letzten 1, 5 und 15 Minut
top_processes read_only=True Die N Prozesse mit der höchsten CPU-Last
disk_usage: {'total_gb': 228.3, 'used_gb': 213.4, 'free_gb': 14.9, 'percent': 93.5}
Fehlerfall: True Error executing tool top_processes: 1 validation error for top_process
Why 2>/dev/null? stdout belongs to the protocol, so
the server logs to stderr
(e.g. Tool 'top_processes' rejected arguments). In an MCP
server you must never print() to stdout –
that destroys the JSON-RPC stream. read_only_hint tells
clients like Claude that the tool changes nothing; some of them then
stop asking for confirmation.
Save your progress? Sign up for free
Drill 8: Tests – agent without a model, MCP without a process
The fake client returns real ChatCompletionMessage
objects; the MCP test connects mcp.Client directly to the
server object in the same process.
mkdir -p tests
cat > tests/test_ops_agent.py <<'EOF'
import asyncio
import json
import subprocess
from types import SimpleNamespace as NS
from typing import Any
from unittest.mock import MagicMock
import pytest
from mcp import Client
from openai.types.chat import ChatCompletionMessage
from ops_agent import tools
from ops_agent.agent import AgentError, Limits, run_agent, run_tool
from ops_agent.mcp_server import server
def reply(content: str | None = None, calls: list[Any] | None = None) -> NS:
msg = ChatCompletionMessage.model_validate(
{"role": "assistant", "content": content, "tool_calls": calls}
)
return NS(choices=[NS(message=msg)])
def call(name: str, args: str = "{}") -> dict[str, Any]:
fn = {"name": name, "arguments": args}
return {"id": "c1", "type": "function", "function": fn}
def test_disk_usage_rejects_relative_path() -> None:
with pytest.raises(ValueError):
tools.disk_usage("etc")
def test_top_processes_parses_ps(monkeypatch: pytest.MonkeyPatch) -> None:
out = " 1 0.5 /sbin/launchd\n 42 12.0 /usr/bin/python3 -m x\n"
fake = MagicMock(return_value=NS(stdout=out))
monkeypatch.setattr(subprocess, "run", fake)
rows = tools.top_processes(n=1)
assert rows == [{"pid": 42, "cpu": 12.0, "cmd": "python3 -m x"}]
@pytest.mark.parametrize(
("name", "args", "expected"),
[
("rm_rf", "{}", "unbekanntes Tool"),
("top_processes", '{"n": 99}', "ValidationError"),
("disk_usage", "{kaputt", "JSONDecodeError"),
],
)
def test_run_tool_guardrails(name: str, args: str, expected: str) -> None:
assert expected in run_tool(name, args)
def test_agent_calls_tool_then_answers() -> None:
client = MagicMock()
client.chat.completions.create.side_effect = [
reply(calls=[call("load_average")]),
reply("Last ist niedrig."),
]
assert run_agent(client, "Last?") == "Last ist niedrig."
messages = client.chat.completions.create.call_args.kwargs["messages"]
assert messages[-1]["role"] == "tool"
assert "load_1m" in json.loads(messages[-1]["content"])
def test_agent_stops_after_max_steps() -> None:
client = MagicMock()
client.chat.completions.create.return_value = reply(calls=[call("load_average")])
with pytest.raises(AgentError, match="2 Schritten"):
run_agent(client, "Endlos?", Limits(max_steps=2))
def test_mcp_server_lists_all_tools() -> None:
async def names() -> set[str]:
async with Client(server) as client:
return {t.name for t in (await client.list_tools()).tools}
assert asyncio.run(names()) == set(tools.TOOLS)
EOF
uv run pytest -q
uv run ruff check . && uv run --with mypy mypy --strict srcExpected:
........ [100%]
8 passed in 0.52s
All checks passed!
Success: no issues found in 6 source files
Why asyncio.run in the test? The MCP SDK is async. For a
single test you don’t need a plugin like pytest-asyncio; a
small async def plus asyncio.run is enough.
test_agent_stops_after_max_steps proves the most important
property: the agent stops.
Save your progress? Sign up for free
Drill 9: The tool is done
uv tool install --editable .
cd ~
ops-agent "Wie viel Platz ist auf / noch frei?"
ops-agent --help | head -3Expected (text varies):
Installed 2 executables: ops-agent, ops-mcp
Auf dem Root-Pfad `/` sind noch **14,6 GB** frei, das entspricht etwa **6,4 %**
der Gesamtkapazität.
Usage: ops-agent [OPTIONS] {question}
You register the MCP server in Claude Code with a single command
(syntax per claude mcp add --help, not executed here
because it changes your Claude configuration):
claude mcp add ops-tools -- uv --directory ~/py-lab/tag12-ops-agent run -q ops-mcpExpected (abridged, may differ by version):
Added stdio MCP server ops-tools with command: uv --directory ... run -q ops-mcp
Why uv --directory? The client starts the server from an
arbitrary working directory; this way uv still finds the right project
and venv.
Save your progress? Sign up for free
Checkpoint
cd ~/py-lab/tag12-ops-agent
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
check "Tests grün" "uv run pytest -q"
check "ruff sauber" "uv run ruff check ."
check "mypy --strict sauber" "uv run --with mypy mypy --strict src"
G='from ops_agent.agent import run_tool; print(run_tool("shell", "{}"))'
check "Guardrail: unbekanntes Tool" "uv run python -c '$G' | grep -q unbekannt"
check "MCP-Server antwortet" "uv run python mcp_check.py | grep -q read_only=True"
check "Agent antwortet" "uv run ops-agent 'Wie hoch ist die Last?' | grep -q ."
check "Abbruch mit Exit 1" "! uv run ops-agent --max-steps 1 'Prozesse?'"Expected:
✔ Tests grün
✔ ruff sauber
✔ mypy --strict sauber
✔ Guardrail: unbekanntes Tool
✔ MCP-Server antwortet
✔ Agent antwortet
✔ Abbruch mit Exit 1
Challenge
Add a fourth read-only tool file_age(path) that returns
the age of a file in hours – but only under /var/log and
~/py-lab. A path like
~/py-lab/../.ssh/id_ed25519 must fail. The agent and the
MCP server should know the tool without any further change.
Hint: First Path.resolve(), then
is_relative_to() – in this order, otherwise ..
and symlinks slip through.
Solution
In src/ops_agent/tools.py, add the imports
import time and from pathlib import Path and
replace TOOLS like this:
ALLOWED_ROOTS = [Path("/var/log"), Path.home() / "py-lab"]
def file_age(
path: Annotated[str, Field(description="Datei unter /var/log oder ~/py-lab")],
) -> dict[str, Any]:
"""Alter einer Datei in Stunden (nur unter erlaubten Verzeichnissen)."""
target = Path(path).expanduser().resolve()
if not any(target.is_relative_to(r.resolve()) for r in ALLOWED_ROOTS):
raise ValueError(f"{target} liegt außerhalb der erlaubten Verzeichnisse")
hours = (time.time() - target.stat().st_mtime) / 3600
return {"path": str(target), "age_h": round(hours, 1)}
TOOLS: dict[str, Callable[..., Any]] = {
f.__name__: f for f in (disk_usage, load_average, top_processes, file_age)
}Add the test (from pathlib import Path at the top of the
test file) and run it:
cat >> tests/test_ops_agent.py <<'EOF'
def test_file_age_blocks_escape(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(tools, "ALLOWED_ROOTS", [tmp_path])
(tmp_path / "app.log").write_text("x")
assert tools.file_age(str(tmp_path / "app.log"))["age_h"] == 0.0
with pytest.raises(ValueError, match="außerhalb"):
tools.file_age(str(tmp_path / ".." / "geheim.txt"))
EOF
uv run pytest -q
uv run ops-agent -v "Wie alt ist /var/log/system.log?"Expected (values vary):
......... [100%]
9 passed in 1.50s
Schritt 1: file_age({"path":"/var/log/system.log"}) -> {"path": "/private/var/log/
Die Datei `/var/log/system.log` ist etwa **0,1 Stunden** (ca. **6 Minuten**) alt.
Why /private/var/log? On macOS, /var is a
symlink. resolve() shows the real path – which is exactly
why every allowed root is resolved before the comparison, too.
Save your progress? Sign up for free
Enterprise Note
- Separate tools by risk: read-only ones freely, writing ones only with confirmation by a human (human in the loop) and a dedicated service account with minimal permissions.
- Audit every tool call with arguments, result size and user (structured logs, OpenTelemetry spans per step).
- Run MCP servers over HTTP only with authentication (OAuth/token), TLS and rate limits; stdio servers run with the permissions of the user who starts them.
- Treat MCP servers from third parties like dependencies: review the code, pin the version, check tool descriptions for hidden instructions (tool poisoning).
- Enforce cost and time budgets per request centrally, not just in the client; watch aborts as a metric.