Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

fix(mcp-fixer): stop the repair agent mutating cloud infrastructure (#887)

Aurora Capitalb55b52d25f76
diff --git a/claude-ops/hooks/mcp-fixer-infra-guard.py b/claude-ops/hooks/mcp-fixer-infra-guard.py
new file mode 100755
index 00000000..4e5f1bfa
--- /dev/null
+++ b/claude-ops/hooks/mcp-fixer-infra-guard.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""PreToolUse guard for the headless MCP fixer agent.
+
+The fixer is dispatched unattended by ops-mcp-watchdog and runs with
+`--dangerously-skip-permissions`, so it inherits whatever cloud credentials the
+user's shell has. Its remit is local MCP servers and the services backing them;
+it has no reason to mutate cloud infrastructure.
+
+This exists because of a real incident. A fixer run dispatched for an unrelated
+`whatsapp: unreachable` fault decided the fix was to stop an EC2 instance. It
+first cleared the instance's stop-protection attribute, then stopped it. That
+instance hosted the user's LLM proxy, so the action took down every model call
+on the machine, including the fixer's own, which then failed on the resulting
+gateway error. Two hours of debugging pointed at the proxy before anyone
+suspected the repair agent.
+
+Prompt wording alone does not prevent this; a denied tool call does. Read-only
+calls stay allowed, because diagnosis legitimately needs them.
+
+Contract: PreToolUse hook. Reads the tool call as JSON on stdin, writes a JSON
+permission decision on stdout. Unmatched commands are allowed. Never raises:
+a guard that crashes the fixer is worse than the fault it guards against.
+"""
+
+import json
+import re
+import sys
+
+# (pattern, human-readable reason). Matched against the whitespace-normalised
+# command so `aws ec2 stop-instances` cannot slip through on spacing, and
+# with the subcommand decoupled from the service word so a global flag placed
+# before it (`aws --region x ec2 stop-instances`) still matches.
+DENY_PATTERNS = [
+ # EC2 lifecycle, and the attribute that gates it. modify-instance-attribute
+ # matters as much as stop-instances: it is how stop-protection gets cleared
+ # immediately before a stop.
+ (r"\baws\b.*\bec2\b.*\b(stop|terminate|reboot)-instances\b",
+ "stopping, terminating or rebooting EC2 instances"),
+ (r"\baws\b.*\bec2\b.*\bmodify-instance-attribute\b",
+ "modifying EC2 instance attributes, including stop-protection"),
+ (r"\baws\b.*\bec2\b.*\b(delete|release|disassociate|detach)-\w+",
+ "deleting or releasing EC2 resources"),
+ (r"\baws\b.*\bec2\b.*\b(revoke|authorize)-security-group-\w+",
+ "changing security group rules"),
+ # IAM. Listed explicitly because an agent that hits an explicit-deny policy
+ # can otherwise decide the fix is to remove the policy.
+ (r"\baws\b.*\biam\b.*\b(delete|put|attach|detach|create|update)-\w+",
+ "changing IAM identities or policies"),
+ (r"\baws\b.*\b(rds|elasticache|dynamodb)\b.*\b(delete|stop|reboot|modify)-\w+",
+ "mutating managed database or cache resources"),
+ (r"\baws\b.*\b(globalaccelerator|cloudfront|route53|elbv2|elb)\b"
+ r".*\b(delete|update|remove|deregister|disable)\w*",
+ "mutating edge, DNS or load-balancer configuration"),
+ # `rb` removes a bucket outright and takes --force rather than --recursive,
+ # so keying only on --recursive would miss the more destructive of the two.
+ (r"\baws\b.*\bs3\b.*\brb\b",
+ "removing an S3 bucket"),
+ (r"\baws\b.*\bs3\b.*\brm\b.*--recursive",
+ "recursive S3 deletion"),
+ (r"\baws\b.*\bs3api\b.*\bdelete-\w+",
+ "S3 deletion"),
+ (r"\bgcloud\b.*\b(compute|sql)\b.*\b(delete|stop|reset)\b",
+ "mutating GCP compute or SQL resources"),
+ (r"\baz\b\s+(vm|group|sql)\b.*\b(delete|stop|deallocate)\b",
+ "mutating Azure resources"),
+ (r"\bssh\b.*\b(shutdown|halt|poweroff|reboot)\b",
+ "shutting down or rebooting a remote host"),
+ # Global options may sit between the binary and the subcommand
+ # (`terraform -chdir=/infra destroy`), so do not require adjacency.
+ (r"\bterraform\b[^;&|]*\b(destroy|apply)\b",
+ "applying or destroying Terraform state"),
+]
+
+COMPILED = [(re.compile(p, re.IGNORECASE), why) for p, why in DENY_PATTERNS]
+
+# A dry run asks the API to validate and change nothing, which is exactly the
+# kind of read a diagnosing agent should be encouraged to make. The exemption is
+# applied per segment, never to the whole input: in
+# `aws ec2 describe-instances --dry-run && aws ec2 stop-instances ...` the flag
+# belongs to the harmless half, and honouring it globally would wave the real
+# command through.
+DRY_RUN = re.compile(r"--dry-run\b", re.IGNORECASE)
+
+# Shell operators that separate one command from the next. Splitting on these
+# can only make the guard stricter: a destructive command still lies wholly
+# within one segment, while a flag can no longer vouch for its neighbours.
+SEGMENT_SEPARATORS = re.compile(r"&&|\|\||[;\n|]")
+
+REASON_SUFFIX = (
+ "This agent repairs local MCP servers and must not mutate cloud "
+ "infrastructure. A previous run stopped the EC2 instance hosting the LLM "
+ "proxy and took every model call on the machine down with it. If cloud "
+ "infrastructure really is the root cause, that is a useful finding: do not "
+ "act on it. Send one desktop notification naming the resource and the "
+ "evidence, then stop."
+)
+
+
+def denial_reason(command):
+ """Return a reason string if the command must be blocked, else None.
+
+ Each shell segment is judged on its own so that a --dry-run in one command
+ cannot exempt a real mutation chained after it.
+ """
+ for segment in SEGMENT_SEPARATORS.split(command):
+ normalised = " ".join(segment.split())
+ if not normalised or DRY_RUN.search(normalised):
+ continue
+ for pattern, why in COMPILED:
+ if pattern.search(normalised):
+ return why
+ return None
+
+
+def main():
+ try:
+ payload = json.load(sys.stdin)
+ except Exception:
+ return 0
+
+ if payload.get("tool_name") != "Bash":
+ return 0
+
+ command = payload.get("tool_input", {}).get("command", "")
+ if not command:
+ return 0
+
+ why = denial_reason(command)
+ if why is None:
+ return 0
+
+ json.dump(
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": (
+ f"BLOCKED by mcp-fixer-infra-guard: {why}. {REASON_SUFFIX}"
+ ),
+ }
+ },
+ sys.stdout,
+ )
+ sys.stdout.write("\n")
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except Exception:
+ sys.exit(0)
diff --git a/claude-ops/scripts/ops-mcp-fixer.sh b/claude-ops/scripts/ops-mcp-fixer.sh
index e5c87dff..0f62b080 100755
--- a/claude-ops/scripts/ops-mcp-fixer.sh
+++ b/claude-ops/scripts/ops-mcp-fixer.sh
@@ -94,9 +94,48 @@ Approach:
5. ONLY if it still fails after 2 attempts: send exactly one desktop notification (osascript on macOS, notify-send on Linux) naming each server, the cause, and the concrete manual action (max 200 chars). On success: NO notification.
6. Write a 1-3 line summary of what you did to ~/.claude/state/mcp-watchdog/fixer-last-result.txt
-Hard limits: delete nothing outside npx caches, never enter passwords, no browser logins, no outbound messages (mail/chat/SMS)."
+Hard limits: delete nothing outside npx caches, never enter passwords, no browser logins, no outbound messages (mail/chat/SMS).
-"$CLAUDE_BIN" -p "$PROMPT" --dangerously-skip-permissions --max-turns "$MAX_TURNS" >> "$LOG" 2>&1
+CLOUD INFRASTRUCTURE IS OUT OF SCOPE. Your remit is local MCP servers and the services backing them. Never stop, reboot, terminate or reconfigure cloud resources (EC2, RDS, IAM, security groups, Global Accelerator, CloudFront, Route53, Terraform), on any cloud, for any reason. Read-only calls for diagnosis are fine. A previous fixer run chasing an unrelated MCP fault stopped the EC2 instance hosting the LLM proxy, which took down every model call on the machine including its own. If you conclude cloud infrastructure is the root cause, that is a correct and useful finding: do not act on it, send one desktop notification naming the resource and the evidence, and stop."
+
+# ── Infra guard ──────────────────────────────────────────────────────────────
+# The prompt above is guidance; this is not. A PreToolUse hook denies
+# destructive cloud commands however the agent phrases them. --settings needs an
+# absolute path to the hook, so the file is generated per run rather than
+# shipped, which also keeps it correct when the plugin moves between versioned
+# install directories.
+GUARD_HOOK="$SCRIPT_DIR/../hooks/mcp-fixer-infra-guard.py"
+GUARD_ARGS=()
+if [ -f "$GUARD_HOOK" ]; then
+ GUARD_SETTINGS="$STATE_DIR/fixer-guard-settings.json"
+ python3 - "$GUARD_HOOK" > "$GUARD_SETTINGS" <<'PY'
+import json, sys
+hook = sys.argv[1]
+json.dump({"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [
+ {"type": "command", "command": f'/usr/bin/env python3 "{hook}"', "timeout": 8}
+]}]}}, sys.stdout)
+PY
+ if [ -s "$GUARD_SETTINGS" ]; then
+ GUARD_ARGS=(--settings "$GUARD_SETTINGS")
+ fi
+fi
+if [ ${#GUARD_ARGS[@]} -eq 0 ]; then
+ # Never fail open silently: an unguarded fixer is exactly how the incident above happened.
+ log "WARNING: infra guard unavailable ($GUARD_HOOK) — running unguarded"
+ notify "MCP fixer running unguarded" "infra guard missing — destructive cloud commands are not blocked"
+fi
+
+"$CLAUDE_BIN" -p "$PROMPT" \
+ --dangerously-skip-permissions \
+ "${GUARD_ARGS[@]}" \
+ --disallowedTools \
+ "Bash(aws ec2 stop-instances:*)" \
+ "Bash(aws ec2 terminate-instances:*)" \
+ "Bash(aws ec2 reboot-instances:*)" \
+ "Bash(aws ec2 modify-instance-attribute:*)" \
+ "Bash(aws iam:*)" \
+ "Bash(terraform destroy:*)" \
+ --max-turns "$MAX_TURNS" >> "$LOG" 2>&1
RC=$?
log "fixer agent done (exit $RC)"
diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.sh
index 635471f2..4e825de9 100755
--- a/claude-ops/tests/run-all.sh
+++ b/claude-ops/tests/run-all.sh
@@ -66,6 +66,7 @@ run_suite "$TESTS_DIR/test-ops-daemon-manager.sh"
run_suite "$TESTS_DIR/test-ops-package.sh"
run_suite "$TESTS_DIR/test-safety-hooks.sh"
run_suite "$TESTS_DIR/outbound-guard/run.sh"
+run_suite "$TESTS_DIR/test-mcp-fixer-infra-guard.sh"
run_suite "$TESTS_DIR/test-deploy-fix-hooks.sh"
run_suite "$TESTS_DIR/test-deploy-fix-fleet.sh"
run_suite "$TESTS_DIR/test-cloudflare-dns-lib.sh"
diff --git a/claude-ops/tests/test-mcp-fixer-infra-guard.sh b/claude-ops/tests/test-mcp-fixer-infra-guard.sh
new file mode 100755
index 00000000..e1e4e5a7
--- /dev/null
+++ b/claude-ops/tests/test-mcp-fixer-infra-guard.sh
@@ -0,0 +1,147 @@
+#!/usr/bin/env bash
+# Checks the MCP fixer's infra guard blocks destructive cloud commands and lets
+# the fixer's real work through.
+#
+# The cases live inside this file rather than on the command line for the same
+# reason as the outbound-guard suite: a machine running this may itself have a
+# PreToolUse guard watching Bash commands, and a test that spelled the patterns
+# out as arguments would be blocked before it ran.
+#
+# run-all.sh invokes suites with bash, so the Python driver is embedded here
+# rather than registered as a .py suite.
+set -uo pipefail
+
+HERE="$(cd "$(dirname "$0")" && pwd)"
+HOOK="${MCP_FIXER_INFRA_HOOK:-$HERE/../hooks/mcp-fixer-infra-guard.py}"
+
+if [ ! -f "$HOOK" ]; then
+ echo "FAIL: infra guard hook not found at $HOOK"
+ exit 1
+fi
+
+# The fixer wires the hook in itself; if that wiring is dropped the guard is
+# inert no matter how well it matches, so assert the invocation too.
+FIXER="$HERE/../scripts/ops-mcp-fixer.sh"
+if ! grep -q -- "--settings" "$FIXER"; then
+ echo "FAIL: ops-mcp-fixer.sh no longer passes --settings; the guard would not load"
+ exit 1
+fi
+if ! grep -q "mcp-fixer-infra-guard.py" "$FIXER"; then
+ echo "FAIL: ops-mcp-fixer.sh no longer references the guard hook"
+ exit 1
+fi
+
+python3 - "$HOOK" <<'PY'
+import json
+import subprocess
+import sys
+
+HOOK = sys.argv[1]
+
+# The two commands from the incident that motivated this guard, plus the
+# evasions worth caring about: extra spacing, and a global flag placed before
+# the service word.
+MUST_BLOCK = [
+ ("stop an instance", "aws ec2 stop-instances --instance-ids i-0123456789abcdef0"),
+ ("clear stop-protection", "aws ec2 modify-instance-attribute --instance-id i-0123456789abcdef0 --no-disable-api-stop"),
+ ("spacing evasion", "aws ec2 stop-instances --instance-ids i-0123456789abcdef0"),
+ ("global flag first", "aws --region us-east-1 ec2 terminate-instances --instance-ids i-0123456789abcdef0"),
+ ("reboot an instance", "aws ec2 reboot-instances --instance-ids i-0123456789abcdef0"),
+ ("security group edit", "aws ec2 revoke-security-group-ingress --group-id sg-0123 --port 443"),
+ ("remove its own guard policy", "aws iam delete-user-policy --user-name someone --policy-name deny-stop"),
+ ("stop a database", "aws rds stop-db-instance --db-instance-identifier prod"),
+ ("delete an accelerator", "aws globalaccelerator delete-accelerator --accelerator-arn arn:aws:x"),
+ ("recursive bucket wipe", "aws s3 rm s3://some-bucket/ --recursive"),
+ ("remote shutdown", "ssh user@host sudo shutdown -h now"),
+ ("terraform destroy", "terraform destroy -auto-approve"),
+ # A flag in one segment must not vouch for the next. Without per-segment
+ # evaluation the --dry-run here exempted the whole string, which is the
+ # most dangerous shape this guard can be in: it reads as protected.
+ ("dry-run does not exempt a chained mutation",
+ "aws ec2 describe-instances --dry-run && aws ec2 stop-instances --instance-ids i-0123456789abcdef0"),
+ ("mutation after a semicolon",
+ "echo starting; aws ec2 terminate-instances --instance-ids i-0123456789abcdef0"),
+ ("mutation piped onward",
+ "aws ec2 stop-instances --instance-ids i-0123456789abcdef0 | tee /tmp/out"),
+ # rb takes --force, not --recursive, and removes the bucket outright.
+ ("bucket removal with --force", "aws s3 rb s3://some-bucket --force"),
+ # Global options may precede the subcommand.
+ ("terraform behind a global flag", "terraform -chdir=/infra destroy -auto-approve"),
+]
+
+# Everything the fixer legitimately does, including read-only cloud diagnosis.
+MUST_PASS = [
+ ("describe instances", "aws ec2 describe-instances --instance-ids i-0123456789abcdef0"),
+ ("dry run is a read", "aws ec2 stop-instances --instance-ids i-0123456789abcdef0 --dry-run"),
+ ("ssm port forward", "aws ssm start-session --target i-0123456789abcdef0 --document-name AWS-StartPortForwardingSessionToRemoteHost"),
+ ("restart a launchd service", "launchctl kickstart -k gui/501/com.example.service"),
+ ("restart a systemd service", "ssh user@host sudo systemctl restart someservice"),
+ ("clear an npx cache entry", "rm -rf ~/.npm/_npx/abc123"),
+ ("probe a local MCP", "curl -sS http://127.0.0.1:8092/health"),
+ ("read cloudtrail", "aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=StopInstances"),
+ # The exemption is per segment, so it still holds when the dry run is the
+ # segment that carries it.
+ ("read chained with a genuine dry run",
+ "aws ec2 describe-instances && aws ec2 stop-instances --instance-ids i-0123456789abcdef0 --dry-run"),
+ ("single object delete is not a bucket wipe", "aws s3 rm s3://some-bucket/one-file.txt"),
+ ("non-Bash tool is ignored", None),
+]
+
+
+def blocked(command, tool="Bash"):
+ payload = {"tool_name": tool, "tool_input": {"command": command} if command else {}}
+ out = subprocess.run(
+ ["python3", HOOK],
+ input=json.dumps(payload),
+ capture_output=True,
+ text=True,
+ timeout=15,
+ )
+ if out.returncode != 0:
+ raise AssertionError(f"hook exited {out.returncode}: {out.stderr[:200]}")
+ if not out.stdout.strip():
+ return False
+ decision = json.loads(out.stdout)
+ return decision["hookSpecificOutput"]["permissionDecision"] == "deny"
+
+
+failures = 0
+
+for name, command in MUST_BLOCK:
+ try:
+ if blocked(command):
+ print(f" ok blocked: {name}")
+ else:
+ print(f" FAIL allowed but must block: {name}")
+ failures += 1
+ except Exception as exc:
+ print(f" FAIL errored on {name}: {exc}")
+ failures += 1
+
+for name, command in MUST_PASS:
+ try:
+ tool = "Bash" if command else "Read"
+ if blocked(command, tool=tool):
+ print(f" FAIL blocked but must allow: {name}")
+ failures += 1
+ else:
+ print(f" ok allowed: {name}")
+ except Exception as exc:
+ print(f" FAIL errored on {name}: {exc}")
+ failures += 1
+
+# A guard that crashes the fixer is worse than the fault it guards against, so
+# malformed input must be a silent allow rather than a traceback.
+malformed = subprocess.run(
+ ["python3", HOOK], input="not json", capture_output=True, text=True, timeout=15
+)
+if malformed.returncode == 0 and not malformed.stdout.strip():
+ print(" ok malformed input allows rather than crashing")
+else:
+ print(f" FAIL malformed input: rc={malformed.returncode} out={malformed.stdout[:80]}")
+ failures += 1
+
+total = len(MUST_BLOCK) + len(MUST_PASS) + 1
+print(f"\nmcp-fixer-infra-guard: {total - failures}/{total} checks passed")
+sys.exit(1 if failures else 0)
+PY