#!/usr/bin/env bash set -euo pipefail VSIX_PATH="${1:-}" BASE_URL="${DSDX_BASE_URL:-https://dualsoft.ai}" INSTALL_DIR="${DSDX_INSTALL_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/DualSoft/DSDX/mcp}" CONFIG_ROOT="${DSDX_CONFIG_ROOT:-}" SKIP_VERIFY="${DSDX_SKIP_VERIFY:-0}" if [[ "$VSIX_PATH" == "--skip-verify" ]]; then SKIP_VERIFY="1" VSIX_PATH="${2:-}" fi command -v python3 >/dev/null 2>&1 || { echo "[DSDX-MCP] python3 is required" >&2; exit 1; } command -v dotnet >/dev/null 2>&1 || { echo "[DSDX-MCP] .NET 9 runtime (dotnet) is required on macOS/Linux" >&2; exit 1; } TMP_VSIX="" TMP_SHA="" cleanup() { if [[ -n "$TMP_VSIX" && -f "$TMP_VSIX" ]]; then rm -f "$TMP_VSIX" fi if [[ -n "$TMP_SHA" && -f "$TMP_SHA" ]]; then rm -f "$TMP_SHA" fi } trap cleanup EXIT if [[ -z "$VSIX_PATH" ]]; then command -v curl >/dev/null 2>&1 || { echo "[DSDX-MCP] curl is required to download VSIX" >&2; exit 1; } TMP_VSIX="$(mktemp /tmp/dsdx-vscode-XXXXXX.vsix)" TMP_SHA="$(mktemp /tmp/dsdx-vscode-XXXXXX.sha256)" URL="${BASE_URL%/}/download/dsdx-vscode-latest.vsix" SHA_URL="${BASE_URL%/}/download/dsdx-vscode-latest.vsix.sha256" echo "[DSDX-MCP] Downloading single-artifact bundle: $URL" curl -fsSL "$URL" -o "$TMP_VSIX" if curl -fsSL "$SHA_URL" -o "$TMP_SHA" 2>/dev/null; then python3 -X utf8 - "$TMP_VSIX" "$TMP_SHA" <<'PYSHA' import hashlib, pathlib, re, sys vsix_p, sha_p = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]) m = re.match(r"^\s*([0-9a-fA-F]{64})\b", sha_p.read_text(encoding="utf-8", errors="replace")) if m: expected = m.group(1).lower() h = hashlib.sha256() with vsix_p.open("rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) actual = h.hexdigest().lower() if actual != expected: raise SystemExit(f"[DSDX-MCP] SHA-256 mismatch (expected {expected}, got {actual})") print(f"[DSDX-MCP] Verified SHA-256 checksum ({actual[:16]}...)") PYSHA else echo "[DSDX-MCP] Warning: could not fetch SHA-256 file ($SHA_URL); skipping checksum check." >&2 fi VSIX_PATH="$TMP_VSIX" fi python3 -X utf8 - "$VSIX_PATH" "$INSTALL_DIR" "$CONFIG_ROOT" "$SKIP_VERIFY" <<'PYEOF' import json import os import pathlib import shutil import subprocess import sys import zipfile vsix_path = pathlib.Path(sys.argv[1]).resolve() install_dir = pathlib.Path(sys.argv[2]).resolve() config_root = pathlib.Path(sys.argv[3]).resolve() if sys.argv[3] else pathlib.Path.home() skip_verify = sys.argv[4] == "1" staging = install_dir.with_name(f"{install_dir.name}.staging.{os.getpid()}") backup = install_dir.with_name(f"{install_dir.name}.prev.{os.getpid()}") shutil.rmtree(staging, ignore_errors=True) staging.mkdir(parents=True, exist_ok=True) try: with zipfile.ZipFile(vsix_path, "r") as zf: names = {info.filename.replace("\\", "/") for info in zf.infolist() if not info.is_dir()} use_portable = (not sys.platform.startswith("win")) and ("extension/runtime-portable/Dsdx.Authoring.dll" in names) portable_has_assets = any(n.startswith("extension/runtime-portable/assets/") for n in names) count = 0 for info in zf.infolist(): if info.is_dir(): continue name = info.filename.replace("\\", "/") rel = None if use_portable: if name.startswith("extension/runtime-portable/"): rel = name[len("extension/runtime-portable/"):] elif (not portable_has_assets) and name.startswith("extension/runtime/assets/"): rel = "assets/" + name[len("extension/runtime/assets/"):] elif name.startswith("extension/fixtures/"): rel = "fixtures/" + name[len("extension/fixtures/"):] else: if name.startswith("extension/runtime/"): rel = name[len("extension/runtime/"):] elif name.startswith("extension/fixtures/"): rel = "fixtures/" + name[len("extension/fixtures/"):] if not rel: continue parts = [p for p in rel.split("/") if p and p not in (".", "..")] if not parts: continue dest = staging.joinpath(*parts) dest.parent.mkdir(parents=True, exist_ok=True) with zf.open(info) as src, open(dest, "wb") as dst: shutil.copyfileobj(src, dst) count += 1 if count == 0: raise RuntimeError(f"No extension/runtime payload found inside VSIX: {vsix_path}") install_dir.parent.mkdir(parents=True, exist_ok=True) shutil.rmtree(backup, ignore_errors=True) moved_old = False if install_dir.exists(): install_dir.rename(backup) moved_old = True try: staging.rename(install_dir) except Exception: if moved_old and backup.exists() and not install_dir.exists(): backup.rename(install_dir) raise if moved_old: shutil.rmtree(backup, ignore_errors=True) finally: if staging.exists(): shutil.rmtree(staging, ignore_errors=True) dll_path = install_dir / "Dsdx.Authoring.dll" exe_path = install_dir / "Dsdx.Authoring.exe" if sys.platform.startswith("win") and exe_path.is_file(): cmd = str(exe_path) args = ["--stdio"] elif dll_path.is_file(): cmd = "dotnet" args = [str(dll_path), "--stdio"] else: raise RuntimeError(f"Missing Dsdx.Authoring runtime inside {install_dir}") if not skip_verify: init_req = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "dsdx-setup", "version": "1.0"}}}) list_req = json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}) proc = subprocess.run([cmd, *args], input=init_req + "\n" + list_req + "\n", text=True, capture_output=True, encoding="utf-8", timeout=30) if proc.returncode != 0: raise RuntimeError(f"Local MCP stdio verify failed: {proc.stderr}") tool_count = 0 for line in proc.stdout.splitlines(): if line.strip().startswith("{"): msg = json.loads(line) if msg.get("id") == 2: tool_count = len(msg.get("result", {}).get("tools", [])) if tool_count < 60: raise RuntimeError(f"Expected >= 60 tools from --stdio, got {tool_count}") print(f"[DSDX-MCP] Verified local MCP stdio server ({tool_count} tools)") def merge_json(path: pathlib.Path, include_type: bool = False) -> None: data = {} if path.is_file(): raw = path.read_text(encoding="utf-8").strip() if raw: data = json.loads(raw) if not isinstance(data.get("mcpServers"), dict): data["mcpServers"] = {} entry = {"command": cmd, "args": args} if include_type: entry["type"] = "stdio" data["mcpServers"]["dsdx"] = entry path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n") print(f"[DSDX-MCP] Registered JSON MCP server -> {path}") def merge_codex_toml(path: pathlib.Path) -> None: lines = [] if path.is_file(): in_sec = False for line in path.read_text(encoding="utf-8").splitlines(): stripped = line.strip() if stripped.startswith("[") and "]" in stripped: sec = stripped[1:stripped.index("]")].strip() in_sec = (sec == "mcp_servers.dsdx" or sec.startswith("mcp_servers.dsdx.")) if in_sec: continue if not in_sec: lines.append(line) while lines and not lines[-1].strip(): lines.pop() esc = lambda s: s.replace("\\", "\\\\").replace('"', '\\"') if lines: lines.append("") lines.extend([ "[mcp_servers.dsdx]", f'command = "{esc(cmd)}"', "args = [" + ", ".join(f'"{esc(a)}"' for a in args) + "]", ]) path.parent.mkdir(parents=True, exist_ok=True) path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") print(f"[DSDX-MCP] Registered TOML MCP server -> {path}") claude_desktop = ( config_root / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json" if sys.platform == "darwin" else config_root / ".config" / "Claude" / "claude_desktop_config.json" ) for kind, target_path, inc_type in ( ("json", config_root / ".gemini" / "antigravity" / "mcp_config.json", False), ("json", config_root / ".gemini" / "settings.json", False), ("json", config_root / ".claude.json", True), ("json", claude_desktop, False), ("toml", config_root / ".codex" / "config.toml", False), ("json", config_root / ".cursor" / "mcp.json", False), ("json", config_root / ".codeium" / "windsurf" / "mcp_config.json", False), ): try: if kind == "toml": merge_codex_toml(target_path) else: merge_json(target_path, include_type=inc_type) except Exception as exc: print(f"[DSDX-MCP] Warning: skipped {target_path}: {exc}", file=sys.stderr) PYEOF