r/MCPservers • u/Upbeat-Bus2143 • 6h ago
How to guard MCP tool calls with deterministic PreToolUse hooks (Python pattern + pitfalls)
When connecting coding agents to external MCP servers, most setups rely on prompt instructions or coarse-grained server-level allowlists. The gap is that an agent can still invoke an approved MCP tool with dangerous arguments (e.g., querying prod tables with unparameterized SQL, reading `.env` / SSH keys via a filesystem MCP server, or exfiltrating secrets through a fetch/HTTP MCP tool).
A clean defense-in-depth pattern is adding a deterministic `PreToolUse` hook on the agent client side that inspects every `mcp__<server>__<tool>` invocation *before* the JSON-RPC `tools/call` request ever leaves the host.
1. Why `PreToolUse` instead of prompt rules alone?
- **Deterministic:** Runs as an out-of-band subprocess before execution; prompt injection inside a repo or issue body cannot override it.
- **Argument-level inspection:** Unlike static allow/deny lists per tool name, you can inspect `tool_input` fields (SQL strings, file paths, target hosts, flags).
- **Fast fail with feedback:** Returning exit code `2` (or a structured JSON `permissionDecision: "deny"` with a reason) blocks the call and feeds the exact policy reason back to the model so it can self-correct.
2. Minimal Python `PreToolUse` guard for MCP tools
```python import json import re import sys
SENSITIVE_PATH_RE = re.compile( r"(^|/)(?:\.env(?:\..*)?|id_rsa|id_ed25519|\.aws/credentials|\.npmrc)$", re.IGNORECASE, ) DANGEROUS_SQL_RE = re.compile( r"\b(DROP|TRUNCATE|ALTER|DELETE\s+FROM|GRANT)\b", re.IGNORECASE, )
def main() -> int: payload = json.load(sys.stdin) tool_name = payload.get("tool_name", "") tool_input = payload.get("tool_input") or {}
# Only inspect MCP tool calls (e.g. mcp__postgres__query, mcp__fs__read_file)
if not tool_name.startswith("mcp__"):
return 0
parts = tool_name.split("__", 2)
server = parts\[1\] if len(parts) > 1 else ""
action = parts\[2\] if len(parts) > 2 else ""
# 1. Block filesystem MCP reads/writes on credential files
for key in ("path", "file_path", "target", "uri"):
val = str(tool_input.get(key, ""))
if val and SENSITIVE_PATH_RE.search(val.replace("\\\\", "/")):
print(f"Blocked MCP call {tool_name}: access to sensitive path '{val}' is denied.", file=sys.stderr)
return 2
# 2. Enforce read-only guardrails on database MCP servers
if server in {"postgres", "sqlite", "mysql"} or "query" in action:
sql = str(tool_input.get("sql") or tool_input.get("query") or "")
if DANGEROUS_SQL_RE.search(sql):
print(f"Blocked MCP call {tool_name}: mutating SQL statement requires manual approval.", file=sys.stderr)
return 2
return 0if __name__ == "__main__": raise SystemExit(main()) ```
3. Three subtle pitfalls when writing MCP `PreToolUse` hooks
- **Path normalization & traversal:** Always resolve symlinks / `..` segments (or normalize Windows backslashes) before matching paths—otherwise `./configs/../.env` slips past naive substring checks.
- **Argument schema variance across MCP servers:** One filesystem MCP server uses `path`, another uses `file_path` or `paths: [...]` (list). Flatten nested dicts/lists in `tool_input` if you want universal secret-path protection.
- **Fail-closed on malformed JSON:** If your hook throws an unhandled exception on unexpected `tool_input` types, some clients treat non-zero exit codes other than `2` as "hook error, continue anyway." Catch `Exception` and explicitly deny/log if strict enforcement is required.
Curious how others here are handling argument-level policies for MCP servers—are you validating inside the MCP server itself, via client `PreToolUse` hooks, or through an MCP proxy?