Sub topic 13
Securing tools that touch real systems
This chapter assumes you have built a server with FastMCP, understand typed tool schemas, and know the stdio and Streamable HTTP transports. Here you will harden tools that act on real systems. Your server is a bridge between a model and your infrastructure, so treat every call as untrusted input.
The threat model
A model chooses tool arguments from text it has read. That text may include a web page, a ticket, or a log line written by someone else. An attacker can hide instructions in that text (prompt injection) and steer the model into calling your tools with harmful arguments. Your server cannot tell whether the model or an attacker wrote the arguments. So the server must enforce its own limits.
Apply least privilege
Give the server only the access its tools need. If a tool reads deploy history, its API token should be read-only. Do not reuse an admin token because it is convenient.
- Create a dedicated service account for the server.
- Scope its token to the exact APIs the tools call.
- Read credentials from environment variables, never from tool arguments or source code.
- Split read tools and write tools into separate servers when their risk differs. A team can then enable the safe one by default.
Validate every input
Schema types are the first check, but they are not enough. A str parameter accepts any text. Add constraints, and then check against an allowlist before touching a real system.
import os
import re
import subprocess
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("team-tools")
ALLOWED_SERVICES = {"billing", "search"}
SERVICE_PATTERN = re.compile(r"^[a-z][a-z0-9-]{1,30}$")
@mcp.tool()
def restart_worker(service: str) -> str:
"""Restart the worker for a service. Changes production state."""
if not SERVICE_PATTERN.fullmatch(service) or service not in ALLOWED_SERVICES:
raise ValueError(f"Service not allowed: {service!r}")
# Pass arguments as a list. Never build a shell string from model input.
result = subprocess.run(
["systemctl", "restart", f"{service}-worker"],
capture_output=True,
text=True,
timeout=30,
env={"PATH": os.environ.get("PATH", "")},
)
if result.returncode != 0:
raise RuntimeError("Restart failed. Check the service logs.")
return f"Restarted {service}-worker."
if __name__ == "__main__":
mcp.run()This tool does four things:
- It matches the name against a strict pattern.
- It checks the name against an allowlist, so even a well-formed name must be known.
- It passes a list to
subprocess.run, which avoids shell injection. - It sets a timeout and a minimal environment, so secrets in your process environment do not leak to the child.
The error message does not echo stderr. Raw command output can contain internal paths or tokens, and the model would pass it on to the user. Log the details to stderr on the server and return a short message.
Require user confirmation
Validation limits what a tool can do. Confirmation decides whether it should happen now. MCP lets the host show tool calls to the user before running them, and the protocol expects hosts to keep a human in the loop for sensitive actions. You cannot force a host to do this, so help it:
- State side effects in the description, as
restart_workerdoes ("Changes production state"). - Mark read-only tools clearly, so hosts can auto-approve them and prompt for the rest.
- Make dangerous operations two-step. A
plan_cleanuptool returns what would be deleted. A separateapply_cleanuptool performs it.
Protect the transport
Stdio servers run as your user and inherit your access, so only configure servers you trust. For Streamable HTTP, add authentication. Never expose an unauthenticated server on a network. Bind to 127.0.0.1 unless remote access is required, serve over TLS, and check the Origin header to block malicious web pages from reaching a local server.
Log and audit
Record each call with the tool name, arguments, caller, and outcome. Write logs to stderr or a file, never stdout on stdio. Redact tokens and personal data before logging.
Exercise
A tool takes a path: str and returns the file contents. Name two risks and one fix for each.
Show answer
Risk 1 is path traversal, such as ../../etc/passwd. Fix it by resolving the path and checking that it sits inside an allowed directory. Risk 2 is reading secrets, such as .env files. Fix it with an allowlist of readable files or extensions, and run the server with a account that cannot read secrets.