@mcpview/compose 0.11.0 → 0.13.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 (143) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +87 -1
  3. package/esm/_dnt.polyfills.d.ts +51 -2
  4. package/esm/_dnt.polyfills.d.ts.map +1 -1
  5. package/esm/_dnt.polyfills.js +36 -0
  6. package/esm/src/code-mode/board.d.ts +66 -0
  7. package/esm/src/code-mode/board.d.ts.map +1 -0
  8. package/esm/src/code-mode/board.js +88 -0
  9. package/esm/src/code-mode/chain.d.ts +20 -0
  10. package/esm/src/code-mode/chain.d.ts.map +1 -0
  11. package/esm/src/code-mode/chain.js +240 -0
  12. package/esm/src/code-mode/connections.d.ts +33 -0
  13. package/esm/src/code-mode/connections.d.ts.map +1 -0
  14. package/esm/src/code-mode/connections.js +120 -0
  15. package/esm/src/code-mode/mod.d.ts +8 -0
  16. package/esm/src/code-mode/mod.d.ts.map +1 -0
  17. package/esm/src/code-mode/mod.js +6 -0
  18. package/esm/src/code-mode/provider-tools.d.ts +38 -0
  19. package/esm/src/code-mode/provider-tools.d.ts.map +1 -0
  20. package/esm/src/code-mode/provider-tools.js +113 -0
  21. package/esm/src/code-mode/providers.d.ts +20 -0
  22. package/esm/src/code-mode/providers.d.ts.map +1 -0
  23. package/esm/src/code-mode/providers.js +9 -0
  24. package/esm/src/code-mode/sandbox.d.ts +10 -0
  25. package/esm/src/code-mode/sandbox.d.ts.map +1 -0
  26. package/esm/src/code-mode/sandbox.js +147 -0
  27. package/esm/src/code-mode/tool.d.ts +13 -0
  28. package/esm/src/code-mode/tool.d.ts.map +1 -0
  29. package/esm/src/code-mode/tool.js +54 -0
  30. package/esm/src/core/collector/collector.d.ts +2 -1
  31. package/esm/src/core/collector/collector.d.ts.map +1 -1
  32. package/esm/src/core/collector/collector.js +6 -0
  33. package/esm/src/core/types/resources.d.ts +4 -0
  34. package/esm/src/core/types/resources.d.ts.map +1 -1
  35. package/esm/src/core/types/resources.js +10 -1
  36. package/esm/src/host/renderer/css/base.d.ts.map +1 -1
  37. package/esm/src/host/renderer/css/base.js +3 -0
  38. package/esm/src/host/renderer/css/layouts.d.ts.map +1 -1
  39. package/esm/src/host/renderer/css/layouts.js +17 -14
  40. package/esm/src/host/renderer/css/panel-controls.d.ts +3 -0
  41. package/esm/src/host/renderer/css/panel-controls.d.ts.map +1 -0
  42. package/esm/src/host/renderer/css/panel-controls.js +89 -0
  43. package/esm/src/host/renderer/html-generator.d.ts.map +1 -1
  44. package/esm/src/host/renderer/html-generator.js +38 -42
  45. package/esm/src/host/renderer/js/card-height.d.ts +3 -0
  46. package/esm/src/host/renderer/js/card-height.d.ts.map +1 -0
  47. package/esm/src/host/renderer/js/card-height.js +58 -0
  48. package/esm/src/host/renderer/js/event-bus.d.ts.map +1 -1
  49. package/esm/src/host/renderer/js/event-bus.js +32 -12
  50. package/esm/src/host/renderer/panel-controls.d.ts +23 -0
  51. package/esm/src/host/renderer/panel-controls.d.ts.map +1 -0
  52. package/esm/src/host/renderer/panel-controls.js +5 -0
  53. package/esm/src/host/renderer/panel-movement.d.ts +8 -0
  54. package/esm/src/host/renderer/panel-movement.d.ts.map +1 -0
  55. package/esm/src/host/renderer/panel-movement.js +392 -0
  56. package/esm/src/host/renderer/panel-reflow.d.ts +17 -0
  57. package/esm/src/host/renderer/panel-reflow.d.ts.map +1 -0
  58. package/esm/src/host/renderer/panel-reflow.js +342 -0
  59. package/esm/src/host/renderer/panel-resizing.d.ts +11 -0
  60. package/esm/src/host/renderer/panel-resizing.d.ts.map +1 -0
  61. package/esm/src/host/renderer/panel-resizing.js +347 -0
  62. package/esm/src/runtime/compose.d.ts.map +1 -1
  63. package/esm/src/runtime/compose.js +3 -0
  64. package/esm/src/runtime/manifest.d.ts.map +1 -1
  65. package/esm/src/runtime/manifest.js +4 -0
  66. package/esm/src/runtime/types.d.ts +2 -0
  67. package/esm/src/runtime/types.d.ts.map +1 -1
  68. package/esm/src/sdk/mcp-sdk.d.ts +2 -1
  69. package/esm/src/sdk/mcp-sdk.d.ts.map +1 -1
  70. package/esm/src/sdk/mcp-sdk.js +2 -2
  71. package/esm/src/version.d.ts +1 -1
  72. package/esm/src/version.js +1 -1
  73. package/package.json +13 -2
  74. package/script/_dnt.polyfills.d.ts +51 -2
  75. package/script/_dnt.polyfills.d.ts.map +1 -1
  76. package/script/_dnt.polyfills.js +36 -0
  77. package/script/src/code-mode/board.d.ts +66 -0
  78. package/script/src/code-mode/board.d.ts.map +1 -0
  79. package/script/src/code-mode/board.js +96 -0
  80. package/script/src/code-mode/chain.d.ts +20 -0
  81. package/script/src/code-mode/chain.d.ts.map +1 -0
  82. package/script/src/code-mode/chain.js +243 -0
  83. package/script/src/code-mode/connections.d.ts +33 -0
  84. package/script/src/code-mode/connections.d.ts.map +1 -0
  85. package/script/src/code-mode/connections.js +123 -0
  86. package/script/src/code-mode/mod.d.ts +8 -0
  87. package/script/src/code-mode/mod.d.ts.map +1 -0
  88. package/script/src/code-mode/mod.js +13 -0
  89. package/script/src/code-mode/provider-tools.d.ts +38 -0
  90. package/script/src/code-mode/provider-tools.d.ts.map +1 -0
  91. package/script/src/code-mode/provider-tools.js +116 -0
  92. package/script/src/code-mode/providers.d.ts +20 -0
  93. package/script/src/code-mode/providers.d.ts.map +1 -0
  94. package/script/src/code-mode/providers.js +13 -0
  95. package/script/src/code-mode/sandbox.d.ts +10 -0
  96. package/script/src/code-mode/sandbox.d.ts.map +1 -0
  97. package/script/src/code-mode/sandbox.js +152 -0
  98. package/script/src/code-mode/tool.d.ts +13 -0
  99. package/script/src/code-mode/tool.d.ts.map +1 -0
  100. package/script/src/code-mode/tool.js +57 -0
  101. package/script/src/core/collector/collector.d.ts +2 -1
  102. package/script/src/core/collector/collector.d.ts.map +1 -1
  103. package/script/src/core/collector/collector.js +6 -0
  104. package/script/src/core/types/resources.d.ts +4 -0
  105. package/script/src/core/types/resources.d.ts.map +1 -1
  106. package/script/src/core/types/resources.js +11 -0
  107. package/script/src/host/renderer/css/base.d.ts.map +1 -1
  108. package/script/src/host/renderer/css/base.js +3 -0
  109. package/script/src/host/renderer/css/layouts.d.ts.map +1 -1
  110. package/script/src/host/renderer/css/layouts.js +17 -14
  111. package/script/src/host/renderer/css/panel-controls.d.ts +3 -0
  112. package/script/src/host/renderer/css/panel-controls.d.ts.map +1 -0
  113. package/script/src/host/renderer/css/panel-controls.js +92 -0
  114. package/script/src/host/renderer/html-generator.d.ts.map +1 -1
  115. package/script/src/host/renderer/html-generator.js +38 -42
  116. package/script/src/host/renderer/js/card-height.d.ts +3 -0
  117. package/script/src/host/renderer/js/card-height.d.ts.map +1 -0
  118. package/script/src/host/renderer/js/card-height.js +61 -0
  119. package/script/src/host/renderer/js/event-bus.d.ts.map +1 -1
  120. package/script/src/host/renderer/js/event-bus.js +32 -12
  121. package/script/src/host/renderer/panel-controls.d.ts +23 -0
  122. package/script/src/host/renderer/panel-controls.d.ts.map +1 -0
  123. package/script/src/host/renderer/panel-controls.js +11 -0
  124. package/script/src/host/renderer/panel-movement.d.ts +8 -0
  125. package/script/src/host/renderer/panel-movement.d.ts.map +1 -0
  126. package/script/src/host/renderer/panel-movement.js +395 -0
  127. package/script/src/host/renderer/panel-reflow.d.ts +17 -0
  128. package/script/src/host/renderer/panel-reflow.d.ts.map +1 -0
  129. package/script/src/host/renderer/panel-reflow.js +345 -0
  130. package/script/src/host/renderer/panel-resizing.d.ts +11 -0
  131. package/script/src/host/renderer/panel-resizing.d.ts.map +1 -0
  132. package/script/src/host/renderer/panel-resizing.js +350 -0
  133. package/script/src/runtime/compose.d.ts.map +1 -1
  134. package/script/src/runtime/compose.js +3 -0
  135. package/script/src/runtime/manifest.d.ts.map +1 -1
  136. package/script/src/runtime/manifest.js +4 -0
  137. package/script/src/runtime/types.d.ts +2 -0
  138. package/script/src/runtime/types.d.ts.map +1 -1
  139. package/script/src/sdk/mcp-sdk.d.ts +2 -1
  140. package/script/src/sdk/mcp-sdk.d.ts.map +1 -1
  141. package/script/src/sdk/mcp-sdk.js +2 -2
  142. package/script/src/version.d.ts +1 -1
  143. package/script/src/version.js +1 -1
