#!/usr/bin/env bash
# create-mcp.sh — register an MCP, discover its tools, mint a scoped client key.
#
# Usage:
#   AIRONCLAW_TOKEN=... ./create-mcp.sh "stripe-mcp" "https://mcp.stripe.example.com" "sk_live_..."

set -euo pipefail

NAME="${1:?usage: create-mcp.sh <name> <url> [upstream-bearer]}"
URL="${2:?usage: create-mcp.sh <name> <url> [upstream-bearer]}"
UPSTREAM_TOKEN="${3:-}"

BASE="${AIRONCLAW_BASE_URL:-https://dashboard.aironclaw.com}"
TOKEN="${AIRONCLAW_TOKEN:?AIRONCLAW_TOKEN must be set — see SKILL.md § Initial setup}"

# 1. Build the create body (with or without upstream auth)
if [[ -n "$UPSTREAM_TOKEN" ]]; then
  BODY=$(jq -nc --arg name "$NAME" --arg url "$URL" --arg t "$UPSTREAM_TOKEN" \
    '{name:$name, url:$url, authType:"bearer", authToken:$t}')
else
  BODY=$(jq -nc --arg name "$NAME" --arg url "$URL" \
    '{name:$name, url:$url, authType:"none"}')
fi

# 2. Create the MCP
echo ">>> creating MCP '$NAME'"
SERVER=$(curl -fsS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE}/api/mcp" -d "$BODY")
MCP_ID=$(echo "$SERVER" | jq -r '.server.id')
PROXY_HOST=$(echo "$SERVER" | jq -r '.server.proxyHost')
echo "    id:         $MCP_ID"
echo "    proxy host: $PROXY_HOST"

# 3. Discover the upstream tools (so the catalog is populated)
echo ">>> discovering tools"
TOOLS=$(curl -fsS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE}/api/mcp/${MCP_ID}/tools")
echo "$TOOLS" | jq -r '.tools[]?.name' | sed 's/^/    - /'

# 4. Mint a client key with access to all tools on this MCP
echo ">>> minting a client API key (all-tools access)"
KEY_BODY=$(jq -nc --arg name "${NAME}-allkeys" --arg id "$MCP_ID" \
  '{name:$name, mcpPermissions:[{id:$id, tools:["*"]}]}')
KEY=$(curl -fsS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE}/api/keys" -d "$KEY_BODY")
PLAINTEXT=$(echo "$KEY" | jq -r '.key.key')
KEY_ID=$(echo "$KEY"     | jq -r '.key.id')
echo "    key id:     $KEY_ID"
echo "    plaintext:  $PLAINTEXT"
echo "                ^ store this now — it cannot be retrieved later"

cat <<EOF

Done.

Clients can now call the MCP at:
  https://${PROXY_HOST}/

with header:
  Authorization: Bearer ${PLAINTEXT}
EOF
