@mcpview/compose 0.10.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 (77) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +92 -2
  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/core/types/mcp-apps.d.ts +1 -1
  30. package/esm/src/host/renderer/js/event-bus.d.ts.map +1 -1
  31. package/esm/src/host/renderer/js/event-bus.js +4 -3
  32. package/esm/src/runtime/cluster.d.ts.map +1 -1
  33. package/esm/src/runtime/cluster.js +38 -10
  34. package/esm/src/runtime/types.d.ts +3 -3
  35. package/esm/src/runtime/types.d.ts.map +1 -1
  36. package/esm/src/sdk/mcp-sdk.d.ts +4 -4
  37. package/esm/src/sdk/mcp-sdk.js +2 -2
  38. package/esm/src/version.d.ts +1 -1
  39. package/esm/src/version.js +1 -1
  40. package/package.json +17 -3
  41. package/script/_dnt.polyfills.d.ts +6 -6
  42. package/script/_dnt.polyfills.d.ts.map +1 -1
  43. package/script/src/code-mode/board.d.ts +62 -0
  44. package/script/src/code-mode/board.d.ts.map +1 -0
  45. package/script/src/code-mode/board.js +91 -0
  46. package/script/src/code-mode/chain.d.ts +20 -0
  47. package/script/src/code-mode/chain.d.ts.map +1 -0
  48. package/script/src/code-mode/chain.js +243 -0
  49. package/script/src/code-mode/connections.d.ts +33 -0
  50. package/script/src/code-mode/connections.d.ts.map +1 -0
  51. package/script/src/code-mode/connections.js +123 -0
  52. package/script/src/code-mode/mod.d.ts +8 -0
  53. package/script/src/code-mode/mod.d.ts.map +1 -0
  54. package/script/src/code-mode/mod.js +13 -0
  55. package/script/src/code-mode/provider-tools.d.ts +38 -0
  56. package/script/src/code-mode/provider-tools.d.ts.map +1 -0
  57. package/script/src/code-mode/provider-tools.js +116 -0
  58. package/script/src/code-mode/providers.d.ts +20 -0
  59. package/script/src/code-mode/providers.d.ts.map +1 -0
  60. package/script/src/code-mode/providers.js +13 -0
  61. package/script/src/code-mode/sandbox.d.ts +10 -0
  62. package/script/src/code-mode/sandbox.d.ts.map +1 -0
  63. package/script/src/code-mode/sandbox.js +152 -0
  64. package/script/src/code-mode/tool.d.ts +13 -0
  65. package/script/src/code-mode/tool.d.ts.map +1 -0
  66. package/script/src/code-mode/tool.js +57 -0
  67. package/script/src/core/types/mcp-apps.d.ts +1 -1
  68. package/script/src/host/renderer/js/event-bus.d.ts.map +1 -1
  69. package/script/src/host/renderer/js/event-bus.js +4 -3
  70. package/script/src/runtime/cluster.d.ts.map +1 -1
  71. package/script/src/runtime/cluster.js +60 -32
  72. package/script/src/runtime/types.d.ts +3 -3
  73. package/script/src/runtime/types.d.ts.map +1 -1
  74. package/script/src/sdk/mcp-sdk.d.ts +4 -4
  75. package/script/src/sdk/mcp-sdk.js +2 -2
  76. package/script/src/version.d.ts +1 -1
  77. package/script/src/version.js +1 -1
