diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index 4b5efa9..a3075d4 100644 --- a/devtools/client/flipper/src/__tests__/transport.test.ts +++ b/devtools/client/flipper/src/__tests__/transport.test.ts @@ -1,5 +1,9 @@ import { describe, it, expect, vi } from "vitest"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; import type { FlipperServer } from "flipper-server-client"; + import { FlipperServerTransport } from "../transport"; const INSTALLED = { @@ -25,6 +29,22 @@ function fakeFlipperServer( return { exec } as unknown as FlipperServer; } +/** Access private fields for seeding — avoids real sockets/child processes + * while exercising the connection-state and plugin-activation surfaces. */ +type TransportInternals = { + server: unknown; + refcount: { peek: () => { pid: number; refs: number } | null }; + owns: boolean; + host: string; + port: number; + connectedClientIds: Set; + activeClientIds: Set; +}; + +function internals(transport: FlipperServerTransport): TransportInternals { + return transport as unknown as TransportInternals; +} + /** Reaches into the transport's private fields to set up state without going through `connect()`. */ function attach( transport: FlipperServerTransport, @@ -37,16 +57,25 @@ function attach( activeClientIds?: Array; } = {}, ): void { - const t = transport as unknown as { - server: FlipperServer; - connectedClientIds: Set; - activeClientIds: Set; - }; + const t = internals(transport); t.server = server; t.connectedClientIds = new Set(connectedClientIds); t.activeClientIds = new Set(activeClientIds); } +/** + * A transport whose refcount is stubbed to `null` so tests don't depend on + * (or race) a real `flipper-server.refcount` file possibly left on disk by + * other processes on the machine running the test. + */ +function makeIsolatedTransport( + options?: ConstructorParameters[0], +): FlipperServerTransport { + const transport = new FlipperServerTransport(options); + internals(transport).refcount = { peek: () => null }; + return transport; +} + describe("FlipperServerTransport", () => { describe("ensurePluginInstalled", () => { it("returns the existing plugin without installing when already present", async () => { @@ -263,4 +292,399 @@ describe("FlipperServerTransport", () => { await expect(transport.disablePlugin()).rejects.toThrow("not connected"); }); }); + + describe("getDiagnostics", () => { + it("reports disconnected defaults before connect() is called", () => { + const transport = makeIsolatedTransport(); + expect(transport.getDiagnostics()).toEqual({ + connected: false, + host: "localhost", + port: 52342, + owns: false, + refs: null, + activeClientIds: [], + connectedClientIds: [], + }); + }); + + it("reflects custom host/port options even before connecting", () => { + const transport = makeIsolatedTransport({ + host: "127.0.0.1", + port: 9999, + }); + // host/port are resolved from options at construction time, so they're + // already correct before connect() has ever run. + expect(transport.getDiagnostics()).toMatchObject({ + host: "127.0.0.1", + port: 9999, + }); + }); + + it("reports connected + owns + refs + activeClientIds + connectedClientIds once seeded", () => { + const transport = makeIsolatedTransport(); + const state = internals(transport); + state.server = {}; + state.owns = true; + state.activeClientIds = new Set(["a", "b"]); + state.connectedClientIds = new Set(["a", "b", "c"]); + state.refcount = { peek: () => ({ pid: 123, refs: 1 }) }; + + expect(transport.getDiagnostics()).toEqual({ + connected: true, + host: "localhost", + port: 52342, + owns: true, + refs: 1, + activeClientIds: ["a", "b"], + connectedClientIds: ["a", "b", "c"], + }); + }); + }); + + describe("FlipperRefcount.peek (via getDiagnostics)", () => { + it("does not mutate the refcount file", () => { + const dir = path.join(os.tmpdir(), "player-devtools-mcp"); + const file = path.join(dir, "flipper-server.refcount"); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ pid: process.pid, refs: 4 })); + + try { + const transport = new FlipperServerTransport(); + const before = fs.readFileSync(file, "utf8"); + const { refs } = transport.getDiagnostics(); + const after = fs.readFileSync(file, "utf8"); + + expect(refs).toBe(4); + expect(after).toBe(before); + } finally { + fs.rmSync(file, { force: true }); + } + }); + }); + + describe("restart", () => { + it("soft-errors without touching the daemon when this instance does not own it", async () => { + const transport = new FlipperServerTransport(); + const close = vi.spyOn(transport, "close"); + const connect = vi.spyOn(transport, "connect"); + + const result = await transport.restart(); + + expect(result).toEqual({ + ok: false, + reason: "this instance does not own the flipper-server daemon", + }); + expect(close).not.toHaveBeenCalled(); + expect(connect).not.toHaveBeenCalled(); + }); + + it("soft-errors without touching the daemon when other consumers are attached", async () => { + const transport = new FlipperServerTransport(); + const state = internals(transport); + state.owns = true; + state.refcount = { peek: () => ({ pid: 1, refs: 3 }) }; + + const close = vi.spyOn(transport, "close"); + const connect = vi.spyOn(transport, "connect"); + + const result = await transport.restart(); + + expect(result).toEqual({ + ok: false, + reason: "other consumers are attached to this daemon", + }); + expect(close).not.toHaveBeenCalled(); + expect(connect).not.toHaveBeenCalled(); + }); + + it("closes and reconnects when this instance is the sole owner", async () => { + const transport = new FlipperServerTransport(); + const state = internals(transport); + state.owns = true; + state.refcount = { peek: () => ({ pid: 1, refs: 1 }) }; + + const close = vi.spyOn(transport, "close").mockResolvedValue(undefined); + const connect = vi + .spyOn(transport, "connect") + .mockResolvedValue(undefined); + + const result = await transport.restart(); + + expect(close).toHaveBeenCalledOnce(); + expect(connect).toHaveBeenCalledOnce(); + expect(result).toEqual({ ok: true, host: "localhost", port: 52342 }); + }); + + it("aborts with a soft error when refs change between the initial check and the pre-kill re-check", async () => { + const transport = new FlipperServerTransport(); + const state = internals(transport); + state.owns = true; + let calls = 0; + state.refcount = { + peek: () => { + calls += 1; + // First peek (in the initial guard) sees refs=1; the re-check + // immediately before close() sees a consumer that just attached. + return calls === 1 ? { pid: 1, refs: 1 } : { pid: 1, refs: 2 }; + }, + }; + + const close = vi.spyOn(transport, "close"); + const connect = vi.spyOn(transport, "connect"); + + const result = await transport.restart(); + + expect(result).toEqual({ + ok: false, + reason: "other consumers attached to this daemon just before restart", + }); + expect(close).not.toHaveBeenCalled(); + expect(connect).not.toHaveBeenCalled(); + }); + + it("returns a soft error and resets owns to false when connect() fails after close() succeeds", async () => { + const transport = new FlipperServerTransport(); + const state = internals(transport); + state.owns = true; + state.refcount = { peek: () => ({ pid: 1, refs: 1 }) }; + + const close = vi.spyOn(transport, "close").mockResolvedValue(undefined); + const connect = vi + .spyOn(transport, "connect") + .mockRejectedValue(new Error("Timed out waiting for localhost:52342")); + + const result = await transport.restart(); + + expect(close).toHaveBeenCalledOnce(); + expect(connect).toHaveBeenCalledOnce(); + expect(result).toEqual({ + ok: false, + reason: "Timed out waiting for localhost:52342", + }); + expect(internals(transport).owns).toBe(false); + }); + }); + + describe("getPluginInstallStatus", () => { + it("returns not-installed when the server is not connected", async () => { + const transport = new FlipperServerTransport(); + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ + installed: false, + reason: "not connected", + }); + }); + + it("returns not-installed when the daemon has no matching plugin", async () => { + const transport = new FlipperServerTransport(); + internals(transport).server = { + exec: vi.fn().mockResolvedValue([{ id: "some-other-plugin" }]), + }; + + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ + installed: false, + }); + }); + + it("matches by id and reports the version when present", async () => { + const transport = new FlipperServerTransport(); + internals(transport).server = { + exec: vi + .fn() + .mockResolvedValue([{ id: "player-ui-devtools", version: "1.2.3" }]), + }; + + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ + installed: true, + version: "1.2.3", + }); + }); + + it("matches by name when id is absent, without a version", async () => { + const transport = new FlipperServerTransport(); + internals(transport).server = { + exec: vi.fn().mockResolvedValue([{ name: "player-ui-devtools" }]), + }; + + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ + installed: true, + }); + }); + + it("resolves with a failure reason instead of throwing when exec() rejects", async () => { + const transport = new FlipperServerTransport(); + internals(transport).server = { + exec: vi.fn().mockRejectedValue(new Error("daemon dropped")), + }; + + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ + installed: false, + reason: "daemon dropped", + }); + }); + + it("returns the soft-error shape instead of throwing when exec() resolves with a malformed non-array value", async () => { + const transport = new FlipperServerTransport(); + internals(transport).server = { + // Simulates a version-mismatched daemon response: exec() resolves + // (doesn't reject) with something that isn't an array, so `.find()` + // would throw a TypeError if called outside the try/catch. + exec: vi.fn().mockResolvedValue({ unexpected: "shape" }), + }; + + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ + installed: false, + reason: "plugins.find is not a function", + }); + }); + }); + + describe("close", () => { + it("waits for the killed daemon process to actually exit before resolving", async () => { + vi.useFakeTimers(); + try { + const transport = new FlipperServerTransport(); + const state = internals(transport); + state.refcount = { + peek: () => null, + } as unknown as TransportInternals["refcount"]; + ( + transport as unknown as { + refcount: { release: () => number | null }; + } + ).refcount.release = () => 4242; + + let alive = true; + const killSpy = vi.spyOn(process, "kill").mockImplementation((( + pid: number, + signal?: string | number, + ) => { + if (signal === 0) { + if (!alive) throw new Error("ESRCH"); + return true; + } + return true; + }) as typeof process.kill); + + const closePromise = transport.close(); + let resolved = false; + void closePromise.then(() => { + resolved = true; + }); + + // Still "alive" — close() must not have resolved yet. + await vi.advanceTimersByTimeAsync(300); + expect(resolved).toBe(false); + + // Now the process exits; the next poll should observe it and resolve. + alive = false; + await vi.advanceTimersByTimeAsync(200); + await closePromise; + expect(resolved).toBe(true); + + killSpy.mockRestore(); + } finally { + vi.useRealTimers(); + } + }); + + it("is idempotent: a second concurrent close() does not re-run teardown", async () => { + const transport = new FlipperServerTransport(); + + let releaseCalls = 0; + ( + transport as unknown as { + refcount: { release: () => number | null }; + } + ).refcount = { + peek: () => null, + release: () => { + releaseCalls += 1; + return null; + }, + } as unknown as TransportInternals["refcount"]; + + const first = transport.close(); + const second = transport.close(); + + await Promise.all([first, second]); + + expect(releaseCalls).toBe(1); + }); + }); + + describe("connect", () => { + it("kills the spawned child and waits for it to exit when waitForPort fails after spawn", async () => { + // Exercises connect()'s `shouldStart` spawn path: the real flipper-server + // child is spawned, but nothing is listening on the target port, so + // waitForPort() times out. Nothing has committed this child's PID to + // the refcount file yet, so connect() must kill it itself (via the same + // killAndWait() used elsewhere in this file) or it orphans. + // + // Under this workspace's vitest environment (happy-dom), `vi.mock` + // cannot reliably intercept Node builtin modules (`child_process`, + // `net`) for code paths already resolved outside the test file's own + // module graph, so this spies on the module-level `process.kill` + // instead — the real spawn() runs, but against a port nothing listens + // on, and fake timers fast-forward both waitForPort's 30s polling loop + // and killAndWait's exit-confirmation poll. + let alive = true; + const processKillSpy = vi.spyOn(process, "kill").mockImplementation((( + pid: number, + signal?: string | number, + ) => { + if (signal === 0) { + if (!alive) throw new Error("ESRCH"); + return true; + } + // The SIGTERM sent by killAndWait(). + alive = false; + return true; + }) as typeof process.kill); + + vi.useFakeTimers(); + try { + const transport = new FlipperServerTransport({ + host: "127.0.0.1", + // Reserved/unused port: nothing should ever be listening here in CI + // or locally, so real net.connect attempts genuinely fail fast. + port: 1, + }); + const state = internals(transport); + state.refcount = { + peek: () => null, + } as unknown as TransportInternals["refcount"]; + ( + transport as unknown as { + refcount: { + acquire: () => { + shouldStart: boolean; + commit: (pid: number) => void; + }; + }; + } + ).refcount.acquire = () => ({ + shouldStart: true, + commit: vi.fn(), + }); + + const connectPromise = transport.connect().catch((err) => err as Error); + + // Advance past waitForPort's internal 30s timeout so it rejects, then + // past killAndWait's poll interval so it observes the SIGTERM'd + // child's exit before connect() rethrows. + await vi.advanceTimersByTimeAsync(31_200); + + const result = await connectPromise; + + expect(result).toBeInstanceOf(Error); + // The SIGTERM from killAndWait(). + expect(processKillSpy).toHaveBeenCalledWith(expect.any(Number)); + // The liveness poll from killAndWait()'s isPidAlive(). + expect(processKillSpy).toHaveBeenCalledWith(expect.any(Number), 0); + } finally { + vi.useRealTimers(); + processKillSpy.mockRestore(); + } + }); + }); }); diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index b25151c..75318a5 100644 --- a/devtools/client/flipper/src/transport.ts +++ b/devtools/client/flipper/src/transport.ts @@ -155,6 +155,14 @@ class FlipperRefcount { } } + /** + * Read the current refcount state without mutating it. Still goes through + * `withLock` so a concurrent acquire/release can't be observed mid-write. + */ + peek(): RefcountFile | null { + return this.withLock(() => this.read()); + } + private write(state: RefcountFile): void { fs.writeFileSync(this.file, JSON.stringify(state)); } @@ -234,6 +242,16 @@ export class FlipperServerTransport implements Transport { */ private connectedClientIds = new Set(); + /** Resolved connection target, fixed at construction from `options`. */ + private readonly host: string; + private readonly port: number; + + /** + * Whether this instance started the shared daemon (vs. attaching to one + * another instance started). Only an owner may consider restarting it. + */ + private owns = false; + constructor( private options: { /** Flipper server host; defaults to "localhost" */ @@ -263,16 +281,20 @@ export class FlipperServerTransport implements Transport { */ autoEnablePlugin?: boolean; } = {}, - ) {} + ) { + this.host = this.options.host ?? "localhost"; + this.port = this.options.port ?? 52342; + } async connect(): Promise { - const host = this.options.host ?? "localhost"; - const port = this.options.port ?? 52342; + const host = this.host; + const port = this.port; // Register interest in the shared daemon. The first instance to do so is // told to start it; the rest just attach. The daemon outlives any single // MCP process and is only torn down when the last instance detaches. const { shouldStart, commit } = this.refcount.acquire(); + this.owns = shouldStart; if (shouldStart) { log("[FlipperServerTransport] Starting flipper-server..."); @@ -303,7 +325,20 @@ export class FlipperServerTransport implements Transport { ); }); child.unref(); - await waitForPort(host, port); + try { + await waitForPort(host, port); + } catch (err) { + // Nothing has recorded this PID in the refcount file yet, so nobody + // else can track or kill it — if we leave it running here it becomes + // an orphan daemon that a later connect() would compete with on the + // same port instead of detecting. Wait for it to actually exit (via + // the same bounded kill-and-confirm mechanism used everywhere else in + // this file) before rethrowing, so a caller that retries connect() + // right away doesn't spawn a second daemon racing this one for the + // port during teardown. + await this.killAndWait(child.pid!); + throw err; + } commit(child.pid!); log("[FlipperServerTransport] flipper-server ready."); } else { @@ -543,7 +578,24 @@ export class FlipperServerTransport implements Transport { this.listeners.delete(callback); }; + /** + * In-flight `close()` promise, if one is currently running on this + * instance. Guards `refcount.release()` and `killAndWait()` against being + * invoked twice for a single logical close — e.g. `restart()`'s internal + * `close()` racing an external `MCPServer.stop()` -> `transport.close()`. + */ + private closing: Promise | null = null; + async close(): Promise { + if (this.closing) return this.closing; + + this.closing = this.doClose().finally(() => { + this.closing = null; + }); + return this.closing; + } + + private async doClose(): Promise { this.listeners.clear(); this.activeClientIds.clear(); this.connectedClientIds.clear(); @@ -555,12 +607,160 @@ export class FlipperServerTransport implements Transport { // running for the remaining instances. const pidToKill = this.refcount.release(); if (pidToKill !== null) { + await this.killAndWait(pidToKill); + } + } + + /** + * Send SIGTERM and wait for the process to actually exit (or a bounded + * timeout) before resolving, so callers — notably `restart()` — can rely on + * the port being free once `close()` returns instead of racing a new child + * for it. + */ + private killAndWait(pid: number, timeoutMs = 5_000): Promise { + return new Promise((resolve) => { try { - process.kill(pidToKill); - log("[FlipperServerTransport] Shut down flipper-server."); + process.kill(pid); } catch { - /* already gone */ + // Already gone. + resolve(); + return; } + + const deadline = Date.now() + timeoutMs; + const poll = () => { + if (!this.isPidAlive(pid)) { + log("[FlipperServerTransport] Shut down flipper-server."); + resolve(); + return; + } + if (Date.now() >= deadline) { + log( + "[FlipperServerTransport] Timed out waiting for flipper-server to exit.", + ); + resolve(); + return; + } + setTimeout(poll, 100); + }; + poll(); + }); + } + + private isPidAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + } + + /** Read-only snapshot of this transport's connection to the shared daemon. */ + getDiagnostics(): { + connected: boolean; + host: string; + port: number; + owns: boolean; + refs: number | null; + activeClientIds: string[]; + connectedClientIds: string[]; + } { + const state = this.refcount.peek(); + return { + connected: this.server !== null, + host: this.host, + port: this.port, + owns: this.owns, + refs: state?.refs ?? null, + activeClientIds: [...this.activeClientIds], + connectedClientIds: [...this.connectedClientIds], + }; + } + + /** + * Restart the shared daemon. Only ever acts when this instance both owns + * the daemon (started it) and is its sole remaining consumer — otherwise + * this soft-errors without touching the daemon, since killing it out from + * under other attached instances would break their connections. + */ + async restart(): Promise< + { ok: true; host: string; port: number } | { ok: false; reason: string } + > { + if (!this.owns) { + return { + ok: false, + reason: "this instance does not own the flipper-server daemon", + }; + } + + const state = this.refcount.peek(); + if (state?.refs !== 1) { + return { + ok: false, + reason: "other consumers are attached to this daemon", + }; + } + + // Re-verify immediately before the destructive close(): another instance + // could have called connect()/acquire() between the check above and here, + // bumping refs to 2+. This narrows but does not eliminate the race — a + // consumer could still slip in between this re-check and close() itself; + // a fully atomic fix would need close()+connect() to run inside + // refcount.withLock(), which isn't reentrant-safe with connect()'s own + // internal use of the lock, so we accept this narrow residual window. + const recheck = this.refcount.peek(); + if (recheck?.refs !== 1) { + return { + ok: false, + reason: "other consumers attached to this daemon just before restart", + }; + } + + try { + await this.close(); + await this.connect(); + } catch (err) { + // The daemon this instance owned/attempted to own is now in an unknown + // or dead state — don't leave `owns` set, or a later restart() call + // will misreport "other consumers are attached" against a stale + // refcount for a daemon that no longer exists. + this.owns = false; + return { + ok: false, + reason: err instanceof Error ? err.message : String(err), + }; + } + return { ok: true, host: this.host, port: this.port }; + } + + /** Whether the devtools Flipper plugin is installed, per the live daemon. */ + async getPluginInstallStatus(): Promise<{ + installed: boolean; + version?: string; + reason?: string; + }> { + if (!this.server) return { installed: false, reason: "not connected" }; + + try { + const plugins = (await this.server.exec( + "plugins-get-installed-plugins", + )) as Array<{ id?: string; name?: string; version?: string }>; + + const plugin = plugins.find( + (candidate) => + candidate.id === PLUGIN_API || candidate.name === PLUGIN_API, + ); + + if (!plugin) return { installed: false }; + return plugin.version + ? { installed: true, version: plugin.version } + : { installed: true }; + } catch (err) { + return { + installed: false, + reason: err instanceof Error ? err.message : String(err), + }; } } } diff --git a/devtools/mcp/README.md b/devtools/mcp/README.md index 116fe6c..034cdcf 100644 --- a/devtools/mcp/README.md +++ b/devtools/mcp/README.md @@ -6,7 +6,7 @@ Player instance: list running Players, read their flow / data / logs / config, inspect plugin state, select a Player, and invoke plugin actions. It is the agent-facing sibling of the [browser extension] and the -[Flipper plugin](../flipper-plugin): all three are Devtools *clients* that speak +[Flipper plugin](../flipper-plugin): all three are Devtools _clients_ that speak to the same Player Devtools plugins over the [messenger](../messenger) protocol. The MCP server connects to those plugins through a running [`flipper-server`](https://github.com/facebook/flipper) and re-exposes them as @@ -61,23 +61,49 @@ The server registers the following tools (defined as `ToolDef`s in player-scoped tool takes an optional `playerId` and falls back to the currently selected Player when it's omitted. -| Tool | Args | Returns | -| --- | --- | --- | -| `list_players` | — | All known Player instances and which one is selected. | -| `get_player_status` | `playerId?` | Active status + registered plugin IDs. | -| `get_flow` | `playerId?` | The current flow (from the basic plugin). | -| `get_data` | `playerId?` | The current flow data model. | -| `get_logs` | `playerId?` | Accumulated runtime logs. | -| `get_plugin_data` | `playerId?`, `pluginId`, `dataKey` | A specific data key from any plugin. | -| `describe_plugin` | `playerId?`, `pluginId` | The plugin's capability descriptor — the data keys and actions it exposes. **Call this first** to discover what a plugin supports. | -| `select_player` | `playerId` | Selects a Player as the default target for later calls. | -| `invoke_action` | `playerId?`, `pluginId`, `action`, `payload?` | Invokes a named action (validated against the plugin's declared capabilities). | +| Tool | Args | Returns | +| ------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `list_players` | — | All known Player instances and which one is selected. | +| `get_player_status` | `playerId?` | Active status + registered plugin IDs. | +| `get_flow` | `playerId?` | The current flow (from the basic plugin). | +| `get_data` | `playerId?` | The current flow data model. | +| `get_logs` | `playerId?` | Accumulated runtime logs. | +| `get_plugin_data` | `playerId?`, `pluginId`, `dataKey` | A specific data key from any plugin. | +| `describe_plugin` | `playerId?`, `pluginId` | The plugin's capability descriptor — the data keys and actions it exposes. **Call this first** to discover what a plugin supports. | +| `select_player` | `playerId` | Selects a Player as the default target for later calls. | +| `invoke_action` | `playerId?`, `pluginId`, `action`, `payload?` | Invokes a named action (validated against the plugin's declared capabilities). | A typical agent flow: `list_players` → `select_player` → `describe_plugin` → `get_*` / `invoke_action`. +### Diagnostics + +These tools inspect and manage the MCP server's connection to the shared +[`flipper-server` daemon](#shared-flipper-server-daemon) itself, rather than +any Player instance behind it — useful when an agent needs to tell "no Players +are connected" apart from "the Flipper transport itself is unhealthy." They +soft-error when the server isn't running on a `FlipperServerTransport`. + +All `clientId` args refer to a Flipper **client** — a transport-level +device/app connection — not a Player devtools `playerId` (used by +`list_players` / `select_player` / etc). A client can be connected, and even +have the plugin activated, before any Player instance on it is visible to the +player-scoped tools; one client can also host multiple Players. Unlike +`playerId`, there is no "currently selected" client — omitting `clientId` +targets every connected client instead of falling back to a selection. + +| Tool | Args | Returns | +| --------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `get_flipper_connection_status` | — | Basic connection health: `connected`, `host`, `port`. | +| `get_flipper_consumers` | — | `owns`, `refs` (daemon-wide, not just this process), `activeClientIds`, and `connectedClientIds`. | +| `restart_flipper_server` | — | Restarts the daemon — only when this process owns it and is its sole consumer, otherwise a soft error. | +| `get_flipper_plugin_install_status` | — | Whether the Player UI Devtools Flipper plugin is installed on the daemon (npm-level install, not per-client activation). | +| `get_flipper_plugin_activation_status` | — | Per-client activation split: `activeClientIds` (completed the `init` handshake) vs. `inactiveClientIds` (connected but not yet activated). | +| `enable_flipper_plugin` | `clientId?` | Activates the plugin for `clientId`, or every connected-but-inactive client if omitted (see [Plugin activation](#plugin-activation)). | +| `disable_flipper_plugin` | `clientId?` | Deactivates the plugin for `clientId`, or every currently active client if omitted, without disconnecting. | + > **NOTE** -> Tool handlers return *soft errors* (e.g. `{ "error": "player not found" }`) as +> Tool handlers return _soft errors_ (e.g. `{ "error": "player not found" }`) as > normal results rather than throwing, so a failed call still returns a > structured payload the agent can read. @@ -193,10 +219,10 @@ Register it with an MCP client (e.g. Claude) by pointing the client at the The server reports anonymous usage analytics so we can tell how widely it's used and whether it's working in the field. It is **on by default** and sends: -| | | -| --- | --- | -| Identity | A random UUID generated on first run and stored at `~/.player-ui-devtools/install.json`. It is not derived from anything about you or your machine — delete the file and a new one is generated. | -| Events | Session start (`$mcp_initialize`), tool calls (`$mcp_tool_call`), tool listing (`$mcp_tools_list`), and errors (`$exception`). | +| | | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Identity | A random UUID generated on first run and stored at `~/.player-ui-devtools/install.json`. It is not derived from anything about you or your machine — delete the file and a new one is generated. | +| Events | Session start (`$mcp_initialize`), tool calls (`$mcp_tool_call`), tool listing (`$mcp_tools_list`), and errors (`$exception`). | | Properties | Tool **name**, call duration, whether the call errored, the MCP client name/version (e.g. which editor), the devtools version, OS platform, Node major version, and whether the Flipper transport connected. | **Tool arguments and tool responses are never transmitted.** Those can contain diff --git a/devtools/mcp/src/server.ts b/devtools/mcp/src/server.ts index 18093f3..3c9a63d 100644 --- a/devtools/mcp/src/server.ts +++ b/devtools/mcp/src/server.ts @@ -38,14 +38,22 @@ export class MCPServer { // loosely-typed view to keep inference shallow. const register = this.server.registerTool.bind(this.server) as ( name: string, - config: { description: string; inputSchema: ToolDef["inputSchema"] }, - cb: (args: unknown) => CallToolResult, + config: { + description: string; + inputSchema: ToolDef["inputSchema"]; + annotations?: ToolDef["annotations"]; + }, + cb: (args: unknown) => CallToolResult | Promise, ) => unknown; register( def.name, - { description: def.description, inputSchema: def.inputSchema }, - (args) => def.handle(this.client, args), + { + description: def.description, + inputSchema: def.inputSchema, + annotations: def.annotations, + }, + (args) => def.handle(this.client, args, this.transport), ); } } diff --git a/devtools/mcp/src/tools/__tests__/flipper.test.ts b/devtools/mcp/src/tools/__tests__/flipper.test.ts new file mode 100644 index 0000000..1790c6e --- /dev/null +++ b/devtools/mcp/src/tools/__tests__/flipper.test.ts @@ -0,0 +1,321 @@ +import { describe, it, expect, vi } from "vitest"; +import type { ExtensionClient } from "@player-devtools/client"; +import { FlipperServerTransport } from "@player-devtools/client-flipper"; +import type { Transport } from "@player-devtools/types"; + +import { + handleGetFlipperStatus, + handleGetFlipperConsumers, + handleRestartFlipperServer, + handleGetFlipperPluginInstallStatus, + handleGetFlipperPluginActivationStatus, + handleEnableFlipperPlugin, + handleDisableFlipperPlugin, +} from "../flipper"; + +const client = {} as ExtensionClient; + +function parse(result: { content: Array<{ text?: string }> }): unknown { + return JSON.parse(result.content[0]?.text ?? "{}"); +} + +/** + * A bare, unconnected transport — never calls `connect()`, no real sockets. + * The refcount is stubbed to `null` so tests don't depend on (or race) a real + * `flipper-server.refcount` file possibly left on disk by other processes. + */ +function makeFlipperTransport(): FlipperServerTransport { + const transport = new FlipperServerTransport(); + (transport as unknown as { refcount: { peek: () => unknown } }).refcount = { + peek: () => null, + }; + return transport; +} + +const nonFlipperTransport = { + connect: vi.fn(), + close: vi.fn(), + sendMessage: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), +} as unknown as Transport; + +describe("flipper diagnostic tools", () => { + describe("when the transport is not a FlipperServerTransport", () => { + it("get_flipper_connection_status soft-errors", () => { + const result = handleGetFlipperStatus(client, {}, nonFlipperTransport); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("get_flipper_consumers soft-errors", () => { + const result = handleGetFlipperConsumers(client, {}, nonFlipperTransport); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("restart_flipper_server soft-errors", async () => { + const result = await handleRestartFlipperServer( + client, + {}, + nonFlipperTransport, + ); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("get_flipper_plugin_install_status soft-errors", async () => { + const result = await handleGetFlipperPluginInstallStatus( + client, + {}, + nonFlipperTransport, + ); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("get_flipper_plugin_activation_status soft-errors", () => { + const result = handleGetFlipperPluginActivationStatus( + client, + {}, + nonFlipperTransport, + ); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("enable_flipper_plugin soft-errors", async () => { + const result = await handleEnableFlipperPlugin( + client, + {}, + nonFlipperTransport, + ); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("disable_flipper_plugin soft-errors", async () => { + const result = await handleDisableFlipperPlugin( + client, + {}, + nonFlipperTransport, + ); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + + it("soft-errors when no transport is provided at all", () => { + const result = handleGetFlipperStatus(client, {}, undefined); + expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); + }); + }); + + describe("get_flipper_connection_status", () => { + it("reports connection health from an unconnected transport", () => { + const transport = makeFlipperTransport(); + const result = handleGetFlipperStatus(client, {}, transport); + expect(parse(result)).toEqual({ + connected: false, + host: "localhost", + port: 52342, + }); + }); + }); + + describe("get_flipper_consumers", () => { + it("reports refcount, active client ids, and connected client ids", () => { + const transport = makeFlipperTransport(); + const state = transport as unknown as { + activeClientIds: Set; + connectedClientIds: Set; + }; + state.activeClientIds = new Set(["client-a", "client-b"]); + state.connectedClientIds = new Set(["client-a", "client-b", "client-c"]); + + const result = handleGetFlipperConsumers(client, {}, transport); + expect(parse(result)).toEqual({ + owns: false, + refs: null, + activeClientIds: ["client-a", "client-b"], + connectedClientIds: ["client-a", "client-b", "client-c"], + }); + }); + }); + + describe("restart_flipper_server", () => { + it("soft-errors when this instance does not own the daemon", async () => { + const transport = makeFlipperTransport(); + const result = await handleRestartFlipperServer(client, {}, transport); + expect(parse(result)).toEqual({ + error: "this instance does not own the flipper-server daemon", + }); + }); + + it("soft-errors when other consumers are attached", async () => { + const transport = makeFlipperTransport(); + (transport as unknown as { owns: boolean }).owns = true; + (transport as unknown as { refcount: { peek: () => unknown } }).refcount = + { peek: () => ({ pid: 1, refs: 2 }) }; + + const result = await handleRestartFlipperServer(client, {}, transport); + expect(parse(result)).toEqual({ + error: "other consumers are attached to this daemon", + }); + }); + }); + + describe("get_flipper_plugin_install_status", () => { + it("soft-errors when the transport is not connected", async () => { + const transport = makeFlipperTransport(); + const result = await handleGetFlipperPluginInstallStatus( + client, + {}, + transport, + ); + expect(parse(result)).toEqual({ + error: "flipper transport not connected", + }); + }); + + it("returns the plugin install status when connected", async () => { + const transport = makeFlipperTransport(); + const exec = vi + .fn() + .mockResolvedValue([{ id: "player-ui-devtools", version: "1.2.3" }]); + (transport as unknown as { server: unknown }).server = { exec }; + + const result = await handleGetFlipperPluginInstallStatus( + client, + {}, + transport, + ); + expect(parse(result)).toEqual({ installed: true, version: "1.2.3" }); + }); + + it("returns a soft error (not an unhandled rejection) when exec() rejects", async () => { + const transport = makeFlipperTransport(); + const exec = vi.fn().mockRejectedValue(new Error("daemon dropped")); + (transport as unknown as { server: unknown }).server = { exec }; + + const result = await handleGetFlipperPluginInstallStatus( + client, + {}, + transport, + ); + expect(parse(result)).toEqual({ error: "daemon dropped" }); + }); + }); + + describe("get_flipper_plugin_activation_status", () => { + it("soft-errors when the transport is not connected", () => { + const transport = makeFlipperTransport(); + const result = handleGetFlipperPluginActivationStatus( + client, + {}, + transport, + ); + expect(parse(result)).toEqual({ + error: "flipper transport not connected", + }); + }); + + it("splits connected clients into active and inactive", () => { + const transport = makeFlipperTransport(); + const state = transport as unknown as { + server: unknown; + activeClientIds: Set; + connectedClientIds: Set; + }; + state.server = {}; + state.activeClientIds = new Set(["a"]); + state.connectedClientIds = new Set(["a", "b", "c"]); + + const result = handleGetFlipperPluginActivationStatus( + client, + {}, + transport, + ); + expect(parse(result)).toEqual({ + activeClientIds: ["a"], + inactiveClientIds: ["b", "c"], + }); + }); + }); + + describe("enable_flipper_plugin", () => { + it("calls enablePlugin with the given clientId and reports it back", async () => { + const transport = makeFlipperTransport(); + const enablePlugin = vi + .spyOn(transport, "enablePlugin") + .mockResolvedValue(undefined); + + const result = await handleEnableFlipperPlugin( + client, + { clientId: "a" }, + transport, + ); + + expect(enablePlugin).toHaveBeenCalledWith("a"); + expect(parse(result)).toEqual({ enabled: true, clientId: "a" }); + }); + + it("calls enablePlugin with undefined and reports 'all' when no clientId is given", async () => { + const transport = makeFlipperTransport(); + const enablePlugin = vi + .spyOn(transport, "enablePlugin") + .mockResolvedValue(undefined); + + const result = await handleEnableFlipperPlugin(client, {}, transport); + + expect(enablePlugin).toHaveBeenCalledWith(undefined); + expect(parse(result)).toEqual({ enabled: true, clientId: "all" }); + }); + + it("returns a soft error (not an unhandled rejection) when enablePlugin() rejects", async () => { + const transport = makeFlipperTransport(); + vi.spyOn(transport, "enablePlugin").mockRejectedValue( + new Error("FlipperServerTransport is not connected"), + ); + + const result = await handleEnableFlipperPlugin(client, {}, transport); + expect(parse(result)).toEqual({ + error: "FlipperServerTransport is not connected", + }); + }); + }); + + describe("disable_flipper_plugin", () => { + it("calls disablePlugin with the given clientId and reports it back", async () => { + const transport = makeFlipperTransport(); + const disablePlugin = vi + .spyOn(transport, "disablePlugin") + .mockResolvedValue(undefined); + + const result = await handleDisableFlipperPlugin( + client, + { clientId: "a" }, + transport, + ); + + expect(disablePlugin).toHaveBeenCalledWith("a"); + expect(parse(result)).toEqual({ disabled: true, clientId: "a" }); + }); + + it("calls disablePlugin with undefined and reports 'all' when no clientId is given", async () => { + const transport = makeFlipperTransport(); + const disablePlugin = vi + .spyOn(transport, "disablePlugin") + .mockResolvedValue(undefined); + + const result = await handleDisableFlipperPlugin(client, {}, transport); + + expect(disablePlugin).toHaveBeenCalledWith(undefined); + expect(parse(result)).toEqual({ disabled: true, clientId: "all" }); + }); + + it("returns a soft error (not an unhandled rejection) when disablePlugin() rejects", async () => { + const transport = makeFlipperTransport(); + vi.spyOn(transport, "disablePlugin").mockRejectedValue( + new Error("FlipperServerTransport is not connected"), + ); + + const result = await handleDisableFlipperPlugin(client, {}, transport); + expect(parse(result)).toEqual({ + error: "FlipperServerTransport is not connected", + }); + }); + }); +}); diff --git a/devtools/mcp/src/tools/flipper.ts b/devtools/mcp/src/tools/flipper.ts new file mode 100644 index 0000000..da9a85f --- /dev/null +++ b/devtools/mcp/src/tools/flipper.ts @@ -0,0 +1,196 @@ +import type { ExtensionClient } from "@player-devtools/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { Transport } from "@player-devtools/types"; +import { FlipperServerTransport } from "@player-devtools/client-flipper"; +import { z } from "zod"; + +import { ok, err, type ToolDef } from "./index"; + +const clientIdShape = { + clientId: z + .string() + .optional() + .describe( + "Flipper client ID — a transport-level device/app connection, NOT a Player devtools playerId (see list_players/select_player). A client can be connected, and even activated, before any Player instance on it is visible to those tools. Unlike playerId, there is no 'currently selected' client: omitting this targets every connected client — for enable/disable, only clients not already in the desired state are messaged.", + ), +}; + +const ClientIdInput = z.object(clientIdShape); + +/** Narrow the generic `Transport` to the concrete Flipper implementation. */ +function asFlipperTransport( + transport: Transport | undefined, +): FlipperServerTransport | null { + return transport instanceof FlipperServerTransport ? transport : null; +} + +export function handleGetFlipperStatus( + _client: ExtensionClient, + _args: unknown, + transport?: Transport, +): CallToolResult { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + const { connected, host, port } = flipper.getDiagnostics(); + return ok({ connected, host, port }); +} + +export function handleGetFlipperConsumers( + _client: ExtensionClient, + _args: unknown, + transport?: Transport, +): CallToolResult { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + const { owns, refs, activeClientIds, connectedClientIds } = + flipper.getDiagnostics(); + return ok({ owns, refs, activeClientIds, connectedClientIds }); +} + +export async function handleRestartFlipperServer( + _client: ExtensionClient, + _args: unknown, + transport?: Transport, +): Promise { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + const result = await flipper.restart(); + if (!result.ok) return err(result.reason); + return ok({ restarted: true, host: result.host, port: result.port }); +} + +export async function handleGetFlipperPluginInstallStatus( + _client: ExtensionClient, + _args: unknown, + transport?: Transport, +): Promise { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + if (!flipper.getDiagnostics().connected) { + return err("flipper transport not connected"); + } + + const status = await flipper.getPluginInstallStatus(); + if (!status.installed && status.reason) return err(status.reason); + return ok(status); +} + +export const getFlipperStatusDef: ToolDef = { + name: "get_flipper_connection_status", + description: + "Get the MCP server's basic connection health to the shared flipper-server daemon: whether it's connected, and the host/port it's connected to. For ownership/refcount/client info, use get_flipper_consumers instead.", + inputSchema: {}, + annotations: { readOnlyHint: true, destructiveHint: false }, + handle: handleGetFlipperStatus, +}; + +export const getFlipperConsumersDef: ToolDef = { + name: "get_flipper_consumers", + description: + "Get who else is attached to the shared flipper-server daemon: whether this process owns it, the daemon-wide refcount (reflects all consumers, not just this process), and the connected/active devtools clients on this connection.", + inputSchema: {}, + annotations: { readOnlyHint: true, destructiveHint: false }, + handle: handleGetFlipperConsumers, +}; + +export const restartFlipperServerDef: ToolDef = { + name: "restart_flipper_server", + description: + "Restart the shared flipper-server daemon. Only succeeds when this MCP server owns the daemon and is its sole consumer; otherwise returns a soft error rather than disrupting other consumers.", + inputSchema: {}, + annotations: { readOnlyHint: false, destructiveHint: true }, + handle: handleRestartFlipperServer, +}; + +export const getFlipperPluginInstallStatusDef: ToolDef = { + name: "get_flipper_plugin_install_status", + description: + "Check whether the Player UI Devtools Flipper plugin is installed on the connected daemon.", + inputSchema: {}, + annotations: { readOnlyHint: true, destructiveHint: false }, + handle: handleGetFlipperPluginInstallStatus, +}; + +export function handleGetFlipperPluginActivationStatus( + _client: ExtensionClient, + _args: unknown, + transport?: Transport, +): CallToolResult { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + const { connected, connectedClientIds, activeClientIds } = + flipper.getDiagnostics(); + if (!connected) return err("flipper transport not connected"); + + const active = new Set(activeClientIds); + return ok({ + activeClientIds, + inactiveClientIds: connectedClientIds.filter((id) => !active.has(id)), + }); +} + +export async function handleEnableFlipperPlugin( + _client: ExtensionClient, + args: unknown, + transport?: Transport, +): Promise { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + const { clientId } = ClientIdInput.parse(args); + try { + await flipper.enablePlugin(clientId); + } catch (error) { + return err(error instanceof Error ? error.message : String(error)); + } + return ok({ enabled: true, clientId: clientId ?? "all" }); +} + +export async function handleDisableFlipperPlugin( + _client: ExtensionClient, + args: unknown, + transport?: Transport, +): Promise { + const flipper = asFlipperTransport(transport); + if (!flipper) return err("not using a Flipper transport"); + + const { clientId } = ClientIdInput.parse(args); + try { + await flipper.disablePlugin(clientId); + } catch (error) { + return err(error instanceof Error ? error.message : String(error)); + } + return ok({ disabled: true, clientId: clientId ?? "all" }); +} + +export const getFlipperPluginActivationStatusDef: ToolDef = { + name: "get_flipper_plugin_activation_status", + description: + "Get per-client activation status of the Player UI Devtools Flipper plugin: which connected clients have completed the init handshake (active) versus which are connected but not yet activated (inactive). Distinct from get_flipper_plugin_install_status, which only reports whether the plugin is installed on the daemon, not activated for any specific client.", + inputSchema: {}, + annotations: { readOnlyHint: true, destructiveHint: false }, + handle: handleGetFlipperPluginActivationStatus, +}; + +export const enableFlipperPluginDef: ToolDef = { + name: "enable_flipper_plugin", + description: + "Activate the Player UI Devtools Flipper plugin for a client by sending the init handshake (installing the plugin on the daemon first, if needed). Pass clientId to target one client, or omit it to activate every connected client not already active. There is no direct mapping from clientId to the playerId(s) it hosts — after activating, poll list_players until the expected Player appears.", + inputSchema: clientIdShape, + annotations: { readOnlyHint: false, destructiveHint: false }, + handle: handleEnableFlipperPlugin, +}; + +export const disableFlipperPluginDef: ToolDef = { + name: "disable_flipper_plugin", + description: + "Deactivate the Player UI Devtools Flipper plugin for a client by sending the deinit handshake, without disconnecting it from flipper-server. Pass clientId to target one client, or omit it to deactivate every currently active client.", + inputSchema: clientIdShape, + annotations: { readOnlyHint: false, destructiveHint: false }, + handle: handleDisableFlipperPlugin, +}; diff --git a/devtools/mcp/src/tools/flow.ts b/devtools/mcp/src/tools/flow.ts index 029cb98..2a68d78 100644 --- a/devtools/mcp/src/tools/flow.ts +++ b/devtools/mcp/src/tools/flow.ts @@ -3,7 +3,7 @@ import type { PluginData } from "@player-devtools/types"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import type { ToolDef } from "./index"; +import { ok, err, type ToolDef } from "./index"; type Failure = { error: string }; type PlayerOk = { @@ -51,16 +51,6 @@ function resolveBasicPlugin( return { id, player, basicPlugin }; } -function ok(value: unknown): CallToolResult { - return { content: [{ type: "text", text: JSON.stringify(value) }] }; -} - -function err(message: string): CallToolResult { - return { - content: [{ type: "text", text: JSON.stringify({ error: message }) }], - }; -} - export function handleGetFlow( client: ExtensionClient, input: unknown, diff --git a/devtools/mcp/src/tools/index.ts b/devtools/mcp/src/tools/index.ts index c4a1056..c8f5cc1 100644 --- a/devtools/mcp/src/tools/index.ts +++ b/devtools/mcp/src/tools/index.ts @@ -1,29 +1,60 @@ import type { ExtensionClient } from "@player-devtools/client"; -import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { + CallToolResult, + ToolAnnotations, +} from "@modelcontextprotocol/sdk/types.js"; +import type { Transport } from "@player-devtools/types"; import type { ZodRawShape } from "zod"; /** * A tool definition consumed by the MCP server. `inputSchema` is a Zod raw * shape — the SDK derives the JSON Schema, validates input, and types the - * handler's `args`. The handler receives the running devtools client plus the - * validated args. + * handler's `args`. The handler receives the running devtools client, the + * validated args, and the raw `Transport` for tools that need connection-level + * diagnostics `ExtensionClient` doesn't expose. */ export type ToolDef = { name: string; description: string; inputSchema: Shape; - handle: (client: ExtensionClient, args: unknown) => CallToolResult; + annotations?: ToolAnnotations; + handle: ( + client: ExtensionClient, + args: unknown, + transport?: Transport, + ) => CallToolResult | Promise; }; +/** Shared JSON-envelope helpers used by every tool handler in this package. */ +export function ok(value: unknown): CallToolResult { + return { content: [{ type: "text", text: JSON.stringify(value) }] }; +} + +export function err(message: string): CallToolResult { + return { + content: [{ type: "text", text: JSON.stringify({ error: message }) }], + }; +} + export * from "./flow"; export * from "./players"; export * from "./plugins"; export * from "./select"; +export * from "./flipper"; import { listPlayersDef, getPlayerStatusDef } from "./players"; import { getFlowDef, getDataDef, getLogsDef, getPluginDataDef } from "./flow"; import { describePluginDef } from "./plugins"; import { selectPlayerDef, invokeActionDef } from "./select"; +import { + getFlipperStatusDef, + getFlipperConsumersDef, + restartFlipperServerDef, + getFlipperPluginInstallStatusDef, + getFlipperPluginActivationStatusDef, + enableFlipperPluginDef, + disableFlipperPluginDef, +} from "./flipper"; /** Every tool the MCP server exposes. */ export const TOOL_DEFS: ToolDef[] = [ @@ -36,4 +67,11 @@ export const TOOL_DEFS: ToolDef[] = [ describePluginDef, selectPlayerDef, invokeActionDef, + getFlipperStatusDef, + getFlipperConsumersDef, + restartFlipperServerDef, + getFlipperPluginInstallStatusDef, + getFlipperPluginActivationStatusDef, + enableFlipperPluginDef, + disableFlipperPluginDef, ]; diff --git a/devtools/mcp/src/tools/players.ts b/devtools/mcp/src/tools/players.ts index 47aa7d9..5ab343d 100644 --- a/devtools/mcp/src/tools/players.ts +++ b/devtools/mcp/src/tools/players.ts @@ -2,7 +2,7 @@ import type { ExtensionClient } from "@player-devtools/client"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import type { ToolDef } from "./index"; +import { ok, err, type ToolDef } from "./index"; const playerIdShape = { playerId: z @@ -15,17 +15,7 @@ const GetPlayerStatusInput = z.object(playerIdShape); export function handleListPlayers(client: ExtensionClient): CallToolResult { const { players, current } = client.getState(); - return { - content: [ - { - type: "text", - text: JSON.stringify({ - players: Object.keys(players), - current: current.player, - }), - }, - ], - }; + return ok({ players: Object.keys(players), current: current.player }); } export function handleGetPlayerStatus( @@ -35,26 +25,10 @@ export function handleGetPlayerStatus( const { playerId } = GetPlayerStatusInput.parse(input); const { players, current } = client.getState(); const id = playerId ?? current.player; - if (!id) return errorResult("no player selected"); + if (!id) return err("no player selected"); const player = players[id]; - if (!player) return errorResult(`player not found: ${id}`); - return { - content: [ - { - type: "text", - text: JSON.stringify({ - active: player.active, - plugins: Object.keys(player.plugins), - }), - }, - ], - }; -} - -function errorResult(message: string): CallToolResult { - return { - content: [{ type: "text", text: JSON.stringify({ error: message }) }], - }; + if (!player) return err(`player not found: ${id}`); + return ok({ active: player.active, plugins: Object.keys(player.plugins) }); } export const listPlayersDef: ToolDef = { diff --git a/devtools/mcp/src/tools/plugins.ts b/devtools/mcp/src/tools/plugins.ts index 2caf97b..e6e0c9a 100644 --- a/devtools/mcp/src/tools/plugins.ts +++ b/devtools/mcp/src/tools/plugins.ts @@ -2,7 +2,7 @@ import type { ExtensionClient } from "@player-devtools/client"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import type { ToolDef } from "./index"; +import { ok, err, type ToolDef } from "./index"; const describePluginShape = { playerId: z @@ -14,16 +14,6 @@ const describePluginShape = { const DescribePluginInput = z.object(describePluginShape); -function err(message: string): CallToolResult { - return { - content: [{ type: "text", text: JSON.stringify({ error: message }) }], - }; -} - -function ok(value: unknown): CallToolResult { - return { content: [{ type: "text", text: JSON.stringify(value) }] }; -} - export function handleDescribePlugin( client: ExtensionClient, input: unknown, diff --git a/devtools/mcp/src/tools/select.ts b/devtools/mcp/src/tools/select.ts index 7fa1522..0c237c9 100644 --- a/devtools/mcp/src/tools/select.ts +++ b/devtools/mcp/src/tools/select.ts @@ -2,7 +2,7 @@ import type { ExtensionClient } from "@player-devtools/client"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import type { ToolDef } from "./index"; +import { ok, err, type ToolDef } from "./index"; const selectPlayerShape = { playerId: z.string().describe("The Player ID to select."), @@ -22,16 +22,6 @@ const SelectPlayerInput = z.object(selectPlayerShape); const InvokeActionInput = z.object(invokeActionShape); -function err(message: string): CallToolResult { - return { - content: [{ type: "text", text: JSON.stringify({ error: message }) }], - }; -} - -function ok(value: unknown): CallToolResult { - return { content: [{ type: "text", text: JSON.stringify(value) }] }; -} - export function handleSelectPlayer( client: ExtensionClient, input: unknown,