@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,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"}
@@ -0,0 +1,120 @@
1
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
+ import { isSnippetIdentifier, isSnippetName, } from "./providers.js";
3
+ /**
4
+ * Connect the explicitly configured upstream MCPs. HTTP bindings share one host-owned
5
+ * upstream identity for the lifetime of this pool. For different authorities in a
6
+ * multi-user server, supply a client resolver keyed by the authenticated request context.
7
+ * A partial startup closes every connection opened by the pool.
8
+ */
9
+ export async function connectSnippetProviders(bindings, options = {}) {
10
+ options.signal?.throwIfAborted();
11
+ if (!bindings.length)
12
+ throw new Error("Configure at least one snippet provider.");
13
+ const aliases = new Set();
14
+ const prepared = bindings.map((binding) => {
15
+ const { alias, snippets } = binding;
16
+ if (!isSnippetIdentifier(alias) || aliases.has(alias)) {
17
+ throw new Error("Provider aliases must be valid and unique.");
18
+ }
19
+ aliases.add(alias);
20
+ if (!Array.isArray(snippets) || !snippets.length || !snippets.every(isSnippetName) ||
21
+ new Set(snippets).size !== snippets.length)
22
+ throw new Error("A provider needs a list of unique approved snippet names.");
23
+ if ((binding.url === undefined) === (binding.client === undefined)) {
24
+ throw new Error("Supply exactly one provider URL or client.");
25
+ }
26
+ let url;
27
+ if (binding.url !== undefined) {
28
+ url = new URL(binding.url);
29
+ if (!["http:", "https:"].includes(url.protocol)) {
30
+ throw new Error("Expected an HTTP endpoint.");
31
+ }
32
+ }
33
+ else if (typeof binding.client !== "function" && typeof binding.client?.callTool !== "function") {
34
+ throw new Error("Expected an MCP client or client resolver.");
35
+ }
36
+ return { alias, names: Object.freeze([...snippets]), url, binding };
37
+ });
38
+ const owned = [];
39
+ let closing;
40
+ function close() {
41
+ return closing ??= (async () => {
42
+ const attempts = await Promise.allSettled(owned.map((release) => release()));
43
+ const errors = attempts.flatMap((a) => a.status === "rejected" ? [a.reason] : []);
44
+ if (errors.length) {
45
+ throw new AggregateError(errors, "Failed to close upstream MCP connections.");
46
+ }
47
+ })();
48
+ }
49
+ const opened = await Promise.allSettled(prepared.map(async ({ alias, names, url, binding }) => {
50
+ let source = binding.client;
51
+ if (url !== undefined) {
52
+ const client = new Client({ name: "mcpview-compose-snippet-client", version: "1.0" }, {
53
+ capabilities: {
54
+ extensions: {
55
+ "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
56
+ },
57
+ },
58
+ versionNegotiation: { mode: "auto" },
59
+ });
60
+ const transport = new StreamableHTTPClientTransport(url, {
61
+ requestInit: { ...binding.requestInit, redirect: "error" },
62
+ });
63
+ owned.push(async () => {
64
+ // Closing the client also aborts the HTTP request if DELETE never returns.
65
+ const timer = setTimeout(() => {
66
+ void client.close().catch(() => { });
67
+ }, 3000);
68
+ try {
69
+ await transport.terminateSession();
70
+ }
71
+ finally {
72
+ clearTimeout(timer);
73
+ await client.close();
74
+ }
75
+ });
76
+ await client.connect(transport, { timeout: 15_000, signal: options.signal });
77
+ source = client;
78
+ }
79
+ if (!source)
80
+ throw new Error("Missing snippet provider client.");
81
+ const clientSource = source;
82
+ const provider = {
83
+ names,
84
+ async call(tool, args, signal, context) {
85
+ signal.throwIfAborted();
86
+ if (closing)
87
+ throw new Error("Upstream MCP connections are closed.");
88
+ if (tool !== "list_snippets" &&
89
+ !(tool === "run_snippet" && typeof args.name === "string" && names.includes(args.name))) {
90
+ throw new Error("Choose an approved provider snippet.");
91
+ }
92
+ try {
93
+ const client = typeof clientSource === "function"
94
+ ? await clientSource(context)
95
+ : clientSource;
96
+ signal.throwIfAborted();
97
+ if (closing)
98
+ throw new Error("Upstream MCP connections are closed.");
99
+ return await client.callTool({ name: tool, arguments: args }, {
100
+ signal,
101
+ timeout: 25_000,
102
+ });
103
+ }
104
+ catch {
105
+ signal.throwIfAborted();
106
+ throw new Error(`The ${alias} snippet provider could not complete the request.`);
107
+ }
108
+ },
109
+ };
110
+ return [alias, provider];
111
+ }));
112
+ const failure = opened.find((entry) => entry.status === "rejected");
113
+ if (failure || options.signal?.aborted) {
114
+ await close().catch(() => { });
115
+ options.signal?.throwIfAborted();
116
+ throw failure?.reason;
117
+ }
118
+ const providers = new Map(opened.flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []));
119
+ return { providers, close };
120
+ }
@@ -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,6 @@
1
+ /** Run selected snippets across host-configured MCP providers in one Code Mode call. */
2
+ import "../../_dnt.polyfills.js";
3
+ export { createSnippetChain, } from "./chain.js";
4
+ export { connectSnippetProviders, } from "./connections.js";
5
+ export { createSnippetExecuteTool } from "./tool.js";
6
+ export { registerSnippetProvider, } from "./provider-tools.js";
@@ -0,0 +1,38 @@
1
+ import type { McpApp, MCPTool, ToolHandlerContext } from "@mcpview/server";
2
+ /** A named, host-owned snippet. The runner replays it using the current caller's authority. */
3
+ export interface ProviderSnippetDefinition {
4
+ readonly name: string;
5
+ readonly description: string;
6
+ readonly inputSchema: Record<string, unknown>;
7
+ readonly run: (input: Record<string, unknown>, context?: ToolHandlerContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
8
+ }
9
+ /** Discovery and replay policy for one upstream Code Mode provider. */
10
+ export interface SnippetProviderOptions {
11
+ readonly snippets: readonly ProviderSnippetDefinition[];
12
+ /** Evaluated for each listing and again for each replay, before reading the snippet input. */
13
+ readonly authorize?: (name: string, context?: ToolHandlerContext) => boolean | Promise<boolean>;
14
+ /** OAuth scopes enforced on both discovery and replay by the MCPView host. */
15
+ readonly requiredScopes?: readonly string[];
16
+ readonly runAnnotations?: MCPTool["annotations"];
17
+ /** Static native MCP App resource if all served snippets use the same viewer. */
18
+ readonly runResourceUri?: string;
19
+ }
20
+ /**
21
+ * Register `list_snippets` and `run_snippet`. Expose selected saved programs by name.
22
+ * A successful runner returns its native MCP response with a JSON projection at
23
+ * `structuredContent.value`. Provider-only view metadata is forwarded intact.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * registerSnippetProvider(app, {
28
+ * snippets: [{
29
+ * name: "overdue", description: "List overdue invoices",
30
+ * inputSchema: { type: "object" },
31
+ * run: (input, context) => replayInvoiceSnippet("overdue", input, context),
32
+ * }],
33
+ * requiredScopes: ["invoices:read"],
34
+ * });
35
+ * ```
36
+ */
37
+ export declare function registerSnippetProvider(server: Pick<McpApp, "registerTool" | "getToolNames">, options: SnippetProviderOptions): void;
38
+ //# sourceMappingURL=provider-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-tools.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/provider-tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAI3E,+FAA+F;AAC/F,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9C,QAAQ,CAAC,GAAG,EAAE,CACZ,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,OAAO,CAAC,EAAE,kBAAkB,KACzB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACjE;AAED,uEAAuE;AACvE,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,QAAQ,EAAE,SAAS,yBAAyB,EAAE,CAAC;IACxD,8FAA8F;IAC9F,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,kBAAkB,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAChG,8EAA8E;IAC9E,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IACjD,iFAAiF;IACjF,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CAClC;AAcD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,cAAc,GAAG,cAAc,CAAC,EACrD,OAAO,EAAE,sBAAsB,GAC9B,IAAI,CA6EN"}
@@ -0,0 +1,113 @@
1
+ /** Register the discovery and replay protocol on a snippet-owning MCP server. @module */
2
+ import { Ajv2020 } from "ajv/dist/2020.js";
3
+ import { extractUiMeta } from "../core/collector/extractor.js";
4
+ import { isSnippetName } from "./providers.js";
5
+ function failure(code, text) {
6
+ return {
7
+ isError: true,
8
+ content: [{ type: "text", text }],
9
+ structuredContent: { error: { code } },
10
+ };
11
+ }
12
+ function object(input) {
13
+ return typeof input === "object" && input !== null && !Array.isArray(input);
14
+ }
15
+ /**
16
+ * Register `list_snippets` and `run_snippet`. Expose selected saved programs by name.
17
+ * A successful runner returns its native MCP response with a JSON projection at
18
+ * `structuredContent.value`. Provider-only view metadata is forwarded intact.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * registerSnippetProvider(app, {
23
+ * snippets: [{
24
+ * name: "overdue", description: "List overdue invoices",
25
+ * inputSchema: { type: "object" },
26
+ * run: (input, context) => replayInvoiceSnippet("overdue", input, context),
27
+ * }],
28
+ * requiredScopes: ["invoices:read"],
29
+ * });
30
+ * ```
31
+ */
32
+ export function registerSnippetProvider(server, options) {
33
+ if (server.getToolNames().some((name) => name === "list_snippets" || name === "run_snippet")) {
34
+ throw new Error("Snippet discovery or replay tools are already registered.");
35
+ }
36
+ const resourceUri = options.runResourceUri;
37
+ const schemas = new Ajv2020({ strict: false, useDefaults: true });
38
+ const definitions = options.snippets.map(({ name, description, inputSchema, run }) => {
39
+ if (!isSnippetName(name) || !object(inputSchema) || inputSchema.type !== "object") {
40
+ throw new TypeError("Each snippet needs a valid name and an object input schema.");
41
+ }
42
+ const schema = structuredClone(inputSchema);
43
+ const validate = schemas.compile(schema);
44
+ if ("$async" in validate)
45
+ throw new TypeError("Snippet input schemas must be synchronous.");
46
+ return { descriptor: { name, description, inputSchema: schema }, validate, run };
47
+ });
48
+ const byName = new Map(definitions.map((def) => [def.descriptor.name, def]));
49
+ if (byName.size !== definitions.length)
50
+ throw new Error("Snippet names must be unique.");
51
+ const authorized = async (name, context) => !options.authorize || (await options.authorize(name, context)) === true;
52
+ const scopes = options.requiredScopes ? [...options.requiredScopes] : undefined;
53
+ server.registerTool({
54
+ name: "list_snippets",
55
+ description: "List the saved snippets available to this caller and their input schemas.",
56
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
57
+ requiredScopes: scopes,
58
+ annotations: {
59
+ readOnlyHint: true,
60
+ destructiveHint: false,
61
+ openWorldHint: false,
62
+ idempotentHint: true,
63
+ },
64
+ }, async (_args, context) => {
65
+ const snippets = [];
66
+ for (const { descriptor } of definitions) {
67
+ if (await authorized(descriptor.name, context))
68
+ snippets.push(descriptor);
69
+ }
70
+ return {
71
+ content: snippets.map(({ name }) => name).join(", "),
72
+ structuredContent: { snippets },
73
+ };
74
+ });
75
+ server.registerTool({
76
+ name: "run_snippet",
77
+ description: "Replay a saved snippet using its declared input.",
78
+ inputSchema: {
79
+ type: "object",
80
+ properties: { name: { type: "string" }, input: { type: "object" } },
81
+ required: ["name", "input"],
82
+ additionalProperties: false,
83
+ },
84
+ annotations: {
85
+ readOnlyHint: false,
86
+ destructiveHint: true,
87
+ openWorldHint: true,
88
+ idempotentHint: false,
89
+ ...options.runAnnotations,
90
+ },
91
+ requiredScopes: scopes,
92
+ ...(resourceUri ? { _meta: { ui: { resourceUri } } } : {}),
93
+ }, async (args, context) => {
94
+ const def = typeof args.name === "string" ? byName.get(args.name) : undefined;
95
+ if (!def || !await authorized(def.descriptor.name, context)) {
96
+ return failure("UNAVAILABLE", "The requested snippet is unavailable.");
97
+ }
98
+ if (!object(args.input) || Object.keys(args).length !== 2 || !def.validate(args.input)) {
99
+ return failure("INVALID_INPUT", "Supply the snippet's declared input.");
100
+ }
101
+ const result = await def.run(args.input, context);
102
+ if (result.isError === true)
103
+ return result;
104
+ if (!object(result.structuredContent) || !Object.hasOwn(result.structuredContent, "value")) {
105
+ return failure("UPSTREAM_ERROR", "The saved snippet returned no value.");
106
+ }
107
+ if (!resourceUri || extractUiMeta(result))
108
+ return result;
109
+ const meta = object(result._meta) ? result._meta : {};
110
+ const ui = object(meta.ui) ? meta.ui : {};
111
+ return { ...result, _meta: { ...meta, ui: { ...ui, resourceUri } } };
112
+ });
113
+ }
@@ -0,0 +1,20 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/client";
2
+ /** Trusted, per-request server context, supplied by the host rather than guest code. */
3
+ export interface SnippetChainContext {
4
+ /** Catalog partition derived from the authenticated principal and integration. */
5
+ readonly scope?: string;
6
+ /** Cancellation of the incoming MCP request. */
7
+ readonly signal?: AbortSignal;
8
+ }
9
+ /** A configured MCP binding. The host resolves the caller's upstream authority on every call. */
10
+ export interface SnippetProvider {
11
+ /** The subset of this provider's snippets reachable by a program. */
12
+ readonly names: readonly string[];
13
+ /** Forward only these protocol operations with host-owned transport credentials. */
14
+ call(tool: "list_snippets" | "run_snippet", args: Record<string, unknown>, signal: AbortSignal, context: SnippetChainContext): Promise<CallToolResult>;
15
+ }
16
+ /** Configured aliases identifying providers in a program. */
17
+ export declare function isSnippetIdentifier(value: unknown): value is string;
18
+ /** MCPView catalog names are exact, nonblank strings of at most 256 UTF-8 bytes. */
19
+ export declare function isSnippetName(value: unknown): value is string;
20
+ //# sourceMappingURL=providers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/providers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,wFAAwF;AACxF,MAAM,WAAW,mBAAmB;IAClC,kFAAkF;IAClF,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,gDAAgD;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,iGAAiG;AACjG,MAAM,WAAW,eAAe;IAC9B,qEAAqE;IACrE,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,oFAAoF;IACpF,IAAI,CACF,IAAI,EAAE,eAAe,GAAG,aAAa,EACrC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,cAAc,CAAC,CAAC;CAC5B;AAED,6DAA6D;AAC7D,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEnE;AAED,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAG7D"}
@@ -0,0 +1,9 @@
1
+ /** Configured aliases identifying providers in a program. */
2
+ export function isSnippetIdentifier(value) {
3
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value);
4
+ }
5
+ /** MCPView catalog names are exact, nonblank strings of at most 256 UTF-8 bytes. */
6
+ export function isSnippetName(value) {
7
+ return typeof value === "string" && value.length > 0 && value.length <= 256 &&
8
+ value === value.trim() && new TextEncoder().encode(value).byteLength <= 256;
9
+ }
@@ -0,0 +1,10 @@
1
+ /** Maximum source length accepted by the code-mode execute tool. */
2
+ export declare const maxCodeLength = 16384;
3
+ /** Serialize data crossing the QuickJS boundary within the supplied limit. */
4
+ export declare function encodeValue(value: unknown, limit?: number): string;
5
+ /**
6
+ * Run a function body in an isolated QuickJS context. Only JSON and explicit snippet
7
+ * operations cross into the host. Execute host requests when the guest yields.
8
+ */
9
+ export declare function runProgram(code: string, params: Record<string, unknown>, invoke: (operation: string, args: unknown[], signal: AbortSignal) => Promise<unknown>, callerSignal?: AbortSignal): Promise<unknown>;
10
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/sandbox.ts"],"names":[],"mappings":"AAEA,oEAAoE;AACpE,eAAO,MAAM,aAAa,QAAS,CAAC;AAIpC,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,SAAiB,GAAG,MAAM,CAM1E;AAkBD;;;GAGG;AACH,wBAAsB,UAAU,CAC9B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,OAAO,CAAC,EACrF,YAAY,CAAC,EAAE,WAAW,GACzB,OAAO,CAAC,OAAO,CAAC,CA4HlB"}