Skip to content
Shell
1.8 KB
Raw Blame
#!/bin/bash
# Pre-Playwright Hook
# Auto-reserves a browser context before any Playwright MCP tool call
#
# This hook is triggered by Claude's PreToolUse hook matcher for mcp__playwright-server__*

set -e

# Get session ID from environment or generate one
AGENT_ID="${CLAUDE_SESSION_ID:-session-$$}"

# Read tool input from stdin
INPUT=$(cat)

# Extract tool name
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty')

# Log for debugging (to stderr so it doesn't interfere)
echo "[Playwright Coordinator] Pre-hook for: $TOOL_NAME (agent: $AGENT_ID)" >&2

# Check if this is a Playwright tool
if [[ "$TOOL_NAME" == mcp__playwright-server__* ]]; then
  # Try to reserve a context
  COORDINATOR_DIR="$HOME/.claude/playwright-coordinator"

  # Use the CLI to reserve
  RESULT=$(cd "$COORDINATOR_DIR" && npx ts-node cli.ts reserve "$AGENT_ID" "Auto-reserved for $TOOL_NAME" 2>/dev/null || echo '{"success":false}')

  SUCCESS=$(echo "$RESULT" | jq -r '.success // false')

  if [[ "$SUCCESS" == "true" ]]; then
    CONTEXT_ID=$(echo "$RESULT" | jq -r '.contextId // "unknown"')
    echo "[Playwright Coordinator] Reserved context: $CONTEXT_ID" >&2
  else
    # Check if we're in queue
    WAIT_POS=$(echo "$RESULT" | jq -r '.waitPosition // 0')
    if [[ "$WAIT_POS" != "0" && "$WAIT_POS" != "null" ]]; then
      echo "[Playwright Coordinator] BLOCKED - Queue position: $WAIT_POS" >&2
      echo "ERROR: Browser pool is full. You are position $WAIT_POS in queue. Wait and retry, or use an alternative approach." >&2
      exit 2  # Exit code 2 blocks the tool
    fi

    # Check for error
    ERROR=$(echo "$RESULT" | jq -r '.error // "Unknown error"')
    echo "[Playwright Coordinator] Warning: $ERROR" >&2
    # Don't block, let it proceed (might already have a context)
  fi
fi

# Pass through - allow the tool to proceed
exit 0