holon-ui 0.0.1-dev.3 → 0.0.1-dev.31
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 +67 -103
- package/dist/page.d.ts +86 -0
- package/dist/page.js +1 -0
- package/dist/runtime.host.d.ts +4 -0
- package/dist/runtime.host.js +67 -0
- package/dist/runtime.web.d.ts +6 -0
- package/dist/runtime.web.js +138 -0
- package/dist/vite.d.ts +3 -0
- package/dist/vite.js +44 -0
- package/package.json +22 -24
- package/generated/holon-generated.json +0 -4
- package/generated/index.d.ts +0 -12
- package/generated/index.js +0 -4
- package/runtime.d.ts +0 -21
- package/runtime.mjs +0 -73
package/README.md
CHANGED
|
@@ -1,149 +1,113 @@
|
|
|
1
1
|
# holon-ui
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://holonlabs.ai/docs/)
|
|
4
4
|
|
|
5
|
-
`holon-ui`
|
|
5
|
+
`holon-ui` lets a browser page call your MCP server's tools, with type checking. The same page runs in two places. Inside an MCP Apps host, it appears next to a tool's result. On the open web, it is a regular page that can offer tools to the browser's AI agent through WebMCP.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
|
-
In the app's root directory, next to its `server.json`:
|
|
10
|
-
|
|
11
9
|
```sh
|
|
12
|
-
npm install holon-ui
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
Declare `holon-ui` in the app root's `package.json` even when the view's sources live in a subdirectory: `holon types generate` writes browser clients into `node_modules/holon-ui/generated/` whenever that `package.json` declares `holon-ui` (and into `holon-sh` as well when it declares both).
|
|
16
|
-
|
|
17
|
-
## The generated module
|
|
18
|
-
|
|
19
|
-
```typescript
|
|
20
|
-
import { App, ToolCallError, createApps, exposeTools, registerPageTools, type Inputs, type Outputs, type Resources } from "holon-ui";
|
|
10
|
+
npm install holon-ui
|
|
11
|
+
npm install -D holon-types typescript vite
|
|
21
12
|
```
|
|
22
13
|
|
|
23
|
-
|
|
24
|
-
|---|---|
|
|
25
|
-
| `App` | The `App` from `@modelcontextprotocol/ext-apps` with your own server's `tools`, `resources` and `callTool` typed. Calls go through the host that embeds the page. |
|
|
26
|
-
| `createApps(bindings, options?)` | Clients for servers you reach by endpoint, keyed like `bindings`. |
|
|
27
|
-
| `ToolCallError` | Thrown by `tools.<tool>` when a tool reports an error or asks for more input. |
|
|
28
|
-
| `exposeTools(client, options?)` | Registers a client's tools with the page's WebMCP agent. |
|
|
29
|
-
| `registerPageTools(tools, options?)` | Registers tools implemented by the page itself. |
|
|
30
|
-
| `Inputs`, `Outputs`, `Resources` | Argument, result and resource value types, as `Inputs["dep"]["tool"]`. |
|
|
31
|
-
|
|
32
|
-
Your own server appears under the last segment of its `server.json` name, e.g. `example.com/checkout` → `checkout`: `Inputs["checkout"]`, `Outputs["checkout"]`, and `createApps({ checkout: { endpoint } })` for a standalone page. Every other key is a dependency declared in `server.json`.
|
|
33
|
-
|
|
34
|
-
## Bind a client
|
|
35
|
-
|
|
36
|
-
### Inside an MCP Apps host
|
|
37
|
-
|
|
38
|
-
A view embedded in an MCP Apps host calls its own server through the host, which owns the connection and the credentials. Construct and connect `App` exactly as you would the one from `@modelcontextprotocol/ext-apps`; it is that class with typed members added:
|
|
14
|
+
## Create an app
|
|
39
15
|
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const view = new App({ name: "checkout-view", version: "1.0.0" });
|
|
44
|
-
view.ontoolresult = ({ structuredContent }) => render(structuredContent);
|
|
45
|
-
await view.connect();
|
|
46
|
-
|
|
47
|
-
const { total } = await view.tools.total({ id: "A-1" });
|
|
16
|
+
```sh
|
|
17
|
+
npx create-holon-app foo
|
|
48
18
|
```
|
|
49
19
|
|
|
50
|
-
|
|
20
|
+
This creates an MCP server with a `greet` tool and a page in `ui/main.ts`.
|
|
51
21
|
|
|
52
|
-
|
|
22
|
+
## Calling your server from the page
|
|
53
23
|
|
|
54
|
-
|
|
55
|
-
const apps = createApps({
|
|
56
|
-
checkout: { endpoint: new URL("/mcp", location.origin) },
|
|
57
|
-
orders: { endpoint: "https://orders.example.com/mcp" },
|
|
58
|
-
});
|
|
24
|
+
The server declares the tool's input and output:
|
|
59
25
|
|
|
60
|
-
|
|
26
|
+
```ts
|
|
27
|
+
server.registerTool(
|
|
28
|
+
"greet",
|
|
29
|
+
{
|
|
30
|
+
inputSchema: z.strictObject({ name: z.string() }),
|
|
31
|
+
outputSchema: z.strictObject({ result: z.string() }),
|
|
32
|
+
},
|
|
33
|
+
({ name }) => {
|
|
34
|
+
const output = { result: `Hello, ${name}!` };
|
|
35
|
+
return { content: [{ type: "text", text: output.result }], structuredContent: output };
|
|
36
|
+
},
|
|
37
|
+
);
|
|
61
38
|
```
|
|
62
39
|
|
|
63
|
-
|
|
40
|
+
The page connects and calls it. `holon types check` checks those calls against the server's tools, so a wrong tool name, argument, or result type fails the check:
|
|
64
41
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
```typescript
|
|
68
|
-
const { shipped } = await apps.orders.tools.ship({ id: "A-1" }, {
|
|
69
|
-
elicit: async params => ({ action: "accept", content: await showForm(params) }),
|
|
70
|
-
});
|
|
42
|
+
```sh
|
|
43
|
+
npx holon types check
|
|
71
44
|
```
|
|
72
45
|
|
|
73
|
-
|
|
46
|
+
```ts
|
|
47
|
+
import { connect } from "#holon-ui";
|
|
74
48
|
|
|
75
|
-
|
|
49
|
+
const app = await connect();
|
|
76
50
|
|
|
77
|
-
|
|
51
|
+
const { result } = await app.tools.greet({ name: "Ada" });
|
|
78
52
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const lifetime = new AbortController();
|
|
83
|
-
await apps.orders.resources["orders://summary"].watch(value => render(value.open), { signal: lifetime.signal });
|
|
84
|
-
```
|
|
53
|
+
await app.tools.great({ name: "Ada" });
|
|
54
|
+
// error TS2551: Property 'great' does not exist on type '{ ... }'. Did you mean 'greet'?
|
|
85
55
|
|
|
86
|
-
|
|
56
|
+
await app.tools.greet({ name: 42 });
|
|
57
|
+
// error TS2322: Type 'number' is not assignable to type 'string'.
|
|
87
58
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
`exposeTools` registers the tools of an endpoint-bound client with the page's WebMCP context (`navigator.modelContext`), except those whose `_meta.ui.visibility` omits `"model"`. Calls from the agent go through the client, so they are validated. An agent can only supply arguments, so a question reaches it as a failed call naming the question; to answer for it, pass an `execute` that calls `callTool` with `elicit`. It returns `false` when the browser has no WebMCP context.
|
|
91
|
-
|
|
92
|
-
```typescript
|
|
93
|
-
await exposeTools(apps.orders, { signal: lifetime.signal });
|
|
59
|
+
result.toFixed();
|
|
60
|
+
// error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?
|
|
94
61
|
```
|
|
95
62
|
|
|
96
|
-
|
|
63
|
+
## Tools that run in the page
|
|
97
64
|
|
|
98
|
-
|
|
99
|
-
import { z } from "zod";
|
|
65
|
+
A page can define its own tools for an AI agent to use, such as selecting shapes on a board the person is looking at. `connect` offers them to whichever agent is present, the host's agent or the browser's:
|
|
100
66
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
},
|
|
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
|
+
outputSchema: z.object({ selected: z.array(z.string()) }),
|
|
74
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
75
|
+
execute: ({ ids }) => ({ selected: board.select(ids) }),
|
|
110
76
|
},
|
|
111
77
|
},
|
|
112
|
-
|
|
113
|
-
);
|
|
78
|
+
});
|
|
114
79
|
```
|
|
115
80
|
|
|
116
|
-
|
|
81
|
+
On a web page, the browser's agent can also use your server's tools. Inside a host, the host's agent already has them.
|
|
117
82
|
|
|
118
|
-
The
|
|
83
|
+
## The call that opened a view
|
|
119
84
|
|
|
120
|
-
|
|
121
|
-
// vite.config.ts
|
|
122
|
-
import { defineConfig } from "vite";
|
|
123
|
-
import { viteSingleFile } from "vite-plugin-singlefile";
|
|
85
|
+
Inside an MCP Apps host, a page opens because a tool ran. `app.opened` is that tool call and its result. On a web page it is `undefined`.
|
|
124
86
|
|
|
125
|
-
|
|
87
|
+
```ts
|
|
88
|
+
const opened = await app.opened;
|
|
89
|
+
if (opened?.tool === "greet") greeting.value = opened.output.result;
|
|
126
90
|
```
|
|
127
91
|
|
|
128
|
-
|
|
129
|
-
npm install --save-dev vite vite-plugin-singlefile
|
|
130
|
-
npm install @modelcontextprotocol/ext-apps
|
|
131
|
-
npx vite build
|
|
132
|
-
```
|
|
92
|
+
Features that only exist inside a host are on `app.view`:
|
|
133
93
|
|
|
134
|
-
|
|
94
|
+
```ts
|
|
95
|
+
if (app.view) app.view.onhostcontextchanged = ({ theme }) => { if (theme) document.documentElement.style.colorScheme = theme; };
|
|
96
|
+
```
|
|
135
97
|
|
|
136
|
-
##
|
|
98
|
+
## Building the page
|
|
137
99
|
|
|
138
|
-
`holon-ui/
|
|
100
|
+
`holon-ui/vite` builds the page twice in one `vite build`, once as a web page and once as a single-file view for MCP Apps hosts:
|
|
139
101
|
|
|
140
|
-
|
|
102
|
+
```ts
|
|
103
|
+
import { defineConfig } from "vite";
|
|
104
|
+
import { holon } from "holon-ui/vite";
|
|
141
105
|
|
|
142
|
-
|
|
143
|
-
npm ci
|
|
144
|
-
npm test
|
|
106
|
+
export default defineConfig({ plugins: [holon()] });
|
|
145
107
|
```
|
|
146
108
|
|
|
147
|
-
|
|
109
|
+
`create-holon-app` sets this up for you.
|
|
110
|
+
|
|
111
|
+
## Community
|
|
148
112
|
|
|
149
|
-
[
|
|
113
|
+
Ask questions and share what you're building on the [Holon Discord](https://discord.gg/jXExyBdy).
|
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { App, AppOptions } from "@modelcontextprotocol/ext-apps";
|
|
2
|
+
import type { StandardSchemaV1, StandardSchemaWithJSON, ToolAnnotations } from "@modelcontextprotocol/client";
|
|
3
|
+
import type { EndpointBinding, Identity, Contract, RuntimeClient, SessionClient, ToolClient } from "holon-sh/runtime";
|
|
4
|
+
export type { CreateOptions, EndpointBinding, Identity, Contract, RuntimeClient } from "holon-sh/runtime";
|
|
5
|
+
export type { AuthProvider, CallOptions, CallMetadata, ToolResult, ToolClient } from "holon-sh/runtime";
|
|
6
|
+
/** A tool the page declares. It runs in the browser and acts on what the person is looking at. S and O are its input and output schemas' types. */
|
|
7
|
+
export interface PageTool<S = undefined, O = undefined> {
|
|
8
|
+
/** Shown to the agent. Required and non-empty. */
|
|
9
|
+
description: string;
|
|
10
|
+
/** Validates the agent's arguments, such as a Zod 4 object. Without one the tool takes no arguments. */
|
|
11
|
+
inputSchema?: S & StandardSchemaWithJSON;
|
|
12
|
+
/** Describes and validates the object execute returns, such as a Zod 4 object. */
|
|
13
|
+
outputSchema?: O & 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: {
|
|
17
|
+
signal: AbortSignal;
|
|
18
|
+
}): O extends StandardSchemaV1 ? StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>> : unknown;
|
|
19
|
+
}
|
|
20
|
+
export interface AnyPageTool {
|
|
21
|
+
description: string;
|
|
22
|
+
inputSchema?: StandardSchemaWithJSON;
|
|
23
|
+
outputSchema?: StandardSchemaWithJSON;
|
|
24
|
+
annotations?: ToolAnnotations;
|
|
25
|
+
execute(input: unknown, options: {
|
|
26
|
+
signal: AbortSignal;
|
|
27
|
+
}): unknown;
|
|
28
|
+
}
|
|
29
|
+
export interface ConnectOptions<S extends Record<string, unknown> = {}, O extends Record<string, unknown> = {}> {
|
|
30
|
+
/** Page tools by name, offered to the host's agent in an MCP Apps host and to the browser's agent through WebMCP. */
|
|
31
|
+
tools?: {
|
|
32
|
+
[K in keyof S]: PageTool<S[K], O[K & keyof O]>;
|
|
33
|
+
} & {
|
|
34
|
+
[K in keyof O]: {
|
|
35
|
+
outputSchema?: O[K] & StandardSchemaWithJSON;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
/** On a web page, also offer call_tools, which runs several of the other offered tools in one call. Ignored in an MCP Apps host, whose agent calls the app's tools itself. */
|
|
39
|
+
batch?: "call_tools" extends keyof S ? false : boolean;
|
|
40
|
+
/** The ext-apps App's options in an MCP Apps host, and the transport to connect it with; ignored on a web page. */
|
|
41
|
+
view?: AppOptions & {
|
|
42
|
+
transport?: Parameters<App["connect"]>[0];
|
|
43
|
+
};
|
|
44
|
+
/** The app's binding on a web page, in place of the generated one; its endpoint resolves against the page's origin. Ignored in an MCP Apps host. */
|
|
45
|
+
web?: EndpointBinding;
|
|
46
|
+
}
|
|
47
|
+
type Client = ToolClient<any, any, any, any>;
|
|
48
|
+
/** The tool call that opened a view: typed by its tool, or untyped when the host does not say which tool it was. */
|
|
49
|
+
export type Opened<C extends Client> = {
|
|
50
|
+
[K in keyof C["tools"] & string]: C["tools"][K] extends (input: infer I, ...rest: never[]) => Promise<infer O> ? {
|
|
51
|
+
tool: K;
|
|
52
|
+
input: I;
|
|
53
|
+
output: O;
|
|
54
|
+
} : never;
|
|
55
|
+
}[keyof C["tools"] & string] | {
|
|
56
|
+
tool: undefined;
|
|
57
|
+
input: Record<string, unknown>;
|
|
58
|
+
output: unknown;
|
|
59
|
+
};
|
|
60
|
+
/** The page's own app C, as a view in an MCP Apps host or as a web page, told apart by view. Only a web page can list the app's tools, watch a resource or subscribe to events. close() also unregisters the page's tools and closes the view. */
|
|
61
|
+
export type Page<C extends Client> = (SessionClient<C> & {
|
|
62
|
+
close(): Promise<void>;
|
|
63
|
+
/** The connected ext-apps App, for host-only features. */
|
|
64
|
+
readonly view: App;
|
|
65
|
+
/** The tool call that opened the view, with the output its tool returns. */
|
|
66
|
+
readonly opened: Promise<Opened<C>>;
|
|
67
|
+
}) | (C & {
|
|
68
|
+
/** Undefined on a web page. */
|
|
69
|
+
readonly view: undefined;
|
|
70
|
+
readonly opened: undefined;
|
|
71
|
+
});
|
|
72
|
+
/** 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. */
|
|
73
|
+
export type Connect<C extends Client> = <S extends Record<string, unknown> = {}, O extends Record<string, unknown> = {}>(options?: ConnectOptions<S, O> & {
|
|
74
|
+
tools?: {
|
|
75
|
+
[K in keyof C["tools"]]?: never;
|
|
76
|
+
};
|
|
77
|
+
batch?: "call_tools" extends keyof C["tools"] ? false : boolean;
|
|
78
|
+
}) => Promise<Page<C>>;
|
|
79
|
+
export interface OwnApp {
|
|
80
|
+
identity: Identity;
|
|
81
|
+
contracts: Record<string, Contract | null>;
|
|
82
|
+
own: string;
|
|
83
|
+
/** The app's MCP endpoint on the page's origin, such as "/mcp/checkout". */
|
|
84
|
+
endpoint: string;
|
|
85
|
+
}
|
|
86
|
+
export type Runtime = <S extends Record<string, unknown> = {}, O extends Record<string, unknown> = {}>(app: OwnApp, options?: ConnectOptions<S, O>) => Promise<Page<RuntimeClient>>;
|
package/dist/page.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,67 @@
|
|
|
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
|
+
export { bindApps, ToolCallError };
|
|
8
|
+
export const connect = async ({ identity, contracts, own }, { tools = {}, view: { transport, ...options } = {} } = {}) => {
|
|
9
|
+
const bind = (session) => bindApps(identity, contracts, { [own]: { session } })[own];
|
|
10
|
+
const app = new App({ name: identity.name, version: identity.version }, {}, options);
|
|
11
|
+
const session = {
|
|
12
|
+
callTool: (request, { signal, timeout } = {}) => app.callServerTool(request, { signal, timeout }),
|
|
13
|
+
readResource: (request, { signal, timeout } = {}) => app.readServerResource(request, { signal, timeout }),
|
|
14
|
+
};
|
|
15
|
+
// Registered before connecting, so the view declares the tools capability in ui/initialize.
|
|
16
|
+
for (const [name, { description, inputSchema, outputSchema, annotations, execute }] of Object.entries(tools)) {
|
|
17
|
+
const output = outputSchema?.["~standard"];
|
|
18
|
+
const run = async (input, { mcpReq: { signal } }) => {
|
|
19
|
+
try {
|
|
20
|
+
const result = await execute(input, { signal });
|
|
21
|
+
const checked = output ? await output.validate(result) : { value: result };
|
|
22
|
+
if (checked.issues)
|
|
23
|
+
throw new Error(`Invalid output for ${name}: ${JSON.stringify(checked.issues)}`);
|
|
24
|
+
return toolResult(checked.value);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
// A tool's own failure is a result the agent can read, not a protocol error.
|
|
28
|
+
// https://modelcontextprotocol.io/specification/2026-07-28/server/tools#error-handling
|
|
29
|
+
return { isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] };
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
// ext-apps validates input against inputSchema first, and calls a tool without one with the request context alone.
|
|
33
|
+
const listed = output && { "~standard": { ...output, validate: (value) => ({ value }) } };
|
|
34
|
+
if (inputSchema)
|
|
35
|
+
app.registerTool(name, { description, inputSchema, outputSchema: listed, annotations }, run);
|
|
36
|
+
else
|
|
37
|
+
app.registerTool(name, { description, outputSchema: listed, annotations }, extra => run({}, extra));
|
|
38
|
+
}
|
|
39
|
+
// The host sends the call that opened the view once, right after the handshake, so listen before connecting.
|
|
40
|
+
// https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#data-passing
|
|
41
|
+
const delivered = new Promise((resolve, reject) => {
|
|
42
|
+
let input = {};
|
|
43
|
+
app.addEventListener("toolinput", params => { input = params.arguments ?? {}; });
|
|
44
|
+
app.addEventListener("toolresult", result => resolve({ input, result }));
|
|
45
|
+
app.addEventListener("toolcancelled", ({ reason }) => reject(new Error(`The tool call that opened the view was cancelled${reason ? `: ${reason}` : "."}`)));
|
|
46
|
+
});
|
|
47
|
+
await app.connect(transport);
|
|
48
|
+
// Replaying the delivered result through the app's own client gives exactly what calling the tool would have: the
|
|
49
|
+
// same output validation and ToolCallError. When the host does not say which tool it was, the call comes as delivered.
|
|
50
|
+
// https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#host-context-in-mcpuiinitializeresult
|
|
51
|
+
const opened = delivered.then(async ({ input, result }) => {
|
|
52
|
+
const tool = app.getHostContext()?.toolInfo?.tool.name;
|
|
53
|
+
const replay = tool && bind({ ...session, callTool: async () => result }).tools[tool];
|
|
54
|
+
return replay ? { tool, input, output: await replay(input) } : { tool: undefined, input, output: result };
|
|
55
|
+
});
|
|
56
|
+
// A page that never reads opened must not see an unhandled rejection.
|
|
57
|
+
opened.catch(() => { });
|
|
58
|
+
const client = bind(session);
|
|
59
|
+
// Closing the view removes its tools from the host.
|
|
60
|
+
return Object.freeze({ tools: client.tools, callTool: client.callTool, resources: client.resources, view: app, opened, close: () => app.close() });
|
|
61
|
+
};
|
|
62
|
+
function toolResult(value) {
|
|
63
|
+
if (value === undefined)
|
|
64
|
+
return { content: [] };
|
|
65
|
+
const structured = typeof value === "object" && value !== null && !Array.isArray(value);
|
|
66
|
+
return { content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(structured && { structuredContent: value }) };
|
|
67
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { bindApps, ToolCallError } from "holon-sh/runtime";
|
|
2
|
+
import type { Runtime } from "./page.js";
|
|
3
|
+
export { bindApps, ToolCallError };
|
|
4
|
+
export type { AuthProvider, CallMetadata, CallOptions, Connect, ConnectOptions, Contract, CreateOptions, EndpointBinding, Identity, Opened, Page, PageTool, RuntimeClient, ToolClient, ToolResult } from "./page.js";
|
|
5
|
+
/** 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. */
|
|
6
|
+
export declare const connect: Runtime;
|
|
@@ -0,0 +1,138 @@
|
|
|
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 { fromJsonSchema, getDisplayName } from "@modelcontextprotocol/client";
|
|
5
|
+
import { bindApps, ToolCallError } from "holon-sh/runtime";
|
|
6
|
+
export { bindApps, ToolCallError };
|
|
7
|
+
/** 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. */
|
|
8
|
+
export const connect = async ({ identity, contracts, own, endpoint }, { tools = {}, batch = false, web = { endpoint } } = {}) => {
|
|
9
|
+
const client = bindApps(identity, contracts, { [own]: { ...web, endpoint: new URL(web.endpoint, location.origin) } })[own];
|
|
10
|
+
const lifetime = new AbortController();
|
|
11
|
+
const context = globalThis.document?.modelContext;
|
|
12
|
+
// Offering tools is secondary to the page working: the page does not wait for it, and a failure is only reported.
|
|
13
|
+
// Aborting the lifetime unregisters every tool. https://webmachinelearning.github.io/webmcp/#dom-modelcontext-registertool
|
|
14
|
+
if (context) {
|
|
15
|
+
const { signal } = lifetime;
|
|
16
|
+
const offered = new Map();
|
|
17
|
+
const register = (tool) => context.registerTool(tool, { signal }).then(() => true, error => console.warn(`WebMCP did not accept the tool ${tool.name}:`, error));
|
|
18
|
+
const offer = async (tool) => await register(tool) && offered.set(tool.name, tool);
|
|
19
|
+
const offers = Object.entries(tools).map(([name, tool]) => offer(pageTool(name, tool)));
|
|
20
|
+
const listed = client.listTools({ signal }).then(({ tools: listed }) => {
|
|
21
|
+
const contract = contracts[own];
|
|
22
|
+
const contractedNames = contract && new Set(contract.tools.map(tool => tool.name));
|
|
23
|
+
for (const tool of listed) {
|
|
24
|
+
// MCP Apps: a tool whose visibility omits "model" must not reach the agent; absent means ["model", "app"].
|
|
25
|
+
// https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery
|
|
26
|
+
// A typed client calls only its contract's tools, and an agent cannot write a file argument.
|
|
27
|
+
if (!visibleToModel(tool) || (contractedNames && !contractedNames.has(tool.name)))
|
|
28
|
+
continue;
|
|
29
|
+
const inputSchema = withoutFiles(tool.inputSchema);
|
|
30
|
+
if (typeof inputSchema === "object" && inputSchema !== null)
|
|
31
|
+
offers.push(offer(serverTool(own, client, tool, inputSchema)));
|
|
32
|
+
}
|
|
33
|
+
}, error => signal.aborted || console.warn(`Could not list the tools of ${own} for WebMCP:`, error));
|
|
34
|
+
if (batch)
|
|
35
|
+
listed.then(() => Promise.all(offers)).then(() => offered.size > 0 && register(batchTool(offered)));
|
|
36
|
+
}
|
|
37
|
+
return Object.freeze({ ...client, view: undefined, opened: undefined, close: async () => { lifetime.abort(); await client.close(); } });
|
|
38
|
+
};
|
|
39
|
+
function visibleToModel(tool) {
|
|
40
|
+
const ui = tool._meta?.ui;
|
|
41
|
+
const visibility = typeof ui === "object" && ui !== null && "visibility" in ui ? ui.visibility ?? ["model"] : ["model"];
|
|
42
|
+
return Array.isArray(visibility) && visibility.includes("model");
|
|
43
|
+
}
|
|
44
|
+
function pageTool(name, { description, inputSchema, outputSchema, annotations, execute }) {
|
|
45
|
+
const standard = inputSchema?.["~standard"];
|
|
46
|
+
const output = outputSchema?.["~standard"];
|
|
47
|
+
return {
|
|
48
|
+
name, title: annotations?.title, description, annotations: hints(annotations),
|
|
49
|
+
inputSchema: standard?.jsonSchema.input({ target: "draft-2020-12" }),
|
|
50
|
+
outputSchema: output?.jsonSchema.output({ target: "draft-2020-12" }),
|
|
51
|
+
execute: async (input, { signal }) => {
|
|
52
|
+
const parsed = standard ? await standard.validate(input) : { value: {} };
|
|
53
|
+
if (parsed.issues)
|
|
54
|
+
throw new Error(`Invalid arguments for ${name}: ${JSON.stringify(parsed.issues)}`);
|
|
55
|
+
const result = await execute(parsed.value, { signal });
|
|
56
|
+
const checked = output ? await output.validate(result) : { value: result };
|
|
57
|
+
if (checked.issues)
|
|
58
|
+
throw new Error(`Invalid output for ${name}: ${JSON.stringify(checked.issues)}`);
|
|
59
|
+
return checked.value;
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function serverTool(own, client, tool, inputSchema) {
|
|
64
|
+
return {
|
|
65
|
+
// MCP lets a tool go without a description; WebMCP requires one.
|
|
66
|
+
name: tool.name, title: tool.title ?? tool.annotations?.title, description: tool.description || getDisplayName(tool),
|
|
67
|
+
inputSchema, outputSchema: tool.outputSchema, annotations: hints(tool.annotations),
|
|
68
|
+
execute: async (input, { signal }) => {
|
|
69
|
+
const result = await client.callTool({ name: tool.name, arguments: input }, { signal });
|
|
70
|
+
// An agent can only supply arguments, so it cannot answer a question the server asks back.
|
|
71
|
+
if (result.resultType === "input_required" || result.isError)
|
|
72
|
+
throw new ToolCallError(own, tool.name, result);
|
|
73
|
+
return result.structuredContent ?? result.content;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function batchTool(offered) {
|
|
78
|
+
const call = { type: "object", properties: { tool: { enum: [...offered.keys()] }, input: { type: "object" } }, required: ["tool", "input"] };
|
|
79
|
+
const inputSchema = { type: "object", properties: { calls: { type: "array", items: call } }, required: ["calls"] };
|
|
80
|
+
const { validate } = fromJsonSchema(inputSchema)["~standard"];
|
|
81
|
+
const members = Object.fromEntries(offered);
|
|
82
|
+
const hinted = Object.values(members).map(tool => tool.annotations);
|
|
83
|
+
return {
|
|
84
|
+
name: "call_tools",
|
|
85
|
+
description: "Run several of this page's tools in order, in one call. Stops at the first that fails, and returns the outputs before it and its error.",
|
|
86
|
+
inputSchema,
|
|
87
|
+
annotations: {
|
|
88
|
+
readOnlyHint: hinted.every(hint => hint.readOnlyHint),
|
|
89
|
+
consequentialHint: hinted.some(hint => hint.consequentialHint),
|
|
90
|
+
untrustedContentHint: hinted.some(hint => hint.untrustedContentHint),
|
|
91
|
+
},
|
|
92
|
+
execute: async (input, client) => {
|
|
93
|
+
const outputs = [];
|
|
94
|
+
try {
|
|
95
|
+
const parsed = await validate(input);
|
|
96
|
+
if (parsed.issues)
|
|
97
|
+
throw new Error(`Invalid arguments for call_tools: ${JSON.stringify(parsed.issues)}`);
|
|
98
|
+
for (const { tool, input } of parsed.value.calls) {
|
|
99
|
+
client.signal.throwIfAborted();
|
|
100
|
+
outputs.push(await members[tool].execute(input, client));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
return { outputs, error: String(error) };
|
|
105
|
+
}
|
|
106
|
+
return { outputs };
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// MCP's hints default to the cautious reading (not read-only, destructive, open-world); WebMCP's all default to false.
|
|
111
|
+
// So each MCP hint is read with its own default, then translated, and an unannotated tool stays consequential.
|
|
112
|
+
// https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations
|
|
113
|
+
// https://webmachinelearning.github.io/webmcp/#dictdef-toolannotations
|
|
114
|
+
function hints(annotations) {
|
|
115
|
+
const readOnlyHint = annotations?.readOnlyHint === true;
|
|
116
|
+
return { readOnlyHint, consequentialHint: !readOnlyHint && annotations?.destructiveHint !== false, untrustedContentHint: annotations?.openWorldHint !== false };
|
|
117
|
+
}
|
|
118
|
+
const FILE = Symbol("schema requires a file");
|
|
119
|
+
// An agent writes arguments as tokens, so it is not shown a file argument (x-mcp-file): an anyOf or oneOf branch that
|
|
120
|
+
// holds one is left out, and a tool that still has one is not exposed.
|
|
121
|
+
// https://github.com/modelcontextprotocol/experimental-ext-file-uploads/blob/main/specification/draft/file-uploads.md#file-arguments
|
|
122
|
+
function withoutFiles(node, key) {
|
|
123
|
+
if (Array.isArray(node)) {
|
|
124
|
+
const items = node.map(item => withoutFiles(item));
|
|
125
|
+
if (!items.includes(FILE))
|
|
126
|
+
return items;
|
|
127
|
+
if (key !== "anyOf" && key !== "oneOf")
|
|
128
|
+
return FILE;
|
|
129
|
+
const kept = items.filter(item => item !== FILE);
|
|
130
|
+
return kept.length ? kept : FILE;
|
|
131
|
+
}
|
|
132
|
+
if (typeof node !== "object" || node === null)
|
|
133
|
+
return node;
|
|
134
|
+
if (Object.hasOwn(node, "x-mcp-file"))
|
|
135
|
+
return FILE;
|
|
136
|
+
const entries = Object.entries(node).map(([key, value]) => [key, withoutFiles(value, key)]);
|
|
137
|
+
return entries.some(([, value]) => value === FILE) ? FILE : Object.fromEntries(entries);
|
|
138
|
+
}
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { Plugin } from "vite";
|
|
2
|
+
/** Builds the page in ui/index.html twice in one vite build: the web page into dist/web, and into dist/mcp the MCP Apps view, one self-contained HTML file whose holon-ui calls its app through the host. A view that would need a file beside it fails the build. */
|
|
3
|
+
export declare function holon(): Plugin;
|
package/dist/vite.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Builds the page in ui/index.html twice in one vite build: the web page into dist/web, and into dist/mcp the MCP Apps view, one self-contained HTML file whose holon-ui calls its app through the host. A view that would need a file beside it fails the build. */
|
|
2
|
+
export function holon() {
|
|
3
|
+
return {
|
|
4
|
+
name: "holon",
|
|
5
|
+
config: () => ({
|
|
6
|
+
root: "ui",
|
|
7
|
+
base: "./",
|
|
8
|
+
builder: {},
|
|
9
|
+
build: { outDir: "../dist/web", emptyOutDir: true },
|
|
10
|
+
environments: {
|
|
11
|
+
mcp: {
|
|
12
|
+
consumer: "client",
|
|
13
|
+
build: {
|
|
14
|
+
outDir: "../dist/mcp",
|
|
15
|
+
copyPublicDir: false,
|
|
16
|
+
assetsInlineLimit: () => true,
|
|
17
|
+
rolldownOptions: { output: { codeSplitting: false } },
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
}),
|
|
22
|
+
applyToEnvironment: ({ name }) => name === "mcp",
|
|
23
|
+
resolveId: { order: "pre", handler: id => (id === "holon-ui/runtime" ? `${import.meta.dirname}/runtime.host.js` : null) },
|
|
24
|
+
generateBundle: {
|
|
25
|
+
order: "post",
|
|
26
|
+
handler(_, bundle) {
|
|
27
|
+
const { "index.html": page, ...files } = bundle;
|
|
28
|
+
if (page?.type !== "asset" || typeof page.source !== "string")
|
|
29
|
+
return this.error("holon-ui/vite builds the view from ui/index.html");
|
|
30
|
+
for (const [name, file] of Object.entries(files)) {
|
|
31
|
+
const url = page.source.indexOf(`"./${name}"`);
|
|
32
|
+
const inlined = file.type === "chunk"
|
|
33
|
+
? `<script type="module">${file.code.replaceAll("<!--", "\\x3C!--")}`
|
|
34
|
+
: typeof file.source === "string" ? `<style>${file.source.replaceAll("</", "<\\/")}</style>` : undefined;
|
|
35
|
+
if (url < 0 || inlined === undefined)
|
|
36
|
+
this.error(`holon-ui/vite cannot inline ${name} into the view, which a host loads as one HTML file; import a worker with ?worker&inline`);
|
|
37
|
+
const startTag = page.source.slice(page.source.lastIndexOf("<", url), page.source.indexOf(">", url) + 1);
|
|
38
|
+
page.source = page.source.replace(startTag, () => inlined);
|
|
39
|
+
delete bundle[name];
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
package/package.json
CHANGED
|
@@ -1,55 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "holon-ui",
|
|
3
|
-
"version": "0.0.1-dev.
|
|
4
|
-
"description": "Typed MCP clients for browser
|
|
3
|
+
"version": "0.0.1-dev.31",
|
|
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"
|
|
8
8
|
},
|
|
9
9
|
"license": "Apache-2.0",
|
|
10
10
|
"type": "module",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=22"
|
|
13
|
+
},
|
|
11
14
|
"sideEffects": false,
|
|
12
15
|
"publishConfig": {
|
|
13
16
|
"access": "public"
|
|
14
17
|
},
|
|
15
|
-
"holon": {
|
|
16
|
-
"slot": "generated",
|
|
17
|
-
"contractVersion": 1
|
|
18
|
-
},
|
|
19
18
|
"exports": {
|
|
20
|
-
".": {
|
|
21
|
-
"types": "./generated/index.d.ts",
|
|
22
|
-
"import": "./generated/index.js"
|
|
23
|
-
},
|
|
24
19
|
"./runtime": {
|
|
25
|
-
"types": "./runtime.d.ts",
|
|
26
|
-
"
|
|
20
|
+
"types": "./dist/runtime.web.d.ts",
|
|
21
|
+
"mcp-app": "./dist/runtime.host.js",
|
|
22
|
+
"default": "./dist/runtime.web.js"
|
|
23
|
+
},
|
|
24
|
+
"./vite": {
|
|
25
|
+
"types": "./dist/vite.d.ts",
|
|
26
|
+
"default": "./dist/vite.js"
|
|
27
27
|
}
|
|
28
28
|
},
|
|
29
29
|
"files": [
|
|
30
|
-
"
|
|
31
|
-
"runtime.d.ts",
|
|
32
|
-
"generated/",
|
|
30
|
+
"dist",
|
|
33
31
|
"README.md"
|
|
34
32
|
],
|
|
35
33
|
"scripts": {
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"test": "npm run build && node --test tests/*.test.mjs",
|
|
39
|
-
"fixtures": "node scripts/fixtures.mjs"
|
|
34
|
+
"prepack": "tsc",
|
|
35
|
+
"test": "tsc && node --test --test-timeout=30000 tests/*.test.mjs && node --conditions=mcp-app --test --test-timeout=30000 tests/mcp-app/*.test.mjs"
|
|
40
36
|
},
|
|
41
37
|
"dependencies": {
|
|
42
|
-
"
|
|
38
|
+
"@modelcontextprotocol/client": "^2.3.1",
|
|
39
|
+
"holon-sh": "^0.0.1-dev.37"
|
|
43
40
|
},
|
|
44
41
|
"peerDependencies": {
|
|
45
|
-
"@modelcontextprotocol/ext-apps": "
|
|
42
|
+
"@modelcontextprotocol/ext-apps": "^2.0.0"
|
|
46
43
|
},
|
|
47
44
|
"devDependencies": {
|
|
48
|
-
"@modelcontextprotocol/ext-apps": "^
|
|
49
|
-
"@modelcontextprotocol/node": "2.1.
|
|
50
|
-
"@modelcontextprotocol/server": "2.
|
|
45
|
+
"@modelcontextprotocol/ext-apps": "^2.0.4",
|
|
46
|
+
"@modelcontextprotocol/node": "2.1.2",
|
|
47
|
+
"@modelcontextprotocol/server": "2.4.0",
|
|
51
48
|
"@types/node": "^22.0.0",
|
|
52
49
|
"typescript": "~5.9.3",
|
|
50
|
+
"vite": "8.3.8",
|
|
53
51
|
"zod": "4.6.6"
|
|
54
52
|
}
|
|
55
53
|
}
|
package/generated/index.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
// holon-generated-apps-v1 placeholder
|
|
2
|
-
export type Apps = Record<never, never>;
|
|
3
|
-
export type Inputs = Record<never, never>;
|
|
4
|
-
export type Outputs = Record<never, never>;
|
|
5
|
-
export type InputTypes = Inputs;
|
|
6
|
-
export type OutputTypes = Outputs;
|
|
7
|
-
export type Resources = Record<never, never>;
|
|
8
|
-
export { ToolCallError } from "holon-sh/protocol";
|
|
9
|
-
export type { EndpointBinding, CreateOptions } from "../runtime.js";
|
|
10
|
-
export { exposeTools, registerPageTools } from "../runtime.js";
|
|
11
|
-
import type { CreateOptions } from "../runtime.js";
|
|
12
|
-
export declare function createApps(bindings: Record<string, never>, options?: CreateOptions): Apps;
|
package/generated/index.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// holon-generated-apps-v1 placeholder
|
|
2
|
-
import {bindApps} from "../runtime.mjs";
|
|
3
|
-
export {ToolCallError,exposeTools,registerPageTools} from "../runtime.mjs";
|
|
4
|
-
export function createApps(bindings, options) { return bindApps({name:"unconfigured",version:"0",requires:{}}, {}, bindings, options); }
|
package/runtime.d.ts
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
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";
|
|
4
|
-
export type { AuthProvider, CallOptions, CallMetadata, ToolResult, ToolClient } from "holon-sh/runtime";
|
|
5
|
-
export { ToolCallError } from "holon-sh/runtime";
|
|
6
|
-
|
|
7
|
-
export interface CreateOptions { validator?: (schema: object) => (value: unknown) => boolean }
|
|
8
|
-
export declare function createApps(identity: Identity, contracts: Record<string, Contract | null>, bindings?: Record<string, EndpointBinding>, options?: CreateOptions): Readonly<Record<string, RuntimeClient>>;
|
|
9
|
-
export declare function bindApps(identity: Identity, contracts: Record<string, Contract | null>, bindings: Record<string, EndpointBinding>, options?: CreateOptions): Readonly<Record<string, RuntimeClient>>;
|
|
10
|
-
/** The ext-apps App with the app's own tools and resources typed; calls go through the host that embeds the page. */
|
|
11
|
-
export type View = App & Pick<RuntimeClient, "tools" | "resources" | "callTool">;
|
|
12
|
-
export declare function appClass(identity: Identity, contracts: Record<string, Contract | null>, own: string): new (...args: ConstructorParameters<typeof App>) => View;
|
|
13
|
-
export interface ExposeOptions { signal?: AbortSignal; execute?: (name: string, args: Record<string, unknown>) => Promise<unknown> }
|
|
14
|
-
export declare function exposeTools(app: Pick<RuntimeClient, "callTool" | "listTools">, options?: ExposeOptions): Promise<boolean>;
|
|
15
|
-
export type PageResult<I> = { readonly value: I; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string }> };
|
|
16
|
-
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 } } }
|
|
17
|
-
export type PageInput<S> = S extends PageSchema<infer I> ? I : never;
|
|
18
|
-
export interface PageAnnotations { title?: string; readOnlyHint?: boolean; destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean }
|
|
19
|
-
export interface PageTool<S extends PageSchema = PageSchema> { description: string; inputSchema: S; annotations?: PageAnnotations; execute: (args: PageInput<S>) => unknown }
|
|
20
|
-
export interface PageHost { registerTool(name: string, config: { description: string; inputSchema: PageSchema; annotations?: PageAnnotations }, callback: (args: any, extra: any) => any): { remove(): void } }
|
|
21
|
-
export declare function registerPageTools<S extends { [name: string]: PageSchema }>(tools: { [K in keyof S]: PageTool<S[K]> }, options?: { view?: PageHost; signal?: AbortSignal }): Promise<boolean>;
|
package/runtime.mjs
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import { App } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import { createApps as create, bindApps, ToolCallError } from "holon-sh/runtime";
|
|
3
|
-
|
|
4
|
-
export { ToolCallError };
|
|
5
|
-
|
|
6
|
-
export { bindApps };
|
|
7
|
-
|
|
8
|
-
// Browser clients have no process environment or host-wide default binding.
|
|
9
|
-
export function createApps(identity, contracts, bindings, options) {
|
|
10
|
-
return create(identity, contracts, bindings, { ...options, resolve: () => undefined });
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
// appClass returns the ext-apps App with the app's own tools and resources (contracts[own]) typed.
|
|
14
|
-
// Calls go through the host that embeds the page, so connect the App first, as with any App.
|
|
15
|
-
export function appClass(identity, contracts, own) {
|
|
16
|
-
return class extends App {
|
|
17
|
-
#client = bindApps(identity, { [own]: contracts[own] }, { [own]: {} }, {
|
|
18
|
-
session: () => ({
|
|
19
|
-
callTool: (request, { signal, timeout } = {}) => this.callServerTool(request, { signal, timeout }),
|
|
20
|
-
readResource: (request, { signal, timeout } = {}) => this.readServerResource(request, { signal, timeout }),
|
|
21
|
-
listTools: () => { throw new Error("The host owns the tool catalog; bind an endpoint to list tools."); },
|
|
22
|
-
}),
|
|
23
|
-
})[own];
|
|
24
|
-
get tools() { return this.#client.tools; }
|
|
25
|
-
get resources() { return this.#client.resources; }
|
|
26
|
-
callTool(request, options) { return this.#client.callTool(request, options); }
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export async function exposeTools(app, options = {}) {
|
|
31
|
-
const context = globalThis.document?.modelContext ?? globalThis.navigator?.modelContext;
|
|
32
|
-
if (!context) return false;
|
|
33
|
-
const { signal } = options;
|
|
34
|
-
const execute = options.execute ?? (async (name, args) => {
|
|
35
|
-
const result = await app.callTool({ name, arguments: args }, { signal });
|
|
36
|
-
// An agent can only supply arguments, so it cannot answer. A custom execute can.
|
|
37
|
-
if (result.resultType === "input_required") throw new ToolCallError("page", name, result);
|
|
38
|
-
return result;
|
|
39
|
-
});
|
|
40
|
-
const { tools } = await app.listTools({ signal });
|
|
41
|
-
for (const tool of tools) {
|
|
42
|
-
// MCP Apps: a tool whose visibility omits "model" must not reach the agent; absent means ["model", "app"].
|
|
43
|
-
// https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery
|
|
44
|
-
if (!(tool._meta?.ui?.visibility ?? ["model"]).includes("model")) continue;
|
|
45
|
-
await context.registerTool({
|
|
46
|
-
name: tool.name, title: tool.title, description: tool.description ?? "", inputSchema: tool.inputSchema, annotations: tool.annotations,
|
|
47
|
-
execute: args => execute(tool.name, args ?? {}),
|
|
48
|
-
}, { signal });
|
|
49
|
-
}
|
|
50
|
-
return true;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export async function registerPageTools(tools, { view, signal } = {}) {
|
|
54
|
-
const context = globalThis.document?.modelContext ?? globalThis.navigator?.modelContext;
|
|
55
|
-
const removals = [];
|
|
56
|
-
for (const [name, { description, inputSchema, annotations, execute }] of Object.entries(tools)) {
|
|
57
|
-
if (view) {
|
|
58
|
-
removals.push(view.registerTool(name, { description, inputSchema, annotations }, args => execute(args)).remove);
|
|
59
|
-
} else if (context) {
|
|
60
|
-
const standard = inputSchema["~standard"];
|
|
61
|
-
await context.registerTool({
|
|
62
|
-
name, description, annotations, inputSchema: standard.jsonSchema.input({ target: "draft-2020-12" }),
|
|
63
|
-
execute: async args => {
|
|
64
|
-
const parsed = await standard.validate(args ?? {});
|
|
65
|
-
if (parsed.issues) throw new Error(`Invalid arguments for ${name}: ${JSON.stringify(parsed.issues)}`);
|
|
66
|
-
return execute(parsed.value);
|
|
67
|
-
},
|
|
68
|
-
}, { signal });
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
signal?.addEventListener("abort", () => { for (const remove of removals) remove(); }, { once: true });
|
|
72
|
-
return Boolean(view || context);
|
|
73
|
-
}
|