#!/usr/bin/env bash
# Build the Claude Desktop extension, dist/<name>-<version>.mcpb, from desktop/, and check that it starts.
# Needs npx (Node) for the MCPB CLI and uv. The bundle installs the release that desktop/pyproject.toml pins
# from PyPI, so build it after that release is out (scripts/release.py bumps the pin). Nothing in it names
# jobwatch: copy it to another package with a desktop/ folder as it is.
#
#   scripts/build-mcpb             # validate, pack, then start the packed server and list its tools
#   scripts/build-mcpb --no-smoke  # validate and pack only
set -euo pipefail
cd "$(dirname "$0")/.."

MCPB="@anthropic-ai/mcpb@2.1.2"  # pinned: the CLI that validates and packs the manifest
name=$(sed -n 's/^  "name": "\(.*\)",$/\1/p' desktop/manifest.json)
version=$(sed -n 's/^  "version": "\(.*\)",$/\1/p' desktop/manifest.json)
out="dist/$name-$version.mcpb"

npx --yes "$MCPB" validate desktop/manifest.json
mkdir -p dist
rm -f "$out"
npx --yes "$MCPB" pack desktop "$out"

if [[ "${1:-}" != "--no-smoke" ]]; then
  # What Claude Desktop does on install: unpack, then `uv run --directory <bundle> server.py`.
  unpacked=$(mktemp -d)
  trap 'rm -rf "$unpacked"' EXIT
  npx --yes "$MCPB" unpack "$out" "$unpacked" >/dev/null
  JOBWATCH_CONFIG="$unpacked/watchlist.yaml" python3 scripts/mcp_smoke.py -- \
    uv run --quiet --directory "$unpacked" server.py
fi
echo "Built $out"
