@particle-academy/agent-integrations 0.44.0 → 0.46.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.
- package/README.md +42 -3
- package/dist/bridges/artboard.d.cts +3 -3
- package/dist/bridges/artboard.d.ts +3 -3
- package/dist/bridges/catalog.d.cts +3 -3
- package/dist/bridges/catalog.d.ts +3 -3
- package/dist/bridges/charts.d.cts +3 -3
- package/dist/bridges/charts.d.ts +3 -3
- package/dist/bridges/cms.d.cts +3 -3
- package/dist/bridges/cms.d.ts +3 -3
- package/dist/bridges/code.d.cts +3 -3
- package/dist/bridges/code.d.ts +3 -3
- package/dist/bridges/doc.d.cts +3 -3
- package/dist/bridges/doc.d.ts +3 -3
- package/dist/bridges/features.d.cts +3 -3
- package/dist/bridges/features.d.ts +3 -3
- package/dist/bridges/files.d.cts +3 -3
- package/dist/bridges/files.d.ts +3 -3
- package/dist/bridges/flow.d.cts +3 -3
- package/dist/bridges/flow.d.ts +3 -3
- package/dist/bridges/forms.d.cts +3 -3
- package/dist/bridges/forms.d.ts +3 -3
- package/dist/bridges/git.d.cts +3 -3
- package/dist/bridges/git.d.ts +3 -3
- package/dist/bridges/grid.d.cts +3 -3
- package/dist/bridges/grid.d.ts +3 -3
- package/dist/bridges/map.d.cts +3 -3
- package/dist/bridges/map.d.ts +3 -3
- package/dist/bridges/passkeys.d.cts +3 -3
- package/dist/bridges/passkeys.d.ts +3 -3
- package/dist/bridges/scene.d.cts +3 -3
- package/dist/bridges/scene.d.ts +3 -3
- package/dist/bridges/screens.d.cts +3 -3
- package/dist/bridges/screens.d.ts +3 -3
- package/dist/bridges/sheets.d.cts +3 -3
- package/dist/bridges/sheets.d.ts +3 -3
- package/dist/bridges/slides.d.cts +3 -3
- package/dist/bridges/slides.d.ts +3 -3
- package/dist/bridges/terminal.d.cts +3 -3
- package/dist/bridges/terminal.d.ts +3 -3
- package/dist/bridges/tui.d.cts +2 -2
- package/dist/bridges/tui.d.ts +2 -2
- package/dist/bridges/whiteboard.d.cts +3 -3
- package/dist/bridges/whiteboard.d.ts +3 -3
- package/dist/bridges-artboard.cjs.map +1 -1
- package/dist/bridges-artboard.js +2 -2
- package/dist/bridges-catalog.cjs.map +1 -1
- package/dist/bridges-catalog.js +3 -3
- package/dist/bridges-charts.cjs.map +1 -1
- package/dist/bridges-charts.js +3 -3
- package/dist/bridges-cms.cjs.map +1 -1
- package/dist/bridges-cms.js +4 -4
- package/dist/bridges-code.cjs.map +1 -1
- package/dist/bridges-code.js +3 -3
- package/dist/bridges-doc.cjs.map +1 -1
- package/dist/bridges-doc.js +3 -3
- package/dist/bridges-features.cjs.map +1 -1
- package/dist/bridges-features.js +3 -3
- package/dist/bridges-files.cjs.map +1 -1
- package/dist/bridges-files.js +3 -3
- package/dist/bridges-flow.cjs.map +1 -1
- package/dist/bridges-flow.js +2 -2
- package/dist/bridges-forms.cjs.map +1 -1
- package/dist/bridges-forms.js +3 -3
- package/dist/bridges-git.cjs.map +1 -1
- package/dist/bridges-git.js +3 -3
- package/dist/bridges-grid.cjs.map +1 -1
- package/dist/bridges-grid.js +3 -3
- package/dist/bridges-map.cjs.map +1 -1
- package/dist/bridges-map.js +3 -3
- package/dist/bridges-passkeys.cjs.map +1 -1
- package/dist/bridges-passkeys.js +3 -3
- package/dist/bridges-scene.cjs.map +1 -1
- package/dist/bridges-scene.js +3 -3
- package/dist/bridges-screens.cjs.map +1 -1
- package/dist/bridges-screens.js +3 -3
- package/dist/bridges-sheets.cjs.map +1 -1
- package/dist/bridges-sheets.js +3 -3
- package/dist/bridges-slides.cjs.map +1 -1
- package/dist/bridges-slides.js +3 -3
- package/dist/bridges-terminal.cjs.map +1 -1
- package/dist/bridges-terminal.js +3 -3
- package/dist/bridges-tui.cjs.map +1 -1
- package/dist/bridges-tui.js +2 -2
- package/dist/bridges-whiteboard.cjs.map +1 -1
- package/dist/bridges-whiteboard.js +3 -3
- package/dist/{chunk-5W6YOXLT.js → chunk-36MKPTVD.js} +4 -4
- package/dist/{chunk-5W6YOXLT.js.map → chunk-36MKPTVD.js.map} +1 -1
- package/dist/{chunk-SXVRIIXW.js → chunk-3HVYUMQF.js} +4 -4
- package/dist/{chunk-SXVRIIXW.js.map → chunk-3HVYUMQF.js.map} +1 -1
- package/dist/{chunk-MZ74LLDS.js → chunk-3UUF5KKZ.js} +4 -4
- package/dist/{chunk-MZ74LLDS.js.map → chunk-3UUF5KKZ.js.map} +1 -1
- package/dist/{chunk-WEXMZMJH.js → chunk-3WVXAB3D.js} +3 -3
- package/dist/{chunk-WEXMZMJH.js.map → chunk-3WVXAB3D.js.map} +1 -1
- package/dist/{chunk-OZBUPO4K.js → chunk-5W34X4EY.js} +263 -58
- package/dist/chunk-5W34X4EY.js.map +1 -0
- package/dist/{chunk-Z4L2GOAK.js → chunk-5ZWNCHZS.js} +4 -4
- package/dist/{chunk-Z4L2GOAK.js.map → chunk-5ZWNCHZS.js.map} +1 -1
- package/dist/{chunk-TEB5U6Y5.js → chunk-7NVATRLE.js} +4 -4
- package/dist/{chunk-TEB5U6Y5.js.map → chunk-7NVATRLE.js.map} +1 -1
- package/dist/{chunk-PUMQDV67.js → chunk-AXWMWYH5.js} +4 -4
- package/dist/{chunk-PUMQDV67.js.map → chunk-AXWMWYH5.js.map} +1 -1
- package/dist/{chunk-NKAH67JK.js → chunk-CS3CHGYC.js} +4 -4
- package/dist/{chunk-NKAH67JK.js.map → chunk-CS3CHGYC.js.map} +1 -1
- package/dist/{chunk-QJYRWEXD.js → chunk-CZV3WUW5.js} +35 -8
- package/dist/chunk-CZV3WUW5.js.map +1 -0
- package/dist/{chunk-PCFRBVKS.js → chunk-FCXSR7I5.js} +4 -4
- package/dist/{chunk-PCFRBVKS.js.map → chunk-FCXSR7I5.js.map} +1 -1
- package/dist/{chunk-NIFPRC7P.js → chunk-GVTBMJU6.js} +4 -4
- package/dist/{chunk-NIFPRC7P.js.map → chunk-GVTBMJU6.js.map} +1 -1
- package/dist/{chunk-E2I3YVKC.js → chunk-JLHVQWOV.js} +3 -3
- package/dist/{chunk-E2I3YVKC.js.map → chunk-JLHVQWOV.js.map} +1 -1
- package/dist/{chunk-2LSU3NFO.js → chunk-LQB42OSA.js} +4 -4
- package/dist/{chunk-2LSU3NFO.js.map → chunk-LQB42OSA.js.map} +1 -1
- package/dist/{chunk-VJD3Y7E5.js → chunk-MIDZWKIF.js} +4 -4
- package/dist/{chunk-VJD3Y7E5.js.map → chunk-MIDZWKIF.js.map} +1 -1
- package/dist/{chunk-LOD77NCD.js → chunk-PWYEW6NL.js} +4 -4
- package/dist/{chunk-LOD77NCD.js.map → chunk-PWYEW6NL.js.map} +1 -1
- package/dist/{chunk-HVDHT7DM.js → chunk-R4XXOGQH.js} +3 -3
- package/dist/{chunk-HVDHT7DM.js.map → chunk-R4XXOGQH.js.map} +1 -1
- package/dist/{chunk-7LLMILTM.js → chunk-RVMM4BHK.js} +4 -4
- package/dist/{chunk-7LLMILTM.js.map → chunk-RVMM4BHK.js.map} +1 -1
- package/dist/{chunk-NIXOY473.js → chunk-SWWJUOCY.js} +3 -3
- package/dist/{chunk-NIXOY473.js.map → chunk-SWWJUOCY.js.map} +1 -1
- package/dist/{chunk-EIBV76IB.js → chunk-VFWFT3OK.js} +4 -4
- package/dist/{chunk-EIBV76IB.js.map → chunk-VFWFT3OK.js.map} +1 -1
- package/dist/{chunk-2Q4EGZHJ.js → chunk-VMRUW4B4.js} +4 -4
- package/dist/{chunk-2Q4EGZHJ.js.map → chunk-VMRUW4B4.js.map} +1 -1
- package/dist/{chunk-GT63LSPJ.js → chunk-VOCUGTZB.js} +4 -4
- package/dist/{chunk-GT63LSPJ.js.map → chunk-VOCUGTZB.js.map} +1 -1
- package/dist/{chunk-N5VOPV64.js → chunk-Z5NL5D4J.js} +4 -4
- package/dist/{chunk-N5VOPV64.js.map → chunk-Z5NL5D4J.js.map} +1 -1
- package/dist/components-shared-whiteboard.cjs +33 -6
- package/dist/components-shared-whiteboard.cjs.map +1 -1
- package/dist/components-shared-whiteboard.js +3 -3
- package/dist/index.cjs +33 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +27 -27
- package/dist/mcp/index.d.cts +5 -5
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/stdio.d.cts +94 -0
- package/dist/mcp/stdio.d.ts +94 -0
- package/dist/mcp-stdio.cjs +120 -0
- package/dist/mcp-stdio.cjs.map +1 -0
- package/dist/mcp-stdio.js +117 -0
- package/dist/mcp-stdio.js.map +1 -0
- package/dist/mcp.cjs +33 -6
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/presence/index.d.cts +1 -1
- package/dist/presence/index.d.ts +1 -1
- package/dist/relay-server/index.d.cts +110 -26
- package/dist/relay-server/index.d.ts +110 -26
- package/dist/relay-server-cli.cjs +374 -89
- package/dist/relay-server-cli.cjs.map +1 -1
- package/dist/relay-server-cli.js +120 -38
- package/dist/relay-server-cli.js.map +1 -1
- package/dist/relay-server.cjs +255 -51
- package/dist/relay-server.cjs.map +1 -1
- package/dist/relay-server.js +1 -1
- package/dist/{server-BJNF7pQe.d.cts → server-BIcA3ZtK.d.cts} +32 -3
- package/dist/{server-Dt97UxuD.d.ts → server-DnUyeavY.d.ts} +32 -3
- package/dist/sharing/index.d.cts +3 -3
- package/dist/sharing/index.d.ts +3 -3
- package/dist/sheets-adapter.d.cts +3 -3
- package/dist/sheets-adapter.d.ts +3 -3
- package/dist/{tool-host-BpEBqf5u.d.cts → tool-host-LVBgCN5m.d.cts} +1 -1
- package/dist/{tool-host-xY5F-eqG.d.ts → tool-host-Wo0pkY83.d.ts} +1 -1
- package/dist/{types-DSwsNTBG.d.ts → types-BxNRKSVd.d.ts} +1 -1
- package/dist/{types-C58ZXs4K.d.cts → types-C2DtnHIn.d.cts} +25 -1
- package/dist/{types-C58ZXs4K.d.ts → types-C2DtnHIn.d.ts} +25 -1
- package/dist/{types-C4NaIW6B.d.cts → types-EcElKOlk.d.cts} +1 -1
- package/dist/undo/index.d.cts +2 -2
- package/dist/undo/index.d.ts +2 -2
- package/dist/undo.cjs.map +1 -1
- package/dist/undo.js +3 -3
- package/docs/relay-protocol.md +41 -5
- package/docs/relay-server.md +102 -15
- package/package.json +19 -2
- package/dist/chunk-OZBUPO4K.js.map +0 -1
- package/dist/chunk-QJYRWEXD.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
|
-
|
|
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:
|
|
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.
|
|
149
|
-
this.
|
|
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
|
-
|
|
152
|
-
this.
|
|
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/mcp/types.ts","../src/mcp/tool-host.ts","../src/mcp/server.ts","../src/mcp/transports/in-process.ts","../src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;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,IAAA,IAAA,CAAmB,KAAA,uBAAY,GAAA,EAA4B;AAgB3D;AAAA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AAA,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-
|
|
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-
|
|
3
|
+
import { C as CallToolResult } from '../types-C2DtnHIn.cjs';
|
|
4
4
|
|
|
5
5
|
type ActivityAgent = {
|
|
6
6
|
id: string;
|
package/dist/presence/index.d.ts
CHANGED
|
@@ -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-
|
|
3
|
+
import { C as CallToolResult } from '../types-C2DtnHIn.js';
|
|
4
4
|
|
|
5
5
|
type ActivityAgent = {
|
|
6
6
|
id: string;
|
|
@@ -40,12 +40,34 @@ type Subscriber = {
|
|
|
40
40
|
* of everyone else's tool calls without making one.
|
|
41
41
|
*/
|
|
42
42
|
client?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Present only for a LONG-POLL subscriber, which outlives any one request:
|
|
45
|
+
* it is read by a series of `GET /poll` calls rather than one open stream,
|
|
46
|
+
* so it needs its own liveness record.
|
|
47
|
+
*/
|
|
48
|
+
poll?: {
|
|
49
|
+
/** Last time a poll started or finished (ms since epoch). */
|
|
50
|
+
lastSeen: number;
|
|
51
|
+
/** Polls currently parked on this subscriber. Never pruned while > 0. */
|
|
52
|
+
parked: number;
|
|
53
|
+
/** Wake every parked poll — a frame landed, or the session ended. */
|
|
54
|
+
wakers: Set<() => void>;
|
|
55
|
+
};
|
|
56
|
+
/** Set once the subscriber has been ended (unsubscribed, pruned, or its session is gone). */
|
|
57
|
+
ended?: boolean;
|
|
43
58
|
};
|
|
44
59
|
type RelayBrokerOptions = {
|
|
45
60
|
/** Sessions auto-expire after this many ms of inactivity. Default 4h. */
|
|
46
61
|
ttlMs?: number;
|
|
47
62
|
/** Cleanup tick interval in ms. Default 60 000. */
|
|
48
63
|
reapIntervalMs?: number;
|
|
64
|
+
/**
|
|
65
|
+
* A long-poll subscriber that has not polled for this long is dropped (and,
|
|
66
|
+
* for an outbound one, the page is told the peer left). Checked on the reap
|
|
67
|
+
* tick. Default 60 000 — the PHP relay's window, and comfortably longer than
|
|
68
|
+
* the 25 s maximum park, so a healthy poller is never pruned between polls.
|
|
69
|
+
*/
|
|
70
|
+
pollIdleMs?: number;
|
|
49
71
|
/** Bring-your-own storage layer (redis, etc.). Defaults to in-memory. */
|
|
50
72
|
store?: Store;
|
|
51
73
|
};
|
|
@@ -58,6 +80,7 @@ interface Store {
|
|
|
58
80
|
}
|
|
59
81
|
declare class RelayBroker {
|
|
60
82
|
private readonly ttlMs;
|
|
83
|
+
private readonly pollIdleMs;
|
|
61
84
|
private readonly store;
|
|
62
85
|
/** Per-session, per-direction subscriber list. */
|
|
63
86
|
private subs;
|
|
@@ -125,6 +148,30 @@ declare class RelayBroker {
|
|
|
125
148
|
subscribe(id: string, token: string, direction: Direction, opts?: {
|
|
126
149
|
client?: string;
|
|
127
150
|
}): SubscribeResult;
|
|
151
|
+
/**
|
|
152
|
+
* Attach a LONG-POLL subscriber, or re-attach the one a previous poll created.
|
|
153
|
+
*
|
|
154
|
+
* The CDN-safe receive leg: a series of short requests instead of one open
|
|
155
|
+
* stream, because Cloudflare's HTTP/3 edge resets long-lived SSE. Same
|
|
156
|
+
* contract as the PHP relay in px-ui-sandbox and the one
|
|
157
|
+
* `@particle-academy/fancy-cf-relay` and `mcp-relay-client` speak:
|
|
158
|
+
*
|
|
159
|
+
* - The first poll gets a fresh 16-hex subscriber id; the client echoes it back
|
|
160
|
+
* as `subscriber` on every later poll and reads the same queue.
|
|
161
|
+
* - An id in that shape that this session does not know (pruned, say) is
|
|
162
|
+
* adopted as a NEW subscriber under that id, as the PHP relay does, so a
|
|
163
|
+
* client that went quiet and came back keeps its identity.
|
|
164
|
+
* - An id belonging to a STREAMING subscriber is never adopted: one queue read
|
|
165
|
+
* by two consumers splits its frames between them.
|
|
166
|
+
*
|
|
167
|
+
* Frames queue on the subscriber between polls, so nothing is lost in the gap
|
|
168
|
+
* between one request ending and the next arriving. A poller that stops is
|
|
169
|
+
* pruned after `pollIdleMs`.
|
|
170
|
+
*/
|
|
171
|
+
poll(id: string, token: string, direction: Direction, opts?: {
|
|
172
|
+
subscriber?: string;
|
|
173
|
+
client?: string;
|
|
174
|
+
}): PollResult;
|
|
128
175
|
private getDirSubs;
|
|
129
176
|
/**
|
|
130
177
|
* Record which client asked, keyed by JSON-RPC id.
|
|
@@ -154,6 +201,33 @@ declare class RelayBroker {
|
|
|
154
201
|
/** Deliver to the subscribers of one client only. */
|
|
155
202
|
private fanOutTo;
|
|
156
203
|
private fanOut;
|
|
204
|
+
/**
|
|
205
|
+
* Hand one frame to one subscriber.
|
|
206
|
+
*
|
|
207
|
+
* The resolver is CLEARED before it is called. It used to stay set until the
|
|
208
|
+
* generator resumed on a later microtask, so a second frame in the same tick
|
|
209
|
+
* called an already-settled resolver — a no-op — after shifting its frame out
|
|
210
|
+
* of the queue, and that frame was lost. Cleared first, the second frame just
|
|
211
|
+
* waits in the queue for the generator to come back for it.
|
|
212
|
+
*/
|
|
213
|
+
private deliver;
|
|
214
|
+
/** Tell the page (the inbound side) that an agent arrived or left. */
|
|
215
|
+
private announcePeer;
|
|
216
|
+
/** End one subscriber: close its stream, or release its parked polls. Idempotent. */
|
|
217
|
+
private endSubscriber;
|
|
218
|
+
/**
|
|
219
|
+
* End every subscriber of a session whose session is going away.
|
|
220
|
+
*
|
|
221
|
+
* Streams used to be dropped from the map WITHOUT being woken, so an SSE leg
|
|
222
|
+
* stayed open, heartbeating, for a session that no longer existed — and its
|
|
223
|
+
* client could not learn the page had closed. Ended, the stream closes, the
|
|
224
|
+
* client reconnects, and `events` answers 410.
|
|
225
|
+
*/
|
|
226
|
+
private endSubscribers;
|
|
227
|
+
/** Remove a subscriber from its session, announcing an agent's departure once. */
|
|
228
|
+
private removeSubscriber;
|
|
229
|
+
/** Drop long-poll subscribers that stopped polling. Never one with a poll parked. */
|
|
230
|
+
private prunePollers;
|
|
157
231
|
/**
|
|
158
232
|
* Validate that a peer-supplied payload is a well-formed JSON-RPC 2.0 frame
|
|
159
233
|
* (or batch) before it is fanned out. Previously this was a substring match on
|
|
@@ -168,6 +242,24 @@ declare class RelayBroker {
|
|
|
168
242
|
private isValidFrame;
|
|
169
243
|
private reap;
|
|
170
244
|
}
|
|
245
|
+
type PollResult = {
|
|
246
|
+
ok: false;
|
|
247
|
+
reason: "invalid_token" | "session_gone";
|
|
248
|
+
} | {
|
|
249
|
+
ok: true;
|
|
250
|
+
/** The id the client must echo back as `subscriber` on its next poll. */
|
|
251
|
+
subscriberId: string;
|
|
252
|
+
/** Whether this poll created the subscriber (and, outbound, announced it). */
|
|
253
|
+
created: boolean;
|
|
254
|
+
/**
|
|
255
|
+
* Park up to `ms` for frames, then take everything queued. Returns at once
|
|
256
|
+
* when frames are already waiting, when `ms` is 0, or when the session
|
|
257
|
+
* ends. An aborted `signal` returns `[]` and takes nothing.
|
|
258
|
+
*/
|
|
259
|
+
wait: (ms: number, signal?: AbortSignal) => Promise<string[]>;
|
|
260
|
+
/** Put frames back at the head of the queue — a response that could not be written. */
|
|
261
|
+
requeue: (frames: string[]) => void;
|
|
262
|
+
};
|
|
171
263
|
type SubscribeResult = {
|
|
172
264
|
ok: false;
|
|
173
265
|
reason: string;
|
|
@@ -178,37 +270,27 @@ type SubscribeResult = {
|
|
|
178
270
|
unsubscribe: () => void;
|
|
179
271
|
};
|
|
180
272
|
|
|
181
|
-
/**
|
|
182
|
-
* Node HTTP adapter for {@link RelayBroker}. Returns a single request
|
|
183
|
-
* handler plus per-route handlers, so you can either drop it into
|
|
184
|
-
* `http.createServer(...)` directly or mount the individual handlers
|
|
185
|
-
* onto your existing Node HTTP framework (Express, Hono w/ node-adapter,
|
|
186
|
-
* native http).
|
|
187
|
-
*
|
|
188
|
-
* const relay = createNodeRelay({ pathPrefix: "/mcp-relay" });
|
|
189
|
-
* http.createServer(relay.handler).listen(8787);
|
|
190
|
-
*
|
|
191
|
-
* // Or piecemeal:
|
|
192
|
-
* app.post("/mcp-relay/register", relay.register);
|
|
193
|
-
* app.post("/mcp-relay/:s/inbox", relay.inbox);
|
|
194
|
-
* app.post("/mcp-relay/:s/outbox", relay.outbox);
|
|
195
|
-
* app.get ("/mcp-relay/:s/events", relay.events);
|
|
196
|
-
* app.post("/mcp-relay/:s/unregister", relay.unregister);
|
|
197
|
-
*/
|
|
198
273
|
type NodeRelayOptions = RelayBrokerOptions & {
|
|
199
274
|
/** URL path prefix (without trailing slash). Default `""` — handlers
|
|
200
275
|
* expect paths like `/register`, `/{id}/inbox`, etc. directly. */
|
|
201
276
|
pathPrefix?: string;
|
|
202
|
-
/**
|
|
203
|
-
*
|
|
277
|
+
/**
|
|
278
|
+
* Browser origins allowed to read relay responses: `*`, or a comma-separated
|
|
279
|
+
* list of origins (`"https://example.com,https://www.example.com"`).
|
|
280
|
+
* Default `*` — relays are typically called cross-origin from the demo host.
|
|
281
|
+
*
|
|
282
|
+
* A list is enforced per request: a listed `Origin` is echoed back as
|
|
283
|
+
* `Access-Control-Allow-Origin` with `Vary: Origin`, and an unlisted one
|
|
284
|
+
* gets no allow-origin header at all. `*` mixed into a list, an empty value,
|
|
285
|
+
* `null` or an entry with a path throws here, at construction.
|
|
286
|
+
*/
|
|
204
287
|
corsAllowOrigin?: string;
|
|
205
288
|
/**
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
* session token is the only auth — pair that with a loopback bind.
|
|
289
|
+
* The same allow-list as an array. When non-empty it takes precedence over
|
|
290
|
+
* `corsAllowOrigin`. Recommended for any browser-facing deployment: it blunts
|
|
291
|
+
* DNS rebinding and hostile cross-origin pages reading relay responses. When
|
|
292
|
+
* neither names origins, `*` is used and the session token is the only auth
|
|
293
|
+
* — pair that with a loopback bind.
|
|
212
294
|
*/
|
|
213
295
|
allowedOrigins?: string[];
|
|
214
296
|
};
|
|
@@ -224,8 +306,10 @@ type NodeRelay = {
|
|
|
224
306
|
inbox: NodeHandler;
|
|
225
307
|
outbox: NodeHandler;
|
|
226
308
|
events: NodeHandler;
|
|
309
|
+
/** Long-poll receive leg — the CDN-safe alternative to `events`. */
|
|
310
|
+
poll: NodeHandler;
|
|
227
311
|
unregister: NodeHandler;
|
|
228
312
|
};
|
|
229
313
|
declare function createNodeRelay(opts?: NodeRelayOptions): NodeRelay;
|
|
230
314
|
|
|
231
|
-
export { type Direction, type NodeHandler, type NodeRelay, type NodeRelayOptions, RelayBroker, type RelayBrokerOptions, type Session, type Store, type Subscriber, createNodeRelay };
|
|
315
|
+
export { type Direction, type NodeHandler, type NodeRelay, type NodeRelayOptions, type PollResult, RelayBroker, type RelayBrokerOptions, type Session, type Store, type SubscribeResult, type Subscriber, createNodeRelay };
|
|
@@ -40,12 +40,34 @@ type Subscriber = {
|
|
|
40
40
|
* of everyone else's tool calls without making one.
|
|
41
41
|
*/
|
|
42
42
|
client?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Present only for a LONG-POLL subscriber, which outlives any one request:
|
|
45
|
+
* it is read by a series of `GET /poll` calls rather than one open stream,
|
|
46
|
+
* so it needs its own liveness record.
|
|
47
|
+
*/
|
|
48
|
+
poll?: {
|
|
49
|
+
/** Last time a poll started or finished (ms since epoch). */
|
|
50
|
+
lastSeen: number;
|
|
51
|
+
/** Polls currently parked on this subscriber. Never pruned while > 0. */
|
|
52
|
+
parked: number;
|
|
53
|
+
/** Wake every parked poll — a frame landed, or the session ended. */
|
|
54
|
+
wakers: Set<() => void>;
|
|
55
|
+
};
|
|
56
|
+
/** Set once the subscriber has been ended (unsubscribed, pruned, or its session is gone). */
|
|
57
|
+
ended?: boolean;
|
|
43
58
|
};
|
|
44
59
|
type RelayBrokerOptions = {
|
|
45
60
|
/** Sessions auto-expire after this many ms of inactivity. Default 4h. */
|
|
46
61
|
ttlMs?: number;
|
|
47
62
|
/** Cleanup tick interval in ms. Default 60 000. */
|
|
48
63
|
reapIntervalMs?: number;
|
|
64
|
+
/**
|
|
65
|
+
* A long-poll subscriber that has not polled for this long is dropped (and,
|
|
66
|
+
* for an outbound one, the page is told the peer left). Checked on the reap
|
|
67
|
+
* tick. Default 60 000 — the PHP relay's window, and comfortably longer than
|
|
68
|
+
* the 25 s maximum park, so a healthy poller is never pruned between polls.
|
|
69
|
+
*/
|
|
70
|
+
pollIdleMs?: number;
|
|
49
71
|
/** Bring-your-own storage layer (redis, etc.). Defaults to in-memory. */
|
|
50
72
|
store?: Store;
|
|
51
73
|
};
|
|
@@ -58,6 +80,7 @@ interface Store {
|
|
|
58
80
|
}
|
|
59
81
|
declare class RelayBroker {
|
|
60
82
|
private readonly ttlMs;
|
|
83
|
+
private readonly pollIdleMs;
|
|
61
84
|
private readonly store;
|
|
62
85
|
/** Per-session, per-direction subscriber list. */
|
|
63
86
|
private subs;
|
|
@@ -125,6 +148,30 @@ declare class RelayBroker {
|
|
|
125
148
|
subscribe(id: string, token: string, direction: Direction, opts?: {
|
|
126
149
|
client?: string;
|
|
127
150
|
}): SubscribeResult;
|
|
151
|
+
/**
|
|
152
|
+
* Attach a LONG-POLL subscriber, or re-attach the one a previous poll created.
|
|
153
|
+
*
|
|
154
|
+
* The CDN-safe receive leg: a series of short requests instead of one open
|
|
155
|
+
* stream, because Cloudflare's HTTP/3 edge resets long-lived SSE. Same
|
|
156
|
+
* contract as the PHP relay in px-ui-sandbox and the one
|
|
157
|
+
* `@particle-academy/fancy-cf-relay` and `mcp-relay-client` speak:
|
|
158
|
+
*
|
|
159
|
+
* - The first poll gets a fresh 16-hex subscriber id; the client echoes it back
|
|
160
|
+
* as `subscriber` on every later poll and reads the same queue.
|
|
161
|
+
* - An id in that shape that this session does not know (pruned, say) is
|
|
162
|
+
* adopted as a NEW subscriber under that id, as the PHP relay does, so a
|
|
163
|
+
* client that went quiet and came back keeps its identity.
|
|
164
|
+
* - An id belonging to a STREAMING subscriber is never adopted: one queue read
|
|
165
|
+
* by two consumers splits its frames between them.
|
|
166
|
+
*
|
|
167
|
+
* Frames queue on the subscriber between polls, so nothing is lost in the gap
|
|
168
|
+
* between one request ending and the next arriving. A poller that stops is
|
|
169
|
+
* pruned after `pollIdleMs`.
|
|
170
|
+
*/
|
|
171
|
+
poll(id: string, token: string, direction: Direction, opts?: {
|
|
172
|
+
subscriber?: string;
|
|
173
|
+
client?: string;
|
|
174
|
+
}): PollResult;
|
|
128
175
|
private getDirSubs;
|
|
129
176
|
/**
|
|
130
177
|
* Record which client asked, keyed by JSON-RPC id.
|
|
@@ -154,6 +201,33 @@ declare class RelayBroker {
|
|
|
154
201
|
/** Deliver to the subscribers of one client only. */
|
|
155
202
|
private fanOutTo;
|
|
156
203
|
private fanOut;
|
|
204
|
+
/**
|
|
205
|
+
* Hand one frame to one subscriber.
|
|
206
|
+
*
|
|
207
|
+
* The resolver is CLEARED before it is called. It used to stay set until the
|
|
208
|
+
* generator resumed on a later microtask, so a second frame in the same tick
|
|
209
|
+
* called an already-settled resolver — a no-op — after shifting its frame out
|
|
210
|
+
* of the queue, and that frame was lost. Cleared first, the second frame just
|
|
211
|
+
* waits in the queue for the generator to come back for it.
|
|
212
|
+
*/
|
|
213
|
+
private deliver;
|
|
214
|
+
/** Tell the page (the inbound side) that an agent arrived or left. */
|
|
215
|
+
private announcePeer;
|
|
216
|
+
/** End one subscriber: close its stream, or release its parked polls. Idempotent. */
|
|
217
|
+
private endSubscriber;
|
|
218
|
+
/**
|
|
219
|
+
* End every subscriber of a session whose session is going away.
|
|
220
|
+
*
|
|
221
|
+
* Streams used to be dropped from the map WITHOUT being woken, so an SSE leg
|
|
222
|
+
* stayed open, heartbeating, for a session that no longer existed — and its
|
|
223
|
+
* client could not learn the page had closed. Ended, the stream closes, the
|
|
224
|
+
* client reconnects, and `events` answers 410.
|
|
225
|
+
*/
|
|
226
|
+
private endSubscribers;
|
|
227
|
+
/** Remove a subscriber from its session, announcing an agent's departure once. */
|
|
228
|
+
private removeSubscriber;
|
|
229
|
+
/** Drop long-poll subscribers that stopped polling. Never one with a poll parked. */
|
|
230
|
+
private prunePollers;
|
|
157
231
|
/**
|
|
158
232
|
* Validate that a peer-supplied payload is a well-formed JSON-RPC 2.0 frame
|
|
159
233
|
* (or batch) before it is fanned out. Previously this was a substring match on
|
|
@@ -168,6 +242,24 @@ declare class RelayBroker {
|
|
|
168
242
|
private isValidFrame;
|
|
169
243
|
private reap;
|
|
170
244
|
}
|
|
245
|
+
type PollResult = {
|
|
246
|
+
ok: false;
|
|
247
|
+
reason: "invalid_token" | "session_gone";
|
|
248
|
+
} | {
|
|
249
|
+
ok: true;
|
|
250
|
+
/** The id the client must echo back as `subscriber` on its next poll. */
|
|
251
|
+
subscriberId: string;
|
|
252
|
+
/** Whether this poll created the subscriber (and, outbound, announced it). */
|
|
253
|
+
created: boolean;
|
|
254
|
+
/**
|
|
255
|
+
* Park up to `ms` for frames, then take everything queued. Returns at once
|
|
256
|
+
* when frames are already waiting, when `ms` is 0, or when the session
|
|
257
|
+
* ends. An aborted `signal` returns `[]` and takes nothing.
|
|
258
|
+
*/
|
|
259
|
+
wait: (ms: number, signal?: AbortSignal) => Promise<string[]>;
|
|
260
|
+
/** Put frames back at the head of the queue — a response that could not be written. */
|
|
261
|
+
requeue: (frames: string[]) => void;
|
|
262
|
+
};
|
|
171
263
|
type SubscribeResult = {
|
|
172
264
|
ok: false;
|
|
173
265
|
reason: string;
|
|
@@ -178,37 +270,27 @@ type SubscribeResult = {
|
|
|
178
270
|
unsubscribe: () => void;
|
|
179
271
|
};
|
|
180
272
|
|
|
181
|
-
/**
|
|
182
|
-
* Node HTTP adapter for {@link RelayBroker}. Returns a single request
|
|
183
|
-
* handler plus per-route handlers, so you can either drop it into
|
|
184
|
-
* `http.createServer(...)` directly or mount the individual handlers
|
|
185
|
-
* onto your existing Node HTTP framework (Express, Hono w/ node-adapter,
|
|
186
|
-
* native http).
|
|
187
|
-
*
|
|
188
|
-
* const relay = createNodeRelay({ pathPrefix: "/mcp-relay" });
|
|
189
|
-
* http.createServer(relay.handler).listen(8787);
|
|
190
|
-
*
|
|
191
|
-
* // Or piecemeal:
|
|
192
|
-
* app.post("/mcp-relay/register", relay.register);
|
|
193
|
-
* app.post("/mcp-relay/:s/inbox", relay.inbox);
|
|
194
|
-
* app.post("/mcp-relay/:s/outbox", relay.outbox);
|
|
195
|
-
* app.get ("/mcp-relay/:s/events", relay.events);
|
|
196
|
-
* app.post("/mcp-relay/:s/unregister", relay.unregister);
|
|
197
|
-
*/
|
|
198
273
|
type NodeRelayOptions = RelayBrokerOptions & {
|
|
199
274
|
/** URL path prefix (without trailing slash). Default `""` — handlers
|
|
200
275
|
* expect paths like `/register`, `/{id}/inbox`, etc. directly. */
|
|
201
276
|
pathPrefix?: string;
|
|
202
|
-
/**
|
|
203
|
-
*
|
|
277
|
+
/**
|
|
278
|
+
* Browser origins allowed to read relay responses: `*`, or a comma-separated
|
|
279
|
+
* list of origins (`"https://example.com,https://www.example.com"`).
|
|
280
|
+
* Default `*` — relays are typically called cross-origin from the demo host.
|
|
281
|
+
*
|
|
282
|
+
* A list is enforced per request: a listed `Origin` is echoed back as
|
|
283
|
+
* `Access-Control-Allow-Origin` with `Vary: Origin`, and an unlisted one
|
|
284
|
+
* gets no allow-origin header at all. `*` mixed into a list, an empty value,
|
|
285
|
+
* `null` or an entry with a path throws here, at construction.
|
|
286
|
+
*/
|
|
204
287
|
corsAllowOrigin?: string;
|
|
205
288
|
/**
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
* session token is the only auth — pair that with a loopback bind.
|
|
289
|
+
* The same allow-list as an array. When non-empty it takes precedence over
|
|
290
|
+
* `corsAllowOrigin`. Recommended for any browser-facing deployment: it blunts
|
|
291
|
+
* DNS rebinding and hostile cross-origin pages reading relay responses. When
|
|
292
|
+
* neither names origins, `*` is used and the session token is the only auth
|
|
293
|
+
* — pair that with a loopback bind.
|
|
212
294
|
*/
|
|
213
295
|
allowedOrigins?: string[];
|
|
214
296
|
};
|
|
@@ -224,8 +306,10 @@ type NodeRelay = {
|
|
|
224
306
|
inbox: NodeHandler;
|
|
225
307
|
outbox: NodeHandler;
|
|
226
308
|
events: NodeHandler;
|
|
309
|
+
/** Long-poll receive leg — the CDN-safe alternative to `events`. */
|
|
310
|
+
poll: NodeHandler;
|
|
227
311
|
unregister: NodeHandler;
|
|
228
312
|
};
|
|
229
313
|
declare function createNodeRelay(opts?: NodeRelayOptions): NodeRelay;
|
|
230
314
|
|
|
231
|
-
export { type Direction, type NodeHandler, type NodeRelay, type NodeRelayOptions, RelayBroker, type RelayBrokerOptions, type Session, type Store, type Subscriber, createNodeRelay };
|
|
315
|
+
export { type Direction, type NodeHandler, type NodeRelay, type NodeRelayOptions, type PollResult, RelayBroker, type RelayBrokerOptions, type Session, type Store, type SubscribeResult, type Subscriber, createNodeRelay };
|