@@ -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"}
@@ -0,0 +1,147 @@
1
+ import { getQuickJS, Scope } from "quickjs-emscripten";
2
+ /** Maximum source length accepted by the code-mode execute tool. */
3
+ export const maxCodeLength = 16_384;
4
+ const maxValueLength = 128 * 1024;
5
+ const maxOperations = 16;
6
+ /** Serialize data crossing the QuickJS boundary within the supplied limit. */
7
+ export function encodeValue(value, limit = maxValueLength) {
8
+ const text = JSON.stringify(value);
9
+ if (text === undefined || text.length > limit) {
10
+ throw new Error("Expected a JSON value within the size limit.");
11
+ }
12
+ return text;
13
+ }
14
+ /** Wait for host I/O without allowing a provider that ignores cancellation to hold the VM open. */
15
+ function waitForOperation(invoke, signal) {
16
+ signal.throwIfAborted();
17
+ return new Promise((resolve, reject) => {
18
+ const abort = () => reject(signal.reason);
19
+ signal.addEventListener("abort", abort, { once: true });
20
+ Promise.resolve().then(() => {
21
+ signal.throwIfAborted();
22
+ return invoke();
23
+ }).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
24
+ });
25
+ }
26
+ /**
27
+ * Run a function body in an isolated QuickJS context. Only JSON and explicit snippet
28
+ * operations cross into the host. Execute host requests when the guest yields.
29
+ */
30
+ export async function runProgram(code, params, invoke, callerSignal) {
31
+ if (typeof code !== "string" || !code.trim() || code.length > maxCodeLength) {
32
+ throw new Error("Supply a JavaScript function body of at most 16 KiB.");
33
+ }
34
+ callerSignal?.throwIfAborted();
35
+ const wasm = await getQuickJS();
36
+ callerSignal?.throwIfAborted();
37
+ const controller = new AbortController();
38
+ const signal = controller.signal;
39
+ const abort = () => controller.abort(callerSignal?.reason);
40
+ callerSignal?.addEventListener("abort", abort, { once: true });
41
+ const timer = setTimeout(() => controller.abort(new Error("JavaScript exceeded its time limit.")), 30_000);
42
+ try {
43
+ return await Scope.withScopeAsync(async (scope) => {
44
+ const vm = scope.manage(wasm.newContext());
45
+ let cpuDeadline = performance.now() + 2000;
46
+ vm.runtime.setMemoryLimit(12 * 1024 * 1024);
47
+ vm.runtime.setMaxStackSize(192 * 1024);
48
+ vm.runtime.setInterruptHandler(() => signal.aborted || performance.now() >= cpuDeadline);
49
+ const stringify = scope.manage(vm.unwrapResult(vm.evalCode("JSON.stringify.bind(JSON)")));
50
+ const parse = scope.manage(vm.unwrapResult(vm.evalCode("JSON.parse.bind(JSON)")));
51
+ const pending = [];
52
+ let calls = 0;
53
+ function read(handle) {
54
+ const encoded = vm.unwrapResult(vm.callFunction(stringify, vm.undefined, handle));
55
+ try {
56
+ if (vm.typeof(encoded) !== "string")
57
+ throw new Error("Expected a JSON value.");
58
+ const text = vm.getString(encoded);
59
+ if (text.length > maxValueLength)
60
+ throw new Error("JSON value exceeds the size limit.");
61
+ return JSON.parse(text);
62
+ }
63
+ finally {
64
+ encoded.dispose();
65
+ }
66
+ }
67
+ function decode(value) {
68
+ const encoded = vm.newString(encodeValue(value));
69
+ try {
70
+ return scope.manage(vm.unwrapResult(vm.callFunction(parse, vm.undefined, encoded)));
71
+ }
72
+ finally {
73
+ encoded.dispose();
74
+ }
75
+ }
76
+ const dispatch = scope.manage(vm.newFunction("dispatch", (name, args) => {
77
+ if (++calls > maxOperations || vm.typeof(name) !== "string") {
78
+ throw new Error("Snippet operation limit exceeded.");
79
+ }
80
+ const operation = vm.getString(name);
81
+ const arguments_ = read(args);
82
+ if (!Array.isArray(arguments_))
83
+ throw new Error("Expected snippet arguments.");
84
+ const deferred = scope.manage(vm.newPromise());
85
+ pending.push(async () => {
86
+ try {
87
+ const result = await waitForOperation(() => invoke(operation, arguments_, signal), signal);
88
+ signal.throwIfAborted();
89
+ deferred.resolve(decode(result));
90
+ }
91
+ catch (error) {
92
+ const message = scope.manage(vm.newString(error instanceof Error ? error.message : "Snippet failed."));
93
+ deferred.reject(message);
94
+ }
95
+ });
96
+ return deferred.handle.dup();
97
+ }));
98
+ vm.setProp(vm.global, "dispatch", dispatch);
99
+ vm.setProp(vm.global, "params", decode(params));
100
+ const promise = scope.manage(vm.unwrapResult(vm.evalCode(`(() => {
101
+ const call = globalThis.dispatch, params = globalThis.params;
102
+ delete globalThis.dispatch;
103
+ delete globalThis.params;
104
+ const api = Object.freeze({
105
+ params,
106
+ listSnippets: (...args) => call("listSnippets", args),
107
+ runSnippet: (...args) => call("runSnippet", args),
108
+ panel: (...args) => call("panel", args),
109
+ });
110
+ return (async function(api) { "use strict";\n${code}\n})(api);
111
+ })()`, "mcpview-code-mode.js", { type: "global" })));
112
+ for (;;) {
113
+ signal.throwIfAborted();
114
+ if (performance.now() >= cpuDeadline) {
115
+ throw new Error("JavaScript exceeded its time limit.");
116
+ }
117
+ const state = vm.getPromiseState(promise);
118
+ if (state.type === "fulfilled") {
119
+ const value = scope.manage(state.value);
120
+ if (pending.length) {
121
+ throw new Error("Await every snippet operation, including api.panel().");
122
+ }
123
+ return vm.typeof(value) === "undefined" ? null : read(value);
124
+ }
125
+ if (state.type === "rejected") {
126
+ const reason = scope.manage(state.error);
127
+ throw new Error(vm.typeof(reason) === "string" ? vm.getString(reason) : "JavaScript failed.");
128
+ }
129
+ if (vm.runtime.hasPendingJob()) {
130
+ vm.unwrapResult(vm.runtime.executePendingJobs(1));
131
+ }
132
+ else if (pending.length) {
133
+ const before = performance.now();
134
+ await pending.shift()();
135
+ cpuDeadline += performance.now() - before;
136
+ }
137
+ else {
138
+ throw new Error("JavaScript is waiting on an unresolved promise.");
139
+ }
140
+ }
141
+ });
142
+ }
143
+ finally {
144
+ clearTimeout(timer);
145
+ callerSignal?.removeEventListener("abort", abort);
146
+ }
147
+ }
@@ -0,0 +1,13 @@
1
+ import type { MCPTool } from "@mcpview/server";
2
+ import type { SnippetProvider } from "./providers.js";
3
+ /** Configure the single model-facing tool and its MCP Apps board resource. */
4
+ export interface SnippetExecuteToolOptions {
5
+ readonly resourceUri: string;
6
+ readonly providers: ReadonlyMap<string, Pick<SnippetProvider, "names">>;
7
+ /** Enable this when the chain uses a catalog and the host supplies a trusted scope. */
8
+ readonly savedChains?: boolean;
9
+ readonly annotations?: MCPTool["annotations"];
10
+ }
11
+ /** Build the tool declaration for registration with an MCPView server. */
12
+ export declare function createSnippetExecuteTool(options: SnippetExecuteToolOptions): MCPTool;
13
+ //# sourceMappingURL=tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/tool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAGtD,8EAA8E;AAC9E,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC,CAAC;IACxE,uFAAuF;IACvF,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;CAC/C;AAED,0EAA0E;AAC1E,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAqDpF"}
@@ -0,0 +1,54 @@
1
+ import { maxCodeLength } from "./sandbox.js";
2
+ /** Build the tool declaration for registration with an MCPView server. */
3
+ export function createSnippetExecuteTool(options) {
4
+ if (!options.resourceUri.startsWith("ui://") || !URL.canParse(options.resourceUri) ||
5
+ !new URL(options.resourceUri).host) {
6
+ throw new Error("Supply a ui:// resource URI for the board.");
7
+ }
8
+ const available = [...options.providers.keys()];
9
+ return {
10
+ name: "execute",
11
+ description: [
12
+ "Run a JavaScript function body with api.params (the supplied JSON object).",
13
+ "Use await api.listSnippets(provider) to discover approved snippets.",
14
+ "Configured provider aliases: " + JSON.stringify(available) + ".",
15
+ "await api.runSnippet(provider, name, input) returns a receipt {id, value}.",
16
+ "Pass values between calls. Use await api.panel(receipt.id, optionalTitle) for each result to display, in display order. Return a JSON summary.",
17
+ ...(options.savedChains
18
+ ? [
19
+ "Use saveAs to save a successful chain, listSaved to list your saved chains, or replay with the saved name and new params.",
20
+ ]
21
+ : []),
22
+ ].join(" "),
23
+ inputSchema: {
24
+ type: "object",
25
+ additionalProperties: false,
26
+ properties: {
27
+ code: { type: "string", minLength: 1, maxLength: maxCodeLength },
28
+ params: { type: "object" },
29
+ ...(options.savedChains
30
+ ? {
31
+ saveAs: { type: "string", minLength: 1, maxLength: 256 },
32
+ replay: { type: "string", minLength: 1, maxLength: 256 },
33
+ listSaved: { type: "boolean", const: true },
34
+ }
35
+ : {}),
36
+ },
37
+ ...(options.savedChains
38
+ ? { oneOf: [{ required: ["code"] }, { required: ["replay"] }, { required: ["listSaved"] }] }
39
+ : { required: ["code"] }),
40
+ },
41
+ annotations: {
42
+ readOnlyHint: false,
43
+ destructiveHint: true,
44
+ idempotentHint: false,
45
+ openWorldHint: true,
46
+ ...options.annotations,
47
+ ...(options.savedChains ? { readOnlyHint: false } : {}),
48
+ },
49
+ _meta: {
50
+ ui: { resourceUri: options.resourceUri, visibility: ["model"] },
51
+ ...{ "openai/outputTemplate": options.resourceUri },
52
+ },
53
+ };
54
+ }
@@ -31,7 +31,7 @@ export type McpUiPermissions = McpUiResourcePermissions;
31
31
  * Shape of an MCP tool call result that may contain UI metadata.
