@mcpview/compose 0.11.0 → 0.12.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 (59) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +60 -0
  3. package/esm/_dnt.polyfills.d.ts +6 -6
  4. package/esm/_dnt.polyfills.d.ts.map +1 -1
  5. package/esm/src/code-mode/board.d.ts +62 -0
  6. package/esm/src/code-mode/board.d.ts.map +1 -0
  7. package/esm/src/code-mode/board.js +86 -0
  8. package/esm/src/code-mode/chain.d.ts +20 -0
  9. package/esm/src/code-mode/chain.d.ts.map +1 -0
  10. package/esm/src/code-mode/chain.js +240 -0
  11. package/esm/src/code-mode/connections.d.ts +33 -0
  12. package/esm/src/code-mode/connections.d.ts.map +1 -0
  13. package/esm/src/code-mode/connections.js +120 -0
  14. package/esm/src/code-mode/mod.d.ts +8 -0
  15. package/esm/src/code-mode/mod.d.ts.map +1 -0
  16. package/esm/src/code-mode/mod.js +6 -0
  17. package/esm/src/code-mode/provider-tools.d.ts +38 -0
  18. package/esm/src/code-mode/provider-tools.d.ts.map +1 -0
  19. package/esm/src/code-mode/provider-tools.js +113 -0
  20. package/esm/src/code-mode/providers.d.ts +20 -0
  21. package/esm/src/code-mode/providers.d.ts.map +1 -0
  22. package/esm/src/code-mode/providers.js +9 -0
  23. package/esm/src/code-mode/sandbox.d.ts +10 -0
  24. package/esm/src/code-mode/sandbox.d.ts.map +1 -0
  25. package/esm/src/code-mode/sandbox.js +147 -0
  26. package/esm/src/code-mode/tool.d.ts +13 -0
  27. package/esm/src/code-mode/tool.d.ts.map +1 -0
  28. package/esm/src/code-mode/tool.js +54 -0
  29. package/esm/src/version.d.ts +1 -1
  30. package/esm/src/version.js +1 -1
  31. package/package.json +13 -2
  32. package/script/_dnt.polyfills.d.ts +6 -6
  33. package/script/_dnt.polyfills.d.ts.map +1 -1
  34. package/script/src/code-mode/board.d.ts +62 -0
  35. package/script/src/code-mode/board.d.ts.map +1 -0
  36. package/script/src/code-mode/board.js +91 -0
  37. package/script/src/code-mode/chain.d.ts +20 -0
  38. package/script/src/code-mode/chain.d.ts.map +1 -0
  39. package/script/src/code-mode/chain.js +243 -0
  40. package/script/src/code-mode/connections.d.ts +33 -0
  41. package/script/src/code-mode/connections.d.ts.map +1 -0
  42. package/script/src/code-mode/connections.js +123 -0
  43. package/script/src/code-mode/mod.d.ts +8 -0
  44. package/script/src/code-mode/mod.d.ts.map +1 -0
  45. package/script/src/code-mode/mod.js +13 -0
  46. package/script/src/code-mode/provider-tools.d.ts +38 -0
  47. package/script/src/code-mode/provider-tools.d.ts.map +1 -0
  48. package/script/src/code-mode/provider-tools.js +116 -0
  49. package/script/src/code-mode/providers.d.ts +20 -0
  50. package/script/src/code-mode/providers.d.ts.map +1 -0
  51. package/script/src/code-mode/providers.js +13 -0
  52. package/script/src/code-mode/sandbox.d.ts +10 -0
  53. package/script/src/code-mode/sandbox.d.ts.map +1 -0
  54. package/script/src/code-mode/sandbox.js +152 -0
  55. package/script/src/code-mode/tool.d.ts +13 -0
  56. package/script/src/code-mode/tool.d.ts.map +1 -0
  57. package/script/src/code-mode/tool.js +57 -0
  58. package/script/src/version.d.ts +1 -1
  59. package/script/src/version.js +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,17 @@ documented in this file.
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.12.0] - 2026-11-26
9
+
10
+ ### Added
11
+
12
+ - `@mcpview/compose/code-mode` connects approved snippets on independent MCP servers to a single
13
+ `execute` tool. Programs can pass values between providers, select and order their results, and
14
+ save or replay a chain in a caller-scoped catalog.
15
+ - `@mcpview/compose/code-mode/board` turns selected receipts into a Compose descriptor for one
16
+ interactive MCP App. It preserves repeated views as separate panels and reuses the original
17
+ results when rendering.
18
+
8
19
  ## [0.11.0] - 2026-10-24
