#!/usr/bin/env bash
# note-mcp-call.sh  -  PostToolUse hook on MCP tools (mcp__.*), registered async.
#
# Counts a successful MCP call for the usage record's `tools` field by appending
# one short line, `<session id> <tool name>`, to <log root>/mcp-calls.log. It
# starts no node process and parses no JSON: it reads the first 8 KiB of the
# payload (the host writes session_id, hook_event_name and tool_name before the
# tool's input and response, so a large tool_response is never read), takes the
# first occurrence of each of the three keys, and appends. The report folds the
# log into per-session counts (note-mcp-failure.mjs foldCalls).
#
# Off, with nothing read or written, unless the marker file
# <log root>/mcp-counting-on exists and the preferences file is not newer than
# it. A shell script cannot parse the preferences reliably, so it never tries:
# the marker is written (and its time renewed) by note-mcp-failure.mjs
# syncCountingSentinel with a real parser, only while usageLog.enabled is true
# and neither usageLog.optOut nor mcpFailures.enabled false is set, and removed
# otherwise. Any change to the preferences makes the marker older than them, so
# an edit that opts out stops the hook at once, and counting resumes when the
# next report or failure hook renews the marker.
#
# The log stops growing at 2 MiB until the next report folds it. Exits 0 on every
# path with no output: bookkeeping never holds a tool call.

set -u

PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
DIR="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
MARKER="$DIR/mcp-counting-on"
[ -f "$MARKER" ] || exit 0
[ -L "$MARKER" ] && exit 0
[ -f "$PREFS" ] || exit 0
[ "$PREFS" -nt "$MARKER" ] && exit 0

HEAD="$(head -c 8192 2>/dev/null)" || exit 0
SID="" EVENT="" TOOL=""
while IFS='=' read -r key value; do
  case "$key" in
    session_id) SID="$value" ;;
    hook_event_name) EVENT="$value" ;;
    tool_name) TOOL="$value" ;;
  esac
done <<EOF
$(printf '%s' "$HEAD" | awk '
{
  s = $0; n = length(s); d = 0; st = 0; i = 1
  while (i <= n) {
    c = substr(s, i, 1)
    if (c == "\"") {
      j = i + 1; str = ""
      while (j <= n) {
        ch = substr(s, j, 1)
        if (ch == "\\") { str = str substr(s, j, 2); j += 2; continue }
        if (ch == "\"") break
        str = str ch; j++
      }
      if (d == 1) {
        if (st == 0) { key = str; st = 1 }
        else if (st == 2) {
          if ((key == "session_id" || key == "hook_event_name" || key == "tool_name") && !(key in seen)) {
            seen[key] = 1; print key "=" str
          }
          st = 3
        }
      }
      i = j + 1; continue
    }
    if (c == ":" && d == 1) st = 2
    else if (c == "," && d == 1) st = 0
    else if (c == "{" || c == "[") d++
    else if (c == "}" || c == "]") d--
    i++
  }
}')
EOF

[ "$EVENT" = "PostToolUse" ] || exit 0
printf '%s' "$SID" | grep -Eq '^[A-Za-z0-9_-]{8,64}$' || exit 0
printf '%s' "$TOOL" | grep -Eq '^mcp__[A-Za-z0-9_-]{1,100}$' || exit 0

LOG="$DIR/mcp-calls.log"
( umask 077; mkdir -p "$DIR" ) 2>/dev/null || exit 0
[ -L "$LOG" ] && exit 0
if [ -f "$LOG" ]; then
  SIZE="$(wc -c < "$LOG" 2>/dev/null | tr -d ' ')"
  [ "${SIZE:-0}" -ge 2097152 ] 2>/dev/null && exit 0
fi
( umask 077; printf '%s %s\n' "$SID" "$TOOL" >> "$LOG" ) 2>/dev/null
exit 0
