@particle-academy/agent-integrations 0.43.0 → 0.45.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 (180) hide show
  1. package/README.md +32 -0
  2. package/dist/bridges/artboard.d.cts +3 -3
  3. package/dist/bridges/artboard.d.ts +3 -3
  4. package/dist/bridges/catalog.d.cts +3 -3
  5. package/dist/bridges/catalog.d.ts +3 -3
  6. package/dist/bridges/charts.d.cts +3 -3
  7. package/dist/bridges/charts.d.ts +3 -3
  8. package/dist/bridges/cms.d.cts +3 -3
  9. package/dist/bridges/cms.d.ts +3 -3
  10. package/dist/bridges/code.d.cts +3 -3
  11. package/dist/bridges/code.d.ts +3 -3
  12. package/dist/bridges/doc.d.cts +3 -3
  13. package/dist/bridges/doc.d.ts +3 -3
  14. package/dist/bridges/features.d.cts +3 -3
  15. package/dist/bridges/features.d.ts +3 -3
  16. package/dist/bridges/files.d.cts +3 -3
  17. package/dist/bridges/files.d.ts +3 -3
  18. package/dist/bridges/flow.d.cts +3 -3
  19. package/dist/bridges/flow.d.ts +3 -3
  20. package/dist/bridges/forms.d.cts +3 -3
  21. package/dist/bridges/forms.d.ts +3 -3
  22. package/dist/bridges/git.d.cts +3 -3
  23. package/dist/bridges/git.d.ts +3 -3
  24. package/dist/bridges/grid.d.cts +3 -3
  25. package/dist/bridges/grid.d.ts +3 -3
  26. package/dist/bridges/map.d.cts +3 -3
  27. package/dist/bridges/map.d.ts +3 -3
  28. package/dist/bridges/passkeys.d.cts +3 -3
  29. package/dist/bridges/passkeys.d.ts +3 -3
  30. package/dist/bridges/scene.d.cts +3 -3
  31. package/dist/bridges/scene.d.ts +3 -3
  32. package/dist/bridges/screens.d.cts +3 -3
  33. package/dist/bridges/screens.d.ts +3 -3
  34. package/dist/bridges/sheets.d.cts +3 -3
  35. package/dist/bridges/sheets.d.ts +3 -3
  36. package/dist/bridges/slides.d.cts +3 -3
  37. package/dist/bridges/slides.d.ts +3 -3
  38. package/dist/bridges/terminal.d.cts +3 -3
  39. package/dist/bridges/terminal.d.ts +3 -3
  40. package/dist/bridges/tui.d.cts +2 -2
  41. package/dist/bridges/tui.d.ts +2 -2
  42. package/dist/bridges/whiteboard.d.cts +3 -3
  43. package/dist/bridges/whiteboard.d.ts +3 -3
  44. package/dist/bridges-artboard.cjs.map +1 -1
  45. package/dist/bridges-artboard.js +2 -2
  46. package/dist/bridges-catalog.cjs.map +1 -1
  47. package/dist/bridges-catalog.js +3 -3
  48. package/dist/bridges-charts.cjs.map +1 -1
  49. package/dist/bridges-charts.js +3 -3
  50. package/dist/bridges-cms.cjs.map +1 -1
  51. package/dist/bridges-cms.js +4 -4
  52. package/dist/bridges-code.cjs.map +1 -1
  53. package/dist/bridges-code.js +3 -3
  54. package/dist/bridges-doc.cjs.map +1 -1
  55. package/dist/bridges-doc.js +3 -3
  56. package/dist/bridges-features.cjs.map +1 -1
  57. package/dist/bridges-features.js +3 -3
  58. package/dist/bridges-files.cjs.map +1 -1
  59. package/dist/bridges-files.js +3 -3
  60. package/dist/bridges-flow.cjs.map +1 -1
  61. package/dist/bridges-flow.js +2 -2
  62. package/dist/bridges-forms.cjs.map +1 -1
  63. package/dist/bridges-forms.js +3 -3
  64. package/dist/bridges-git.cjs.map +1 -1
  65. package/dist/bridges-git.js +3 -3
  66. package/dist/bridges-grid.cjs.map +1 -1
  67. package/dist/bridges-grid.js +3 -3
  68. package/dist/bridges-map.cjs.map +1 -1
  69. package/dist/bridges-map.js +3 -3
  70. package/dist/bridges-passkeys.cjs.map +1 -1
  71. package/dist/bridges-passkeys.js +3 -3
  72. package/dist/bridges-scene.cjs.map +1 -1
  73. package/dist/bridges-scene.js +3 -3
  74. package/dist/bridges-screens.cjs.map +1 -1
  75. package/dist/bridges-screens.js +3 -3
  76. package/dist/bridges-sheets.cjs.map +1 -1
  77. package/dist/bridges-sheets.js +3 -3
  78. package/dist/bridges-slides.cjs.map +1 -1
  79. package/dist/bridges-slides.js +3 -3
  80. package/dist/bridges-terminal.cjs.map +1 -1
  81. package/dist/bridges-terminal.js +3 -3
  82. package/dist/bridges-tui.cjs.map +1 -1
  83. package/dist/bridges-tui.js +2 -2
  84. package/dist/bridges-whiteboard.cjs.map +1 -1
  85. package/dist/bridges-whiteboard.js +3 -3
  86. package/dist/{chunk-5W6YOXLT.js → chunk-36MKPTVD.js} +4 -4
  87. package/dist/{chunk-5W6YOXLT.js.map → chunk-36MKPTVD.js.map} +1 -1
  88. package/dist/{chunk-SXVRIIXW.js → chunk-3HVYUMQF.js} +4 -4
  89. package/dist/{chunk-SXVRIIXW.js.map → chunk-3HVYUMQF.js.map} +1 -1
  90. package/dist/{chunk-MZ74LLDS.js → chunk-3UUF5KKZ.js} +4 -4
  91. package/dist/{chunk-MZ74LLDS.js.map → chunk-3UUF5KKZ.js.map} +1 -1
  92. package/dist/{chunk-WEXMZMJH.js → chunk-3WVXAB3D.js} +3 -3
  93. package/dist/{chunk-WEXMZMJH.js.map → chunk-3WVXAB3D.js.map} +1 -1
  94. package/dist/{chunk-Z4L2GOAK.js → chunk-5ZWNCHZS.js} +4 -4
  95. package/dist/{chunk-Z4L2GOAK.js.map → chunk-5ZWNCHZS.js.map} +1 -1
  96. package/dist/{chunk-TEB5U6Y5.js → chunk-7NVATRLE.js} +4 -4
  97. package/dist/{chunk-TEB5U6Y5.js.map → chunk-7NVATRLE.js.map} +1 -1
  98. package/dist/{chunk-PUMQDV67.js → chunk-AXWMWYH5.js} +4 -4
  99. package/dist/{chunk-PUMQDV67.js.map → chunk-AXWMWYH5.js.map} +1 -1
  100. package/dist/{chunk-NKAH67JK.js → chunk-CS3CHGYC.js} +4 -4
  101. package/dist/{chunk-NKAH67JK.js.map → chunk-CS3CHGYC.js.map} +1 -1
  102. package/dist/{chunk-QJYRWEXD.js → chunk-CZV3WUW5.js} +35 -8
  103. package/dist/chunk-CZV3WUW5.js.map +1 -0
  104. package/dist/{chunk-PCFRBVKS.js → chunk-FCXSR7I5.js} +4 -4
  105. package/dist/{chunk-PCFRBVKS.js.map → chunk-FCXSR7I5.js.map} +1 -1
  106. package/dist/{chunk-NIFPRC7P.js → chunk-GVTBMJU6.js} +4 -4
  107. package/dist/{chunk-NIFPRC7P.js.map → chunk-GVTBMJU6.js.map} +1 -1
  108. package/dist/{chunk-E2I3YVKC.js → chunk-JLHVQWOV.js} +3 -3
  109. package/dist/{chunk-E2I3YVKC.js.map → chunk-JLHVQWOV.js.map} +1 -1
  110. package/dist/{chunk-2LSU3NFO.js → chunk-LQB42OSA.js} +4 -4
  111. package/dist/{chunk-2LSU3NFO.js.map → chunk-LQB42OSA.js.map} +1 -1
  112. package/dist/{chunk-VJD3Y7E5.js → chunk-MIDZWKIF.js} +4 -4
  113. package/dist/{chunk-VJD3Y7E5.js.map → chunk-MIDZWKIF.js.map} +1 -1
  114. package/dist/{chunk-QOANLXSW.js → chunk-OZBUPO4K.js} +110 -8
  115. package/dist/chunk-OZBUPO4K.js.map +1 -0
  116. package/dist/{chunk-LOD77NCD.js → chunk-PWYEW6NL.js} +4 -4
  117. package/dist/{chunk-LOD77NCD.js.map → chunk-PWYEW6NL.js.map} +1 -1
  118. package/dist/{chunk-HVDHT7DM.js → chunk-R4XXOGQH.js} +3 -3
  119. package/dist/{chunk-HVDHT7DM.js.map → chunk-R4XXOGQH.js.map} +1 -1
  120. package/dist/{chunk-7LLMILTM.js → chunk-RVMM4BHK.js} +4 -4
  121. package/dist/{chunk-7LLMILTM.js.map → chunk-RVMM4BHK.js.map} +1 -1
  122. package/dist/{chunk-NIXOY473.js → chunk-SWWJUOCY.js} +3 -3
  123. package/dist/{chunk-NIXOY473.js.map → chunk-SWWJUOCY.js.map} +1 -1
  124. package/dist/{chunk-EIBV76IB.js → chunk-VFWFT3OK.js} +4 -4
  125. package/dist/{chunk-EIBV76IB.js.map → chunk-VFWFT3OK.js.map} +1 -1
  126. package/dist/{chunk-2Q4EGZHJ.js → chunk-VMRUW4B4.js} +4 -4
  127. package/dist/{chunk-2Q4EGZHJ.js.map → chunk-VMRUW4B4.js.map} +1 -1
  128. package/dist/{chunk-GT63LSPJ.js → chunk-VOCUGTZB.js} +4 -4
  129. package/dist/{chunk-GT63LSPJ.js.map → chunk-VOCUGTZB.js.map} +1 -1
  130. package/dist/{chunk-N5VOPV64.js → chunk-Z5NL5D4J.js} +4 -4
  131. package/dist/{chunk-N5VOPV64.js.map → chunk-Z5NL5D4J.js.map} +1 -1
  132. package/dist/components-shared-whiteboard.cjs +33 -6
  133. package/dist/components-shared-whiteboard.cjs.map +1 -1
  134. package/dist/components-shared-whiteboard.js +3 -3
  135. package/dist/index.cjs +33 -6
  136. package/dist/index.cjs.map +1 -1
  137. package/dist/index.d.cts +7 -7
  138. package/dist/index.d.ts +7 -7
  139. package/dist/index.js +27 -27
  140. package/dist/mcp/index.d.cts +5 -5
  141. package/dist/mcp/index.d.ts +5 -5
  142. package/dist/mcp/stdio.d.cts +94 -0
  143. package/dist/mcp/stdio.d.ts +94 -0
  144. package/dist/mcp-stdio.cjs +120 -0
  145. package/dist/mcp-stdio.cjs.map +1 -0
  146. package/dist/mcp-stdio.js +117 -0
  147. package/dist/mcp-stdio.js.map +1 -0
  148. package/dist/mcp.cjs +33 -6
  149. package/dist/mcp.cjs.map +1 -1
  150. package/dist/mcp.js +1 -1
  151. package/dist/presence/index.d.cts +1 -1
  152. package/dist/presence/index.d.ts +1 -1
  153. package/dist/relay-server/index.d.cts +44 -2
  154. package/dist/relay-server/index.d.ts +44 -2
  155. package/dist/relay-server-cli.cjs +108 -6
  156. package/dist/relay-server-cli.cjs.map +1 -1
  157. package/dist/relay-server-cli.js +1 -1
  158. package/dist/relay-server.cjs +108 -6
  159. package/dist/relay-server.cjs.map +1 -1
  160. package/dist/relay-server.js +1 -1
  161. package/dist/{server-BJNF7pQe.d.cts → server-BIcA3ZtK.d.cts} +32 -3
  162. package/dist/{server-Dt97UxuD.d.ts → server-DnUyeavY.d.ts} +32 -3
  163. package/dist/sharing/index.d.cts +3 -3
  164. package/dist/sharing/index.d.ts +3 -3
  165. package/dist/sheets-adapter.d.cts +3 -3
  166. package/dist/sheets-adapter.d.ts +3 -3
  167. package/dist/{tool-host-BpEBqf5u.d.cts → tool-host-LVBgCN5m.d.cts} +1 -1
  168. package/dist/{tool-host-xY5F-eqG.d.ts → tool-host-Wo0pkY83.d.ts} +1 -1
  169. package/dist/{types-DSwsNTBG.d.ts → types-BxNRKSVd.d.ts} +1 -1
  170. package/dist/{types-C58ZXs4K.d.cts → types-C2DtnHIn.d.cts} +25 -1
  171. package/dist/{types-C58ZXs4K.d.ts → types-C2DtnHIn.d.ts} +25 -1
  172. package/dist/{types-C4NaIW6B.d.cts → types-EcElKOlk.d.cts} +1 -1
  173. package/dist/undo/index.d.cts +2 -2
  174. package/dist/undo/index.d.ts +2 -2
  175. package/dist/undo.cjs.map +1 -1
  176. package/dist/undo.js +3 -3
  177. package/docs/relay-protocol.md +33 -0
  178. package/package.json +13 -2
  179. package/dist/chunk-QJYRWEXD.js.map +0 -1
  180. package/dist/chunk-QOANLXSW.js.map +0 -1