9
20
 
10
21
  ### Changed
package/README.md CHANGED
@@ -67,6 +67,66 @@ npm i @mcpview/compose
67
67
  import { buildCompositeUi, createCollector, renderComposite } from "@mcpview/compose";
68
68
  ```
69
69
 
70
+ ## Code Mode across MCP servers
71
+
72
+ A chat can call one `execute` tool that runs snippets on several MCP servers. For example, a CAD
73
+ provider generates a plate and returns an STL digest. A slicing provider accepts that digest and
74
+ estimates print time. The script decides which results to show and in what order.
75
+
76
+ ```js
77
+ const plate = await api.runSnippet("cad", "plate-stl", { thicknessMm: api.params.thicknessMm });
78
+ const estimate = await api.runSnippet("slicer", "pla-print-estimate", {
79
+ stlSha256: plate.value.stlSha256,
80
+ });
81
+ await api.panel(estimate.id, "PLA estimate");
82
+ await api.panel(plate.id, "Plate geometry");
83
+ return { seconds: estimate.value.print_time_s };
84
+ ```
85
+
86
+ To offer this workflow, register the upstream connections on the server that owns the board. The
87
+ following code assumes an existing MCPView `app` with a registered MCP App resource at
88
+ `ui://parts/board`.
89
+
90
+ ```ts
91
+ import {
92
+ connectSnippetProviders,
93
+ createSnippetChain,
94
+ createSnippetExecuteTool,
95
+ } from "@mcpview/compose/code-mode";
96
+
97
+ const connections = await connectSnippetProviders([
98
+ { alias: "cad", url: "http://127.0.0.1:3614/mcp", snippets: ["plate-stl"] },
99
+ { alias: "slicer", url: "http://127.0.0.1:3622/mcp", snippets: ["pla-print-estimate"] },
100
+ ]);
101
+ const execute = createSnippetChain(connections.providers);
102
+ app.registerTool(
103
+ createSnippetExecuteTool({ resourceUri: "ui://parts/board", providers: connections.providers }),
104
+ (args, ctx) => execute(args, { signal: ctx?.request?.signal }),
105
+ );
106
+ // On shutdown, await connections.close().
107
+ ```
108
+
109
+ On an upstream MCPView server, `registerSnippetProvider(app, { snippets, authorize })` exposes
110
+ `list_snippets` and `run_snippet`. Each definition supplies its name, description, JSON input schema
111
+ and `run(input, context)` callback for its saved program. The callback returns a native MCP result
112
+ with the script-visible JSON in `structuredContent.value`. Discovery and replay both check the
113
+ configured authorization. A configured URL uses the host's upstream identity. Where users have
114
+ different permissions, bind a client resolver for the authenticated caller.
115
+
116
+ To save complete workflows, pass a catalog from `@mcpview/server/snippets` as the second argument to
117
+ `createSnippetChain`, set `savedChains: true` on the tool declaration and supply a trusted `scope`
118
+ per call. The host derives this scope from the authenticated user and integration. `saveAs` retains
119
+ the program and its parameter types. `replay` runs it with fresh inputs and the caller's current
120
+ provider permissions.
121
+
122
+ In the board's MCP Apps tool-result handler, call `composeSnippetBoard(result, { layout: "split" })`
123
+ from `@mcpview/compose/code-mode/board`. Each selected receipt has its own component ID, including
124
+ two instances of the same viewer. The board renders each child from `child.context.panel.result`.
125
+ For a result with no declared UI resource, supply `resolveView` to select a local renderer. This
126
+ path uses results already returned by the script. The runnable engineering example includes the
127
+ server, both providers, and a single-frame board with a 3D viewer and interactive print report.
128
+ [Engineering example and setup](https://github.com/mcpview/mcpview/tree/main/packages/compose/examples/multi-mcp-snippets)
129
+
70
130
  ## MCP SDK compatibility
71
131
 
72
132
  Compose uses MCP Apps 2.x and the split MCP SDK 2.x packages. Integrations importing SDK types or
@@ -1,9 +1,3 @@
1
- declare global {
2
- interface Error {
3
- cause?: unknown;
4
- }
5
- }
6
- export {};
7
1
  declare global {
8
2
  interface Object {
9
3
  /**
@@ -15,4 +9,10 @@ declare global {
15
9
  }
16
10
  }
17
11
  export {};
12
+ declare global {
13
+ interface Error {
14
+ cause?: unknown;
15
+ }
16
+ }
17
+ export {};
18
18
  //# sourceMappingURL=_dnt.polyfills.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"_dnt.polyfills.d.ts","sourceRoot":"","sources":["../src/_dnt.polyfills.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,KAAK;QACb,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB;CACF;AAED,OAAO,EAAE,CAAC;AAgBV,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd;;;;WAIG;QACH,MAAM,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;KAC5C;CACF;AAED,OAAO,EAAE,CAAC"}
1
+ {"version":3,"file":"_dnt.polyfills.d.ts","sourceRoot":"","sources":["../src/_dnt.polyfills.ts"],"names":[],"mappings":"AAeA,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd;;;;WAIG;QACH,MAAM,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;KAC5C;CACF;AAED,OAAO,EAAE,CAAC;AACV,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,KAAK;QACb,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB;CACF;AAED,OAAO,EAAE,CAAC"}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Browser-side composition of completed Code Mode results.
3
+ * @module
4
+ */
5
+ import "../../_dnt.polyfills.js";
6
+ import type { ComponentSurface } from "../core/types/components.js";
7
+ import type { CompositeUiDescriptor } from "../core/types/descriptor.js";
8
+ import type { UiLayout } from "../core/types/layout.js";
9
+ /** MCP App result metadata containing the receipts selected by the program. */
10
+ export declare const SNIPPET_PANELS_META_KEY = "io.mcpview/snippet-panels";
11
+ /** A selected provider result. The receipt ID distinguishes calls to the same snippet. */
12
+ export interface SnippetPanel {
13
+ readonly id: string;
14
+ readonly provider: string;
15
+ readonly name: string;
16
+ readonly title: string;
17
+ readonly result: Record<string, unknown>;
18
+ }
19
+ /** An App-owned view for a receipt, with optional renderer data and component selection. */
20
+ export interface SnippetPanelView {
21
+ readonly resourceUri: string;
22
+ readonly context?: Record<string, unknown>;
23
+ readonly surface?: ComponentSurface;
24
+ }
25
+ /** Display options supplied by the board hosting the results. */
26
+ export interface SnippetBoardOptions {
27
+ /** A Compose layout or a function of the number of mounted panels. Defaults to stack. */
28
+ readonly layout?: UiLayout | ((count: number) => UiLayout);
29
+ /** Provide a local view adapter or return undefined to use the result's native MCP App URI. */
30
+ readonly resolveView?: (panel: SnippetPanel) => SnippetPanelView | undefined;
31
+ }
32
+ /**
33
+ * Return selected receipts in display order from the App-only MCP result metadata.
34
+ * Invalid entries and repeated receipt IDs are ignored. Distinct receipts can
35
+ * point to the same snippet and viewer.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * for (const panel of readSnippetPanels(toolResult)) {
40
+ * console.log(panel.provider, panel.name, panel.title);
41
+ * }
42
+ * ```
43
+ */
44
+ export declare function readSnippetPanels(result: unknown): SnippetPanel[];
45
+ /**
46
+ * Build a Compose descriptor from the current execution, without making any provider calls.
47
+ * Each child keeps its receipt in `context.panel` and adapter data in `context.view`.
48
+ * The returned summary is shared as `sharedContext.value` when the execution has a value.
49
+ * A data-only receipt needs a local view adapter to produce a child.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const board = composeSnippetBoard(toolResult, {
54
+ * layout: "split",
55
+ * resolveView: (panel) => panel.provider === "metrics"
56
+ * ? { resourceUri: "ui://my-board/metrics" }
57
+ * : undefined,
58
+ * });
59
+ * ```
60
+ */
61
+ export declare function composeSnippetBoard(result: unknown, options?: SnippetBoardOptions): CompositeUiDescriptor;
62
+ //# sourceMappingURL=board.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"board.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/board.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,yBAAyB,CAAC;AAMjC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACzE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAExD,+EAA+E;AAC/E,eAAO,MAAM,uBAAuB,8BAA8B,CAAC;AAEnE,0FAA0F;AAC1F,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C;AAED,4FAA4F;AAC5F,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC3C,QAAQ,CAAC,OAAO,CAAC,EAAE,gBAAgB,CAAC;CACrC;AAED,iEAAiE;AACjE,MAAM,WAAW,mBAAmB;IAClC,yFAAyF;IACzF,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,QAAQ,CAAC,CAAC;IAC3D,+FAA+F;IAC/F,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,gBAAgB,GAAG,SAAS,CAAC;CAC9E;AAcD;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,OAAO,GAAG,YAAY,EAAE,CAajE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,OAAO,EACf,OAAO,GAAE,mBAAwB,GAChC,qBAAqB,CAyBvB"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Browser-side composition of completed Code Mode results.
3
+ * @module
4
+ */
5
+ import "../../_dnt.polyfills.js";
6
+ import { createCollector } from "../core/collector/collector.js";
7
+ import { extractUiMeta } from "../core/collector/extractor.js";
8
+ import { buildCompositeUi } from "../core/composer/composer.js";
9
+ /** MCP App result metadata containing the receipts selected by the program. */
10
+ export const SNIPPET_PANELS_META_KEY = "io.mcpview/snippet-panels";
11
+ function record(value) {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+ function isPanel(value) {
15
+ return record(value) &&
16
+ typeof value.id === "string" && value.id.length > 0 &&
17
+ typeof value.provider === "string" && value.provider.length > 0 &&
18
+ typeof value.name === "string" && value.name.length > 0 &&
19
+ typeof value.title === "string" && record(value.result);
20
+ }
21
+ /**
22
+ * Return selected receipts in display order from the App-only MCP result metadata.
23
+ * Invalid entries and repeated receipt IDs are ignored. Distinct receipts can
24
+ * point to the same snippet and viewer.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * for (const panel of readSnippetPanels(toolResult)) {
29
+ * console.log(panel.provider, panel.name, panel.title);
30
+ * }
31
+ * ```
32
+ */
33
+ export function readSnippetPanels(result) {
34
+ if (!record(result) || !record(result._meta))
35
+ return [];
36
+ const items = result._meta[SNIPPET_PANELS_META_KEY];
37
+ if (!Array.isArray(items))
38
+ return [];
39
+ const seen = new Set();
40
+ const panels = [];
41
+ for (const item of items) {
42
+ if (isPanel(item) && !seen.has(item.id)) {
43
+ panels.push(item);
44
+ seen.add(item.id);
45
+ }
46
+ }
47
+ return panels;
48
+ }
49
+ /**
50
+ * Build a Compose descriptor from the current execution, without making any provider calls.
51
+ * Each child keeps its receipt in `context.panel` and adapter data in `context.view`.
52
+ * The returned summary is shared as `sharedContext.value` when the execution has a value.
53
+ * A data-only receipt needs a local view adapter to produce a child.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const board = composeSnippetBoard(toolResult, {
58
+ * layout: "split",
59
+ * resolveView: (panel) => panel.provider === "metrics"
60
+ * ? { resourceUri: "ui://my-board/metrics" }
61
+ * : undefined,
62
+ * });
63
+ * ```
64
+ */
65
+ export function composeSnippetBoard(result, options = {}) {
66
+ const summary = record(result) && record(result.structuredContent)
67
+ ? result.structuredContent
68
+ : {};
69
+ const collector = createCollector();
70
+ for (const panel of readSnippetPanels(result)) {
71
+ const view = options.resolveView?.(panel);
72
+ const resourceUri = view?.resourceUri ?? extractUiMeta(panel.result)?.resourceUri;
73
+ if (!resourceUri || !/^ui:\/\/[^\s]+$/.test(resourceUri))
74
+ continue;
75
+ collector.collect(`${panel.provider}:${panel.name}`, { _meta: { ui: { resourceUri } } }, {
76
+ panel,
77
+ ...(view?.context === undefined ? {} : { view: view.context }),
78
+ ...(Object.hasOwn(summary, "value") ? { value: summary.value } : {}),
79
+ }, { componentId: panel.id, surface: view?.surface });
80
+ }
81
+ const resources = collector.getResources();
82
+ const layout = typeof options.layout === "function"
83
+ ? options.layout(resources.length)
84
+ : options.layout;
85
+ return buildCompositeUi(resources, { layout: layout ?? "stack", sharedContext: ["value"] });
86
+ }
@@ -0,0 +1,20 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/client";
2
+ import type { SnippetCatalog } from "@mcpview/server/snippets";
3
+ import { type SnippetChainContext, type SnippetProvider } from "./providers.js";
4
+ /** Selected native result, available only to the MCP App in result metadata. */
5
+ export interface SnippetPanelReceipt {
6
+ id: string;
7
+ provider: string;
8
+ name: string;
9
+ title: string;
10
+ result: CallToolResult;
11
+ }
12
+ /** Execute input from the MCP tool using trusted context supplied separately by the host. */
13
+ export type SnippetChainExecutor = (input: Record<string, unknown>, context?: SnippetChainContext) => Promise<CallToolResult>;
14
+ /**
15
+ * Run JavaScript against host-configured snippet providers. Selected results stay
16
+ * out of guest memory except for their declared JSON value. Supplying a catalog
17
+ * enables named chains for calls with a trusted scope.
18
+ */
19
+ export declare function createSnippetChain(providers: ReadonlyMap<string, SnippetProvider>, catalog?: SnippetCatalog): SnippetChainExecutor;
20
+ //# sourceMappingURL=chain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chain.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/chain.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,cAAc,EAAqB,MAAM,0BAA0B,CAAC;AAElF,OAAO,EAAiB,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAI/F,gFAAgF;AAChF,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,cAAc,CAAC;CACxB;AAqED,6FAA6F;AAC7F,MAAM,MAAM,oBAAoB,GAAG,CACjC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,OAAO,CAAC,EAAE,mBAAmB,KAC1B,OAAO,CAAC,cAAc,CAAC,CAAC;AAE7B;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,EAC/C,OAAO,CAAC,EAAE,cAAc,GACvB,oBAAoB,CAyMtB"}
@@ -0,0 +1,240 @@
1
+ import { SNIPPET_PANELS_META_KEY } from "./board.js";
2
+ import { isSnippetName } from "./providers.js";
3
+ import { encodeValue, runProgram } from "./sandbox.js";
4
+ const maxNativeSize = 4 * 1024 * 1024;
5
+ const maxNativeBytes = 6 * 1024 * 1024;
6
+ const maxSavedChains = 64;
7
+ const afterDispatch = "One or more upstream operations may have completed. Check their effects before replaying the chain.";
8
+ function isRecord(value) {
9
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10
+ }
11
+ const providerErrors = new Map([
12
+ ["INVALID_INPUT", "Check the snippet input against its declared schema."],
13
+ ["ARTIFACT_UNAVAILABLE", "The input artifact is unavailable. Regenerate it before retrying."],
14
+ ["PROFILE_INVALID", "The configured provider profile is invalid or unavailable."],
15
+ ["UPSTREAM_ERROR", "The upstream operation failed."],
16
+ ["TIMEOUT", "The upstream operation timed out."],
17
+ ]);
18
+ function providerError(result) {
19
+ const data = result.structuredContent;
20
+ const error = isRecord(data) ? data.error : undefined;
21
+ const code = isRecord(error) ? error.code : undefined;
22
+ return (typeof code === "string" ? providerErrors.get(code) : undefined) ??
23
+ "The provider reported an execution error.";
24
+ }
25
+ function validateParams(input, shape) {
26
+ if (!isRecord(input))
27
+ throw new Error("Supply params as a JSON object.");
28
+ encodeValue(input, 8192);
29
+ if (shape) {
30
+ const keys = Object.keys(input);
31
+ if (keys.length !== Object.keys(shape).length ||
32
+ keys.some((key) => {
33
+ const value = input[key];
34
+ const kind = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
35
+ return !Object.hasOwn(shape, key) || shape[key] !== kind;
36
+ })) {
37
+ throw new Error("Replay parameters must match the saved key names and JSON types.");
38
+ }
39
+ }
40
+ return input;
41
+ }
42
+ function output(value, panels = [], saved) {
43
+ const visible = {
44
+ value,
45
+ panels: panels.map(({ result: _result, ...panel }) => panel),
46
+ ...(saved === undefined ? {} : { saved }),
47
+ };
48
+ return {
49
+ content: [{ type: "text", text: JSON.stringify(visible) }],
50
+ structuredContent: visible,
51
+ _meta: { [SNIPPET_PANELS_META_KEY]: panels },
52
+ };
53
+ }
54
+ /**
55
+ * Run JavaScript against host-configured snippet providers. Selected results stay
56
+ * out of guest memory except for their declared JSON value. Supplying a catalog
57
+ * enables named chains for calls with a trusted scope.
58
+ */
59
+ export function createSnippetChain(providers, catalog) {
60
+ // Keep admission state only while saves overlap. Persistent catalogs are read again
61
+ // on the next save so a completed tenant leaves no resident quota state here.
62
+ const activeSaves = new Map();
63
+ async function execute(code, params, context, status) {
64
+ const receipts = new Map();
65
+ const selected = new Map();
66
+ let totalBytes = 0;
67
+ const value = await runProgram(code, params, async (operation, args, signal) => {
68
+ signal.throwIfAborted();
69
+ const [first, second, input] = args;
70
+ if (operation === "panel") {
71
+ const panel = typeof first === "string" ? receipts.get(first) : undefined;
72
+ if (!panel || args.length > 2)
73
+ throw new Error("Select a receipt from this execution.");
74
+ if (second !== undefined && (typeof second !== "string" || second.length > 120)) {
75
+ throw new Error("Panel titles may contain at most 120 characters.");
76
+ }
77
+ selected.set(panel.id, { ...panel, title: second ?? panel.title });
78
+ return null;
79
+ }
80
+ const provider = typeof first === "string" ? providers.get(first) : undefined;
81
+ if (!provider)
82
+ throw new Error("Unknown snippet provider.");
83
+ if (operation === "listSnippets" && args.length === 1) {
84
+ const catalog = await provider.call("list_snippets", {}, signal, context);
85
+ signal.throwIfAborted();
86
+ const snippets = isRecord(catalog.structuredContent)
87
+ ? catalog.structuredContent.snippets
88
+ : undefined;
89
+ if (catalog.isError || !Array.isArray(snippets)) {
90
+ throw new Error("Provider snippet catalog is unavailable.");
91
+ }
92
+ return snippets.filter((item) => isRecord(item) && typeof item.name === "string" && provider.names.includes(item.name)).map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
93
+ }
94
+ if (operation !== "runSnippet" || args.length !== 3 || typeof second !== "string" ||
95
+ !provider.names.includes(second) || !isRecord(input)) {
96
+ throw new Error("Choose an approved named snippet and supply its input object.");
97
+ }
98
+ status.dispatched = true;
99
+ status.diagnostic = undefined;
100
+ const result = await provider.call("run_snippet", { name: second, input }, signal, context);
101
+ signal.throwIfAborted();
102
+ if (result.isError) {
103
+ status.diagnostic = `Snippet ${second}: ${providerError(result)}`;
104
+ throw new Error(status.diagnostic);
105
+ }
106
+ if (!isRecord(result.structuredContent) || !Object.hasOwn(result.structuredContent, "value")) {
107
+ status.diagnostic = `Snippet ${second} returned an invalid result.`;
108
+ throw new Error(status.diagnostic);
109
+ }
110
+ const value = result.structuredContent.value;
111
+ encodeValue(value);
112
+ totalBytes += new TextEncoder().encode(encodeValue(result, maxNativeSize)).byteLength;
113
+ if (totalBytes > maxNativeBytes) {
114
+ throw new Error("Native snippet receipts exceed the board size limit.");
115
+ }
116
+ const id = crypto.randomUUID();
117
+ receipts.set(id, { id, provider: first, name: second, title: second, result });
118
+ return { id, value };
119
+ }, context.signal);
120
+ return { value, panels: [...selected.values()] };
121
+ }
122
+ async function call(input, context, status) {
123
+ const { signal, scope } = context;
124
+ signal?.throwIfAborted();
125
+ if (!isRecord(input))
126
+ throw new Error("Supply execute inputs as a JSON object.");
127
+ const has = (key) => Object.hasOwn(input, key);
128
+ const keysAllowed = (...keys) => Object.keys(input).every((key) => keys.includes(key));
129
+ if (has("code") && !has("saveAs") && keysAllowed("code", "params")) {
130
+ if (typeof input.code !== "string")
131
+ throw new Error("Supply a JavaScript function body.");
132
+ const result = await execute(input.code, validateParams(input.params === undefined ? {} : input.params), context, status);
133
+ signal?.throwIfAborted();
134
+ return output(result.value, result.panels);
135
+ }
136
+ if (!catalog || typeof scope !== "string" || !scope.trim()) {
137
+ throw new Error("Saved chains require a configured catalog and a trusted scope.");
138
+ }
139
+ if (input.listSaved === true && keysAllowed("listSaved")) {
140
+ const snippets = await catalog.list(scope);
141
+ signal?.throwIfAborted();
142
+ return output({ snippets });
143
+ }
144
+ if (isSnippetName(input.replay) && keysAllowed("replay", "params")) {
145
+ const result = await catalog.run(scope, input.replay, input.params === undefined ? {} : input.params, {
146
+ validate: validateParams,
147
+ execute: (code, params) => execute(code, params, context, status),
148
+ });
149
+ signal?.throwIfAborted();
150
+ return output(result.value, result.panels);
151
+ }
152
+ if (typeof input.code !== "string" || !has("saveAs") || !keysAllowed("code", "saveAs", "params")) {
153
+ throw new Error("Supply code, replay, or listSaved.");
154
+ }
155
+ const name = input.saveAs;
156
+ if (!isSnippetName(name)) {
157
+ throw new Error("Supply a nonempty saved chain name of up to 256 UTF-8 bytes without surrounding whitespace.");
158
+ }
159
+ const params = validateParams(input.params === undefined ? {} : input.params);
160
+ const keys = Object.keys(params);
161
+ if (keys.length > 32 || keys.some((key) => new TextEncoder().encode(key).byteLength > 128)) {
162
+ throw new Error("Saved chain parameter contract exceeds its size limit.");
163
+ }
164
+ let usage = activeSaves.get(scope);
165
+ if (!usage) {
166
+ usage = {
167
+ users: 0,
168
+ stored: catalog.list(scope).then((entries) => new Set(entries.map((entry) => entry.name))),
169
+ saving: new Set(),
170
+ };
171
+ activeSaves.set(scope, usage);
172
+ }
173
+ usage.users++;
174
+ let reserved = false;
175
+ try {
176
+ const savedNames = await usage.stored;
177
+ signal?.throwIfAborted();
178
+ if (usage.saving.has(name))
179
+ throw new Error("A save for this chain is already in progress.");
180
+ if (!savedNames.has(name)) {
181
+ if (savedNames.size >= maxSavedChains)
182
+ throw new Error("The saved chain catalog is full.");
183
+ savedNames.add(name);
184
+ reserved = true;
185
+ }
186
+ // Serialize writes to this name within an executor, without blocking other names.
187
+ usage.saving.add(name);
188
+ try {
189
+ if (!reserved) {
190
+ const previous = await catalog.inspect(scope, name);
191
+ if (previous.code !== input.code)
192
+ throw new Error("Snippet name already in use.");
193
+ validateParams(params, previous.parameters);
194
+ }
195
+ signal?.throwIfAborted();
196
+ const result = await execute(input.code, params, context, status);
197
+ signal?.throwIfAborted();
198
+ status.saving = true;
199
+ const ref = catalog.recordSuccess(scope, input.code, params);
200
+ const saved = await catalog.save(scope, ref, name);
201
+ reserved = false;
202
+ return output(result.value, result.panels, saved.name);
203
+ }
204
+ finally {
205
+ usage.saving.delete(name);
206
+ if (reserved)
207
+ savedNames.delete(name);
208
+ }
209
+ }
210
+ finally {
211
+ if (--usage.users === 0)
212
+ activeSaves.delete(scope);
213
+ }
214
+ }
215
+ return async (input, context = {}) => {
216
+ const status = { dispatched: false, saving: false };
217
+ try {
218
+ return await call(input, context, status);
219
+ }
220
+ catch (error) {
221
+ if (!status.dispatched)
222
+ throw error;
223
+ if (context.signal?.aborted) {
224
+ const reason = context.signal.reason;
225
+ const name = reason instanceof DOMException && reason.name === "TimeoutError"
226
+ ? "TimeoutError"
227
+ : "AbortError";
228
+ throw new DOMException(`Chain interrupted. ${afterDispatch}`, name);
229
+ }
230
+ // Preserve only diagnostics derived from known provider codes. A transport,
231
+ // guest or storage exception may contain credentials, paths or native data.
232
+ const message = status.saving
233
+ ? "Failed to confirm that the chain was saved."
234
+ : status.diagnostic && error instanceof Error && error.message === status.diagnostic
235
+ ? status.diagnostic
236
+ : "Chain execution failed.";
237
+ throw new Error(`${message} ${afterDispatch}`);
238
+ }
239
+ };
240
+ }
@@ -0,0 +1,33 @@
1
+ import { Client } from "@modelcontextprotocol/client";
2
+ import { type SnippetChainContext, type SnippetProvider } from "./providers.js";
3
+ /** The MCP operation used by a snippet binding. The host retains ownership of supplied clients. */
4
+ export type SnippetMcpClient = Pick<Client, "callTool">;
5
+ /** Use an explicit HTTP endpoint or a client already authorized by the host. */
6
+ export type SnippetProviderBinding = {
7
+ readonly alias: string;
8
+ readonly snippets: readonly string[];
9
+ } & ({
10
+ readonly url: URL | string;
11
+ readonly requestInit?: RequestInit;
12
+ readonly client?: never;
13
+ } | {
14
+ /** A resolver can select a borrowed client using the trusted request scope. */
15
+ readonly client: SnippetMcpClient | ((context: SnippetChainContext) => SnippetMcpClient | Promise<SnippetMcpClient>);
16
+ readonly url?: never;
17
+ readonly requestInit?: never;
18
+ });
19
+ /** Connections available to a snippet chain. Close once the containing MCP server is stopped. */
20
+ export interface SnippetProviderConnections {
21
+ readonly providers: ReadonlyMap<string, SnippetProvider>;
22
+ close(): Promise<void>;
23
+ }
24
+ /**
25
+ * Connect the explicitly configured upstream MCPs. HTTP bindings share one host-owned
26
+ * upstream identity for the lifetime of this pool. For different authorities in a
27
+ * multi-user server, supply a client resolver keyed by the authenticated request context.
28
+ * A partial startup closes every connection opened by the pool.
29
+ */
30
+ export declare function connectSnippetProviders(bindings: readonly SnippetProviderBinding[], options?: {
31
+ readonly signal?: AbortSignal;
32
+ }): Promise<SnippetProviderConnections>;
33
+ //# sourceMappingURL=connections.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connections.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/connections.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiC,MAAM,8BAA8B,CAAC;AACrF,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACrB,MAAM,gBAAgB,CAAC;AAExB,mGAAmG;AACnG,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAExD,gFAAgF;AAChF,MAAM,MAAM,sBAAsB,GAC9B;IACA,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC,GACC,CAAC;IACD,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAAC;IAC3B,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC;IACnC,QAAQ,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC;CACzB,GAAG;IACF,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EACX,gBAAgB,GAChB,CAAC,CAAC,OAAO,EAAE,mBAAmB,KAAK,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC;IACrF,QAAQ,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC;CAC9B,CAAC,CAAC;AAEL,iGAAiG;AACjG,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACzD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,SAAS,sBAAsB,EAAE,EAC3C,OAAO,GAAE;IAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAO,GAC9C,OAAO,CAAC,0BAA0B,CAAC,CAiHrC"}