PulseCanvas / app · pulsecanvas.ai / scripts / pulsecanvas-mcp-example.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Exercise a running PulseCanvas Studio host over its bundled STDIO bridge.""" |
| 3 | |
| 4 | import argparse |
| 5 | import itertools |
| 6 | import json |
| 7 | import subprocess |
| 8 | import sys |
| 9 | import time |
| 10 | import uuid |
| 11 | from typing import Any |
| 12 | |
| 13 | |
| 14 | class PulseCanvas: |
| 15 | def __init__(self, executable: str) -> None: |
| 16 | self.process = subprocess.Popen( |
| 17 | [executable, "--mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 18 | text=True, encoding="utf-8", |
| 19 | ) |
| 20 | self.ids = itertools.count(1) |
| 21 | self.rpc("initialize", { |
| 22 | "protocolVersion": "2025-11-25", |
| 23 | "capabilities": {}, |
| 24 | "clientInfo": {"name": "pulsecanvas-examples", "version": "1"}, |
| 25 | }) |
| 26 | self.send({"jsonrpc": "2.0", "method": "notifications/initialized"}) |
| 27 | |
| 28 | def send(self, request: dict[str, Any]) -> None: |
| 29 | assert self.process.stdin is not None |
| 30 | self.process.stdin.write(json.dumps(request) + "\n") |
| 31 | self.process.stdin.flush() |
| 32 | |
| 33 | def rpc(self, method: str, params: dict[str, Any]) -> dict[str, Any]: |
| 34 | request_id = next(self.ids) |
| 35 | self.send({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}) |
| 36 | assert self.process.stdout is not None |
| 37 | line = self.process.stdout.readline() |
| 38 | if not line: |
| 39 | raise RuntimeError("PulseCanvas closed its STDIO connection.") |
| 40 | response = json.loads(line) |
| 41 | if response.get("id") != request_id or "error" in response: |
| 42 | raise RuntimeError(str(response.get("error", response))) |
| 43 | return response["result"] |
| 44 | |
| 45 | def call(self, name: str, **arguments: Any) -> dict[str, Any]: |
| 46 | result = self.rpc("tools/call", {"name": name, "arguments": arguments}) |
| 47 | if result.get("isError"): |
| 48 | raise RuntimeError(result["content"][0]["text"]) |
| 49 | return result["structuredContent"] |
| 50 | |
| 51 | def close(self) -> None: |
| 52 | assert self.process.stdin is not None |
| 53 | self.process.stdin.close() |
| 54 | self.process.wait(timeout=10) |
| 55 | |
| 56 | |
| 57 | def favorites(client: PulseCanvas, visualizer_id: str) -> None: |
| 58 | kind = "visualizer" |
| 59 | saved = client.call("list_favorites", kind=kind) |
| 60 | original = any(item["id"] == visualizer_id for item in saved["favorites"]) |
| 61 | print(json.dumps(saved)) |
| 62 | try: |
| 63 | print(client.call("set_favorite", kind=kind, id=visualizer_id, favorite=True)) |
| 64 | print(client.call("set_favorite", kind=kind, id=visualizer_id, favorite=False)) |
| 65 | finally: |
| 66 | client.call("set_favorite", kind=kind, id=visualizer_id, favorite=original) |
| 67 | |
| 68 | |
| 69 | def playback(client: PulseCanvas, song: str) -> None: |
| 70 | revision = client.call("get_playback_state")["revision"] |
| 71 | loaded = client.call("load_song", path=song, expectedRevision=revision) |
| 72 | print(loaded) |
| 73 | print(client.call("set_playback_state", state="play")) |
| 74 | time.sleep(1) |
| 75 | print(client.call("set_playback_state", state="pause")) |
| 76 | print(client.call("seek", seconds=loaded["durationSeconds"] / 2)) |
| 77 | |
| 78 | |
| 79 | def video(client: PulseCanvas, song: str, project: str, output: str) -> None: |
| 80 | revision = client.call("get_playback_state")["revision"] |
| 81 | result = client.call("create_music_video", songPath=song, projectPath=project, outputPath=output, |
| 82 | aspect="wide", resolution=1080, fps=30, barsPerScene=4, fallback="metal", |
| 83 | strobeEnabled=False, requestKey=str(uuid.uuid4()), expectedRevision=revision) |
| 84 | job_id = result["job"]["id"] |
| 85 | print(f"Saved {result['projectPath']}. Export job {job_id}.", flush=True) |
| 86 | while True: |
| 87 | job = client.call("get_export_status", id=job_id)["job"] |
| 88 | if job["phase"] == "completed": |
| 89 | print(json.dumps(job, indent=2)) |
| 90 | return |
| 91 | if job["phase"] in ("failed", "cancelled"): |
| 92 | raise RuntimeError(str(job)) |
| 93 | print(f"{job['phase']}: {job['framesRendered']}/{job['totalFrames']} frames", flush=True) |
| 94 | time.sleep(2) |
| 95 | |
| 96 | |
| 97 | def main() -> None: |
| 98 | parser = argparse.ArgumentParser(description=__doc__) |
| 99 | parser.add_argument("executable", help="Absolute path to PulseCanvas in the installed Mac app bundle") |
| 100 | examples = parser.add_subparsers(dest="example", required=True) |
| 101 | examples.add_parser("favorites").add_argument("visualizer_id") |
| 102 | examples.add_parser("playback").add_argument("song") |
| 103 | video_args = examples.add_parser("video") |
| 104 | video_args.add_argument("song") |
| 105 | video_args.add_argument("project") |
| 106 | video_args.add_argument("output") |
| 107 | args = parser.parse_args() |
| 108 | client = PulseCanvas(args.executable) |
| 109 | try: |
| 110 | status = client.call("get_app_status") |
| 111 | if not status["enabled"]: |
| 112 | raise RuntimeError("Open PulseCanvas and enable Settings → Agent access.") |
| 113 | if args.example == "favorites": |
| 114 | favorites(client, args.visualizer_id) |
| 115 | elif args.example == "playback": |
| 116 | playback(client, args.song) |
| 117 | else: |
| 118 | video(client, args.song, args.project, args.output) |
| 119 | finally: |
| 120 | client.close() |
| 121 | |
| 122 | |
| 123 | if __name__ == "__main__": |
| 124 | try: |
| 125 | main() |
| 126 | except RuntimeError as error: |
| 127 | sys.exit(str(error)) |