holon-ui 0.0.1-dev.12 → 0.0.1-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![Docs](https://img.shields.io/badge/docs-holonlabs.ai-blue)](https://holonlabs.ai/docs/)
4
4
 
5
- Typed MCP clients for browser pages: MCP App views, and pages that call MCP servers directly.
5
+ Typed MCP clients for browser pages. One `connect()` serves a page as an MCP Apps view inside a host and as a web page that offers its tools to the browser's agent through WebMCP.
6
6
 
7
7
  ## Install
8
8
 
@@ -17,9 +17,9 @@ npm install -D holon-types typescript
17
17
  npx create-holon-app foo
18
18
  ```
19
19
 
20
- This creates an MCP server with a `greet` tool and a view in `ui/main.ts`.
20
+ This creates an MCP server with a `greet` tool and a page in `ui/main.ts`.
21
21
 
22
- ## Calling your server from a view
22
+ ## Calling your server from the page
23
23
 
24
24
  The server declares the tool's input and output:
25
25
 
@@ -37,33 +37,79 @@ server.registerTool(
37
37
  );
38
38
  ```
39
39
 
40
- The `App` from `#holon-ui` types the server's tools, so a wrong tool name, argument or result is a type error:
40
+ `connect` from `#holon-ui` types the server's tools, so a wrong tool name, argument or result is a type error:
41
41
 
42
42
  ```sh
43
43
  npx holon types check
44
44
  ```
45
45
 
46
46
  ```ts
47
- import { App } from "#holon-ui";
47
+ import { connect } from "#holon-ui";
48
48
 
49
- const view = new App({ name: "foo", version: "0.1.0" });
50
- await view.connect();
49
+ const app = await connect();
51
50
 
52
- const { result } = await view.tools.greet({ name: "Ada" });
51
+ const { result } = await app.tools.greet({ name: "Ada" });
53
52
 
54
- await view.tools.great({ name: "Ada" });
53
+ await app.tools.great({ name: "Ada" });
55
54
  // error TS2551: Property 'great' does not exist on type '{ readonly greet: (input: { name: string; }, options?: ToolCallOptions | undefined) => Promise<{ result: string; }>; }'. Did you mean 'greet'?
56
55
 
57
- await view.tools.greet({ name: 42 });
56
+ await app.tools.greet({ name: 42 });
58
57
  // error TS2322: Type 'number' is not assignable to type 'string'.
59
58
 
60
- await view.tools.greet({});
61
- // error TS2741: Property '"name"' is missing in type '{}' but required in type '{ name: string; }'.
62
-
63
59
  result.toFixed();
64
60
  // error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?
65
61
  ```
66
62
 
63
+ ## Tools that run in the page
64
+
65
+ `connect` offers them to whichever agent is present: the host's agent in an MCP Apps host, the browser's agent through WebMCP on a web page.
66
+
67
+ ```ts
68
+ const app = await connect({
69
+ tools: {
70
+ select_shapes: {
71
+ description: "Select shapes on the board the person is looking at.",
72
+ inputSchema: z.object({ ids: z.array(z.string()) }),
73
+ annotations: { destructiveHint: false, openWorldHint: false },
74
+ execute: ({ ids }) => ({ selected: board.select(ids) }),
75
+ },
76
+ },
77
+ });
78
+ ```
79
+
80
+ `execute` also receives a `signal` that aborts when the agent cancels.
81
+
82
+ On a web page, the browser's agent is also offered the server's tools that the generated clients know, leaving out those whose `_meta.ui.visibility` lacks `"model"` and those that need a file argument. In a host, its agent already has them.
83
+
84
+ ## The call that opened a view
85
+
86
+ In an MCP Apps host, `app.opened` is the tool call that opened the view, with the output its tool returns. On a web page it is `undefined`.
87
+
88
+ ```ts
89
+ const opened = await app.opened;
90
+ if (opened?.tool === "greet") greeting.value = opened.output.result;
91
+ ```
92
+
93
+ Host-only features are on `app.view`, the ext-apps `App`:
94
+
95
+ ```ts
96
+ if (app.view) app.view.onhostcontextchanged = ({ theme }) => { if (theme) document.documentElement.style.colorScheme = theme; };
97
+ ```
98
+
99
+ ## Building the view
100
+
101
+ A view is its own build. Set the `mcp-app` condition in it, and `holon-ui` calls through the host there and over HTTP everywhere else:
102
+
103
+ ```ts
104
+ import { defaultClientConditions, defineConfig } from "vite";
105
+
106
+ export default defineConfig(({ mode }) => ({
107
+ resolve: { conditions: mode === "mcp" ? ["mcp-app", ...defaultClientConditions] : undefined },
108
+ }));
109
+ ```
110
+
111
+ `create-holon-app` sets this up.
112
+
67
113
  ## Community
68
114
 
69
115
  Ask questions and share what you're building on the [Holon Discord](https://discord.gg/jXExyBdy).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "holon-ui",
3
- "version": "0.0.1-dev.12",
4
- "description": "Typed MCP clients for browser views: MCP Apps host bindings and WebMCP tool exposure.",
3
+ "version": "0.0.1-dev.14",
4
+ "description": "Typed MCP clients for browser pages: one connect() for MCP Apps views and WebMCP pages.",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/holon-sh/sdk-ui.git"
@@ -15,20 +15,23 @@
15
15
  "exports": {
16
16
  "./runtime": {
17
17
  "types": "./runtime.d.ts",
18
- "import": "./runtime.mjs"
18
+ "mcp-app": "./runtime.host.mjs",
19
+ "default": "./runtime.web.mjs"
19
20
  }
20
21
  },
21
22
  "files": [
22
- "runtime.mjs",
23
23
  "runtime.d.ts",
24
+ "runtime.host.mjs",
25
+ "runtime.web.mjs",
24
26
  "README.md"
25
27
  ],
26
28
  "scripts": {
27
- "test": "node --test tests/*.test.mjs",
29
+ "test": "node --test --test-timeout=30000 tests/*.test.mjs && node --conditions=mcp-app --test --test-timeout=30000 tests/mcp-app/*.test.mjs",
28
30
  "fixtures": "node scripts/fixtures.mjs"
29
31
  },
30
32
  "dependencies": {
31
- "holon-sh": "^0.0.1-dev.8"
33
+ "@modelcontextprotocol/client": "^2.3.1",
34
+ "holon-sh": "^0.0.1-dev.23"
32
35
  },
33
36
  "peerDependencies": {
34
37
  "@modelcontextprotocol/ext-apps": "^2.0.0"
package/runtime.d.ts CHANGED
@@ -1,20 +1,43 @@
1
- import type { App } from "@modelcontextprotocol/ext-apps";
2
- import type { Binding as EndpointBinding, Identity, Contract, RuntimeClient } from "holon-sh/runtime";
3
- export type { Binding as EndpointBinding, Identity, Contract, RuntimeClient } from "holon-sh/runtime";
1
+ import type { App, AppOptions } from "@modelcontextprotocol/ext-apps";
2
+ import type { StandardSchemaV1, StandardSchemaWithJSON, ToolAnnotations, Transport } from "@modelcontextprotocol/client";
3
+ import type { EndpointBinding, Identity, Contract, RuntimeClient } from "holon-sh/runtime";
4
+ export type { CreateOptions, EndpointBinding, Identity, Contract, RuntimeClient } from "holon-sh/runtime";
4
5
  export type { AuthProvider, CallOptions, CallMetadata, ToolResult, ToolClient } from "holon-sh/runtime";
5
- export { ToolCallError } from "holon-sh/runtime";
6
+ export { bindApps, ToolCallError } from "holon-sh/runtime";
6
7
 
7
- export interface CreateOptions { validator?: (schema: object) => (value: unknown) => boolean }
8
- export declare function bindApps(identity: Identity, contracts: Record<string, Contract | null>, bindings: Record<string, EndpointBinding>, options?: CreateOptions): Readonly<Record<string, RuntimeClient>>;
9
- /** The ext-apps App with the app's own tools and resources typed; calls go through the host that embeds the page. */
10
- export type View = App & Pick<RuntimeClient, "tools" | "resources" | "callTool">;
11
- export declare function appClass(identity: Identity, contracts: Record<string, Contract | null>, own: string): new (info?: ConstructorParameters<typeof App>[0], ...rest: ConstructorParameters<typeof App> extends [unknown, ...infer Rest] ? Rest : never) => View;
12
- export interface ExposeOptions { signal?: AbortSignal; execute?: (name: string, args: Record<string, unknown>) => Promise<unknown> }
13
- export declare function exposeTools(app: Pick<RuntimeClient, "callTool" | "listTools">, options?: ExposeOptions): Promise<boolean>;
14
- export type PageResult<I> = { readonly value: I; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string }> };
15
- export interface PageSchema<I = unknown> { readonly "~standard": { readonly version: 1; readonly vendor: string; readonly types?: { readonly input: unknown; readonly output: I }; readonly validate: (value: unknown) => PageResult<I> | Promise<PageResult<I>>; readonly jsonSchema: { readonly input: (options: { target: "draft-2020-12" }) => object } } }
16
- export type PageInput<S> = S extends PageSchema<infer I> ? I : never;
17
- export interface PageAnnotations { title?: string; readOnlyHint?: boolean; destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean }
18
- export interface PageTool<S extends PageSchema = PageSchema> { description: string; inputSchema: S; annotations?: PageAnnotations; execute: (args: PageInput<S>) => unknown }
19
- export interface PageHost { registerTool(name: string, config: { description: string; inputSchema: PageSchema; annotations?: PageAnnotations }, callback: (args: any, extra: any) => any): { remove(): void } }
20
- export declare function registerPageTools<S extends { [name: string]: PageSchema }>(tools: { [K in keyof S]: PageTool<S[K]> }, options?: { view?: PageHost; signal?: AbortSignal }): Promise<boolean>;
8
+ /** A tool the page declares. It runs in the browser and acts on what the person is looking at. S is its input schema's type. */
9
+ export interface PageTool<S = undefined> {
10
+ /** Shown to the agent. Required and non-empty. */
11
+ description: string;
12
+ /** Validates the agent's arguments, such as a Zod 4 object. Without one the tool takes no arguments. */
13
+ inputSchema?: S & StandardSchemaWithJSON;
14
+ annotations?: ToolAnnotations;
15
+ /** Receives validated input. Returns a JSON value, or a promise of one; throwing reports failure. signal aborts when the agent cancels. */
16
+ execute: (input: S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<S> : Record<string, never>, options: { signal: AbortSignal }) => unknown;
17
+ }
18
+ // S is inferred per tool. A tool without an input schema leaves its slot unknown, so the slots are unconstrained.
19
+ export interface ConnectOptions<S extends Record<string, unknown> = {}> {
20
+ /** Page tools by name, offered to the host's agent in an MCP Apps host and to the browser's agent through WebMCP. */
21
+ tools?: { [K in keyof S]: PageTool<S[K]> };
22
+ /** The ext-apps App's options in an MCP Apps host, and the transport to connect it with; ignored on a web page. */
23
+ view?: AppOptions & { transport?: Transport };
24
+ }
25
+ type Tools<C> = C extends { tools: infer T } ? T : never;
26
+ /** The tool call that opened a view: typed by its tool, or untyped when the host does not say which tool it was. */
27
+ export type Opened<C> =
28
+ | { [K in keyof Tools<C> & string]: Tools<C>[K] extends (input: infer I, ...rest: never[]) => Promise<infer O> ? { tool: K; input: I; output: O } : never }[keyof Tools<C> & string]
29
+ | { tool: undefined; input: Record<string, unknown>; output: unknown };
30
+ /** The page's own app C, called through the host in an MCP Apps view and over HTTP on a web page. close() also unregisters the page's tools and closes the view. */
31
+ export type Page<C> = C & {
32
+ /** The connected ext-apps App in an MCP Apps host; undefined on a web page. */
33
+ readonly view: App | undefined;
34
+ /** In an MCP Apps host, the tool call that opened the view, with the output its tool returns; undefined on a web page. */
35
+ readonly opened: Promise<Opened<C>> | undefined;
36
+ };
37
+ /** connect, narrowed by the generated #holon-ui module to the client C of the project's own app. A page tool cannot take the name of one of the app's tools. */
38
+ export type Connect<C> = <S extends Record<string, unknown> = {}>(options?: ConnectOptions<S> & { tools?: { [K in keyof Tools<C>]?: never } }) => Promise<Page<C>>;
39
+ /** Bind the page to its own app on the surface its build chose, and offer every tool to whichever agent is present. Most pages call the generated connect from #holon-ui. */
40
+ export declare function connect<S extends Record<string, unknown> = {}>(
41
+ app: { identity: Identity; contracts: Record<string, Contract | null>; own: string; /** The app's MCP endpoint on the page's origin, such as "/mcp/checkout". */ endpoint: string },
42
+ options?: ConnectOptions<S>,
43
+ ): Promise<Page<RuntimeClient>>;
@@ -0,0 +1,59 @@
1
+ // holon-ui/runtime for an MCP Apps view in a host's iframe: package.json resolves to it under the mcp-app condition,
2
+ // which the view's build sets. The host is the app's MCP client, so its agent already has the app's tools: the view
3
+ // offers it only the page's own tools, and calls its app through the host.
4
+ // https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#standard-mcp-messages
5
+ import { App } from "@modelcontextprotocol/ext-apps";
6
+ import { bindApps, ToolCallError } from "holon-sh/runtime";
7
+
8
+ export { bindApps, ToolCallError };
9
+
10
+ export async function connect({ identity, contracts, own }, { tools = {}, view: { transport, ...options } = {} } = {}) {
11
+ const bind = session => bindApps(identity, contracts, { [own]: { session } })[own];
12
+ const app = new App({ name: identity.name, version: identity.version }, {}, options);
13
+ // Registered before connecting, so the view declares the tools capability in ui/initialize.
14
+ for (const [name, { description, inputSchema, annotations, execute }] of Object.entries(tools)) {
15
+ const run = async (input, { mcpReq: { signal } }) => {
16
+ try {
17
+ return toolResult(await execute(input, { signal }));
18
+ } catch (error) {
19
+ // A tool's own failure is a result the agent can read, not a protocol error.
20
+ // https://modelcontextprotocol.io/specification/2026-07-28/server/tools#error-handling
21
+ return { isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] };
22
+ }
23
+ };
24
+ // ext-apps validates input against inputSchema first, and calls a tool without one with the request context alone.
25
+ app.registerTool(name, { description, inputSchema, annotations }, inputSchema ? run : extra => run({}, extra));
26
+ }
27
+ // The host sends the call that opened the view once, right after the handshake, so listen before connecting.
28
+ // https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#data-passing
29
+ const delivered = new Promise((resolve, reject) => {
30
+ let input = {};
31
+ app.addEventListener("toolinput", params => { input = params.arguments ?? {}; });
32
+ app.addEventListener("toolresult", result => resolve({ input, result }));
33
+ app.addEventListener("toolcancelled", ({ reason }) => reject(new Error(`The tool call that opened the view was cancelled${reason ? `: ${reason}` : "."}`)));
34
+ });
35
+ await app.connect(transport);
36
+ // Replaying the delivered result through the app's own client gives exactly what calling the tool would have: the
37
+ // same output validation and ToolCallError. When the host does not say which tool it was, the call comes as delivered.
38
+ // https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#host-context-in-mcpuiinitializeresult
39
+ const opened = delivered.then(async ({ input, result }) => {
40
+ const tool = app.getHostContext()?.toolInfo?.tool.name;
41
+ const replay = tool && bind({ callTool: async () => result }).tools[tool];
42
+ return replay ? { tool, input, output: await replay(input) } : { tool: undefined, input, output: result };
43
+ });
44
+ // A page that never reads opened must not see an unhandled rejection.
45
+ opened.catch(() => {});
46
+ const client = bind({
47
+ callTool: (request, { signal, timeout }) => app.callServerTool(request, { signal, timeout }),
48
+ readResource: (request, { signal, timeout }) => app.readServerResource(request, { signal, timeout }),
49
+ listTools: async () => { throw new Error("An MCP Apps host owns the tool catalog, so a view cannot list tools."); },
50
+ });
51
+ // Closing the view removes its tools from the host.
52
+ return Object.freeze({ ...client, view: app, opened, close: () => app.close() });
53
+ }
54
+
55
+ function toolResult(value) {
56
+ if (value === undefined) return { content: [] };
57
+ const structured = typeof value === "object" && value !== null && !Array.isArray(value);
58
+ return { content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(structured && { structuredContent: value }) };
59
+ }
@@ -0,0 +1,91 @@
1
+ // holon-ui/runtime for a web page, a document of its own: package.json resolves to it unless the build sets mcp-app.
2
+ // The page calls its app over HTTP, and the browser's agent, if any, learns every tool through WebMCP, because nothing
3
+ // else tells it about them. https://webmachinelearning.github.io/webmcp/#dom-document-modelcontext
4
+ import { getDisplayName } from "@modelcontextprotocol/client";
5
+ import { bindApps, ToolCallError } from "holon-sh/runtime";
6
+
7
+ export { bindApps, ToolCallError };
8
+
9
+ export async function connect({ identity, contracts, own, endpoint }, { tools = {} } = {}) {
10
+ const client = bindApps(identity, contracts, { [own]: { endpoint: new URL(endpoint, location.origin) } })[own];
11
+ const lifetime = new AbortController();
12
+ const context = globalThis.document?.modelContext;
13
+ // Offering tools is secondary to the page working: the page does not wait for it, and a failure is only reported.
14
+ // Aborting the lifetime unregisters every tool. https://webmachinelearning.github.io/webmcp/#dom-modelcontext-registertool
15
+ if (context) {
16
+ const { signal } = lifetime;
17
+ const offer = tool => context.registerTool(tool, { signal }).catch(error => console.warn(`WebMCP did not accept the tool ${tool.name}:`, error));
18
+ for (const [name, tool] of Object.entries(tools)) offer(pageTool(name, tool));
19
+ const contracted = name => !contracts[own] || contracts[own].tools.some(tool => tool.name === name);
20
+ client.listTools({ signal }).then(
21
+ ({ tools: listed }) => {
22
+ for (const tool of listed) {
23
+ // MCP Apps: a tool whose visibility omits "model" must not reach the agent; absent means ["model", "app"].
24
+ // https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery
25
+ // A typed client calls only its contract's tools, and an agent cannot write a file argument.
26
+ const inputSchema = withoutFiles(tool.inputSchema);
27
+ if ((tool._meta?.ui?.visibility ?? ["model"]).includes("model") && contracted(tool.name) && inputSchema) offer(serverTool(own, client, tool, inputSchema));
28
+ }
29
+ },
30
+ error => signal.aborted || console.warn(`Could not list the tools of ${own} for WebMCP:`, error),
31
+ );
32
+ }
33
+ return Object.freeze({ ...client, view: undefined, opened: undefined, close: async () => { lifetime.abort(); await client.close(); } });
34
+ }
35
+
36
+ function pageTool(name, { description, inputSchema, annotations, execute }) {
37
+ const standard = inputSchema?.["~standard"];
38
+ return {
39
+ name, title: annotations?.title, description, annotations: hints(annotations),
40
+ inputSchema: standard?.jsonSchema.input({ target: "draft-2020-12" }),
41
+ execute: async (input, { signal }) => {
42
+ if (!standard) return execute({}, { signal });
43
+ const parsed = await standard.validate(input);
44
+ if (parsed.issues) throw new Error(`Invalid arguments for ${name}: ${JSON.stringify(parsed.issues)}`);
45
+ return execute(parsed.value, { signal });
46
+ },
47
+ };
48
+ }
49
+
50
+ function serverTool(own, client, tool, inputSchema) {
51
+ return {
52
+ // MCP lets a tool go without a description; WebMCP requires one.
53
+ name: tool.name, title: tool.title ?? tool.annotations?.title, description: tool.description || getDisplayName(tool),
54
+ inputSchema, outputSchema: tool.outputSchema, annotations: hints(tool.annotations),
55
+ execute: async (input, { signal }) => {
56
+ const result = await client.callTool({ name: tool.name, arguments: input }, { signal });
57
+ // An agent can only supply arguments, so it cannot answer a question the server asks back.
58
+ if (result.resultType === "input_required" || result.isError) throw new ToolCallError(own, tool.name, result);
59
+ return result.structuredContent ?? result.content;
60
+ },
61
+ };
62
+ }
63
+
64
+ // MCP's hints default to the cautious reading (not read-only, destructive, open-world); WebMCP's all default to false.
65
+ // So each MCP hint is read with its own default, then translated, and an unannotated tool stays consequential.
66
+ // https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations
67
+ // https://webmachinelearning.github.io/webmcp/#dictdef-toolannotations
68
+ function hints(annotations) {
69
+ const readOnlyHint = annotations?.readOnlyHint === true;
70
+ return { readOnlyHint, consequentialHint: !readOnlyHint && annotations?.destructiveHint !== false, untrustedContentHint: annotations?.openWorldHint !== false };
71
+ }
72
+
73
+ const hasFile = node => Array.isArray(node) ? node.some(hasFile) : typeof node === "object" && node !== null && ("x-mcp-file" in node || Object.values(node).some(hasFile));
74
+
75
+ // An agent writes arguments as tokens, so it is not shown a file argument (x-mcp-file): an anyOf or oneOf branch that
76
+ // holds one is left out, and a tool that still has one is not exposed.
77
+ // https://github.com/modelcontextprotocol/experimental-ext-file-uploads/blob/main/specification/draft/file-uploads.md#file-arguments
78
+ function withoutFiles(schema) {
79
+ const prune = node => {
80
+ if (Array.isArray(node)) return node.map(prune);
81
+ if (typeof node !== "object" || node === null) return node;
82
+ const pruned = Object.fromEntries(Object.entries(node).map(([key, value]) => [key, prune(value)]));
83
+ for (const key of ["anyOf", "oneOf"]) {
84
+ const kept = Array.isArray(pruned[key]) ? pruned[key].filter(branch => !hasFile(branch)) : [];
85
+ if (kept.length) pruned[key] = kept;
86
+ }
87
+ return pruned;
88
+ };
89
+ const pruned = prune(schema);
90
+ return hasFile(pruned) ? undefined : pruned;
91
+ }
package/runtime.mjs DELETED
@@ -1,91 +0,0 @@
1
- import { App } from "@modelcontextprotocol/ext-apps";
2
- import { bindApps, ToolCallError } from "holon-sh/runtime";
3
-
4
- export { bindApps, ToolCallError };
5
-
6
- // appClass returns the ext-apps App with the app's own tools and resources (contracts[own]) typed.
7
- // Calls go through the host that embeds the page, so connect the App first, as with any App.
8
- // Unless told otherwise, the page introduces itself to the host as the app.
9
- export function appClass(identity, contracts, own) {
10
- return class extends App {
11
- constructor(info = { name: identity.name, version: identity.version }, ...rest) { super(info, ...rest); }
12
- #client = bindApps(identity, { [own]: contracts[own] }, { [own]: {} }, {
13
- session: () => ({
14
- callTool: (request, { signal, timeout } = {}) => this.callServerTool(request, { signal, timeout }),
15
- readResource: (request, { signal, timeout } = {}) => this.readServerResource(request, { signal, timeout }),
16
- listTools: () => { throw new Error("The host owns the tool catalog; bind an endpoint to list tools."); },
17
- }),
18
- })[own];
19
- get tools() { return this.#client.tools; }
20
- get resources() { return this.#client.resources; }
21
- callTool(request, options) { return this.#client.callTool(request, options); }
22
- };
23
- }
24
-
25
- const hasFile = node => Array.isArray(node) ? node.some(hasFile) : typeof node === "object" && node !== null && ("x-mcp-file" in node || Object.values(node).some(hasFile));
26
-
27
- // An agent writes arguments as tokens, so it is not shown a file argument (x-mcp-file): an anyOf or oneOf branch that
28
- // holds one is left out, and a tool that still has one is not exposed.
29
- // https://github.com/modelcontextprotocol/experimental-ext-file-uploads/blob/main/specification/draft/file-uploads.md#file-arguments
30
- function withoutFiles(schema) {
31
- const prune = node => {
32
- if (Array.isArray(node)) return node.map(prune);
33
- if (typeof node !== "object" || node === null) return node;
34
- const pruned = Object.fromEntries(Object.entries(node).map(([key, value]) => [key, prune(value)]));
35
- for (const key of ["anyOf", "oneOf"]) {
36
- const kept = Array.isArray(pruned[key]) ? pruned[key].filter(branch => !hasFile(branch)) : [];
37
- if (kept.length) pruned[key] = kept;
38
- }
39
- return pruned;
40
- };
41
- const pruned = hasFile(schema) ? prune(schema) : schema;
42
- return hasFile(pruned) ? undefined : pruned;
43
- }
44
-
45
- export async function exposeTools(app, options = {}) {
46
- const context = globalThis.document?.modelContext ?? globalThis.navigator?.modelContext;
47
- if (!context) return false;
48
- const { signal } = options;
49
- const execute = options.execute ?? (async (name, args) => {
50
- const result = await app.callTool({ name, arguments: args }, { signal });
51
- // An agent can only supply arguments, so it cannot answer. A custom execute can.
52
- if (result.resultType === "input_required") throw new ToolCallError("page", name, result);
53
- const { downloads, ...shown } = result;
54
- return shown;
55
- });
56
- const { tools } = await app.listTools({ signal });
57
- for (const tool of tools) {
58
- // MCP Apps: a tool whose visibility omits "model" must not reach the agent; absent means ["model", "app"].
59
- // https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery
60
- if (!(tool._meta?.ui?.visibility ?? ["model"]).includes("model")) continue;
61
- const inputSchema = withoutFiles(tool.inputSchema);
62
- if (!inputSchema) continue;
63
- await context.registerTool({
64
- name: tool.name, title: tool.title, description: tool.description ?? "", inputSchema, annotations: tool.annotations,
65
- execute: args => execute(tool.name, args ?? {}),
66
- }, { signal });
67
- }
68
- return true;
69
- }
70
-
71
- export async function registerPageTools(tools, { view, signal } = {}) {
72
- const context = globalThis.document?.modelContext ?? globalThis.navigator?.modelContext;
73
- const removals = [];
74
- for (const [name, { description, inputSchema, annotations, execute }] of Object.entries(tools)) {
75
- if (view) {
76
- removals.push(view.registerTool(name, { description, inputSchema, annotations }, args => execute(args)).remove);
77
- } else if (context) {
78
- const standard = inputSchema["~standard"];
79
- await context.registerTool({
80
- name, description, annotations, inputSchema: standard.jsonSchema.input({ target: "draft-2020-12" }),
81
- execute: async args => {
82
- const parsed = await standard.validate(args ?? {});
83
- if (parsed.issues) throw new Error(`Invalid arguments for ${name}: ${JSON.stringify(parsed.issues)}`);
84
- return execute(parsed.value);
85
- },
86
- }, { signal });
87
- }
88
- }
89
- signal?.addEventListener("abort", () => { for (const remove of removals) remove(); }, { once: true });
90
- return Boolean(view || context);
91
- }