"""Install one version-pinned publisher skill from Inspacy's MCP catalog. Requires Python 3.11+.""" import argparse import base64 import hashlib import io import json import os import shutil import tempfile import zipfile from pathlib import Path, PurePosixPath from urllib.parse import urlparse from urllib.request import HTTPRedirectHandler, Request, build_opener class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args): return None class Client: def __init__(self): origin = os.environ["INSPACY_API_ORIGIN"].rstrip("/") parsed = urlparse(origin) local = parsed.hostname in {"localhost", "127.0.0.1", "::1"} and parsed.scheme == "http" if (not local and parsed.scheme != "https") or not parsed.netloc or parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment: raise ValueError("Use the HTTPS origin of the Inspacy API.") self.url = origin + "/mcp" self.headers = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json", "X-Api-Key": os.environ["INSPACY_API_KEY"]} self.http = build_opener(NoRedirect()) self.sequence = 0 hello = self.call("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "publisher-skill-install", "version": "1"}}) self.headers["MCP-Protocol-Version"] = hello["protocolVersion"] self.call("notifications/initialized", {}, notify=True) def call(self, method, params, notify=False): data = {"jsonrpc": "2.0", "method": method, "params": params} if not notify: self.sequence += 1 data["id"] = self.sequence with self.http.open(Request(self.url, json.dumps(data).encode(), self.headers), timeout=30) as reply: if reply.headers.get("Mcp-Session-Id"): self.headers["Mcp-Session-Id"] = reply.headers["Mcp-Session-Id"] if notify: return if reply.headers.get_content_type() == "text/event-stream": for line in reply: if line.startswith(b"data:"): result = json.loads(line[5:]) if result.get("id") == self.sequence: break else: raise RuntimeError("MCP closed before sending the result") else: result = json.load(reply) if "error" in result: raise RuntimeError(result["error"]["message"]) return result["result"] def tool(self, name, arguments): result = self.call("tools/call", {"name": name, "arguments": arguments}) if result.get("isError"): raise RuntimeError(result["content"][0]["text"]) body = result.get("structuredContent") or json.loads(result["content"][0]["text"]) return body["data"] def install(client, name, version, destination): catalog = client.tool("list_publisher_skills", {}) entry = next((item for item in catalog if item["name"] == name and any(v["version"] == version for v in item["versions"])), None) if entry is None: raise ValueError("The skill or version is unavailable. Call list_publisher_skills for this release.") archive = client.tool(entry["downloadTool"], {"version": version}) raw = base64.b64decode(archive["archiveBase64"], validate=True) digest = hashlib.sha256(raw).hexdigest() if (archive["name"], archive["version"], len(raw), digest) != (name, version, archive["byteLength"], archive["sha256"]): raise ValueError("Archive metadata or SHA-256 mismatch.") destination.mkdir(parents=True, exist_ok=True) target = destination / name if target.exists(): raise FileExistsError(f"Choose a clean destination or archive the installed version first: {target}") with tempfile.TemporaryDirectory(dir=destination) as folder: staged = Path(folder) with zipfile.ZipFile(io.BytesIO(raw)) as z: for item in z.infolist(): parts = PurePosixPath(item.filename).parts if not parts or parts[0] != name or any(p in {".", ".."} or ":" in p or "\\" in p for p in parts): raise ValueError("Invalid skill archive path") if item.is_dir(): continue file = staged.joinpath(*parts) file.parent.mkdir(parents=True, exist_ok=True) with file.open("xb") as out, z.open(item) as source: shutil.copyfileobj(source, out) if not (staged / name / "SKILL.md").is_file(): raise ValueError("SKILL.md missing") (staged / name).rename(target) print(f"{target / 'SKILL.md'} sha256={digest}") if __name__ == "__main__": p = argparse.ArgumentParser(description=__doc__) p.add_argument("--name", required=True) p.add_argument("--version", required=True) p.add_argument("--destination", type=Path, choices=None, default=Path(".agents/skills")) args = p.parse_args() install(Client(), args.name, args.version, args.destination)