#!/bin/sh
# Wrapper around mcp-remote for Claude Code MCP subprocess.
# Kills orphaned mcp-remote processes for this URL and cleans stale lock files
# before launching, so a new Claude Code session doesn't conflict with a prior one.
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"

TARGET_URL="$1"

# Kill any existing mcp-remote process already connected to the same URL.
# When Claude Code exits without cleanly stopping its MCP subprocesses, the
# old process keeps running and blocks the new session from connecting.
pgrep -f "mcp-remote.*${TARGET_URL}" | while read -r pid; do
  [ "$pid" != "$$" ] && kill "$pid" 2>/dev/null
done

# Clean up stale lock files whose recorded PID is no longer running.
# mcp-remote uses these to coordinate the OAuth callback port; a stale lock
# from a killed process blocks the callback server from binding.
for mcp_auth_dir in "${HOME}/.mcp-auth/mcp-remote-"*; do
  [ -d "$mcp_auth_dir" ] || continue
  for lock in "$mcp_auth_dir"/*_lock.json; do
    [ -f "$lock" ] || continue
    lock_pid=$(python3 -c "import json,sys; print(json.load(open('$lock')).get('pid',''))" 2>/dev/null)
    if [ -n "$lock_pid" ] && ! kill -0 "$lock_pid" 2>/dev/null; then
      rm -f "$lock"
    fi
  done
done

exec npx mcp-remote "$@"
