Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
434 changes: 429 additions & 5 deletions devtools/client/flipper/src/__tests__/transport.test.ts

Large diffs are not rendered by default.

214 changes: 207 additions & 7 deletions devtools/client/flipper/src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down Expand Up @@ -234,6 +242,16 @@ export class FlipperServerTransport implements Transport {
*/
private connectedClientIds = new Set<string>();

/** Resolved connection target, fixed at construction from `options`. */
private readonly host: string;
private readonly port: number;

/**
* Whether this instance started the shared daemon (vs. attaching to one
* another instance started). Only an owner may consider restarting it.
*/
private owns = false;

constructor(
private options: {
/** Flipper server host; defaults to "localhost" */
Expand Down Expand Up @@ -263,16 +281,20 @@ export class FlipperServerTransport implements Transport {
*/
autoEnablePlugin?: boolean;
} = {},
) {}
) {
this.host = this.options.host ?? "localhost";
this.port = this.options.port ?? 52342;
}

async connect(): Promise<void> {
const host = this.options.host ?? "localhost";
const port = this.options.port ?? 52342;
const host = this.host;
const port = this.port;

// Register interest in the shared daemon. The first instance to do so is
// told to start it; the rest just attach. The daemon outlives any single
// MCP process and is only torn down when the last instance detaches.
const { shouldStart, commit } = this.refcount.acquire();
this.owns = shouldStart;

if (shouldStart) {
log("[FlipperServerTransport] Starting flipper-server...");
Expand Down Expand Up @@ -303,7 +325,20 @@ export class FlipperServerTransport implements Transport {
);
});
child.unref();
await waitForPort(host, port);
try {
await waitForPort(host, port);
} catch (err) {
// Nothing has recorded this PID in the refcount file yet, so nobody
// else can track or kill it — if we leave it running here it becomes
// an orphan daemon that a later connect() would compete with on the
// same port instead of detecting. Wait for it to actually exit (via
// the same bounded kill-and-confirm mechanism used everywhere else in
// this file) before rethrowing, so a caller that retries connect()
// right away doesn't spawn a second daemon racing this one for the
// port during teardown.
await this.killAndWait(child.pid!);
throw err;
}
commit(child.pid!);
log("[FlipperServerTransport] flipper-server ready.");
} else {
Expand Down Expand Up @@ -543,7 +578,24 @@ export class FlipperServerTransport implements Transport {
this.listeners.delete(callback);
};

/**
* In-flight `close()` promise, if one is currently running on this
* instance. Guards `refcount.release()` and `killAndWait()` against being
* invoked twice for a single logical close — e.g. `restart()`'s internal
* `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
*/
private closing: Promise<void> | null = null;

async close(): Promise<void> {
if (this.closing) return this.closing;

this.closing = this.doClose().finally(() => {
this.closing = null;
});
return this.closing;
}

private async doClose(): Promise<void> {
this.listeners.clear();
this.activeClientIds.clear();
this.connectedClientIds.clear();
Expand All @@ -555,12 +607,160 @@ export class FlipperServerTransport implements Transport {
// running for the remaining instances.
const pidToKill = this.refcount.release();
if (pidToKill !== null) {
await this.killAndWait(pidToKill);
}
}

/**
* Send SIGTERM and wait for the process to actually exit (or a bounded
* timeout) before resolving, so callers — notably `restart()` — can rely on
* the port being free once `close()` returns instead of racing a new child
* for it.
*/
private killAndWait(pid: number, timeoutMs = 5_000): Promise<void> {
return new Promise((resolve) => {
try {
process.kill(pidToKill);
log("[FlipperServerTransport] Shut down flipper-server.");
process.kill(pid);
} catch {
/* already gone */
// Already gone.
resolve();
return;
}

const deadline = Date.now() + timeoutMs;
const poll = () => {
if (!this.isPidAlive(pid)) {
log("[FlipperServerTransport] Shut down flipper-server.");
resolve();
return;
}
if (Date.now() >= deadline) {
log(
"[FlipperServerTransport] Timed out waiting for flipper-server to exit.",
);
resolve();
return;
}
setTimeout(poll, 100);
};
poll();
});
}

private isPidAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}

/** Read-only snapshot of this transport's connection to the shared daemon. */
getDiagnostics(): {
connected: boolean;
host: string;
port: number;
owns: boolean;
refs: number | null;
activeClientIds: string[];
connectedClientIds: string[];
} {
const state = this.refcount.peek();
return {
connected: this.server !== null,
host: this.host,
port: this.port,
owns: this.owns,
refs: state?.refs ?? null,
activeClientIds: [...this.activeClientIds],
connectedClientIds: [...this.connectedClientIds],
};
}

/**
* Restart the shared daemon. Only ever acts when this instance both owns
* the daemon (started it) and is its sole remaining consumer — otherwise
* this soft-errors without touching the daemon, since killing it out from
* under other attached instances would break their connections.
*/
async restart(): Promise<
{ ok: true; host: string; port: number } | { ok: false; reason: string }
> {
if (!this.owns) {
return {
ok: false,
reason: "this instance does not own the flipper-server daemon",
};
}

const state = this.refcount.peek();
if (state?.refs !== 1) {
return {
ok: false,
reason: "other consumers are attached to this daemon",
};
}

// Re-verify immediately before the destructive close(): another instance
// could have called connect()/acquire() between the check above and here,
// bumping refs to 2+. This narrows but does not eliminate the race — a
// consumer could still slip in between this re-check and close() itself;
// a fully atomic fix would need close()+connect() to run inside
// refcount.withLock(), which isn't reentrant-safe with connect()'s own
// internal use of the lock, so we accept this narrow residual window.
const recheck = this.refcount.peek();
if (recheck?.refs !== 1) {
return {
ok: false,
reason: "other consumers attached to this daemon just before restart",
};
}

try {
await this.close();
await this.connect();
} catch (err) {
// The daemon this instance owned/attempted to own is now in an unknown
// or dead state — don't leave `owns` set, or a later restart() call
// will misreport "other consumers are attached" against a stale
// refcount for a daemon that no longer exists.
this.owns = false;
return {
ok: false,
reason: err instanceof Error ? err.message : String(err),
};
}
return { ok: true, host: this.host, port: this.port };
}

/** Whether the devtools Flipper plugin is installed, per the live daemon. */
async getPluginInstallStatus(): Promise<{
installed: boolean;
version?: string;
reason?: string;
}> {
if (!this.server) return { installed: false, reason: "not connected" };

try {
const plugins = (await this.server.exec(
"plugins-get-installed-plugins",
)) as Array<{ id?: string; name?: string; version?: string }>;

const plugin = plugins.find(
(candidate) =>
candidate.id === PLUGIN_API || candidate.name === PLUGIN_API,
);

if (!plugin) return { installed: false };
return plugin.version
? { installed: true, version: plugin.version }
: { installed: true };
} catch (err) {
return {
installed: false,
reason: err instanceof Error ? err.message : String(err),
};
}
}
}
60 changes: 43 additions & 17 deletions devtools/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -61,23 +61,49 @@ The server registers the following tools (defined as `ToolDef`s in
player-scoped tool takes an optional `playerId` and falls back to the currently
selected Player when it's omitted.

| Tool | Args | Returns |
| --- | --- | --- |
| `list_players` | — | All known Player instances and which one is selected. |
| `get_player_status` | `playerId?` | Active status + registered plugin IDs. |
| `get_flow` | `playerId?` | The current flow (from the basic plugin). |
| `get_data` | `playerId?` | The current flow data model. |
| `get_logs` | `playerId?` | Accumulated runtime logs. |
| `get_plugin_data` | `playerId?`, `pluginId`, `dataKey` | A specific data key from any plugin. |
| `describe_plugin` | `playerId?`, `pluginId` | The plugin's capability descriptor — the data keys and actions it exposes. **Call this first** to discover what a plugin supports. |
| `select_player` | `playerId` | Selects a Player as the default target for later calls. |
| `invoke_action` | `playerId?`, `pluginId`, `action`, `payload?` | Invokes a named action (validated against the plugin's declared capabilities). |
| Tool | Args | Returns |
| ------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `list_players` | — | All known Player instances and which one is selected. |
| `get_player_status` | `playerId?` | Active status + registered plugin IDs. |
| `get_flow` | `playerId?` | The current flow (from the basic plugin). |
| `get_data` | `playerId?` | The current flow data model. |
| `get_logs` | `playerId?` | Accumulated runtime logs. |
| `get_plugin_data` | `playerId?`, `pluginId`, `dataKey` | A specific data key from any plugin. |
| `describe_plugin` | `playerId?`, `pluginId` | The plugin's capability descriptor — the data keys and actions it exposes. **Call this first** to discover what a plugin supports. |
| `select_player` | `playerId` | Selects a Player as the default target for later calls. |
| `invoke_action` | `playerId?`, `pluginId`, `action`, `payload?` | Invokes a named action (validated against the plugin's declared capabilities). |

A typical agent flow: `list_players` → `select_player` → `describe_plugin` →
`get_*` / `invoke_action`.

### Diagnostics

These tools inspect and manage the MCP server's connection to the shared
[`flipper-server` daemon](#shared-flipper-server-daemon) itself, rather than
any Player instance behind it — useful when an agent needs to tell "no Players
are connected" apart from "the Flipper transport itself is unhealthy." They
soft-error when the server isn't running on a `FlipperServerTransport`.

All `clientId` args refer to a Flipper **client** — a transport-level
device/app connection — not a Player devtools `playerId` (used by
`list_players` / `select_player` / etc). A client can be connected, and even
have the plugin activated, before any Player instance on it is visible to the
player-scoped tools; one client can also host multiple Players. Unlike
`playerId`, there is no "currently selected" client — omitting `clientId`
targets every connected client instead of falling back to a selection.

| Tool | Args | Returns |
| --------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `get_flipper_connection_status` | — | Basic connection health: `connected`, `host`, `port`. |
| `get_flipper_consumers` | — | `owns`, `refs` (daemon-wide, not just this process), `activeClientIds`, and `connectedClientIds`. |
| `restart_flipper_server` | — | Restarts the daemon — only when this process owns it and is its sole consumer, otherwise a soft error. |
| `get_flipper_plugin_install_status` | — | Whether the Player UI Devtools Flipper plugin is installed on the daemon (npm-level install, not per-client activation). |
| `get_flipper_plugin_activation_status` | — | Per-client activation split: `activeClientIds` (completed the `init` handshake) vs. `inactiveClientIds` (connected but not yet activated). |
| `enable_flipper_plugin` | `clientId?` | Activates the plugin for `clientId`, or every connected-but-inactive client if omitted (see [Plugin activation](#plugin-activation)). |
| `disable_flipper_plugin` | `clientId?` | Deactivates the plugin for `clientId`, or every currently active client if omitted, without disconnecting. |

> **NOTE**
> Tool handlers return *soft errors* (e.g. `{ "error": "player not found" }`) as
> Tool handlers return _soft errors_ (e.g. `{ "error": "player not found" }`) as
> normal results rather than throwing, so a failed call still returns a
> structured payload the agent can read.

Expand Down Expand Up @@ -193,10 +219,10 @@ Register it with an MCP client (e.g. Claude) by pointing the client at the
The server reports anonymous usage analytics so we can tell how widely it's used
and whether it's working in the field. It is **on by default** and sends:

| | |
| --- | --- |
| Identity | A random UUID generated on first run and stored at `~/.player-ui-devtools/install.json`. It is not derived from anything about you or your machine — delete the file and a new one is generated. |
| Events | Session start (`$mcp_initialize`), tool calls (`$mcp_tool_call`), tool listing (`$mcp_tools_list`), and errors (`$exception`). |
| | |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Identity | A random UUID generated on first run and stored at `~/.player-ui-devtools/install.json`. It is not derived from anything about you or your machine — delete the file and a new one is generated. |
| Events | Session start (`$mcp_initialize`), tool calls (`$mcp_tool_call`), tool listing (`$mcp_tools_list`), and errors (`$exception`). |
| Properties | Tool **name**, call duration, whether the call errored, the MCP client name/version (e.g. which editor), the devtools version, OS platform, Node major version, and whether the Flipper transport connected. |

**Tool arguments and tool responses are never transmitted.** Those can contain
Expand Down
16 changes: 12 additions & 4 deletions devtools/mcp/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<CallToolResult>,
) => 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),
);
}
}
Expand Down
Loading