trusted-user-agent 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/dist/acp/agent.js +601 -0
  3. package/dist/acp/backend.js +2 -0
  4. package/dist/acp/config-options.js +26 -0
  5. package/dist/acp/mock-backend.js +277 -0
  6. package/dist/acp/sdk-backend.js +495 -0
  7. package/dist/browser/mcp-acp-client.js +81 -0
  8. package/dist/browser/provider.js +1045 -0
  9. package/dist/browser/schemas.js +221 -0
  10. package/dist/capability-registry.js +92 -0
  11. package/dist/client-heartbeat.js +118 -0
  12. package/dist/compose/schemas.js +90 -0
  13. package/dist/contacts/schemas.js +26 -0
  14. package/dist/installer/cli.js +70 -0
  15. package/dist/installer/common.js +93 -0
  16. package/dist/installer/index.js +341 -0
  17. package/dist/installer/mcp-clients.js +555 -0
  18. package/dist/installer/mcp.js +166 -0
  19. package/dist/installer/platforms.js +277 -0
  20. package/dist/logger.js +54 -0
  21. package/dist/mail/schemas.js +98 -0
  22. package/dist/mutation/schemas.js +31 -0
  23. package/dist/native-host/broker-ipc.js +344 -0
  24. package/dist/native-host/framing.js +76 -0
  25. package/dist/native-host/main.js +520 -0
  26. package/dist/native-host/mcp-server.js +322 -0
  27. package/dist/native-host/mcp-stdio-bridge.js +179 -0
  28. package/dist/native-host/mcp-stdio-main.js +13 -0
  29. package/dist/native-host/relay.js +84 -0
  30. package/dist/native-host/skills-startup.js +167 -0
  31. package/dist/native-host/transport.js +248 -0
  32. package/dist/permission-store.js +207 -0
  33. package/dist/repl/fs-sandbox.js +187 -0
  34. package/dist/repl/provider.js +252 -0
  35. package/dist/repl/runtime.js +436 -0
  36. package/dist/repl/types.js +10 -0
  37. package/dist/repl/worker.js +731 -0
  38. package/dist/skills/extension.js +99 -0
  39. package/dist/skills/grants-file.js +145 -0
  40. package/dist/skills/isolated-runner.js +259 -0
  41. package/dist/skills/mock-session-factory.js +49 -0
  42. package/dist/skills/package-roots.js +25 -0
  43. package/dist/skills/pi-bridge.js +8 -0
  44. package/dist/skills/pi-integration.js +110 -0
  45. package/dist/skills/planner.js +128 -0
  46. package/dist/skills/registry.js +104 -0
  47. package/dist/skills/skills-protocol.js +253 -0
  48. package/dist/skills/skills-service.js +195 -0
  49. package/dist/tool-bridge.js +8 -0
  50. package/dist/workspace.js +70 -0
  51. package/extensions/pi-browser-tools.ts +65 -0
  52. package/extensions/pi-browser.ts +60 -0
  53. package/extensions/pi-skills.ts +14 -0
  54. package/native/pi-agent-host +2 -0
  55. package/native/pi-browser-host +5 -0
  56. package/native/pi-browser-host.cmd +3 -0
  57. package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
  58. package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
  59. package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
  60. package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
  61. package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
  62. package/node_modules/@pi-browser/protocol/dist/callers.d.ts +108 -0
  63. package/node_modules/@pi-browser/protocol/dist/callers.js +56 -0
  64. package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
  65. package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
  66. package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
  67. package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
  68. package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
  69. package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
  70. package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
  71. package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
  72. package/node_modules/@pi-browser/protocol/dist/index.d.ts +16 -0
  73. package/node_modules/@pi-browser/protocol/dist/index.js +16 -0
  74. package/node_modules/@pi-browser/protocol/dist/integration.d.ts +409 -0
  75. package/node_modules/@pi-browser/protocol/dist/integration.js +260 -0
  76. package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
  77. package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
  78. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
  79. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
  80. package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
  81. package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
  82. package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
  83. package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
  84. package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
  85. package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
  86. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
  87. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
  88. package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
  89. package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
  90. package/node_modules/@pi-browser/protocol/package.json +14 -0
  91. package/package.json +71 -6
  92. package/skills/browser-walk/SKILL.md +98 -0
  93. package/README.md +0 -3
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Pi Browser tools MCP server (MCP over unix socket / Windows named pipe).
3
+ *
4
+ * Pi subagent children run as separate node processes: they have no ACP
5
+ * channel to the connected app and no in-process tool bridge (the bridge
6
+ * module state lives only in this broker process). This server gives them
7
+ * browser and mail access the standard way — the broker, which owns both
8
+ * the ACP pipe and the tool bridge, exposes the add-on tools as a plain MCP
9
+ * server on a private unix socket: Firefox's browser tools, the host-side
10
+ * `javascript` REPL, and Thunderbird's mail / compose / mail-organization /
11
+ * contacts tools. Calls route to whichever connected app serves the tool
12
+ * (the broker's cross-app routing), so a subagent reaches Thunderbird even
13
+ * when its parent session lives in Firefox, and vice versa.
14
+ *
15
+ * The list is static (every tool family, whether or not its app is
16
+ * connected right now): MCP clients cache tools/list and this server
17
+ * announces listChanged:false. A call for an app that is not connected
18
+ * fails with "no connected client provides tool: <name>".
19
+ *
20
+ * Wire format: MCP JSON-RPC 2.0, newline-delimited (the same JSONL framing
21
+ * as the MCP stdio transport; pi-mcp-adapter's UnixSocketClientTransport
22
+ * speaks exactly this). Methods served: initialize, notifications/
23
+ * initialized, ping, tools/list, tools/call.
24
+ *
25
+ * Callers (openspec external-mcp-callers): every connection is its own
26
+ * *caller session* (`mcp:<uuid>`) named by the `pi-browser/caller`
27
+ * notification the stdio bridge sends first, or by the client's own
28
+ * `initialize` clientInfo. Its calls route through the capability registry
29
+ * with no add-on chat session, go through the caller gate (external access +
30
+ * per-app caller approval) and keep their own grants and REPL state; the
31
+ * session ends when the connection closes. A connection whose bridge
32
+ * reports the broker's own PI_BROWSER_HOST_CHILD (or whose parent process
33
+ * is the broker) belongs to a pi session the host spawned: its calls keep
34
+ * the old routing to the most recently active add-on session.
35
+ *
36
+ * Security model (mirrors broker-ipc.ts): same-user only — the socket lives
37
+ * in the 0700 run dir under $HOME and is 0600, no localhost TCP. Any
38
+ * same-user process (e.g. a pi-subagents child spawned by the broker) can
39
+ * connect; tool calls are then routed through the provider's standard
40
+ * routing + permission path, so per-tool approvals in the add-on UI still
41
+ * apply.
42
+ *
43
+ * Windows: the endpoint is a named pipe (ipcEndpoint). Pipes have no file
44
+ * mode; their default DACL gives the creating user full access and other
45
+ * accounts READ only. A read-only handle cannot send a JSON-RPC request and
46
+ * each connection is its own pipe instance, so another account can neither
47
+ * call a tool nor observe this user's traffic.
48
+ */
49
+ import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs";
50
+ import net from "node:net";
51
+ import os from "node:os";
52
+ import path from "node:path";
53
+ import { randomUUID } from "node:crypto";
54
+ import { MCP_CALLER_NOTIFICATION, PI_BROWSER_META, PI_BROKER, UNKNOWN_CALLER_NAME, parseCallerInfo, } from "@pi-browser/protocol";
55
+ import { ipcEndpoint, isNamedPipe } from "./broker-ipc.js";
56
+ import { BROWSER_TOOL_SCHEMAS, REPL_TOOL_SCHEMAS } from "../browser/schemas.js";
57
+ import { MAIL_TOOL_SCHEMAS } from "../mail/schemas.js";
58
+ import { COMPOSE_TOOL_SCHEMAS } from "../compose/schemas.js";
59
+ import { MAIL_MUTATION_TOOL_SCHEMAS } from "../mutation/schemas.js";
60
+ import { CONTACTS_TOOL_SCHEMAS } from "../contacts/schemas.js";
61
+ import { MCP_PROTOCOL_VERSION } from "../browser/mcp-acp-client.js";
62
+ const SERVER_INFO = { name: "pi-browser", version: PI_BROWSER_META.version };
63
+ /** Every tool this server lists and accepts (see the header for why static). */
64
+ export const MCP_TOOL_SCHEMAS = [
65
+ // Firefox (add-on-routed) + the host-side `javascript` REPL.
66
+ ...BROWSER_TOOL_SCHEMAS,
67
+ ...REPL_TOOL_SCHEMAS,
68
+ // Thunderbird (add-on-routed).
69
+ ...MAIL_TOOL_SCHEMAS,
70
+ ...COMPOSE_TOOL_SCHEMAS,
71
+ ...MAIL_MUTATION_TOOL_SCHEMAS,
72
+ ...CONTACTS_TOOL_SCHEMAS,
73
+ ];
74
+ const MCP_TOOL_NAMES = new Set(MCP_TOOL_SCHEMAS.map((t) => t.name));
75
+ /** initialize result (shared with the stdio bridge, which answers it locally). */
76
+ export function mcpInitializeResult() {
77
+ return {
78
+ protocolVersion: MCP_PROTOCOL_VERSION,
79
+ capabilities: { tools: { listChanged: false } },
80
+ serverInfo: SERVER_INFO,
81
+ instructions: "Pi Browser tools: browser_* act on the Firefox tab bound to this connection — start with " +
82
+ "browser_list_tabs + browser_bind_tab (or browser_open_tab). mail_*, compose_*, contacts_* act on " +
83
+ "Thunderbird. Each tool runs in the app that serves it, and the user approves each tool call there.",
84
+ };
85
+ }
86
+ /** tools/list result (shared with the stdio bridge). */
87
+ export function mcpToolListResult() {
88
+ return {
89
+ tools: MCP_TOOL_SCHEMAS.map((t) => ({
90
+ name: t.name,
91
+ ...(t.description ? { description: t.description } : {}),
92
+ inputSchema: t.parameters,
93
+ })),
94
+ };
95
+ }
96
+ /** The broker's MCP endpoint (PI_BROWSER_BROKER_DIR honored): unix socket, or a named pipe on Windows. */
97
+ export function defaultMcpEndpoint() {
98
+ const dir = process.env.PI_BROWSER_BROKER_DIR || path.join(os.homedir(), ".pi", PI_BROKER.runDir);
99
+ return ipcEndpoint(dir, PI_BROKER.mcpSocketFile);
100
+ }
101
+ function isRecord(value) {
102
+ return typeof value === "object" && value !== null && !Array.isArray(value);
103
+ }
104
+ function reply(socket, id, result) {
105
+ socket.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
106
+ }
107
+ function replyError(socket, id, code, message) {
108
+ socket.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`);
109
+ }
110
+ /**
111
+ * Handle one line-delimited MCP request. Returns the MCP tools/call-shaped
112
+ * result (or a JSON-RPC error reply for protocol-level failures).
113
+ */
114
+ async function dispatch(socket, msg, bridge, log, caller, isHostChild) {
115
+ const { id, method, params } = msg;
116
+ const isNotification = id === undefined;
117
+ switch (method) {
118
+ case MCP_CALLER_NOTIFICATION:
119
+ caller.info = parseCallerInfo(params);
120
+ caller.announced = true;
121
+ log.info(`mcp browser: caller ${caller.id} is "${caller.info.name}"${caller.info.version ? ` ${caller.info.version}` : ""}` +
122
+ `${caller.info.pid !== undefined ? ` (bridge pid ${caller.info.pid})` : ""}${isHostChild(caller.info) ? " [host child]" : ""}`);
123
+ return;
124
+ case "initialize": {
125
+ const clientInfo = isRecord(params) ? params.clientInfo : undefined;
126
+ if (!caller.announced && isRecord(clientInfo)) {
127
+ const parsed = parseCallerInfo(clientInfo);
128
+ caller.info = { ...caller.info, name: parsed.name, ...(parsed.version ? { version: parsed.version } : {}) };
129
+ log.info(`mcp browser: caller ${caller.id} is "${caller.info.name}" (from initialize)`);
130
+ }
131
+ reply(socket, id, mcpInitializeResult());
132
+ return;
133
+ }
134
+ case "notifications/initialized":
135
+ return; // notification: no response
136
+ case "ping":
137
+ reply(socket, id, {});
138
+ return;
139
+ case "tools/list":
140
+ reply(socket, id, mcpToolListResult());
141
+ return;
142
+ case "tools/call": {
143
+ const p = isRecord(params) ? params : {};
144
+ const tool = typeof p.name === "string" ? p.name : "";
145
+ const args = isRecord(p.arguments) ? p.arguments : {};
146
+ if (!MCP_TOOL_NAMES.has(tool)) {
147
+ if (isNotification)
148
+ return;
149
+ replyError(socket, id, -32602, `unknown tool: ${tool}`);
150
+ return;
151
+ }
152
+ const hostChild = isHostChild(caller.info);
153
+ log.info(`mcp browser: tools/call ${tool} (${hostChild ? "host child" : `caller ${caller.info.name}, ${caller.id}`})`);
154
+ try {
155
+ let result;
156
+ if (hostChild) {
157
+ // Spawned by this host (a pi subagent's MCP client): keep the
158
+ // routing to the most recently active add-on session.
159
+ result = await bridge.call({ tool, args });
160
+ }
161
+ else {
162
+ caller.used = true;
163
+ result = await bridge.call({ tool, args, sessionId: caller.id, caller: caller.info });
164
+ }
165
+ reply(socket, id, {
166
+ content: result.content,
167
+ ...(result.isError ? { isError: true } : {}),
168
+ });
169
+ }
170
+ catch (err) {
171
+ // Tool-level failure → MCP tools/call result with isError (per MCP
172
+ // spec), not a JSON-RPC error: the connection stays usable.
173
+ const text = err instanceof Error ? err.message : String(err);
174
+ log.warn(`mcp browser: ${tool} failed: ${text}`);
175
+ reply(socket, id, {
176
+ content: [{ type: "text", text: `${tool} failed: ${text}` }],
177
+ isError: true,
178
+ });
179
+ }
180
+ return;
181
+ }
182
+ default:
183
+ if (isNotification)
184
+ return;
185
+ replyError(socket, id, -32601, `method not found: ${String(method)}`);
186
+ }
187
+ }
188
+ /**
189
+ * Start the browser-tools MCP server on a private unix socket.
190
+ *
191
+ * Reclaims a stale socket only when the owning process is gone (same
192
+ * caution as reclaimBrokerSocket: never unlink a live listener).
193
+ */
194
+ export async function startMcpBrowserServer(opts) {
195
+ const { log, bridge } = opts;
196
+ const brokerPid = opts.brokerPid ?? process.pid;
197
+ const isHostChild = (info) => (opts.instanceId !== undefined && info.hostChild === opts.instanceId) ||
198
+ (info.ppid !== undefined && info.ppid === brokerPid);
199
+ const dir = process.env.PI_BROWSER_BROKER_DIR || path.join(os.homedir(), ".pi", PI_BROKER.runDir);
200
+ const socketPath = opts.socketPath ?? defaultMcpEndpoint();
201
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
202
+ try {
203
+ chmodSync(dir, 0o700); // mkdir mode is subject to umask
204
+ }
205
+ catch {
206
+ /* best-effort */
207
+ }
208
+ if (existsSync(socketPath)) {
209
+ // Probe: a listener on the socket means a live broker (possibly ours
210
+ // from a prior run that lost its state) owns it — do not steal it.
211
+ const probe = net.createConnection(socketPath);
212
+ const stale = await new Promise((resolve) => {
213
+ const done = (v) => {
214
+ probe.destroy();
215
+ resolve(v);
216
+ };
217
+ probe.once("connect", () => done(false));
218
+ probe.once("error", () => done(true));
219
+ setTimeout(() => done(true), 500).unref?.();
220
+ });
221
+ if (!stale) {
222
+ throw new Error(`MCP socket already in use: ${socketPath}`);
223
+ }
224
+ if (!isNamedPipe(socketPath))
225
+ rmSync(socketPath, { force: true });
226
+ }
227
+ const connections = new Set();
228
+ const server = net.createServer((socket) => {
229
+ connections.add(socket);
230
+ handleConnection(socket, bridge, log);
231
+ });
232
+ await new Promise((resolve, reject) => {
233
+ const onError = (err) => {
234
+ server.removeListener("error", onError);
235
+ reject(err);
236
+ };
237
+ server.once("error", onError);
238
+ server.listen(socketPath, () => {
239
+ server.removeListener("error", onError);
240
+ resolve();
241
+ });
242
+ });
243
+ if (!isNamedPipe(socketPath)) {
244
+ try {
245
+ chmodSync(socketPath, 0o600);
246
+ }
247
+ catch {
248
+ /* best-effort */
249
+ }
250
+ }
251
+ log.info(`mcp browser server: listening on ${socketPath}`);
252
+ function handleConnection(socket, bridge, log) {
253
+ let buffer = "";
254
+ const pending = new Set();
255
+ const caller = {
256
+ id: `mcp:${randomUUID()}`,
257
+ info: { name: UNKNOWN_CALLER_NAME },
258
+ announced: false,
259
+ used: false,
260
+ };
261
+ log.debug(`mcp browser: client connected (${caller.id})`);
262
+ socket.on("data", (chunk) => {
263
+ buffer += chunk.toString("utf8");
264
+ let nl;
265
+ while ((nl = buffer.indexOf("\n")) !== -1) {
266
+ const line = buffer.slice(0, nl);
267
+ buffer = buffer.slice(nl + 1);
268
+ if (line.trim() === "")
269
+ continue;
270
+ let msg;
271
+ try {
272
+ msg = JSON.parse(line);
273
+ }
274
+ catch {
275
+ replyError(socket, null, -32700, "parse error");
276
+ continue;
277
+ }
278
+ const p = dispatch(socket, msg, bridge, log, caller, isHostChild);
279
+ pending.add(p);
280
+ void p.finally(() => pending.delete(p));
281
+ }
282
+ });
283
+ let cleaned = false;
284
+ const cleanup = () => {
285
+ if (cleaned)
286
+ return;
287
+ cleaned = true;
288
+ connections.delete(socket);
289
+ log.debug(`mcp browser: client disconnected (${caller.id})`);
290
+ for (const p of pending)
291
+ void p.catch(() => undefined);
292
+ pending.clear();
293
+ // End the caller session: grants, pending prompts, REPL worker.
294
+ if (caller.used) {
295
+ try {
296
+ bridge.closeSession(caller.id);
297
+ }
298
+ catch (err) {
299
+ log.debug(`mcp browser: closing ${caller.id} failed: ${err instanceof Error ? err.message : String(err)}`);
300
+ }
301
+ }
302
+ };
303
+ socket.on("close", cleanup);
304
+ socket.on("error", (err) => {
305
+ log.debug(`mcp browser: socket error: ${err.message}`);
306
+ cleanup();
307
+ });
308
+ }
309
+ return {
310
+ socketPath,
311
+ close: async () => {
312
+ server.close(); // stop accepting; tracked sockets are destroyed below
313
+ for (const socket of connections)
314
+ socket.destroy();
315
+ connections.clear();
316
+ await new Promise((resolve) => server.close(() => resolve()));
317
+ if (!isNamedPipe(socketPath))
318
+ rmSync(socketPath, { force: true });
319
+ },
320
+ };
321
+ }
322
+ //# sourceMappingURL=mcp-server.js.map
@@ -0,0 +1,179 @@
1
+ /**
2
+ * stdio ⇄ broker bridge for the Pi Browser MCP server.
3
+ *
4
+ * The broker serves MCP over a private unix socket / Windows named pipe
5
+ * (mcp-server.ts). pi-mcp-adapter can dial that socket directly, but pi's
6
+ * built-in MCP client (pi >= 1.5) only speaks stdio and HTTP. This script is
7
+ * a plain stdio MCP server that every client can launch
8
+ * (`/pi-browser mcp install` writes `{ command: <node>, args: [<dist>/native-host/mcp-stdio-main.js] }`):
9
+ *
10
+ * - initialize, ping and tools/list are answered locally, from the same
11
+ * static tool list the broker serves (mcp-server.ts). The server is
12
+ * therefore always available to the MCP client — even before Firefox or
13
+ * Thunderbird has started the host — and its tool list never depends on
14
+ * timing.
15
+ * - tools/call is forwarded to the broker's socket, connecting lazily and
16
+ * reconnecting after the broker restarts. With no broker running, the
17
+ * call returns an MCP tool error telling the model what to do instead of
18
+ * hanging.
19
+ *
20
+ * - Caller identity: the bridge remembers the client's `initialize`
21
+ * clientInfo and, as the first line of every broker connection (including
22
+ * reconnects), sends the `pi-browser/caller` notification: name, version,
23
+ * its own pid and parent pid, and the PI_BROWSER_HOST_CHILD value it
24
+ * inherited. The broker runs the connection as that caller's session.
25
+ * An older broker ignores the notification.
26
+ *
27
+ * Wire format on both sides: newline-delimited JSON-RPC 2.0 (MCP stdio).
28
+ * stdout carries protocol messages only; diagnostics go to stderr.
29
+ */
30
+ import net from "node:net";
31
+ import { createInterface } from "node:readline";
32
+ import { HOST_CHILD_ENV, MCP_CALLER_NOTIFICATION, normalizeCallerName } from "@pi-browser/protocol";
33
+ import { defaultMcpEndpoint, mcpInitializeResult, mcpToolListResult } from "./mcp-server.js";
34
+ /** How long a tools/call waits to connect to the broker before giving up. */
35
+ const CONNECT_TIMEOUT_MS = 3_000;
36
+ const NOT_RUNNING = "Pi Browser is not running: open Firefox (or Thunderbird) with the Pi add-on — its native host serves these tools — then retry.";
37
+ /** Run the bridge until `input` ends. Resolves when it has shut down. */
38
+ export function runMcpStdioBridge(opts) {
39
+ const endpoint = opts.endpoint ?? defaultMcpEndpoint();
40
+ const log = opts.log ?? (() => { });
41
+ const write = (msg) => opts.output.write(`${JSON.stringify(msg)}\n`);
42
+ const reply = (id, result) => write({ jsonrpc: "2.0", id, result });
43
+ const replyError = (id, code, message) => write({ jsonrpc: "2.0", id, error: { code, message } });
44
+ const toolError = (id, text) => reply(id, { content: [{ type: "text", text }], isError: true });
45
+ const env = opts.env ?? process.env;
46
+ /** Who is calling: filled from initialize's clientInfo. */
47
+ const caller = { name: normalizeCallerName(undefined), pid: process.pid, ppid: process.ppid };
48
+ const hostChild = env[HOST_CHILD_ENV];
49
+ if (hostChild)
50
+ caller.hostChild = hostChild;
51
+ let socket;
52
+ let connecting;
53
+ /** tools/call ids forwarded on the current connection, awaiting a reply. */
54
+ const pending = new Set();
55
+ function connect() {
56
+ if (socket && !socket.destroyed)
57
+ return Promise.resolve(socket);
58
+ connecting ??= new Promise((resolve) => {
59
+ const s = net.createConnection(endpoint);
60
+ const timer = setTimeout(() => {
61
+ s.destroy();
62
+ resolve(undefined);
63
+ }, CONNECT_TIMEOUT_MS);
64
+ s.once("connect", () => {
65
+ clearTimeout(timer);
66
+ socket = s;
67
+ // Identify the caller first: the broker names this connection's
68
+ // caller session from it (older brokers drop unknown notifications).
69
+ s.write(`${JSON.stringify({ jsonrpc: "2.0", method: MCP_CALLER_NOTIFICATION, params: caller })}\n`);
70
+ let buf = "";
71
+ s.setEncoding("utf8");
72
+ s.on("data", (chunk) => {
73
+ buf += chunk;
74
+ let nl;
75
+ while ((nl = buf.indexOf("\n")) !== -1) {
76
+ const line = buf.slice(0, nl);
77
+ buf = buf.slice(nl + 1);
78
+ if (!line.trim())
79
+ continue;
80
+ try {
81
+ const msg = JSON.parse(line);
82
+ pending.delete(msg.id);
83
+ }
84
+ catch {
85
+ // not JSON: pass through untouched; the client reports it
86
+ }
87
+ opts.output.write(`${line}\n`);
88
+ }
89
+ });
90
+ const lost = () => {
91
+ if (socket === s)
92
+ socket = undefined;
93
+ for (const id of pending)
94
+ toolError(id, "Lost the connection to Pi Browser while the tool was running. Retry the call.");
95
+ pending.clear();
96
+ };
97
+ s.on("close", lost);
98
+ s.on("error", (err) => log(`broker connection error: ${err.message}`));
99
+ resolve(s);
100
+ });
101
+ s.once("error", (err) => {
102
+ clearTimeout(timer);
103
+ log(`broker not reachable at ${endpoint}: ${err.message}`);
104
+ resolve(undefined);
105
+ });
106
+ }).finally(() => {
107
+ connecting = undefined;
108
+ });
109
+ return connecting;
110
+ }
111
+ async function forward(msg, line) {
112
+ const s = await connect();
113
+ if (!s) {
114
+ toolError(msg.id, NOT_RUNNING);
115
+ return;
116
+ }
117
+ pending.add(msg.id);
118
+ s.write(`${line}\n`);
119
+ }
120
+ function handle(line) {
121
+ let msg;
122
+ try {
123
+ msg = JSON.parse(line);
124
+ }
125
+ catch {
126
+ replyError(null, -32700, "parse error");
127
+ return;
128
+ }
129
+ const isRequest = msg.id !== undefined && msg.id !== null;
130
+ switch (msg.method) {
131
+ case "initialize": {
132
+ const info = msg.params?.clientInfo;
133
+ if (info && typeof info === "object") {
134
+ caller.name = normalizeCallerName(info.name);
135
+ if (typeof info.version === "string" && info.version.trim())
136
+ caller.version = info.version.trim().slice(0, 32);
137
+ }
138
+ if (isRequest)
139
+ reply(msg.id, mcpInitializeResult());
140
+ return;
141
+ }
142
+ case "ping":
143
+ if (isRequest)
144
+ reply(msg.id, {});
145
+ return;
146
+ case "tools/list":
147
+ if (isRequest)
148
+ reply(msg.id, mcpToolListResult());
149
+ return;
150
+ case "tools/call":
151
+ if (isRequest)
152
+ void forward(msg, line);
153
+ return;
154
+ default:
155
+ // notifications/* and anything else: notifications get no reply
156
+ if (isRequest)
157
+ replyError(msg.id, -32601, `method not found: ${String(msg.method)}`);
158
+ }
159
+ }
160
+ return new Promise((resolve) => {
161
+ const rl = createInterface({ input: opts.input, crlfDelay: Infinity });
162
+ rl.on("line", (line) => {
163
+ if (line.trim())
164
+ handle(line);
165
+ });
166
+ rl.on("close", () => {
167
+ // Let in-flight calls finish briefly, then shut down.
168
+ const done = () => {
169
+ socket?.end();
170
+ resolve();
171
+ };
172
+ if (pending.size === 0)
173
+ done();
174
+ else
175
+ setTimeout(done, 1_000).unref?.();
176
+ });
177
+ });
178
+ }
179
+ //# sourceMappingURL=mcp-stdio-bridge.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Entry point of the Pi Browser stdio MCP server (see mcp-stdio-bridge.ts).
3
+ * Launched by MCP clients via the `/pi-browser mcp install` config entry:
4
+ * { "command": "<node>", "args": ["<pkg>/dist/native-host/mcp-stdio-main.js"] }
5
+ */
6
+ import { runMcpStdioBridge } from "./mcp-stdio-bridge.js";
7
+ await runMcpStdioBridge({
8
+ input: process.stdin,
9
+ output: process.stdout,
10
+ log: (line) => process.stderr.write(`[pi-browser mcp] ${line}\n`),
11
+ });
12
+ process.exit(0);
13
+ //# sourceMappingURL=mcp-stdio-main.js.map
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Pipe app stdin → channel and channel → app stdout with backpressure.
3
+ * Resolves (and ends the links) when either side goes away: the app closed
4
+ * its port, or the broker disconnected. The caller exits the process.
5
+ */
6
+ export function runRelay(channel, initial, stdin, stdout, log) {
7
+ return new Promise((resolve) => {
8
+ let done = false;
9
+ const finish = (reason) => {
10
+ if (done)
11
+ return;
12
+ done = true;
13
+ log.info(`relay: closing (${reason})`);
14
+ try {
15
+ channel.end();
16
+ }
17
+ catch {
18
+ /* already closed */
19
+ }
20
+ try {
21
+ stdout.end();
22
+ }
23
+ catch {
24
+ /* already closed */
25
+ }
26
+ resolve();
27
+ };
28
+ // App → broker (stdin → channel).
29
+ stdin.on("data", (chunk) => {
30
+ if (done || channel.destroyed || channel.writableEnded)
31
+ return;
32
+ if (!channel.write(chunk)) {
33
+ // Backpressure: pause app input until the socket drains.
34
+ stdin.pause();
35
+ channel.once("drain", () => {
36
+ if (!done)
37
+ stdin.resume();
38
+ });
39
+ }
40
+ });
41
+ // Broker → app (channel → stdout). Only this pipe writes stdout.
42
+ channel.on("data", (chunk) => {
43
+ if (done)
44
+ return;
45
+ if (chunk.length === 0)
46
+ return;
47
+ if (!stdout.write(chunk)) {
48
+ channel.pause();
49
+ stdout.once("drain", () => {
50
+ if (!done)
51
+ channel.resume();
52
+ });
53
+ }
54
+ });
55
+ if (initial.length > 0) {
56
+ // Bytes that arrived with the handshake ack already belong to the
57
+ // app stream and must precede any piped data.
58
+ if (!stdout.write(initial)) {
59
+ channel.pause();
60
+ stdout.once("drain", () => {
61
+ if (!done)
62
+ channel.resume();
63
+ });
64
+ }
65
+ }
66
+ stdin.on("end", () => finish("app stdin closed"));
67
+ stdin.on("close", () => finish("app stdin closed"));
68
+ stdin.on("error", (err) => {
69
+ log.error("relay: stdin error", err);
70
+ finish("stdin error");
71
+ });
72
+ channel.on("end", () => finish("broker closed"));
73
+ channel.on("close", () => finish("broker closed"));
74
+ channel.on("error", (err) => {
75
+ log.error("relay: broker socket error", err);
76
+ finish("broker socket error");
77
+ });
78
+ stdout.on("error", (err) => {
79
+ log.error("relay: stdout error", err);
80
+ finish("stdout error");
81
+ });
82
+ });
83
+ }
84
+ //# sourceMappingURL=relay.js.map