package/dist/mcp.cjs CHANGED
@@ -69,10 +69,18 @@ var MicroMcpServer = class extends ToolRegistry {
69
69
  constructor(options) {
70
70
  super();
71
71
  this.transports = /* @__PURE__ */ new Set();
72
- this.notifyListChangedScheduled = false;
72
+ /**
73
+ * Transports owed a `tools/list_changed` at the end of this tick. Empty when
74
+ * none is scheduled. See {@link scheduleListChangedNotification}.
75
+ */
76
+ this.listChangedOwed = /* @__PURE__ */ new Set();
73
77
  this.info = options.info;
74
78
  this.capabilities = options.capabilities ?? { tools: { listChanged: true } };
75
79
  this.instructions = options.instructions;
80
+ if (options.protocolVersions && options.protocolVersions.length === 0) {
81
+ throw new Error("MicroMcpServer: protocolVersions is empty \u2014 a server must speak at least one protocol revision.");
82
+ }
83
+ this.protocolVersions = options.protocolVersions ? [...options.protocolVersions] : [MCP_PROTOCOL_VERSION];
76
84
  }
77
85
  attach(transport) {
78
86
  this.transports.add(transport);
@@ -118,7 +126,7 @@ var MicroMcpServer = class extends ToolRegistry {
118
126
  switch (method) {
119
127
  case "initialize":
120
128
  return {
121
- protocolVersion: MCP_PROTOCOL_VERSION,
129
+ protocolVersion: this.negotiate(params?.protocolVersion),
122
130
  capabilities: this.capabilities,
123
131
  serverInfo: this.info,
124
132
  ...this.instructions ? { instructions: this.instructions } : {}
@@ -144,12 +152,31 @@ var MicroMcpServer = class extends ToolRegistry {
144
152
  throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);
145
153
  }
146
154
  }
155
+ /** The revision to answer `initialize` with: the one asked for if spoken, else the newest. */
156
+ negotiate(requested) {
157
+ return typeof requested === "string" && this.protocolVersions.includes(requested) ? requested : this.protocolVersions[0];
158
+ }
159
+ /**
160
+ * Tell the transports that SAW the old tool list that it changed.
161
+ *
162
+ * Changes in one tick coalesce into one notification. The recipients are the
163
+ * transports attached at the moment of a change, not at the moment the
164
+ * notification goes out: a transport attached afterwards never had the old
165
+ * list, so "your list is stale" is noise to it — and on stdio, where a host
166
+ * builds the server and attaches stdin/stdout in the same tick, it was the
167
+ * first frame a client received, before it had even sent `initialize`.
168
+ */
147
169
  scheduleListChangedNotification() {
148
- if (this.notifyListChangedScheduled) return;
149
- this.notifyListChangedScheduled = true;
170
+ if (this.transports.size === 0) return;
171
+ const scheduled = this.listChangedOwed.size > 0;
172
+ for (const t of this.transports) this.listChangedOwed.add(t);
173
+ if (scheduled) return;
150
174
  queueMicrotask(() => {
151
- this.notifyListChangedScheduled = false;
152
- this.broadcast({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
175
+ const owed = this.listChangedOwed;
176
+ this.listChangedOwed = /* @__PURE__ */ new Set();
177
+ for (const t of owed) {
178
+ if (this.transports.has(t)) t.send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
179
+ }
153
180
  });
154
181
  }
155
182
  /** Send an application notification to every client, or one attached transport. */
package/dist/mcp.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src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E/C,YAAoB,OAAA,EAAuB;AAAvB,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAAA,EAAwB;AAAA,EAE5C,WAAW,MAAA,EAA8B;AACvC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,KAAK,OAAA,EAA+B;AAClC,IAAA,IAAA,CAAK,OAAA,CAAQ,aAAa,OAAO,CAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,kBAAkB,OAAA,EAAiD;AACvE,IAAA,IAAI,CAAC,IAAA,CAAK,MAAA,EAAQ,MAAM,IAAI,MAAM,oCAAoC,CAAA;AACtE,IAAA,MAAM,UAAU,OAAO,OAAA,KAAY,WAC9B,IAAA,CAAK,KAAA,CAAM,OAAO,CAAA,GACnB,OAAA;AACJ,IAAA,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EACzC;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,QAAQ,OAAA,IAAU;AAAA,EACzB;AACF;AAKO,SAAS,WAAA,CAAY,QAAwB,OAAA,EAAuC;AACzF,EAAA,MAAM,SAAA,GAAY,IAAI,cAAA,CAAe,OAAO,CAAA;AAC5C,EAAA,SAAA,CAAU,WAAW,MAAM,CAAA;AAC3B,EAAA,MAAA,CAAO,OAAO,SAAS,CAAA;AACvB,EAAA,OAAO,SAAA;AACT","file":"mcp.cjs","sourcesContent":["/**\n * Minimal MCP (Model Context Protocol) types — covers the subset this\n * package implements: initialize, tools/list, tools/call, plus JSON-RPC.\n *\n * Aligned with the public MCP spec but trimmed to v0.1 needs. See\n * https://spec.modelcontextprotocol.io/ for the full surface.\n */\n\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | { [key: string]: JsonValue }\n | JsonValue[];\n\nexport type JsonObject = { [key: string]: JsonValue };\n\nexport type JsonRpcId = string | number | null;\n\nexport type JsonRpcRequest = {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n method: string;\n params?: JsonObject;\n};\n\nexport type JsonRpcNotification = {\n jsonrpc: \"2.0\";\n method: string;\n params?: JsonObject;\n};\n\nexport type JsonRpcSuccess = {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n result: JsonValue;\n};\n\nexport type JsonRpcError = {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n error: { code: number; message: string; data?: JsonValue };\n};\n\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;\n\nexport const JSONRPC_PARSE_ERROR = -32700;\nexport const JSONRPC_INVALID_REQUEST = -32600;\nexport const JSONRPC_METHOD_NOT_FOUND = -32601;\nexport const JSONRPC_INVALID_PARAMS = -32602;\nexport const JSONRPC_INTERNAL_ERROR = -32603;\n\nexport type ServerCapabilities = {\n tools?: { listChanged?: boolean };\n resources?: { listChanged?: boolean; subscribe?: boolean };\n prompts?: { listChanged?: boolean };\n logging?: Record<string, never>;\n experimental?: Record<string, JsonValue>;\n};\n\nexport type ServerInfo = {\n name: string;\n version: string;\n title?: string;\n};\n\nexport type InitializeResult = {\n protocolVersion: string;\n capabilities: ServerCapabilities;\n serverInfo: ServerInfo;\n instructions?: string;\n};\n\nexport type ToolInputSchema = {\n type: \"object\";\n properties?: Record<string, JsonValue>;\n required?: string[];\n additionalProperties?: boolean;\n};\n\nexport type ToolDefinition = {\n name: string;\n title?: string;\n description?: string;\n inputSchema: ToolInputSchema;\n};\n\nexport type ContentBlock =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string }\n | { type: \"resource\"; resource: { uri: string; text?: string; mimeType?: string } };\n\nexport type CallToolResult = {\n content: ContentBlock[];\n isError?: boolean;\n /** Structured tool output — non-spec but useful for typed bridges. */\n structuredContent?: JsonValue;\n};\n\n/** Handler signature for a tool registered on the MicroMcpServer. */\nexport type ToolCallContext = { transport?: unknown };\nexport type ToolHandler = (args: JsonObject, context?: ToolCallContext) => Promise<CallToolResult> | CallToolResult;\n\n/** Internal record kept by the server. */\nexport type RegisteredTool = {\n definition: ToolDefinition;\n handler: ToolHandler;\n};\n\nexport const MCP_PROTOCOL_VERSION = \"2025-06-18\";\n","import type {\n CallToolResult,\n JsonObject,\n RegisteredTool,\n ToolDefinition,\n ToolHandler,\n} from \"./types\";\n\n/**\n * ToolHost — the minimal surface a bridge needs to register its tools.\n *\n * Bridges (whiteboard, flow, sheets, code, charts, screens, scene, form)\n * speak only through this interface. The MCP server implements it\n * alongside its transport / JSON-RPC duties, and the standalone\n * {@link ToolRegistry} implements it for in-process agents that don't\n * need any of MCP's wire framing.\n *\n * Net effect: every bridge works equally well behind an MCP server\n * (browser ↔ external agents over SSE) or behind a plain registry\n * (in-process agent calling `host.callTool(\"sheet_set_cell\", { … })`).\n */\nexport interface ToolHost {\n /** Register a tool. Returns a disposer that unregisters it. */\n registerTool(definition: ToolDefinition, handler: ToolHandler): () => void;\n\n /** Look up an already-registered tool's definition + handler, or null. */\n getTool(name: string): RegisteredTool | null;\n\n /** Snapshot of all currently-registered tool definitions. */\n listTools(): ToolDefinition[];\n\n /**\n * Invoke a registered tool directly, bypassing any transport layer.\n * Throws if no tool is registered under `name`.\n *\n * This is the single entry point in-process agents use to drive the\n * surface — no JSON-RPC framing, no transport plumbing.\n */\n callTool(name: string, args?: JsonObject): Promise<CallToolResult>;\n}\n\n/**\n * Standalone in-memory ToolHost. Use this when no MCP server is needed —\n * e.g. an in-process agent that just wants to register the same bridges\n * and call them directly.\n *\n * Example:\n *\n * const host = new ToolRegistry();\n * registerSheetsBridge(host, { adapter });\n * const result = await host.callTool(\"sheet_set_cell\", { address: \"B3\", value: 42 });\n *\n * Pair with a MicroMcpServer in the same app to expose the same tools\n * to remote agents over SSE while in-process agents still get\n * zero-overhead direct calls.\n */\nexport class ToolRegistry implements ToolHost {\n protected readonly tools = new Map<string, RegisteredTool>();\n\n /**\n * Tools that existed and were withdrawn, kept so a call that races an unmount\n * can say WHICH thing happened.\n *\n * The tool surface is dynamic by design — \"site tools always, page tools while\n * mounted\" — so an agent deciding to call a tool while the human navigates\n * away is normal traffic, not an edge case. Reporting that as `Unknown tool`\n * is the least useful thing available: it reads as \"the agent is broken\" or\n * \"you asked for something imaginary\", when the truth is \"that surface just\n * closed\".\n *\n * Names only. Nothing about the handler is retained, so this cannot keep a\n * disposed surface alive.\n */\n protected readonly withdrawn = new Set<string>();\n\n registerTool(definition: ToolDefinition, handler: ToolHandler): () => void {\n this.tools.set(definition.name, { definition, handler });\n // A remounted surface must stop apologising for a previous unmount.\n this.withdrawn.delete(definition.name);\n this.onToolsChanged();\n return () => {\n if (this.tools.delete(definition.name)) {\n this.withdrawn.add(definition.name);\n this.onToolsChanged();\n }\n };\n }\n\n /** Why `name` is not callable, phrased for whoever has to act on it. */\n protected missingToolMessage(name: string): string {\n return this.withdrawn.has(name)\n ? `Tool \"${name}\" was withdrawn: the surface it targets is no longer mounted. `\n + `Call tools/list for the current surface — the site-wide tools remain available.`\n : `Unknown tool: ${name}`;\n }\n\n getTool(name: string): RegisteredTool | null {\n return this.tools.get(name) ?? null;\n }\n\n listTools(): ToolDefinition[] {\n return Array.from(this.tools.values()).map((t) => t.definition);\n }\n\n async callTool(name: string, args: JsonObject = {}): Promise<CallToolResult> {\n const tool = this.tools.get(name);\n if (!tool) {\n throw new Error(this.missingToolMessage(name));\n }\n return tool.handler(args);\n }\n\n /**\n * Hook for subclasses (e.g. MicroMcpServer) to notify subscribers\n * when the tool catalog changes. Default no-op.\n */\n protected onToolsChanged(): void {}\n}\n","import {\n type CallToolResult,\n type JsonObject,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcId,\n type RegisteredTool,\n type ServerCapabilities,\n type ServerInfo,\n type ToolDefinition,\n type ToolHandler,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_METHOD_NOT_FOUND,\n MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n info: ServerInfo;\n /** Defaults to { tools: { listChanged: true } } */\n capabilities?: ServerCapabilities;\n /** Free-text instructions surfaced to clients during initialize. */\n instructions?: string;\n};\n\nexport type Transport = {\n /** Called by the server when it has a message to deliver to the client. */\n send: (message: JsonRpcMessage) => void;\n /** Called by the server when it's torn down so the transport can clean up. */\n close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n * const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n * server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n * const transport = new InProcessTransport();\n * server.attach(transport);\n * transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n private transports = new Set<Transport>();\n private notifyListChangedScheduled = false;\n\n readonly info: ServerInfo;\n readonly capabilities: ServerCapabilities;\n readonly instructions?: string;\n\n constructor(options: McpServerOptions) {\n super();\n this.info = options.info;\n this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n this.instructions = options.instructions;\n }\n\n attach(transport: Transport): () => void {\n this.transports.add(transport);\n return () => this.detach(transport);\n }\n\n detach(transport: Transport): void {\n if (this.transports.delete(transport)) {\n transport.close?.();\n }\n }\n\n unregisterTool(name: string): void {\n if (this.tools.delete(name)) {\n this.scheduleListChangedNotification();\n }\n }\n\n protected onToolsChanged(): void {\n this.scheduleListChangedNotification();\n }\n\n /**\n * Receive a JSON-RPC frame from a client (called by the transport).\n * The transport is responsible for sending the response back.\n */\n async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n const isNotification = !(\"id\" in message);\n if (isNotification) {\n // Notifications are fire-and-forget. We ignore unknown methods.\n return;\n }\n\n const request = message as JsonRpcRequest;\n try {\n const result = await this.handle(request, transport);\n transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n } catch (err) {\n transport.send({\n jsonrpc: \"2.0\",\n id: request.id,\n error: this.toRpcError(err),\n });\n }\n }\n\n private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n const { method, params } = request;\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: this.capabilities,\n serverInfo: this.info,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n };\n\n case \"tools/list\":\n return { tools: this.listTools() };\n\n case \"tools/call\": {\n const name = params?.name;\n const args = (params?.arguments ?? {}) as JsonObject;\n if (typeof name !== \"string\") {\n throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n }\n const tool = this.tools.get(name);\n if (!tool) {\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n }\n const result = await tool.handler(args, { transport });\n return result satisfies CallToolResult;\n }\n\n case \"ping\":\n return {};\n\n default:\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n }\n }\n\n private scheduleListChangedNotification(): void {\n if (this.notifyListChangedScheduled) return;\n this.notifyListChangedScheduled = true;\n queueMicrotask(() => {\n this.notifyListChangedScheduled = false;\n this.broadcast({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n });\n }\n\n /** Send an application notification to every client, or one attached transport. */\n notify(message: JsonRpcMessage, transport?: Transport): void {\n if (transport) transport.send(message);\n else this.broadcast(message);\n }\n\n private broadcast(message: JsonRpcMessage): void {\n for (const t of this.transports) t.send(message);\n }\n\n private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n return err as any;\n }\n return {\n code: JSONRPC_INTERNAL_ERROR,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n return {\n content: [{ type: \"text\", text }],\n ...(structured !== undefined ? { structuredContent: structured } : {}),\n };\n}\n\nexport function errorResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import type { JsonRpcMessage } from \"../types\";\nimport type { MicroMcpServer, Transport } from \"../server\";\n\n/**\n * InProcessTransport — direct function-call wiring between an in-page MCP\n * client (e.g. an embedded chat agent) and a MicroMcpServer running in\n * the same JS context. No serialization, no network.\n *\n * Usage:\n *\n * const t = new InProcessTransport();\n * server.attach(t);\n * t.onServerMessage((msg) => { ... }); // client subscribes\n * t.send({ jsonrpc: \"2.0\", id: 1, method: \"tools/list\" }); // client → server\n */\nexport class InProcessTransport implements Transport {\n private server?: MicroMcpServer;\n private listeners = new Set<(msg: JsonRpcMessage) => void>();\n\n /** Bind to a server. Called from the client's setup, not directly. */\n bindServer(server: MicroMcpServer): void {\n this.server = server;\n }\n\n /** Server → client (delivered to subscribed listeners). */\n send(message: JsonRpcMessage): void {\n for (const l of this.listeners) l(message);\n }\n\n /** Client → server. Awaitable so callers can flush. */\n async deliver(message: JsonRpcMessage): Promise<void> {\n if (!this.server) throw new Error(\"InProcessTransport has no bound server\");\n await this.server.receive(this, message);\n }\n\n /** Subscribe to messages the server pushes to this client. */\n onServerMessage(listener: (msg: JsonRpcMessage) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n close(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * Convenience: create a server-attached in-process transport in one call.\n */\nexport function attachInProcess(server: MicroMcpServer): InProcessTransport {\n const transport = new InProcessTransport();\n transport.bindServer(server);\n server.attach(transport);\n return transport;\n}\n","import type { JsonRpcMessage } from \"../types\";\nimport type { MicroMcpServer, Transport } from \"../server\";\n\n/**\n * RelayTransport — wraps any duplex JSON-frame channel (e.g. a Reverb\n * websocket private channel, a WebRTC data channel) so external agents\n * can talk to a browser-side MicroMcpServer.\n *\n * The host app owns the actual channel. This class only handles framing\n * (JSON.stringify / JSON.parse) and the server contract.\n *\n * Channel contract:\n * - host calls `transport.deliverFromRemote(payload)` with each frame\n * it receives from the remote agent\n * - host implements `sendToRemote(frame)` so the transport can deliver\n * server → client frames outward\n *\n * See docs/relay-protocol.md for the wire format.\n */\nexport type RelayChannel = {\n sendToRemote: (frame: JsonRpcMessage) => void;\n /** Optional: notify the channel that the server is gone. */\n onClose?: () => void;\n};\n\nexport class RelayTransport implements Transport {\n private server?: MicroMcpServer;\n constructor(private channel: RelayChannel) {}\n\n bindServer(server: MicroMcpServer): void {\n this.server = server;\n }\n\n send(message: JsonRpcMessage): void {\n this.channel.sendToRemote(message);\n }\n\n /**\n * Host calls this with each frame received from the remote agent. Accepts\n * either a parsed object or a raw JSON string.\n */\n async deliverFromRemote(payload: JsonRpcMessage | string): Promise<void> {\n if (!this.server) throw new Error(\"RelayTransport has no bound server\");\n const message = typeof payload === \"string\"\n ? (JSON.parse(payload) as JsonRpcMessage)\n : payload;\n await this.server.receive(this, message);\n }\n\n close(): void {\n this.channel.onClose?.();\n }\n}\n\n/**\n * Convenience wiring. Returns the bound transport.\n */\nexport function attachRelay(server: MicroMcpServer, channel: RelayChannel): RelayTransport {\n const transport = new RelayTransport(channel);\n transport.bindServer(server);\n server.attach(transport);\n return transport;\n}\n"]}
1
+ {"version":3,"sources":["../src/mcp/types.ts","../src/mcp/tool-host.ts","../src/mcp/server.ts","../src/mcp/transports/in-process.ts","../src/mcp/transports/relay.ts"],"names":[],"mappings":";;;AA+CO,IAAM,mBAAA,GAAsB;AAC5B,IAAM,uBAAA,GAA0B;AAChC,IAAM,wBAAA,GAA2B;AACjC,IAAM,sBAAA,GAAyB;AAC/B,IAAM,sBAAA,GAAyB;AAgF/B,IAAM,oBAAA,GAAuB;;;AC3E7B,IAAM,eAAN,MAAuC;AAAA,EAAvC,WAAA,GAAA;AACL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AAO,CAAA;AAAA,EACzC;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,QAAQ,OAAA,IAAU;AAAA,EACzB;AACF;AAKO,SAAS,WAAA,CAAY,QAAwB,OAAA,EAAuC;AACzF,EAAA,MAAM,SAAA,GAAY,IAAI,cAAA,CAAe,OAAO,CAAA;AAC5C,EAAA,SAAA,CAAU,WAAW,MAAM,CAAA;AAC3B,EAAA,MAAA,CAAO,OAAO,SAAS,CAAA;AACvB,EAAA,OAAO,SAAA;AACT","file":"mcp.cjs","sourcesContent":["/**\n * Minimal MCP (Model Context Protocol) types — covers the subset this\n * package implements: initialize, tools/list, tools/call, plus JSON-RPC.\n *\n * Aligned with the public MCP spec but trimmed to v0.1 needs. See\n * https://spec.modelcontextprotocol.io/ for the full surface.\n */\n\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | { [key: string]: JsonValue }\n | JsonValue[];\n\nexport type JsonObject = { [key: string]: JsonValue };\n\nexport type JsonRpcId = string | number | null;\n\nexport type JsonRpcRequest = {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n method: string;\n params?: JsonObject;\n};\n\nexport type JsonRpcNotification = {\n jsonrpc: \"2.0\";\n method: string;\n params?: JsonObject;\n};\n\nexport type JsonRpcSuccess = {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n result: JsonValue;\n};\n\nexport type JsonRpcError = {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n error: { code: number; message: string; data?: JsonValue };\n};\n\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;\n\nexport const JSONRPC_PARSE_ERROR = -32700;\nexport const JSONRPC_INVALID_REQUEST = -32600;\nexport const JSONRPC_METHOD_NOT_FOUND = -32601;\nexport const JSONRPC_INVALID_PARAMS = -32602;\nexport const JSONRPC_INTERNAL_ERROR = -32603;\n\nexport type ServerCapabilities = {\n tools?: { listChanged?: boolean };\n resources?: { listChanged?: boolean; subscribe?: boolean };\n prompts?: { listChanged?: boolean };\n logging?: Record<string, never>;\n experimental?: Record<string, JsonValue>;\n};\n\nexport type ServerInfo = {\n name: string;\n version: string;\n title?: string;\n};\n\nexport type InitializeResult = {\n protocolVersion: string;\n capabilities: ServerCapabilities;\n serverInfo: ServerInfo;\n instructions?: string;\n};\n\nexport type ToolInputSchema = {\n /** The JSON Schema dialect, when a server states it (e.g. draft-07). */\n $schema?: string;\n type: \"object\";\n properties?: Record<string, JsonValue>;\n required?: string[];\n additionalProperties?: boolean;\n};\n\n/** Behaviour hints a client may use when presenting or gating a tool. */\nexport type ToolAnnotations = {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\n/**\n * A tool as `tools/list` reports it. Every field is passed to the client\n * verbatim, so the optional ones below are the spec's, not extensions.\n */\nexport type ToolDefinition = {\n name: string;\n title?: string;\n description?: string;\n inputSchema: ToolInputSchema;\n /** JSON Schema for `structuredContent`, when the tool returns it. */\n outputSchema?: ToolInputSchema;\n annotations?: ToolAnnotations;\n /** 2025-11-25: whether the tool may run as a task. */\n execution?: { taskSupport?: \"forbidden\" | \"optional\" | \"required\" };\n _meta?: { [key: string]: JsonValue };\n};\n\nexport type ContentBlock =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string }\n | { type: \"resource\"; resource: { uri: string; text?: string; mimeType?: string } };\n\nexport type CallToolResult = {\n content: ContentBlock[];\n isError?: boolean;\n /** Structured tool output — non-spec but useful for typed bridges. */\n structuredContent?: JsonValue;\n};\n\n/** Handler signature for a tool registered on the MicroMcpServer. */\nexport type ToolCallContext = { transport?: unknown };\nexport type ToolHandler = (args: JsonObject, context?: ToolCallContext) => Promise<CallToolResult> | CallToolResult;\n\n/** Internal record kept by the server. */\nexport type RegisteredTool = {\n definition: ToolDefinition;\n handler: ToolHandler;\n};\n\nexport const MCP_PROTOCOL_VERSION = \"2025-06-18\";\n","import type {\n CallToolResult,\n JsonObject,\n RegisteredTool,\n ToolDefinition,\n ToolHandler,\n} from \"./types\";\n\n/**\n * ToolHost — the minimal surface a bridge needs to register its tools.\n *\n * Bridges (whiteboard, flow, sheets, code, charts, screens, scene, form)\n * speak only through this interface. The MCP server implements it\n * alongside its transport / JSON-RPC duties, and the standalone\n * {@link ToolRegistry} implements it for in-process agents that don't\n * need any of MCP's wire framing.\n *\n * Net effect: every bridge works equally well behind an MCP server\n * (browser ↔ external agents over SSE) or behind a plain registry\n * (in-process agent calling `host.callTool(\"sheet_set_cell\", { … })`).\n */\nexport interface ToolHost {\n /** Register a tool. Returns a disposer that unregisters it. */\n registerTool(definition: ToolDefinition, handler: ToolHandler): () => void;\n\n /** Look up an already-registered tool's definition + handler, or null. */\n getTool(name: string): RegisteredTool | null;\n\n /** Snapshot of all currently-registered tool definitions. */\n listTools(): ToolDefinition[];\n\n /**\n * Invoke a registered tool directly, bypassing any transport layer.\n * Throws if no tool is registered under `name`.\n *\n * This is the single entry point in-process agents use to drive the\n * surface — no JSON-RPC framing, no transport plumbing.\n */\n callTool(name: string, args?: JsonObject): Promise<CallToolResult>;\n}\n\n/**\n * Standalone in-memory ToolHost. Use this when no MCP server is needed —\n * e.g. an in-process agent that just wants to register the same bridges\n * and call them directly.\n *\n * Example:\n *\n * const host = new ToolRegistry();\n * registerSheetsBridge(host, { adapter });\n * const result = await host.callTool(\"sheet_set_cell\", { address: \"B3\", value: 42 });\n *\n * Pair with a MicroMcpServer in the same app to expose the same tools\n * to remote agents over SSE while in-process agents still get\n * zero-overhead direct calls.\n */\nexport class ToolRegistry implements ToolHost {\n protected readonly tools = new Map<string, RegisteredTool>();\n\n /**\n * Tools that existed and were withdrawn, kept so a call that races an unmount\n * can say WHICH thing happened.\n *\n * The tool surface is dynamic by design — \"site tools always, page tools while\n * mounted\" — so an agent deciding to call a tool while the human navigates\n * away is normal traffic, not an edge case. Reporting that as `Unknown tool`\n * is the least useful thing available: it reads as \"the agent is broken\" or\n * \"you asked for something imaginary\", when the truth is \"that surface just\n * closed\".\n *\n * Names only. Nothing about the handler is retained, so this cannot keep a\n * disposed surface alive.\n */\n protected readonly withdrawn = new Set<string>();\n\n registerTool(definition: ToolDefinition, handler: ToolHandler): () => void {\n this.tools.set(definition.name, { definition, handler });\n // A remounted surface must stop apologising for a previous unmount.\n this.withdrawn.delete(definition.name);\n this.onToolsChanged();\n return () => {\n if (this.tools.delete(definition.name)) {\n this.withdrawn.add(definition.name);\n this.onToolsChanged();\n }\n };\n }\n\n /** Why `name` is not callable, phrased for whoever has to act on it. */\n protected missingToolMessage(name: string): string {\n return this.withdrawn.has(name)\n ? `Tool \"${name}\" was withdrawn: the surface it targets is no longer mounted. `\n + `Call tools/list for the current surface — the site-wide tools remain available.`\n : `Unknown tool: ${name}`;\n }\n\n getTool(name: string): RegisteredTool | null {\n return this.tools.get(name) ?? null;\n }\n\n listTools(): ToolDefinition[] {\n return Array.from(this.tools.values()).map((t) => t.definition);\n }\n\n async callTool(name: string, args: JsonObject = {}): Promise<CallToolResult> {\n const tool = this.tools.get(name);\n if (!tool) {\n throw new Error(this.missingToolMessage(name));\n }\n return tool.handler(args);\n }\n\n /**\n * Hook for subclasses (e.g. MicroMcpServer) to notify subscribers\n * when the tool catalog changes. Default no-op.\n */\n protected onToolsChanged(): void {}\n}\n","import {\n type CallToolResult,\n type JsonObject,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcId,\n type RegisteredTool,\n type ServerCapabilities,\n type ServerInfo,\n type ToolDefinition,\n type ToolHandler,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_METHOD_NOT_FOUND,\n MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n info: ServerInfo;\n /** Defaults to { tools: { listChanged: true } } */\n capabilities?: ServerCapabilities;\n /** Free-text instructions surfaced to clients during initialize. */\n instructions?: string;\n /**\n * The protocol revisions this server speaks, NEWEST FIRST.\n *\n * `initialize` echoes the client's requested revision when it is in this\n * list, and answers the first entry otherwise — the spec's rule, which leaves\n * the client to decide whether it can live with the answer.\n *\n * Defaults to `[MCP_PROTOCOL_VERSION]`: one revision, answered whatever the\n * client asks, which is exactly what this server did before the option\n * existed. Only list a revision the tools you register are correct under.\n */\n protocolVersions?: readonly string[];\n};\n\nexport type Transport = {\n /** Called by the server when it has a message to deliver to the client. */\n send: (message: JsonRpcMessage) => void;\n /** Called by the server when it's torn down so the transport can clean up. */\n close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n * const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n * server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n * const transport = new InProcessTransport();\n * server.attach(transport);\n * transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n private transports = new Set<Transport>();\n /**\n * Transports owed a `tools/list_changed` at the end of this tick. Empty when\n * none is scheduled. See {@link scheduleListChangedNotification}.\n */\n private listChangedOwed = new Set<Transport>();\n\n readonly info: ServerInfo;\n readonly capabilities: ServerCapabilities;\n readonly instructions?: string;\n readonly protocolVersions: readonly string[];\n\n constructor(options: McpServerOptions) {\n super();\n this.info = options.info;\n this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n this.instructions = options.instructions;\n if (options.protocolVersions && options.protocolVersions.length === 0) {\n // No answer exists for a client's initialize. Fail here, next to the\n // mistake, rather than in a handshake nobody is watching.\n throw new Error(\"MicroMcpServer: protocolVersions is empty — a server must speak at least one protocol revision.\");\n }\n this.protocolVersions = options.protocolVersions ? [...options.protocolVersions] : [MCP_PROTOCOL_VERSION];\n }\n\n attach(transport: Transport): () => void {\n this.transports.add(transport);\n return () => this.detach(transport);\n }\n\n detach(transport: Transport): void {\n if (this.transports.delete(transport)) {\n transport.close?.();\n }\n }\n\n unregisterTool(name: string): void {\n if (this.tools.delete(name)) {\n this.scheduleListChangedNotification();\n }\n }\n\n protected onToolsChanged(): void {\n this.scheduleListChangedNotification();\n }\n\n /**\n * Receive a JSON-RPC frame from a client (called by the transport).\n * The transport is responsible for sending the response back.\n */\n async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n const isNotification = !(\"id\" in message);\n if (isNotification) {\n // Notifications are fire-and-forget. We ignore unknown methods.\n return;\n }\n\n const request = message as JsonRpcRequest;\n try {\n const result = await this.handle(request, transport);\n transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n } catch (err) {\n transport.send({\n jsonrpc: \"2.0\",\n id: request.id,\n error: this.toRpcError(err),\n });\n }\n }\n\n private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n const { method, params } = request;\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: this.negotiate(params?.protocolVersion),\n capabilities: this.capabilities,\n serverInfo: this.info,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n };\n\n case \"tools/list\":\n return { tools: this.listTools() };\n\n case \"tools/call\": {\n const name = params?.name;\n const args = (params?.arguments ?? {}) as JsonObject;\n if (typeof name !== \"string\") {\n throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n }\n const tool = this.tools.get(name);\n if (!tool) {\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n }\n const result = await tool.handler(args, { transport });\n return result satisfies CallToolResult;\n }\n\n case \"ping\":\n return {};\n\n default:\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n }\n }\n\n /** The revision to answer `initialize` with: the one asked for if spoken, else the newest. */\n private negotiate(requested: unknown): string {\n return typeof requested === \"string\" && this.protocolVersions.includes(requested)\n ? requested\n : this.protocolVersions[0];\n }\n\n /**\n * Tell the transports that SAW the old tool list that it changed.\n *\n * Changes in one tick coalesce into one notification. The recipients are the\n * transports attached at the moment of a change, not at the moment the\n * notification goes out: a transport attached afterwards never had the old\n * list, so \"your list is stale\" is noise to it — and on stdio, where a host\n * builds the server and attaches stdin/stdout in the same tick, it was the\n * first frame a client received, before it had even sent `initialize`.\n */\n private scheduleListChangedNotification(): void {\n if (this.transports.size === 0) return;\n const scheduled = this.listChangedOwed.size > 0;\n for (const t of this.transports) this.listChangedOwed.add(t);\n if (scheduled) return;\n queueMicrotask(() => {\n const owed = this.listChangedOwed;\n this.listChangedOwed = new Set();\n for (const t of owed) {\n // Detached since the change: it is not listening any more.\n if (this.transports.has(t)) t.send({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n }\n });\n }\n\n /** Send an application notification to every client, or one attached transport. */\n notify(message: JsonRpcMessage, transport?: Transport): void {\n if (transport) transport.send(message);\n else this.broadcast(message);\n }\n\n private broadcast(message: JsonRpcMessage): void {\n for (const t of this.transports) t.send(message);\n }\n\n private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n return err as any;\n }\n return {\n code: JSONRPC_INTERNAL_ERROR,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n return {\n content: [{ type: \"text\", text }],\n ...(structured !== undefined ? { structuredContent: structured } : {}),\n };\n}\n\nexport function errorResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import type { JsonRpcMessage } from \"../types\";\nimport type { MicroMcpServer, Transport } from \"../server\";\n\n/**\n * InProcessTransport — direct function-call wiring between an in-page MCP\n * client (e.g. an embedded chat agent) and a MicroMcpServer running in\n * the same JS context. No serialization, no network.\n *\n * Usage:\n *\n * const t = new InProcessTransport();\n * server.attach(t);\n * t.onServerMessage((msg) => { ... }); // client subscribes\n * t.send({ jsonrpc: \"2.0\", id: 1, method: \"tools/list\" }); // client → server\n */\nexport class InProcessTransport implements Transport {\n private server?: MicroMcpServer;\n private listeners = new Set<(msg: JsonRpcMessage) => void>();\n\n /** Bind to a server. Called from the client's setup, not directly. */\n bindServer(server: MicroMcpServer): void {\n this.server = server;\n }\n\n /** Server → client (delivered to subscribed listeners). */\n send(message: JsonRpcMessage): void {\n for (const l of this.listeners) l(message);\n }\n\n /** Client → server. Awaitable so callers can flush. */\n async deliver(message: JsonRpcMessage): Promise<void> {\n if (!this.server) throw new Error(\"InProcessTransport has no bound server\");\n await this.server.receive(this, message);\n }\n\n /** Subscribe to messages the server pushes to this client. */\n onServerMessage(listener: (msg: JsonRpcMessage) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n close(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * Convenience: create a server-attached in-process transport in one call.\n */\nexport function attachInProcess(server: MicroMcpServer): InProcessTransport {\n const transport = new InProcessTransport();\n transport.bindServer(server);\n server.attach(transport);\n return transport;\n}\n","import type { JsonRpcMessage } from \"../types\";\nimport type { MicroMcpServer, Transport } from \"../server\";\n\n/**\n * RelayTransport — wraps any duplex JSON-frame channel (e.g. a Reverb\n * websocket private channel, a WebRTC data channel) so external agents\n * can talk to a browser-side MicroMcpServer.\n *\n * The host app owns the actual channel. This class only handles framing\n * (JSON.stringify / JSON.parse) and the server contract.\n *\n * Channel contract:\n * - host calls `transport.deliverFromRemote(payload)` with each frame\n * it receives from the remote agent\n * - host implements `sendToRemote(frame)` so the transport can deliver\n * server → client frames outward\n *\n * See docs/relay-protocol.md for the wire format.\n */\nexport type RelayChannel = {\n sendToRemote: (frame: JsonRpcMessage) => void;\n /** Optional: notify the channel that the server is gone. */\n onClose?: () => void;\n};\n\nexport class RelayTransport implements Transport {\n private server?: MicroMcpServer;\n constructor(private channel: RelayChannel) {}\n\n bindServer(server: MicroMcpServer): void {\n this.server = server;\n }\n\n send(message: JsonRpcMessage): void {\n this.channel.sendToRemote(message);\n }\n\n /**\n * Host calls this with each frame received from the remote agent. Accepts\n * either a parsed object or a raw JSON string.\n */\n async deliverFromRemote(payload: JsonRpcMessage | string): Promise<void> {\n if (!this.server) throw new Error(\"RelayTransport has no bound server\");\n const message = typeof payload === \"string\"\n ? (JSON.parse(payload) as JsonRpcMessage)\n : payload;\n await this.server.receive(this, message);\n }\n\n close(): void {\n this.channel.onClose?.();\n }\n}\n\n/**\n * Convenience wiring. Returns the bound transport.\n */\nexport function attachRelay(server: MicroMcpServer, channel: RelayChannel): RelayTransport {\n const transport = new RelayTransport(channel);\n transport.bindServer(server);\n server.attach(transport);\n return transport;\n}\n"]}
package/dist/mcp.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { RelayTransport, attachRelay } from './chunk-G6N2TQVO.js';
2
2
  export { InProcessTransport, attachInProcess } from './chunk-AFUULW5E.js';
3
- export { JSONRPC_INTERNAL_ERROR, JSONRPC_INVALID_PARAMS, JSONRPC_INVALID_REQUEST, JSONRPC_METHOD_NOT_FOUND, JSONRPC_PARSE_ERROR, MCP_PROTOCOL_VERSION, MicroMcpServer, errorResult, rpcError, textResult } from './chunk-QJYRWEXD.js';
3
+ export { JSONRPC_INTERNAL_ERROR, JSONRPC_INVALID_PARAMS, JSONRPC_INVALID_REQUEST, JSONRPC_METHOD_NOT_FOUND, JSONRPC_PARSE_ERROR, MCP_PROTOCOL_VERSION, MicroMcpServer, errorResult, rpcError, textResult } from './chunk-CZV3WUW5.js';
4
4
  //# sourceMappingURL=mcp.js.map
5
5
  //# sourceMappingURL=mcp.js.map
@@ -1,6 +1,6 @@
1
1
  import { AutoTarget, ActivityFilter, AutoActivityEvent } from '@particle-academy/fancy-auto-common';
2
2
  export { ActivityFilter, AutoActivityEvent as AgentActivityEvent, AutoActivityListener as AgentActivityListener, AutoTarget as AgentTarget, AutoTargetKind as AgentTargetKind, emitActivity, onActivity, readActivityHistory, resetActivityRegistry } from '@particle-academy/fancy-auto-common';
3
- import { C as CallToolResult } from '../types-C58ZXs4K.cjs';
3
+ import { C as CallToolResult } from '../types-C2DtnHIn.cjs';
4
4
 
5
5
  type ActivityAgent = {
6
6
  id: string;
@@ -1,6 +1,6 @@
1
1
  import { AutoTarget, ActivityFilter, AutoActivityEvent } from '@particle-academy/fancy-auto-common';
2
2
  export { ActivityFilter, AutoActivityEvent as AgentActivityEvent, AutoActivityListener as AgentActivityListener, AutoTarget as AgentTarget, AutoTargetKind as AgentTargetKind, emitActivity, onActivity, readActivityHistory, resetActivityRegistry } from '@particle-academy/fancy-auto-common';
3
- import { C as CallToolResult } from '../types-C58ZXs4K.js';
3
+ import { C as CallToolResult } from '../types-C2DtnHIn.js';
4
4
 
5
5
  type ActivityAgent = {
6
6
  id: string;
@@ -31,6 +31,15 @@ type Subscriber = {
31
31
  direction: Direction;
32
32
  queue: string[];
33
33
  resolveNext: ((frame: string | null) => void) | null;
34
+ /**
35
+ * The caller-supplied client label, when one was given.
36
+ *
37
+ * Used to route a RESPONSE back to whoever asked. Without it the broker
38
+ * cannot tell two holders of one bearer token apart, and every reply goes to
39
+ * every subscriber -- so a second token holder passively receives the results
40
+ * of everyone else's tool calls without making one.
41
+ */
42
+ client?: string;
34
43
  };
35
44
  type RelayBrokerOptions = {
36
45
  /** Sessions auto-expire after this many ms of inactivity. Default 4h. */
@@ -52,6 +61,8 @@ declare class RelayBroker {
52
61
  private readonly store;
53
62
  /** Per-session, per-direction subscriber list. */
54
63
  private subs;
64
+ /** Per-session map of JSON-RPC request id -> the client that asked. */
65
+ private callers;
55
66
  private reaper?;
56
67
  constructor(opts?: RelayBrokerOptions);
57
68
  dispose(): void;
@@ -102,15 +113,46 @@ declare class RelayBroker {
102
113
  /** Drop a session — the page closed, or a test needs it gone. */
103
114
  dropSession(id: string): void;
104
115
  /** Push a frame onto the inbound queue (external agent → browser). */
105
- inbox(id: string, token: string, payload: string): boolean;
116
+ inbox(id: string, token: string, payload: string, opts?: {
117
+ client?: string;
118
+ }): boolean;
106
119
  /** Push a frame onto the outbound queue (browser server → external agents). */
107
120
  outbox(id: string, token: string, payload: string): boolean;
108
121
  /**
109
122
  * Subscribe to a session's queue for one direction. Returns an iterable
110
123
  * the caller (an HTTP handler) pumps as SSE.
111
124
  */
112
- subscribe(id: string, token: string, direction: Direction): SubscribeResult;
125
+ subscribe(id: string, token: string, direction: Direction, opts?: {
126
+ client?: string;
127
+ }): SubscribeResult;
113
128
  private getDirSubs;
129
+ /**
130
+ * Record which client asked, keyed by JSON-RPC id.
131
+ *
132
+ * Only for REQUESTS — a frame with both an `id` and a `method`. A
133
+ * notification answers nobody and a response is not a question.
134
+ */
135
+ private rememberCaller;
136
+ /**
137
+ * The client a RESPONSE belongs to, or `null` when the frame is a broadcast.
138
+ *
139
+ * Returns the empty string for a response whose id nobody is recorded as
140
+ * having asked — routed to NOBODY rather than to everyone. Broadcasting an
141
+ * uncorrelated reply "just in case" is precisely the leak being closed.
142
+ */
143
+ private callerFor;
144
+ /**
145
+ * Has any subscriber on this session told the broker who it is?
146
+ *
147
+ * The discriminator between a scoped session and a legacy one. Checked across
148
+ * BOTH directions: the page subscribes inbound and rarely labels itself, so
149
+ * asking only about the outbound side would misread a scoped session whose
150
+ * agents have not yet attached.
151
+ */
152
+ private anyIdentifiedSubscriber;
153
+ private parseFrame;
154
+ /** Deliver to the subscribers of one client only. */
155
+ private fanOutTo;
114
156
  private fanOut;
115
157
  /**
116
158
  * Validate that a peer-supplied payload is a well-formed JSON-RPC 2.0 frame
@@ -31,6 +31,15 @@ type Subscriber = {
31
31
  direction: Direction;
32
32
  queue: string[];
33
33
  resolveNext: ((frame: string | null) => void) | null;
34
+ /**
35
+ * The caller-supplied client label, when one was given.
36
+ *
37
+ * Used to route a RESPONSE back to whoever asked. Without it the broker
38
+ * cannot tell two holders of one bearer token apart, and every reply goes to
39
+ * every subscriber -- so a second token holder passively receives the results
40
+ * of everyone else's tool calls without making one.
41
+ */
42
+ client?: string;
34
43
  };
35
44
  type RelayBrokerOptions = {
36
45
  /** Sessions auto-expire after this many ms of inactivity. Default 4h. */
@@ -52,6 +61,8 @@ declare class RelayBroker {
52
61
  private readonly store;
53
62
  /** Per-session, per-direction subscriber list. */
54
63
  private subs;
64
+ /** Per-session map of JSON-RPC request id -> the client that asked. */
65
+ private callers;
55
66
  private reaper?;
56
67
  constructor(opts?: RelayBrokerOptions);
57
68
  dispose(): void;
@@ -102,15 +113,46 @@ declare class RelayBroker {
102
113
  /** Drop a session — the page closed, or a test needs it gone. */
103
114
  dropSession(id: string): void;
104
115
  /** Push a frame onto the inbound queue (external agent → browser). */
105
- inbox(id: string, token: string, payload: string): boolean;
116
+ inbox(id: string, token: string, payload: string, opts?: {
117
+ client?: string;
118
+ }): boolean;
106
119
  /** Push a frame onto the outbound queue (browser server → external agents). */
107
120
  outbox(id: string, token: string, payload: string): boolean;
108
121
  /**
109
122
  * Subscribe to a session's queue for one direction. Returns an iterable
110
123
  * the caller (an HTTP handler) pumps as SSE.
111
124
  */
112
- subscribe(id: string, token: string, direction: Direction): SubscribeResult;
125
+ subscribe(id: string, token: string, direction: Direction, opts?: {
126
+ client?: string;
127
+ }): SubscribeResult;
113
128
  private getDirSubs;
129
+ /**
130
+ * Record which client asked, keyed by JSON-RPC id.
131
+ *
132
+ * Only for REQUESTS — a frame with both an `id` and a `method`. A
133
+ * notification answers nobody and a response is not a question.
134
+ */
135
+ private rememberCaller;
136
+ /**
137
+ * The client a RESPONSE belongs to, or `null` when the frame is a broadcast.
138
+ *
139
+ * Returns the empty string for a response whose id nobody is recorded as
140
+ * having asked — routed to NOBODY rather than to everyone. Broadcasting an
141
+ * uncorrelated reply "just in case" is precisely the leak being closed.
142
+ */
143
+ private callerFor;
144
+ /**
145
+ * Has any subscriber on this session told the broker who it is?
146
+ *
147
+ * The discriminator between a scoped session and a legacy one. Checked across
148
+ * BOTH directions: the page subscribes inbound and rarely labels itself, so
149
+ * asking only about the outbound side would misread a scoped session whose
150
+ * agents have not yet attached.
151
+ */
152
+ private anyIdentifiedSubscriber;
153
+ private parseFrame;
154
+ /** Deliver to the subscribers of one client only. */
155
+ private fanOutTo;
114
156
  private fanOut;
115
157
  /**
116
158
  * Validate that a peer-supplied payload is a well-formed JSON-RPC 2.0 frame
@@ -29,6 +29,8 @@ var RelayBroker = class {
29
29
  constructor(opts = {}) {
30
30
  /** Per-session, per-direction subscriber list. */
31
31
  this.subs = /* @__PURE__ */ new Map();
32
+ /** Per-session map of JSON-RPC request id -> the client that asked. */
33
+ this.callers = /* @__PURE__ */ new Map();
32
34
  this.ttlMs = opts.ttlMs ?? 4 * 60 * 60 * 1e3;
33
35
  this.store = opts.store ?? new MemoryStore();
34
36
  const tick = opts.reapIntervalMs ?? 6e4;
@@ -42,6 +44,7 @@ var RelayBroker = class {
42
44
  dispose() {
43
45
  if (this.reaper) clearInterval(this.reaper);
44
46
  this.subs.clear();
47
+ this.callers.clear();
45
48
  }
46
49
  /** Register a session id + token. Idempotent — same id+token re-registers,
47
50
  * different token fails. */
@@ -65,6 +68,7 @@ var RelayBroker = class {
65
68
  if (!this.validate(id, token)) return false;
66
69
  this.store.deleteSession(id);
67
70
  this.subs.delete(id);
71
+ this.callers.delete(id);
68
72
  return true;
69
73
  }
70
74
  /**
@@ -113,11 +117,15 @@ var RelayBroker = class {
113
117
  dropSession(id) {
114
118
  this.store.deleteSession(id);
115
119
  this.subs.delete(id);
120
+ this.callers.delete(id);
116
121
  }
117
122
  /** Push a frame onto the inbound queue (external agent → browser). */
118
- inbox(id, token, payload) {
123
+ inbox(id, token, payload, opts = {}) {
119
124
  if (!this.validate(id, token)) return false;
120
125
  if (!this.isFrame(payload)) return false;
126
+ if (opts.client !== void 0) {
127
+ this.rememberCaller(id, payload, opts.client);
128
+ }
121
129
  this.fanOut(id, "inbound", payload);
122
130
  return true;
123
131
  }
@@ -125,17 +133,28 @@ var RelayBroker = class {
125
133
  outbox(id, token, payload) {
126
134
  if (!this.validate(id, token)) return false;
127
135
  if (!this.isFrame(payload)) return false;
128
- this.fanOut(id, "outbound", payload);
136
+ const target = this.callerFor(id, payload);
137
+ if (target === null) {
138
+ this.fanOut(id, "outbound", payload);
139
+ return true;
140
+ }
141
+ this.fanOutTo(id, "outbound", payload, target);
129
142
  return true;
130
143
  }
131
144
  /**
132
145
  * Subscribe to a session's queue for one direction. Returns an iterable
133
146
  * the caller (an HTTP handler) pumps as SSE.
134
147
  */
135
- subscribe(id, token, direction) {
148
+ subscribe(id, token, direction, opts = {}) {
136
149
  if (!this.validate(id, token)) return { ok: false, reason: "invalid_token" };
137
150
  const subscriberId = crypto.randomBytes(8).toString("hex");
138
- const subscriber = { id: subscriberId, direction, queue: [], resolveNext: null };
151
+ const subscriber = {
152
+ id: subscriberId,
153
+ direction,
154
+ queue: [],
155
+ resolveNext: null,
156
+ client: opts.client
157
+ };
139
158
  this.getDirSubs(id, direction).set(subscriberId, subscriber);
140
159
  if (direction === "outbound") {
141
160
  this.fanOut(
@@ -201,6 +220,85 @@ var RelayBroker = class {
201
220
  }
202
221
  return byDir;
203
222
  }
223
+ /**
224
+ * Record which client asked, keyed by JSON-RPC id.
225
+ *
226
+ * Only for REQUESTS — a frame with both an `id` and a `method`. A
227
+ * notification answers nobody and a response is not a question.
228
+ */
229
+ rememberCaller(sessionId, payload, client) {
230
+ const frame = this.parseFrame(payload);
231
+ if (!frame || frame.id === void 0 || frame.id === null || typeof frame.method !== "string") {
232
+ return;
233
+ }
234
+ let byId = this.callers.get(sessionId);
235
+ if (!byId) {
236
+ byId = /* @__PURE__ */ new Map();
237
+ this.callers.set(sessionId, byId);
238
+ }
239
+ if (byId.size >= 1e3) {
240
+ const oldest = byId.keys().next();
241
+ if (!oldest.done) byId.delete(oldest.value);
242
+ }
243
+ byId.set(String(frame.id), client);
244
+ }
245
+ /**
246
+ * The client a RESPONSE belongs to, or `null` when the frame is a broadcast.
247
+ *
248
+ * Returns the empty string for a response whose id nobody is recorded as
249
+ * having asked — routed to NOBODY rather than to everyone. Broadcasting an
250
+ * uncorrelated reply "just in case" is precisely the leak being closed.
251
+ */
252
+ callerFor(sessionId, payload) {
253
+ const frame = this.parseFrame(payload);
254
+ if (!frame || frame.id === void 0 || frame.id === null || typeof frame.method === "string") {
255
+ return null;
256
+ }
257
+ if (!this.anyIdentifiedSubscriber(sessionId)) {
258
+ return null;
259
+ }
260
+ const byId = this.callers.get(sessionId);
261
+ const key = String(frame.id);
262
+ const client = byId?.get(key);
263
+ byId?.delete(key);
264
+ return client ?? "";
265
+ }
266
+ /**
267
+ * Has any subscriber on this session told the broker who it is?
268
+ *
269
+ * The discriminator between a scoped session and a legacy one. Checked across
270
+ * BOTH directions: the page subscribes inbound and rarely labels itself, so
271
+ * asking only about the outbound side would misread a scoped session whose
272
+ * agents have not yet attached.
273
+ */
274
+ anyIdentifiedSubscriber(sessionId) {
275
+ const dirs = this.subs.get(sessionId);
276
+ if (!dirs) return false;
277
+ for (const dir of dirs.values()) {
278
+ for (const sub of dir.values()) {
279
+ if (sub.client !== void 0) return true;
280
+ }
281
+ }
282
+ return false;
283
+ }
284
+ parseFrame(payload) {
285
+ try {
286
+ const parsed = JSON.parse(payload);
287
+ return parsed && typeof parsed === "object" ? parsed : null;
288
+ } catch {
289
+ return null;
290
+ }
291
+ }
292
+ /** Deliver to the subscribers of one client only. */
293
+ fanOutTo(sessionId, direction, payload, client) {
294
+ const dir = this.subs.get(sessionId)?.get(direction);
295
+ if (!dir) return;
296
+ for (const sub of dir.values()) {
297
+ if (sub.client !== client) continue;
298
+ sub.queue.push(payload);
299
+ sub.resolveNext?.(sub.queue.shift() ?? null);
300
+ }
301
+ }
204
302
  fanOut(sessionId, direction, payload) {
205
303
  const dir = this.subs.get(sessionId)?.get(direction);
206
304
  if (!dir) return;
@@ -251,6 +349,7 @@ var RelayBroker = class {
251
349
  }
252
350
  }
253
351
  this.subs.delete(id);
352
+ this.callers.delete(id);
254
353
  this.store.deleteSession(id);
255
354
  }
256
355
  }
@@ -369,7 +468,8 @@ function createNodeRelay(opts = {}) {
369
468
  if (!auth.ok && auth.reason === "session_gone") {
370
469
  return json(res, 410, { error: "session_gone" });
371
470
  }
372
- const ok = direction === "inbound" ? broker.inbox(session, token, body) : broker.outbox(session, token, body);
471
+ const client = getQuery(req).get("client") ?? void 0;
472
+ const ok = direction === "inbound" ? broker.inbox(session, token, body, { client }) : broker.outbox(session, token, body);
373
473
  return json(res, ok ? 200 : 401, ok ? { ok: true } : { error: "invalid_token_or_frame" });
374
474
  };
375
475
  }
@@ -388,7 +488,9 @@ function createNodeRelay(opts = {}) {
388
488
  const q = getQuery(req);
389
489
  const token = q.get("token") ?? "";
390
490
  const direction = q.get("direction") === "outbound" ? "outbound" : "inbound";
391
- const sub = broker.subscribe(session, token, direction);
491
+ const sub = broker.subscribe(session, token, direction, {
492
+ client: getQuery(req).get("client") ?? void 0
493
+ });
392
494
  if (!sub.ok) {
393
495
  res.statusCode = 401;
394
496
  res.setHeader("content-type", "text/event-stream");