Flag High-Cost MCP Tool Calls Above a Session Threshold

Some external MCP tools carry a real per-call cost (a paid data API, a billed third-party service) that's easy to lose track of inside a long session. This counts calls to a configured set of tool names and warns past a threshold, without blocking the legitimate use that got it there.

Cost & Usage Controls Event: PreToolUse Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""PreToolUse hook — warns once a configured expensive MCP tool is
called more than a session threshold. Wire to matcher "mcp__.*"."""
import json, sys
from pathlib import Path

data = json.load(sys.stdin)
tool_name = data.get("tool_name", "")
session_id = data.get("session_id", "unknown")

EXPENSIVE_TOOLS = {"mcp__market_data_mcp__get_quote"}
THRESHOLD = 50

if tool_name not in EXPENSIVE_TOOLS:
    sys.exit(0)

counter_path = Path(data.get("cwd", ".")) / ".claude" / f"expensive_call_count_{session_id}.txt"
count = int(counter_path.read_text()) + 1 if counter_path.exists() else 1
counter_path.parent.mkdir(parents=True, exist_ok=True)
counter_path.write_text(str(count))

if count > THRESHOLD:
    print(f"NOTICE: {tool_name} called {count} times this session, above "
          f"the {THRESHOLD}-call cost-awareness threshold.", file=sys.stderr)
    sys.exit(1)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/flag-high-cost-mcp-calls.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "mcp__.*",
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/flag-high-cost-mcp-calls.py"}
        ]
      }
    ]
  }
}

Before you use this

A hook runs with your local shell's permissions — review the script above before adding it, the same way you'd review any script you didn't write yourself. See our guide on hook security risks for the specific CVEs this category of feature has already produced.

Related hooks

← All hooks
FEEDBACK