@@ -0,0 +1,66 @@
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
+ export { getPanelControlsCss } from "../host/renderer/css/panel-controls.js";
10
+ export { installPanelMovement, installPanelResizing } from "../host/renderer/panel-controls.js";
11
+ /** MCP App result metadata containing the receipts selected by the program. */
12
+ export declare const SNIPPET_PANELS_META_KEY = "io.mcpview/snippet-panels";
13
+ /** A selected provider result. The receipt ID distinguishes calls to the same snippet. */
14
+ export interface SnippetPanel {
15
+ readonly id: string;
16
+ readonly provider: string;
17
+ readonly name: string;
18
+ readonly title: string;
19
+ readonly result: Record<string, unknown>;
20
+ }
21
+ /** An App-owned view for a receipt, with optional renderer data and component selection. */
22
+ export interface SnippetPanelView {
23
+ readonly resourceUri: string;
24
+ readonly context?: Record<string, unknown>;
25
+ readonly surface?: ComponentSurface;
26
+ /** Widths offered by this local view in CSS pixels. An empty list disables resizing. */
27
+ readonly supportedWidths?: readonly number[];
28
+ }
29
+ /** Display options supplied by the board hosting the results. */
30
+ export interface SnippetBoardOptions {
31
+ /** A Compose layout or a function of the number of mounted panels. Defaults to stack. */
32
+ readonly layout?: UiLayout | ((count: number) => UiLayout);
33
+ /** Provide a local view adapter or return undefined to use the result's native MCP App URI. */
34
+ readonly resolveView?: (panel: SnippetPanel) => SnippetPanelView | undefined;
35
+ }
36
+ /**
37
+ * Return selected receipts in display order from the App-only MCP result metadata.
38
+ * Invalid entries and repeated receipt IDs are ignored. Distinct receipts can
39
+ * point to the same snippet and viewer.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * for (const panel of readSnippetPanels(toolResult)) {
44
+ * console.log(panel.provider, panel.name, panel.title);
45
+ * }
46
+ * ```
47
+ */
48
+ export declare function readSnippetPanels(result: unknown): SnippetPanel[];
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 declare function composeSnippetBoard(result: unknown, options?: SnippetBoardOptions): CompositeUiDescriptor;
66
+ //# 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,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAEhG,+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;IACpC,wFAAwF;IACxF,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC9C;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,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SNIPPET_PANELS_META_KEY = exports.installPanelResizing = exports.installPanelMovement = exports.getPanelControlsCss = void 0;
4
+ exports.readSnippetPanels = readSnippetPanels;
5
+ exports.composeSnippetBoard = composeSnippetBoard;
6
+ /**
7
+ * Browser-side composition of completed Code Mode results.
8
+ * @module
9
+ */
10
+ require("../../_dnt.polyfills.js");
11
+ const collector_js_1 = require("../core/collector/collector.js");
12
+ const extractor_js_1 = require("../core/collector/extractor.js");
13
+ const composer_js_1 = require("../core/composer/composer.js");
14
+ var panel_controls_js_1 = require("../host/renderer/css/panel-controls.js");
15
+ Object.defineProperty(exports, "getPanelControlsCss", { enumerable: true, get: function () { return panel_controls_js_1.getPanelControlsCss; } });
16
+ var panel_controls_js_2 = require("../host/renderer/panel-controls.js");
17
+ Object.defineProperty(exports, "installPanelMovement", { enumerable: true, get: function () { return panel_controls_js_2.installPanelMovement; } });
18
+ Object.defineProperty(exports, "installPanelResizing", { enumerable: true, get: function () { return panel_controls_js_2.installPanelResizing; } });
19
+ /** MCP App result metadata containing the receipts selected by the program. */
20
+ exports.SNIPPET_PANELS_META_KEY = "io.mcpview/snippet-panels";
21
+ function record(value) {
22
+ return value !== null && typeof value === "object" && !Array.isArray(value);
23
+ }
24
+ function isPanel(value) {
25
+ return record(value) &&
26
+ typeof value.id === "string" && value.id.length > 0 &&
27
+ typeof value.provider === "string" && value.provider.length > 0 &&
28
+ typeof value.name === "string" && value.name.length > 0 &&
29
+ typeof value.title === "string" && record(value.result);
30
+ }
31
+ /**
32
+ * Return selected receipts in display order from the App-only MCP result metadata.
33
+ * Invalid entries and repeated receipt IDs are ignored. Distinct receipts can
34
+ * point to the same snippet and viewer.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * for (const panel of readSnippetPanels(toolResult)) {
39
+ * console.log(panel.provider, panel.name, panel.title);
40
+ * }
41
+ * ```
42
+ */
43
+ function readSnippetPanels(result) {
44
+ if (!record(result) || !record(result._meta))
45
+ return [];
46
+ const items = result._meta[exports.SNIPPET_PANELS_META_KEY];
47
+ if (!Array.isArray(items))
48
+ return [];
49
+ const seen = new Set();
50
+ const panels = [];
51
+ for (const item of items) {
52
+ if (isPanel(item) && !seen.has(item.id)) {
53
+ panels.push(item);
54
+ seen.add(item.id);
55
+ }
56
+ }
57
+ return panels;
58
+ }
59
+ /**
60
+ * Build a Compose descriptor from the current execution, without making any provider calls.
61
+ * Each child keeps its receipt in `context.panel` and adapter data in `context.view`.
62
+ * The returned summary is shared as `sharedContext.value` when the execution has a value.
63
+ * A data-only receipt needs a local view adapter to produce a child.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * const board = composeSnippetBoard(toolResult, {
68
+ * layout: "split",
69
+ * resolveView: (panel) => panel.provider === "metrics"
70
+ * ? { resourceUri: "ui://my-board/metrics" }
71
+ * : undefined,
72
+ * });
73
+ * ```
74
+ */
75
+ function composeSnippetBoard(result, options = {}) {
76
+ const summary = record(result) && record(result.structuredContent)
77
+ ? result.structuredContent
78
+ : {};
79
+ const collector = (0, collector_js_1.createCollector)();
80
+ for (const panel of readSnippetPanels(result)) {
81
+ const view = options.resolveView?.(panel);
82
+ const resourceUri = view?.resourceUri ?? (0, extractor_js_1.extractUiMeta)(panel.result)?.resourceUri;
83
+ if (!resourceUri || !/^ui:\/\/[^\s]+$/.test(resourceUri))
84
+ continue;
85
+ collector.collect(`${panel.provider}:${panel.name}`, { _meta: { ui: { resourceUri } } }, {
86
+ panel,
87
+ ...(view?.context === undefined ? {} : { view: view.context }),
88
+ ...(Object.hasOwn(summary, "value") ? { value: summary.value } : {}),
89
+ }, { componentId: panel.id, surface: view?.surface, supportedWidths: view?.supportedWidths });
90
+ }
91
+ const resources = collector.getResources();
92
+ const layout = typeof options.layout === "function"
93
+ ? options.layout(resources.length)
94
+ : options.layout;
95
+ return (0, composer_js_1.buildCompositeUi)(resources, { layout: layout ?? "stack", sharedContext: ["value"] });
96
+ }
@@ -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,243 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSnippetChain = createSnippetChain;
4
+ const board_js_1 = require("./board.js");
5
+ const providers_js_1 = require("./providers.js");
6
+ const sandbox_js_1 = require("./sandbox.js");
7
+ const maxNativeSize = 4 * 1024 * 1024;
8
+ const maxNativeBytes = 6 * 1024 * 1024;
9
+ const maxSavedChains = 64;
10
+ const afterDispatch = "One or more upstream operations may have completed. Check their effects before replaying the chain.";
11
+ function isRecord(value) {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+ const providerErrors = new Map([
15
+ ["INVALID_INPUT", "Check the snippet input against its declared schema."],
16
+ ["ARTIFACT_UNAVAILABLE", "The input artifact is unavailable. Regenerate it before retrying."],
17
+ ["PROFILE_INVALID", "The configured provider profile is invalid or unavailable."],
18
+ ["UPSTREAM_ERROR", "The upstream operation failed."],
19
+ ["TIMEOUT", "The upstream operation timed out."],
20
+ ]);
21
+ function providerError(result) {
22
+ const data = result.structuredContent;
23
+ const error = isRecord(data) ? data.error : undefined;
24
+ const code = isRecord(error) ? error.code : undefined;
25
+ return (typeof code === "string" ? providerErrors.get(code) : undefined) ??
26
+ "The provider reported an execution error.";
27
+ }
28
+ function validateParams(input, shape) {
29
+ if (!isRecord(input))
30
+ throw new Error("Supply params as a JSON object.");
31
+ (0, sandbox_js_1.encodeValue)(input, 8192);
32
+ if (shape) {
33
+ const keys = Object.keys(input);
34
+ if (keys.length !== Object.keys(shape).length ||
35
+ keys.some((key) => {
36
+ const value = input[key];
37
+ const kind = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
38
+ return !Object.hasOwn(shape, key) || shape[key] !== kind;
39
+ })) {
40
+ throw new Error("Replay parameters must match the saved key names and JSON types.");
41
+ }
42
+ }
43
+ return input;
44
+ }
45
+ function output(value, panels = [], saved) {
46
+ const visible = {
47
+ value,
48
+ panels: panels.map(({ result: _result, ...panel }) => panel),
49
+ ...(saved === undefined ? {} : { saved }),
50
+ };
51
+ return {
52
+ content: [{ type: "text", text: JSON.stringify(visible) }],
53
+ structuredContent: visible,
54
+ _meta: { [board_js_1.SNIPPET_PANELS_META_KEY]: panels },
55
+ };
56
+ }
57
+ /**
58
+ * Run JavaScript against host-configured snippet providers. Selected results stay
59
+ * out of guest memory except for their declared JSON value. Supplying a catalog
60
+ * enables named chains for calls with a trusted scope.
61
+ */
62
+ function createSnippetChain(providers, catalog) {
63
+ // Keep admission state only while saves overlap. Persistent catalogs are read again
64
+ // on the next save so a completed tenant leaves no resident quota state here.
65
+ const activeSaves = new Map();
66
+ async function execute(code, params, context, status) {
67
+ const receipts = new Map();
68
+ const selected = new Map();
69
+ let totalBytes = 0;
70
+ const value = await (0, sandbox_js_1.runProgram)(code, params, async (operation, args, signal) => {
71
+ signal.throwIfAborted();
72
+ const [first, second, input] = args;
73
+ if (operation === "panel") {
74
+ const panel = typeof first === "string" ? receipts.get(first) : undefined;
75
+ if (!panel || args.length > 2)
76
+ throw new Error("Select a receipt from this execution.");
77
+ if (second !== undefined && (typeof second !== "string" || second.length > 120)) {
78
+ throw new Error("Panel titles may contain at most 120 characters.");
79
+ }
80
+ selected.set(panel.id, { ...panel, title: second ?? panel.title });
81
+ return null;
82
+ }
83
+ const provider = typeof first === "string" ? providers.get(first) : undefined;
84
+ if (!provider)
85
+ throw new Error("Unknown snippet provider.");
86
+ if (operation === "listSnippets" && args.length === 1) {
87
+ const catalog = await provider.call("list_snippets", {}, signal, context);
88
+ signal.throwIfAborted();
89
+ const snippets = isRecord(catalog.structuredContent)
90
+ ? catalog.structuredContent.snippets
91
+ : undefined;
92
+ if (catalog.isError || !Array.isArray(snippets)) {
93
+ throw new Error("Provider snippet catalog is unavailable.");
94
+ }
95
+ return snippets.filter((item) => isRecord(item) && typeof item.name === "string" && provider.names.includes(item.name)).map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
96
+ }
97
+ if (operation !== "runSnippet" || args.length !== 3 || typeof second !== "string" ||
98
+ !provider.names.includes(second) || !isRecord(input)) {
99
+ throw new Error("Choose an approved named snippet and supply its input object.");
100
+ }
101
+ status.dispatched = true;
102
+ status.diagnostic = undefined;
103
+ const result = await provider.call("run_snippet", { name: second, input }, signal, context);
104
+ signal.throwIfAborted();
105
+ if (result.isError) {
106
+ status.diagnostic = `Snippet ${second}: ${providerError(result)}`;
107
+ throw new Error(status.diagnostic);
108
+ }
109
+ if (!isRecord(result.structuredContent) || !Object.hasOwn(result.structuredContent, "value")) {
110
+ status.diagnostic = `Snippet ${second} returned an invalid result.`;
111
+ throw new Error(status.diagnostic);
112
+ }
113
+ const value = result.structuredContent.value;
114
+ (0, sandbox_js_1.encodeValue)(value);
115
+ totalBytes += new TextEncoder().encode((0, sandbox_js_1.encodeValue)(result, maxNativeSize)).byteLength;
116
+ if (totalBytes > maxNativeBytes) {
117
+ throw new Error("Native snippet receipts exceed the board size limit.");
118
+ }
119
+ const id = crypto.randomUUID();
120
+ receipts.set(id, { id, provider: first, name: second, title: second, result });
121
+ return { id, value };
122
+ }, context.signal);
123
+ return { value, panels: [...selected.values()] };
124
+ }
125
+ async function call(input, context, status) {
126
+ const { signal, scope } = context;
127
+ signal?.throwIfAborted();
128
+ if (!isRecord(input))
129
+ throw new Error("Supply execute inputs as a JSON object.");
130
+ const has = (key) => Object.hasOwn(input, key);
131
+ const keysAllowed = (...keys) => Object.keys(input).every((key) => keys.includes(key));
132
+ if (has("code") && !has("saveAs") && keysAllowed("code", "params")) {
133
+ if (typeof input.code !== "string")
134
+ throw new Error("Supply a JavaScript function body.");
135
+ const result = await execute(input.code, validateParams(input.params === undefined ? {} : input.params), context, status);
136
+ signal?.throwIfAborted();
137
+ return output(result.value, result.panels);
138
+ }
139
+ if (!catalog || typeof scope !== "string" || !scope.trim()) {
140
+ throw new Error("Saved chains require a configured catalog and a trusted scope.");
141
+ }
142
+ if (input.listSaved === true && keysAllowed("listSaved")) {
143
+ const snippets = await catalog.list(scope);
144
+ signal?.throwIfAborted();
145
+ return output({ snippets });
146
+ }
147
+ if ((0, providers_js_1.isSnippetName)(input.replay) && keysAllowed("replay", "params")) {
148
+ const result = await catalog.run(scope, input.replay, input.params === undefined ? {} : input.params, {
149
+ validate: validateParams,
150
+ execute: (code, params) => execute(code, params, context, status),
151
+ });
152
+ signal?.throwIfAborted();
153
+ return output(result.value, result.panels);
154
+ }
155
+ if (typeof input.code !== "string" || !has("saveAs") || !keysAllowed("code", "saveAs", "params")) {
156
+ throw new Error("Supply code, replay, or listSaved.");
157
+ }
158
+ const name = input.saveAs;
159
+ if (!(0, providers_js_1.isSnippetName)(name)) {
160
+ throw new Error("Supply a nonempty saved chain name of up to 256 UTF-8 bytes without surrounding whitespace.");
161
+ }
162
+ const params = validateParams(input.params === undefined ? {} : input.params);
163
+ const keys = Object.keys(params);
164
+ if (keys.length > 32 || keys.some((key) => new TextEncoder().encode(key).byteLength > 128)) {
165
+ throw new Error("Saved chain parameter contract exceeds its size limit.");
166
+ }
167
+ let usage = activeSaves.get(scope);
168
+ if (!usage) {
169
+ usage = {
170
+ users: 0,
171
+ stored: catalog.list(scope).then((entries) => new Set(entries.map((entry) => entry.name))),
172
+ saving: new Set(),
173
+ };
174
+ activeSaves.set(scope, usage);
175
+ }
176
+ usage.users++;
177
+ let reserved = false;
178
+ try {
179
+ const savedNames = await usage.stored;
180
+ signal?.throwIfAborted();
181
+ if (usage.saving.has(name))
182
+ throw new Error("A save for this chain is already in progress.");
183
+ if (!savedNames.has(name)) {
184
+ if (savedNames.size >= maxSavedChains)
185
+ throw new Error("The saved chain catalog is full.");
186
+ savedNames.add(name);
187
+ reserved = true;
188
+ }
189
+ // Serialize writes to this name within an executor, without blocking other names.
190
+ usage.saving.add(name);
191
+ try {
192
+ if (!reserved) {
193
+ const previous = await catalog.inspect(scope, name);
194
+ if (previous.code !== input.code)
195
+ throw new Error("Snippet name already in use.");
196
+ validateParams(params, previous.parameters);
197
+ }
198
+ signal?.throwIfAborted();
199
+ const result = await execute(input.code, params, context, status);
200
+ signal?.throwIfAborted();
201
+ status.saving = true;
202
+ const ref = catalog.recordSuccess(scope, input.code, params);
203
+ const saved = await catalog.save(scope, ref, name);
204
+ reserved = false;
205
+ return output(result.value, result.panels, saved.name);
206
+ }
207
+ finally {
208
+ usage.saving.delete(name);
209
+ if (reserved)
210
+ savedNames.delete(name);
211
+ }
212
+ }
213
+ finally {
214
+ if (--usage.users === 0)
215
+ activeSaves.delete(scope);
216
+ }
217
+ }
218
+ return async (input, context = {}) => {
219
+ const status = { dispatched: false, saving: false };
220
+ try {
221
+ return await call(input, context, status);
222
+ }
223
+ catch (error) {
224
+ if (!status.dispatched)
225
+ throw error;
226
+ if (context.signal?.aborted) {
227
+ const reason = context.signal.reason;
228
+ const name = reason instanceof DOMException && reason.name === "TimeoutError"
229
+ ? "TimeoutError"
230
+ : "AbortError";
231
+ throw new DOMException(`Chain interrupted. ${afterDispatch}`, name);
232
+ }
233
+ // Preserve only diagnostics derived from known provider codes. A transport,
234
+ // guest or storage exception may contain credentials, paths or native data.
235
+ const message = status.saving
236
+ ? "Failed to confirm that the chain was saved."
237
+ : status.diagnostic && error instanceof Error && error.message === status.diagnostic
238
+ ? status.diagnostic
239
+ : "Chain execution failed.";
240
+ throw new Error(`${message} ${afterDispatch}`);
241
+ }
242
+ };
243
+ }
@@ -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"}
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectSnippetProviders = connectSnippetProviders;
4
+ const client_1 = require("@modelcontextprotocol/client");
5
+ const providers_js_1 = require("./providers.js");
6
+ /**
7
+ * Connect the explicitly configured upstream MCPs. HTTP bindings share one host-owned
8
+ * upstream identity for the lifetime of this pool. For different authorities in a
9
+ * multi-user server, supply a client resolver keyed by the authenticated request context.
10
+ * A partial startup closes every connection opened by the pool.
11
+ */
12
+ async function connectSnippetProviders(bindings, options = {}) {
13
+ options.signal?.throwIfAborted();
14
+ if (!bindings.length)
15
+ throw new Error("Configure at least one snippet provider.");
16
+ const aliases = new Set();
17
+ const prepared = bindings.map((binding) => {
18
+ const { alias, snippets } = binding;
19
+ if (!(0, providers_js_1.isSnippetIdentifier)(alias) || aliases.has(alias)) {
20
+ throw new Error("Provider aliases must be valid and unique.");
21
+ }
22
+ aliases.add(alias);
23
+ if (!Array.isArray(snippets) || !snippets.length || !snippets.every(providers_js_1.isSnippetName) ||
24
+ new Set(snippets).size !== snippets.length)
25
+ throw new Error("A provider needs a list of unique approved snippet names.");
26
+ if ((binding.url === undefined) === (binding.client === undefined)) {
27
+ throw new Error("Supply exactly one provider URL or client.");
28
+ }
29
+ let url;
30
+ if (binding.url !== undefined) {
31
+ url = new URL(binding.url);
32
+ if (!["http:", "https:"].includes(url.protocol)) {
33
+ throw new Error("Expected an HTTP endpoint.");
34
+ }
35
+ }
36
+ else if (typeof binding.client !== "function" && typeof binding.client?.callTool !== "function") {
37
+ throw new Error("Expected an MCP client or client resolver.");
38
+ }
39
+ return { alias, names: Object.freeze([...snippets]), url, binding };
40
+ });
41
+ const owned = [];
42
+ let closing;
43
+ function close() {
44
+ return closing ??= (async () => {
45
+ const attempts = await Promise.allSettled(owned.map((release) => release()));
46
+ const errors = attempts.flatMap((a) => a.status === "rejected" ? [a.reason] : []);
47
+ if (errors.length) {
48
+ throw new AggregateError(errors, "Failed to close upstream MCP connections.");
49
+ }
50
+ })();
51
+ }
52
+ const opened = await Promise.allSettled(prepared.map(async ({ alias, names, url, binding }) => {
53
+ let source = binding.client;
54
+ if (url !== undefined) {
55
+ const client = new client_1.Client({ name: "mcpview-compose-snippet-client", version: "1.0" }, {
56
+ capabilities: {
57
+ extensions: {
58
+ "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
59
+ },
60
+ },
61
+ versionNegotiation: { mode: "auto" },
62
+ });
63
+ const transport = new client_1.StreamableHTTPClientTransport(url, {
64
+ requestInit: { ...binding.requestInit, redirect: "error" },
65
+ });
66
+ owned.push(async () => {
67
+ // Closing the client also aborts the HTTP request if DELETE never returns.
68
+ const timer = setTimeout(() => {
69
+ void client.close().catch(() => { });
70
+ }, 3000);
71
+ try {
72
+ await transport.terminateSession();
73
+ }
74
+ finally {
75
+ clearTimeout(timer);
76
+ await client.close();
77
+ }
78
+ });
79
+ await client.connect(transport, { timeout: 15_000, signal: options.signal });
80
+ source = client;
81
+ }
82
+ if (!source)
83
+ throw new Error("Missing snippet provider client.");
84
+ const clientSource = source;
85
+ const provider = {
86
+ names,
87
+ async call(tool, args, signal, context) {
88
+ signal.throwIfAborted();
89
+ if (closing)
90
+ throw new Error("Upstream MCP connections are closed.");
91
+ if (tool !== "list_snippets" &&
92
+ !(tool === "run_snippet" && typeof args.name === "string" && names.includes(args.name))) {
93
+ throw new Error("Choose an approved provider snippet.");
94
+ }
95
+ try {
96
+ const client = typeof clientSource === "function"
97
+ ? await clientSource(context)
98
+ : clientSource;
99
+ signal.throwIfAborted();
100
+ if (closing)
101
+ throw new Error("Upstream MCP connections are closed.");
102
+ return await client.callTool({ name: tool, arguments: args }, {
103
+ signal,
104
+ timeout: 25_000,
105
+ });
106
+ }
107
+ catch {
108
+ signal.throwIfAborted();
109
+ throw new Error(`The ${alias} snippet provider could not complete the request.`);
110
+ }
111
+ },
112
+ };
113
+ return [alias, provider];
114
+ }));
115
+ const failure = opened.find((entry) => entry.status === "rejected");
116
+ if (failure || options.signal?.aborted) {
117
+ await close().catch(() => { });
118
+ options.signal?.throwIfAborted();
119
+ throw failure?.reason;
120
+ }
121
+ const providers = new Map(opened.flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []));
122
+ return { providers, close };
123
+ }
@@ -0,0 +1,8 @@
1
+ /** Run selected snippets across host-configured MCP providers in one Code Mode call. */
2
+ import "../../_dnt.polyfills.js";
3
+ export { createSnippetChain, type SnippetChainExecutor, type SnippetPanelReceipt, } from "./chain.js";
4
+ export { connectSnippetProviders, type SnippetMcpClient, type SnippetProviderBinding, type SnippetProviderConnections, } from "./connections.js";
5
+ export type { SnippetChainContext, SnippetProvider } from "./providers.js";
6
+ export { createSnippetExecuteTool, type SnippetExecuteToolOptions } from "./tool.js";
7
+ export { type ProviderSnippetDefinition, registerSnippetProvider, type SnippetProviderOptions, } from "./provider-tools.js";
8
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/mod.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,OAAO,yBAAyB,CAAC;AAEjC,OAAO,EACL,kBAAkB,EAClB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,uBAAuB,EACvB,KAAK,gBAAgB,EACrB,KAAK,sBAAsB,EAC3B,KAAK,0BAA0B,GAChC,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,KAAK,yBAAyB,EAAE,MAAM,WAAW,CAAC;AACrF,OAAO,EACL,KAAK,yBAAyB,EAC9B,uBAAuB,EACvB,KAAK,sBAAsB,GAC5B,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerSnippetProvider = exports.createSnippetExecuteTool = exports.connectSnippetProviders = exports.createSnippetChain = void 0;
4
+ /** Run selected snippets across host-configured MCP providers in one Code Mode call. */
5
+ require("../../_dnt.polyfills.js");
6
+ var chain_js_1 = require("./chain.js");
7
+ Object.defineProperty(exports, "createSnippetChain", { enumerable: true, get: function () { return chain_js_1.createSnippetChain; } });
8
+ var connections_js_1 = require("./connections.js");
9
+ Object.defineProperty(exports, "connectSnippetProviders", { enumerable: true, get: function () { return connections_js_1.connectSnippetProviders; } });
10
+ var tool_js_1 = require("./tool.js");
11
+ Object.defineProperty(exports, "createSnippetExecuteTool", { enumerable: true, get: function () { return tool_js_1.createSnippetExecuteTool; } });
12
+ var provider_tools_js_1 = require("./provider-tools.js");
13
+ Object.defineProperty(exports, "registerSnippetProvider", { enumerable: true, get: function () { return provider_tools_js_1.registerSnippetProvider; } });