32
32
  *
33
33
  * Structural subset used by the compose collector to extract `_meta.ui`
34
- * without pulling the full `@modelcontextprotocol/sdk` `CallToolResult` type.
34
+ * without pulling the full `@modelcontextprotocol/client` `CallToolResult` type.
35
35
  * Kept compose-local on purpose: the collector is intentionally loose
36
36
  * (`content?: unknown[]`) to accept any SDK shape.
37
37
  *
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../../../../src/src/host/renderer/js/event-bus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAG/E,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAMjE;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,EAAE,qBAAqB,EACjC,KAAK,GAAE,WAAW,CAAC,MAAM,EAAE,2BAA2B,CAAa,GAClE,MAAM,CAkiBR"}
1
+ {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../../../../src/src/host/renderer/js/event-bus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAG/E,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAMjE;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,EAAE,qBAAqB,EACjC,KAAK,GAAE,WAAW,CAAC,MAAM,EAAE,2BAA2B,CAAa,GAClE,MAAM,CAmiBR"}
@@ -127,7 +127,6 @@ export function generateEventBusScript(descriptor, slots = new Map()) {
127
127
  const config = getSlotConfig(slot);
128
128
  const capabilities = {
129
129
  logging: {},
130
- message: { text: {} },
131
130
  experimental: {
132
131
  [COMPONENT_CAPABILITY]: {
133
132
  version: '1',
@@ -513,8 +512,10 @@ export function generateEventBusScript(descriptor, slots = new Map()) {
513
512
  }
514
513
 
515
514
  if (message.method === 'ui/message') {
516
- console.log('[mcp-compose] UI message from slot', sourceSlot, ':', message.params);
517
- ackIfRequested(event.source, message, targetOrigin);
515
+ // Compose ne livre aucun message au modèle : ne jamais acquitter un faux succès.
516
+ if (hasRequestId(message)) {
517
+ respondError(event.source, message.id, -32601, '[mcp-compose] ui/message is not supported', targetOrigin);
518
+ }
518
519
  return;
519
520
  }
520
521
 
@@ -1 +1 @@
1
- {"version":3,"file":"cluster.d.ts","sourceRoot":"","sources":["../../../src/src/runtime/cluster.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAMH,OAAO,KAAK,EACV,UAAU,EACV,aAAa,EAIb,WAAW,EAGZ,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,CA2B/E;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAC/B,OAAO,CAAC,aAAa,CAAC,CAsFxB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EACnC,WAAW,EAAE,MAAM,EAAE,GACpB,UAAU,CAwJZ"}
1
+ {"version":3,"file":"cluster.d.ts","sourceRoot":"","sources":["../../../src/src/runtime/cluster.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAUH,OAAO,KAAK,EACV,UAAU,EACV,aAAa,EAIb,WAAW,EAGZ,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,CA2B/E;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAC/B,OAAO,CAAC,aAAa,CAAC,CAsFxB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EACnC,WAAW,EAAE,MAAM,EAAE,GACpB,UAAU,CAwJZ"}