From d19762f78b9e33c279ab17911165eae66f49fb7a Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:26:20 -0700 Subject: [PATCH 01/13] Add annotations and transport plumbing to ToolDef Widens ToolDef.handle to accept the raw Transport and return a sync or async CallToolResult, and forwards tool annotations through registerTool. This is prep for tools that need connection-level diagnostics ExtensionClient doesn't expose. --- devtools/mcp/src/server.ts | 16 ++++++++++++---- devtools/mcp/src/tools/index.ts | 18 ++++++++++++++---- 2 files changed, 26 insertions(+), 8 deletions(-) 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/index.ts b/devtools/mcp/src/tools/index.ts index c4a1056..09233cf 100644 --- a/devtools/mcp/src/tools/index.ts +++ b/devtools/mcp/src/tools/index.ts @@ -1,18 +1,28 @@ 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; }; export * from "./flow"; From 7ff7567f737c0114290b1a5fb96edd41a8cca64a Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:26:28 -0700 Subject: [PATCH 02/13] Add diagnostics surface to FlipperServerTransport Lifts host/port to instance fields, tracks whether this instance owns the shared flipper-server daemon, and adds getDiagnostics(), restart(), and getPluginInstallStatus() so callers can inspect and manage the transport's connection to the daemon. restart() only acts when this instance owns the daemon and is its sole remaining consumer, otherwise it soft-errors without touching a daemon other instances depend on. FlipperRefcount gains a read-only peek() that never mutates the refcount file. --- devtools/client/flipper/src/transport.ts | 94 +++++++++++++++++++++++- 1 file changed, 92 insertions(+), 2 deletions(-) diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index b25151c..5e545a2 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, set at the top of `connect()`. */ + private host = "localhost"; + private port = 52342; + + /** + * 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" */ @@ -266,13 +284,14 @@ export class FlipperServerTransport implements Transport { ) {} async connect(): Promise { - const host = this.options.host ?? "localhost"; - const port = this.options.port ?? 52342; + const host = (this.host = this.options.host ?? "localhost"); + const port = (this.port = this.options.port ?? 52342); // 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..."); @@ -563,4 +582,75 @@ export class FlipperServerTransport implements Transport { } } } + + /** 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[]; + } { + 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], + }; + } + + /** + * 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", + }; + } + + await this.close(); + await this.connect(); + 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; + }> { + if (!this.server) return { installed: false }; + + 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 }; + } } From 87d151b0b39268b67c92b98639905d1d722b39b3 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:26:43 -0700 Subject: [PATCH 03/13] Add Flipper diagnostic tools Adds four MCP tools exposing FlipperServerTransport's connection state to agents: get_flipper_status, get_flipper_consumers, restart_flipper_server, and get_flipper_plugin_install_status. Each narrows the transport via instanceof and soft-errors when it isn't a FlipperServerTransport. --- devtools/mcp/src/tools/flipper.ts | 111 ++++++++++++++++++++++++++++++ devtools/mcp/src/tools/index.ts | 11 +++ 2 files changed, 122 insertions(+) create mode 100644 devtools/mcp/src/tools/flipper.ts diff --git a/devtools/mcp/src/tools/flipper.ts b/devtools/mcp/src/tools/flipper.ts new file mode 100644 index 0000000..5f4a8ba --- /dev/null +++ b/devtools/mcp/src/tools/flipper.ts @@ -0,0 +1,111 @@ +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 type { ToolDef } from "./index"; + +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) }] }; +} + +/** 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, owns, refs } = flipper.getDiagnostics(); + return ok({ connected, host, port, owns, refs }); +} + +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 } = flipper.getDiagnostics(); + return ok({ owns, refs, activeClientIds }); +} + +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"); + } + + return ok(await flipper.getPluginInstallStatus()); +} + +export const getFlipperStatusDef: ToolDef = { + name: "get_flipper_status", + description: + "Get the MCP server's connection status to the shared flipper-server daemon (host, port, ownership, refcount).", + inputSchema: {}, + annotations: { readOnlyHint: true, destructiveHint: false }, + handle: handleGetFlipperStatus, +}; + +export const getFlipperConsumersDef: ToolDef = { + name: "get_flipper_consumers", + description: + "Get the active devtools clients attached through this Flipper connection, plus the daemon-wide refcount (reflects all consumers of the shared daemon, not just this process).", + 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, +}; diff --git a/devtools/mcp/src/tools/index.ts b/devtools/mcp/src/tools/index.ts index 09233cf..453f0c4 100644 --- a/devtools/mcp/src/tools/index.ts +++ b/devtools/mcp/src/tools/index.ts @@ -29,11 +29,18 @@ 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, +} from "./flipper"; /** Every tool the MCP server exposes. */ export const TOOL_DEFS: ToolDef[] = [ @@ -46,4 +53,8 @@ export const TOOL_DEFS: ToolDef[] = [ describePluginDef, selectPlayerDef, invokeActionDef, + getFlipperStatusDef, + getFlipperConsumersDef, + restartFlipperServerDef, + getFlipperPluginInstallStatusDef, ]; From fe22a1afaf11d1d16b3b6794d10d75b5d6ace255 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:26:50 -0700 Subject: [PATCH 04/13] Add tests for Flipper diagnostics Covers the four MCP flipper tools' handlers (including the non-Flipper and not-owner soft-error paths) and establishes the first test harness for @player-devtools/client-flipper: FlipperServerTransport's getDiagnostics/restart/getPluginInstallStatus, plus a check that FlipperRefcount.peek() never mutates the refcount file. --- .../flipper/src/__tests__/transport.test.ts | 208 +++++++++++++++++- .../mcp/src/tools/__tests__/flipper.test.ts | 156 +++++++++++++ 2 files changed, 359 insertions(+), 5 deletions(-) create mode 100644 devtools/mcp/src/tools/__tests__/flipper.test.ts diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index 4b5efa9..3fca512 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,173 @@ 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: [], + }); + }); + + it("reflects custom host/port options even before connecting", () => { + const transport = makeIsolatedTransport({ + host: "127.0.0.1", + port: 9999, + }); + // host/port are only assigned inside connect(); options alone don't + // seed the instance fields, matching the plan's "set at top of + // connect()" requirement. + expect(transport.getDiagnostics()).toMatchObject({ + host: "localhost", + port: 52342, + }); + }); + + it("reports connected + owns + refs + activeClientIds once seeded", () => { + const transport = makeIsolatedTransport(); + const state = internals(transport); + state.server = {}; + state.owns = true; + state.activeClientIds = new Set(["a", "b"]); + state.refcount = { peek: () => ({ pid: 123, refs: 1 }) }; + + expect(transport.getDiagnostics()).toEqual({ + connected: true, + host: "localhost", + port: 52342, + owns: true, + refs: 1, + activeClientIds: ["a", "b"], + }); + }); + }); + + 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") + .mockImplementation(async () => { + state.host = "localhost"; + state.port = 52342; + }); + + const result = await transport.restart(); + + expect(close).toHaveBeenCalledOnce(); + expect(connect).toHaveBeenCalledOnce(); + expect(result).toEqual({ ok: true, host: "localhost", port: 52342 }); + }); + }); + + 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, + }); + }); + + 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, + }); + }); + }); }); 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..da9c0fb --- /dev/null +++ b/devtools/mcp/src/tools/__tests__/flipper.test.ts @@ -0,0 +1,156 @@ +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, +} 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_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("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_status", () => { + it("reports diagnostics from an unconnected transport", () => { + const transport = makeFlipperTransport(); + const result = handleGetFlipperStatus(client, {}, transport); + expect(parse(result)).toEqual({ + connected: false, + host: "localhost", + port: 52342, + owns: false, + refs: null, + }); + }); + }); + + describe("get_flipper_consumers", () => { + it("reports refcount and active client ids", () => { + const transport = makeFlipperTransport(); + ( + transport as unknown as { activeClientIds: Set } + ).activeClientIds = new Set(["client-a", "client-b"]); + + const result = handleGetFlipperConsumers(client, {}, transport); + expect(parse(result)).toEqual({ + owns: false, + refs: null, + activeClientIds: ["client-a", "client-b"], + }); + }); + }); + + 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" }); + }); + }); +}); From 975814ea29cd51f17106b0e2b5b54c26b050b334 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:26:56 -0700 Subject: [PATCH 05/13] Document Flipper diagnostic tools in README Adds a Diagnostics subheading covering the four new tools, kept visually distinct from the core Player tools table. --- devtools/mcp/README.md | 49 +++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/devtools/mcp/README.md b/devtools/mcp/README.md index 116fe6c..23f5be6 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,38 @@ 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`. + +| Tool | Args | Returns | +| ----------------------------------- | ---- | ------------------------------------------------------------------------------------------------------ | +| `get_flipper_status` | — | Connection health: `connected`, `host`, `port`, `owns`, `refs`. | +| `get_flipper_consumers` | — | `owns`, `refs` (daemon-wide, not just this process), and `activeClientIds`. | +| `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. | + > **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 +208,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 From 70a0f9b8fd127d6420357282895fdbf4842a8055 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:45:21 -0700 Subject: [PATCH 06/13] Fix restart/close/getPluginInstallStatus soft-error and race gaps Code review on the Flipper diagnostic tools found four correctness gaps: - restart() let a failed close()+connect() propagate as an unhandled rejection instead of the soft-error contract every other tool follows, and left `owns` set against a daemon in an unknown state. It now wraps the sequence in try/catch, resets `owns` to false on failure, and returns `{ ok: false, reason }`. - restart()'s owns/refcount check was TOCTOU: another instance could acquire() between the check and the destructive close(). Added a re-peek immediately before close() that aborts with a soft error if refs changed; a one-line comment documents the still-narrow residual window (a full fix would need close()+connect() inside the refcount's lock, which isn't reentrant-safe with connect()'s own lock use). - close() sent SIGTERM and returned without confirming the process actually exited, letting restart()'s immediate connect() race the old daemon for the port. close() now waits for the pid to stop responding to signal 0, bounded by a timeout. - getPluginInstallStatus()'s exec() call was unguarded, so a dropped daemon mid-call propagated as an unhandled rejection. It now catches the rejection and returns `{ installed: false, reason }`, distinct from the "not connected" and "connected, not installed" cases. --- .../flipper/src/__tests__/transport.test.ts | 112 ++++++++++++++++++ devtools/client/flipper/src/transport.ts | 94 +++++++++++++-- .../mcp/src/tools/__tests__/flipper.test.ts | 13 ++ devtools/mcp/src/tools/flipper.ts | 16 +-- 4 files changed, 214 insertions(+), 21 deletions(-) diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index 3fca512..912f98b 100644 --- a/devtools/client/flipper/src/__tests__/transport.test.ts +++ b/devtools/client/flipper/src/__tests__/transport.test.ts @@ -415,6 +415,55 @@ describe("FlipperServerTransport", () => { 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", () => { @@ -422,6 +471,7 @@ describe("FlipperServerTransport", () => { const transport = new FlipperServerTransport(); await expect(transport.getPluginInstallStatus()).resolves.toEqual({ installed: false, + reason: "not connected", }); }); @@ -460,5 +510,67 @@ describe("FlipperServerTransport", () => { 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", + }); + }); + }); + + 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(); + } + }); }); }); diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index 5e545a2..5f0f2e0 100644 --- a/devtools/client/flipper/src/transport.ts +++ b/devtools/client/flipper/src/transport.ts @@ -574,12 +574,52 @@ 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; } } @@ -627,8 +667,35 @@ export class FlipperServerTransport implements Transport { }; } - await this.close(); - await this.connect(); + // 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 }; } @@ -636,12 +703,21 @@ export class FlipperServerTransport implements Transport { async getPluginInstallStatus(): Promise<{ installed: boolean; version?: string; + reason?: string; }> { - if (!this.server) return { installed: false }; + if (!this.server) return { installed: false, reason: "not connected" }; - const plugins = (await this.server.exec( - "plugins-get-installed-plugins", - )) as Array<{ id?: string; name?: string; version?: string }>; + let plugins: Array<{ id?: string; name?: string; version?: string }>; + try { + plugins = (await this.server.exec( + "plugins-get-installed-plugins", + )) as Array<{ id?: string; name?: string; version?: string }>; + } catch (err) { + return { + installed: false, + reason: err instanceof Error ? err.message : String(err), + }; + } const plugin = plugins.find( (candidate) => diff --git a/devtools/mcp/src/tools/__tests__/flipper.test.ts b/devtools/mcp/src/tools/__tests__/flipper.test.ts index da9c0fb..cbde83a 100644 --- a/devtools/mcp/src/tools/__tests__/flipper.test.ts +++ b/devtools/mcp/src/tools/__tests__/flipper.test.ts @@ -152,5 +152,18 @@ describe("flipper diagnostic tools", () => { ); 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" }); + }); }); }); diff --git a/devtools/mcp/src/tools/flipper.ts b/devtools/mcp/src/tools/flipper.ts index 5f4a8ba..1a0806e 100644 --- a/devtools/mcp/src/tools/flipper.ts +++ b/devtools/mcp/src/tools/flipper.ts @@ -3,17 +3,7 @@ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import type { Transport } from "@player-devtools/types"; import { FlipperServerTransport } from "@player-devtools/client-flipper"; -import type { ToolDef } from "./index"; - -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) }] }; -} +import { ok, err, type ToolDef } from "./index"; /** Narrow the generic `Transport` to the concrete Flipper implementation. */ function asFlipperTransport( @@ -71,7 +61,9 @@ export async function handleGetFlipperPluginInstallStatus( return err("flipper transport not connected"); } - return ok(await flipper.getPluginInstallStatus()); + const status = await flipper.getPluginInstallStatus(); + if (!status.installed && status.reason) return err(status.reason); + return ok(status); } export const getFlipperStatusDef: ToolDef = { From c04b0fd7e119e2ee13a6fafc65abb6ef6ddb98c9 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:45:26 -0700 Subject: [PATCH 07/13] Consolidate duplicated ok/err MCP tool result helpers flipper.ts, flow.ts, plugins.ts, select.ts and players.ts each redefined their own identical ok()/err() JSON-envelope helpers (or, in players.ts, an errorResult() equivalent plus inline literals for the success case). Extracted a single ok/err pair into tools/index.ts and updated every tool file to import it instead, with no change to the envelope shape. --- devtools/mcp/src/tools/flow.ts | 12 +---------- devtools/mcp/src/tools/index.ts | 11 ++++++++++ devtools/mcp/src/tools/players.ts | 36 +++++-------------------------- devtools/mcp/src/tools/plugins.ts | 12 +---------- devtools/mcp/src/tools/select.ts | 12 +---------- 5 files changed, 19 insertions(+), 64 deletions(-) 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 453f0c4..529cc63 100644 --- a/devtools/mcp/src/tools/index.ts +++ b/devtools/mcp/src/tools/index.ts @@ -25,6 +25,17 @@ export type ToolDef = { ) => 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"; 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, From b0ff7f8a3bd0aadc3e00ab5eb25d36f96dbb9980 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 21:58:17 -0700 Subject: [PATCH 08/13] Fix close() reentrancy, orphaned spawn cleanup, and getPluginInstallStatus soft-error gap Second re-review pass on the Flipper diagnostics transport: close() could double-run teardown (double refcount release / duplicate kill-wait) under concurrent callers, a failed waitForPort() after a successful spawn left an untracked orphan daemon process running, and getPluginInstallStatus()'s .find() call sat outside its try/catch so a malformed exec() response threw instead of returning the soft-error shape. --- .../flipper/src/__tests__/transport.test.ts | 100 ++++++++++++++++++ devtools/client/flipper/src/transport.ts | 51 ++++++--- 2 files changed, 138 insertions(+), 13 deletions(-) diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index 912f98b..c315039 100644 --- a/devtools/client/flipper/src/__tests__/transport.test.ts +++ b/devtools/client/flipper/src/__tests__/transport.test.ts @@ -522,6 +522,20 @@ describe("FlipperServerTransport", () => { 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.toMatchObject({ + installed: false, + }); + }); }); describe("close", () => { @@ -572,5 +586,91 @@ describe("FlipperServerTransport", () => { vi.useRealTimers(); } }); + + it("is idempotent: a second concurrent close() does not re-run teardown", async () => { + const transport = new FlipperServerTransport(); + const state = internals(transport); + + 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); + expect(state).toBeDefined(); + }); + }); + + describe("connect", () => { + it("kills the spawned child 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 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 `ChildProcess.prototype.kill` instead + // — the real spawn() runs, but against a port nothing listens on, and + // fake timers fast-forward waitForPort's 30s polling loop. + const { ChildProcess } = await import("child_process"); + const killSpy = vi + .spyOn(ChildProcess.prototype, "kill") + .mockImplementation(() => true); + + 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. + await vi.advanceTimersByTimeAsync(31_000); + + const result = await connectPromise; + + expect(result).toBeInstanceOf(Error); + expect(killSpy).toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + killSpy.mockRestore(); + } + }); }); }); diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index 5f0f2e0..f1aa6d1 100644 --- a/devtools/client/flipper/src/transport.ts +++ b/devtools/client/flipper/src/transport.ts @@ -322,7 +322,16 @@ 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. + child.kill(); + throw err; + } commit(child.pid!); log("[FlipperServerTransport] flipper-server ready."); } else { @@ -562,7 +571,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(); @@ -707,26 +733,25 @@ export class FlipperServerTransport implements Transport { }> { if (!this.server) return { installed: false, reason: "not connected" }; - let plugins: Array<{ id?: string; name?: string; version?: string }>; try { - plugins = (await this.server.exec( + 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), }; } - - 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 }; } } From 88be096fd24ee459310e7510f794ffae0edcc7d8 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 22:09:53 -0700 Subject: [PATCH 09/13] Wait for orphaned spawn-failure child to exit before rethrowing connect()'s spawn-failure cleanup called child.kill() but didn't confirm the process actually exited before rethrowing, unlike close()'s killAndWait() which is used for the same purpose everywhere else in this file. A caller retrying connect() right after a waitForPort() timeout could spawn a second flipper-server while the first was still mid- teardown, racing for the same port. Also tighten two test assertions flagged in review: pin the exact soft-error reason for getPluginInstallStatus()'s malformed-response case, and drop a vacuous toBeDefined() assertion in the close() reentrancy test. --- .../flipper/src/__tests__/transport.test.ts | 47 ++++++++++++------- devtools/client/flipper/src/transport.ts | 8 +++- 2 files changed, 37 insertions(+), 18 deletions(-) diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index c315039..9832083 100644 --- a/devtools/client/flipper/src/__tests__/transport.test.ts +++ b/devtools/client/flipper/src/__tests__/transport.test.ts @@ -532,8 +532,9 @@ describe("FlipperServerTransport", () => { exec: vi.fn().mockResolvedValue({ unexpected: "shape" }), }; - await expect(transport.getPluginInstallStatus()).resolves.toMatchObject({ + await expect(transport.getPluginInstallStatus()).resolves.toEqual({ installed: false, + reason: "plugins.find is not a function", }); }); }); @@ -589,7 +590,6 @@ describe("FlipperServerTransport", () => { it("is idempotent: a second concurrent close() does not re-run teardown", async () => { const transport = new FlipperServerTransport(); - const state = internals(transport); let releaseCalls = 0; ( @@ -610,27 +610,37 @@ describe("FlipperServerTransport", () => { await Promise.all([first, second]); expect(releaseCalls).toBe(1); - expect(state).toBeDefined(); }); }); describe("connect", () => { - it("kills the spawned child when waitForPort fails after spawn", async () => { + 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 or it orphans. + // 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 `ChildProcess.prototype.kill` instead - // — the real spawn() runs, but against a port nothing listens on, and - // fake timers fast-forward waitForPort's 30s polling loop. - const { ChildProcess } = await import("child_process"); - const killSpy = vi - .spyOn(ChildProcess.prototype, "kill") - .mockImplementation(() => true); + // 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 { @@ -660,16 +670,21 @@ describe("FlipperServerTransport", () => { const connectPromise = transport.connect().catch((err) => err as Error); - // Advance past waitForPort's internal 30s timeout so it rejects. - await vi.advanceTimersByTimeAsync(31_000); + // 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); - expect(killSpy).toHaveBeenCalled(); + // 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(); - killSpy.mockRestore(); + processKillSpy.mockRestore(); } }); }); diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index f1aa6d1..b175186 100644 --- a/devtools/client/flipper/src/transport.ts +++ b/devtools/client/flipper/src/transport.ts @@ -328,8 +328,12 @@ export class FlipperServerTransport implements Transport { // 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. - child.kill(); + // 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!); From cbf427c290d13e5a9c8f33e3d2a5c7e4383f7a38 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Tue, 22 Sep 2026 19:45:28 -0700 Subject: [PATCH 10/13] Add per-client plugin activation status and enable/disable MCP tools Exposes FlipperServerTransport.enablePlugin()/disablePlugin() and the connected/active client split as MCP tools, so an agent can check whether the devtools plugin is activated for a specific Flipper client and trigger/release that activation directly, instead of only seeing daemon-wide install status. --- .../flipper/src/__tests__/transport.test.ts | 5 +- devtools/client/flipper/src/transport.ts | 2 + devtools/mcp/README.md | 15 +- .../mcp/src/tools/__tests__/flipper.test.ts | 162 +++++++++++++++++- devtools/mcp/src/tools/flipper.ts | 97 ++++++++++- devtools/mcp/src/tools/index.ts | 6 + 6 files changed, 274 insertions(+), 13 deletions(-) diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index 9832083..aa326f2 100644 --- a/devtools/client/flipper/src/__tests__/transport.test.ts +++ b/devtools/client/flipper/src/__tests__/transport.test.ts @@ -303,6 +303,7 @@ describe("FlipperServerTransport", () => { owns: false, refs: null, activeClientIds: [], + connectedClientIds: [], }); }); @@ -320,12 +321,13 @@ describe("FlipperServerTransport", () => { }); }); - it("reports connected + owns + refs + activeClientIds once seeded", () => { + 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({ @@ -335,6 +337,7 @@ describe("FlipperServerTransport", () => { owns: true, refs: 1, activeClientIds: ["a", "b"], + connectedClientIds: ["a", "b", "c"], }); }); }); diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index b175186..d686dc3 100644 --- a/devtools/client/flipper/src/transport.ts +++ b/devtools/client/flipper/src/transport.ts @@ -661,6 +661,7 @@ export class FlipperServerTransport implements Transport { owns: boolean; refs: number | null; activeClientIds: string[]; + connectedClientIds: string[]; } { const state = this.refcount.peek(); return { @@ -670,6 +671,7 @@ export class FlipperServerTransport implements Transport { owns: this.owns, refs: state?.refs ?? null, activeClientIds: [...this.activeClientIds], + connectedClientIds: [...this.connectedClientIds], }; } diff --git a/devtools/mcp/README.md b/devtools/mcp/README.md index 23f5be6..e79b05f 100644 --- a/devtools/mcp/README.md +++ b/devtools/mcp/README.md @@ -84,12 +84,15 @@ 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`. -| Tool | Args | Returns | -| ----------------------------------- | ---- | ------------------------------------------------------------------------------------------------------ | -| `get_flipper_status` | — | Connection health: `connected`, `host`, `port`, `owns`, `refs`. | -| `get_flipper_consumers` | — | `owns`, `refs` (daemon-wide, not just this process), and `activeClientIds`. | -| `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. | +| Tool | Args | Returns | +| -------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------- | +| `get_flipper_status` | — | Connection health: `connected`, `host`, `port`, `owns`, `refs`. | +| `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. | +| `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 diff --git a/devtools/mcp/src/tools/__tests__/flipper.test.ts b/devtools/mcp/src/tools/__tests__/flipper.test.ts index cbde83a..fc4baf9 100644 --- a/devtools/mcp/src/tools/__tests__/flipper.test.ts +++ b/devtools/mcp/src/tools/__tests__/flipper.test.ts @@ -8,6 +8,9 @@ import { handleGetFlipperConsumers, handleRestartFlipperServer, handleGetFlipperPluginInstallStatus, + handleGetFlipperPluginActivationStatus, + handleEnableFlipperPlugin, + handleDisableFlipperPlugin, } from "../flipper"; const client = {} as ExtensionClient; @@ -67,6 +70,33 @@ describe("flipper diagnostic tools", () => { 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" }); @@ -88,17 +118,21 @@ describe("flipper diagnostic tools", () => { }); describe("get_flipper_consumers", () => { - it("reports refcount and active client ids", () => { + it("reports refcount, active client ids, and connected client ids", () => { const transport = makeFlipperTransport(); - ( - transport as unknown as { activeClientIds: Set } - ).activeClientIds = new Set(["client-a", "client-b"]); + 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"], }); }); }); @@ -166,4 +200,124 @@ describe("flipper diagnostic tools", () => { 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 index 1a0806e..9e5e0a0 100644 --- a/devtools/mcp/src/tools/flipper.ts +++ b/devtools/mcp/src/tools/flipper.ts @@ -2,9 +2,21 @@ 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. Omit to target 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, @@ -32,8 +44,9 @@ export function handleGetFlipperConsumers( const flipper = asFlipperTransport(transport); if (!flipper) return err("not using a Flipper transport"); - const { owns, refs, activeClientIds } = flipper.getDiagnostics(); - return ok({ owns, refs, activeClientIds }); + const { owns, refs, activeClientIds, connectedClientIds } = + flipper.getDiagnostics(); + return ok({ owns, refs, activeClientIds, connectedClientIds }); } export async function handleRestartFlipperServer( @@ -101,3 +114,83 @@ export const getFlipperPluginInstallStatusDef: ToolDef = { 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.", + 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/index.ts b/devtools/mcp/src/tools/index.ts index 529cc63..c8f5cc1 100644 --- a/devtools/mcp/src/tools/index.ts +++ b/devtools/mcp/src/tools/index.ts @@ -51,6 +51,9 @@ import { getFlipperConsumersDef, restartFlipperServerDef, getFlipperPluginInstallStatusDef, + getFlipperPluginActivationStatusDef, + enableFlipperPluginDef, + disableFlipperPluginDef, } from "./flipper"; /** Every tool the MCP server exposes. */ @@ -68,4 +71,7 @@ export const TOOL_DEFS: ToolDef[] = [ getFlipperConsumersDef, restartFlipperServerDef, getFlipperPluginInstallStatusDef, + getFlipperPluginActivationStatusDef, + enableFlipperPluginDef, + disableFlipperPluginDef, ]; From 2b8355e087f8280a35837d4de6e7be6f986f30c8 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Tue, 22 Sep 2026 19:49:28 -0700 Subject: [PATCH 11/13] Address tool-organization review: dedupe status fields, clarify naming MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - get_flipper_status no longer duplicates owns/refs from get_flipper_consumers; renamed to get_flipper_connection_status to read distinctly next to it. - Document that clientId is a Flipper transport-level identifier, not a Player devtools playerId, and that it has no "current selection" fallback (unlike playerId) — both in the clientId schema description and the README's Diagnostics section. --- devtools/mcp/README.md | 26 ++++++++++++------- .../mcp/src/tools/__tests__/flipper.test.ts | 8 +++--- devtools/mcp/src/tools/flipper.ts | 12 ++++----- 3 files changed, 26 insertions(+), 20 deletions(-) diff --git a/devtools/mcp/README.md b/devtools/mcp/README.md index e79b05f..034cdcf 100644 --- a/devtools/mcp/README.md +++ b/devtools/mcp/README.md @@ -84,15 +84,23 @@ 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`. -| Tool | Args | Returns | -| -------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------- | -| `get_flipper_status` | — | Connection health: `connected`, `host`, `port`, `owns`, `refs`. | -| `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. | -| `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. | +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 diff --git a/devtools/mcp/src/tools/__tests__/flipper.test.ts b/devtools/mcp/src/tools/__tests__/flipper.test.ts index fc4baf9..1790c6e 100644 --- a/devtools/mcp/src/tools/__tests__/flipper.test.ts +++ b/devtools/mcp/src/tools/__tests__/flipper.test.ts @@ -42,7 +42,7 @@ const nonFlipperTransport = { describe("flipper diagnostic tools", () => { describe("when the transport is not a FlipperServerTransport", () => { - it("get_flipper_status soft-errors", () => { + it("get_flipper_connection_status soft-errors", () => { const result = handleGetFlipperStatus(client, {}, nonFlipperTransport); expect(parse(result)).toEqual({ error: "not using a Flipper transport" }); }); @@ -103,16 +103,14 @@ describe("flipper diagnostic tools", () => { }); }); - describe("get_flipper_status", () => { - it("reports diagnostics from an unconnected 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, - owns: false, - refs: null, }); }); }); diff --git a/devtools/mcp/src/tools/flipper.ts b/devtools/mcp/src/tools/flipper.ts index 9e5e0a0..3b91656 100644 --- a/devtools/mcp/src/tools/flipper.ts +++ b/devtools/mcp/src/tools/flipper.ts @@ -11,7 +11,7 @@ const clientIdShape = { .string() .optional() .describe( - "Flipper client ID. Omit to target every connected client — for enable/disable, only clients not already in the desired state are messaged.", + "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.", ), }; @@ -32,8 +32,8 @@ export function handleGetFlipperStatus( const flipper = asFlipperTransport(transport); if (!flipper) return err("not using a Flipper transport"); - const { connected, host, port, owns, refs } = flipper.getDiagnostics(); - return ok({ connected, host, port, owns, refs }); + const { connected, host, port } = flipper.getDiagnostics(); + return ok({ connected, host, port }); } export function handleGetFlipperConsumers( @@ -80,9 +80,9 @@ export async function handleGetFlipperPluginInstallStatus( } export const getFlipperStatusDef: ToolDef = { - name: "get_flipper_status", + name: "get_flipper_connection_status", description: - "Get the MCP server's connection status to the shared flipper-server daemon (host, port, ownership, refcount).", + "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, @@ -91,7 +91,7 @@ export const getFlipperStatusDef: ToolDef = { export const getFlipperConsumersDef: ToolDef = { name: "get_flipper_consumers", description: - "Get the active devtools clients attached through this Flipper connection, plus the daemon-wide refcount (reflects all consumers of the shared daemon, not just this process).", + "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, From 8811e2f0e822d0320967bc5ad657ce828c6b66a9 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Tue, 22 Sep 2026 20:05:49 -0700 Subject: [PATCH 12/13] Note the missing clientId-to-playerId mapping in enable_flipper_plugin There's no direct way to correlate a Flipper clientId to the playerId(s) it hosts yet. Documented the workaround (poll list_players after activating) directly in the tool description so an agent sees it before calling the tool, rather than only in the README. --- devtools/mcp/src/tools/flipper.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/devtools/mcp/src/tools/flipper.ts b/devtools/mcp/src/tools/flipper.ts index 3b91656..da9a85f 100644 --- a/devtools/mcp/src/tools/flipper.ts +++ b/devtools/mcp/src/tools/flipper.ts @@ -180,7 +180,7 @@ export const getFlipperPluginActivationStatusDef: ToolDef = { 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.", + "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, From de404529ee3a8d72cbe4dd4a60f5d06958cc209e Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Tue, 22 Sep 2026 20:10:36 -0700 Subject: [PATCH 13/13] Resolve host/port from options at construction, make them readonly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit They only ever derived from the options passed to the constructor, so lazily assigning them at the top of connect() served no purpose beyond delaying when getDiagnostics() reflected custom host/port — which was itself surprising, not intentional. Resolving them eagerly and marking them readonly makes that fixed relationship explicit and removes the possibility of drift between calls. --- .../flipper/src/__tests__/transport.test.ts | 14 +++++--------- devtools/client/flipper/src/transport.ts | 15 +++++++++------ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/devtools/client/flipper/src/__tests__/transport.test.ts b/devtools/client/flipper/src/__tests__/transport.test.ts index aa326f2..a3075d4 100644 --- a/devtools/client/flipper/src/__tests__/transport.test.ts +++ b/devtools/client/flipper/src/__tests__/transport.test.ts @@ -312,12 +312,11 @@ describe("FlipperServerTransport", () => { host: "127.0.0.1", port: 9999, }); - // host/port are only assigned inside connect(); options alone don't - // seed the instance fields, matching the plan's "set at top of - // connect()" requirement. + // host/port are resolved from options at construction time, so they're + // already correct before connect() has ever run. expect(transport.getDiagnostics()).toMatchObject({ - host: "localhost", - port: 52342, + host: "127.0.0.1", + port: 9999, }); }); @@ -407,10 +406,7 @@ describe("FlipperServerTransport", () => { const close = vi.spyOn(transport, "close").mockResolvedValue(undefined); const connect = vi .spyOn(transport, "connect") - .mockImplementation(async () => { - state.host = "localhost"; - state.port = 52342; - }); + .mockResolvedValue(undefined); const result = await transport.restart(); diff --git a/devtools/client/flipper/src/transport.ts b/devtools/client/flipper/src/transport.ts index d686dc3..75318a5 100644 --- a/devtools/client/flipper/src/transport.ts +++ b/devtools/client/flipper/src/transport.ts @@ -242,9 +242,9 @@ export class FlipperServerTransport implements Transport { */ private connectedClientIds = new Set(); - /** Resolved connection target, set at the top of `connect()`. */ - private host = "localhost"; - private port = 52342; + /** 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 @@ -281,11 +281,14 @@ 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.host = this.options.host ?? "localhost"); - const port = (this.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