holon-ui 0.0.1-dev.2 → 0.0.1-dev.20

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
@@ -1,150 +1,114 @@
1
1
  # holon-ui
2
2
 
3
- Typed MCP clients for browser pages: views that run inside an MCP Apps host, or standalone pages that talk to MCP servers directly. The [`holon` CLI](https://github.com/holon-sh/cli) generates the clients into this package's `generated/` directory, so `import { createApps } from "holon-ui"` resolves to your app's own types. Clients validate arguments before each call and results after it, and can expose tools to the page's WebMCP agent.
3
+ [![Docs](https://img.shields.io/badge/docs-holonlabs.ai-blue)](https://holonlabs.ai/docs/)
4
4
 
5
- `holon-ui` contains only browser code. Server code uses `holon-sh` ([Node.js](https://github.com/holon-sh/sdk-ts) or [Python](https://github.com/holon-sh/sdk-py)). Start with the [CLI README](https://github.com/holon-sh/cli) for the walkthrough.
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
 
9
- In the app's root directory, next to its `server.json`:
10
-
11
9
  ```sh
12
- npm install holon-ui@dev
10
+ npm install holon-ui
11
+ npm install -D holon-types typescript vite
13
12
  ```
14
13
 
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
14
+ ## Create an app
18
15
 
19
- ```typescript
20
- import { App, ToolCallError, createApps, exposeTools, registerPageTools, type Inputs, type Outputs, type Resources } from "holon-ui";
16
+ ```sh
17
+ npx create-holon-app foo
21
18
  ```
22
19
 
23
- | Export | What it is |
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"]`. |
20
+ This creates an MCP server with a `greet` tool and a page in `ui/main.ts`.
31
21
 
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`.
22
+ ## Calling your server from the page
33
23
 
34
- ## Bind a client
24
+ The server declares the tool's input and output:
35
25
 
36
- ### Inside an MCP Apps host
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
+ );
38
+ ```
37
39
 
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:
40
+ `connect` from `#holon-ui` types the server's tools, so a wrong tool name, argument or result is a type error:
39
41
 
40
- ```typescript
41
- import { App } from "holon-ui";
42
+ ```sh
43
+ npx holon types check
44
+ ```
42
45
 
43
- const view = new App({ name: "checkout-view", version: "1.0.0" });
44
- view.ontoolresult = ({ structuredContent }) => render(structuredContent);
45
- await view.connect();
46
+ ```ts
47
+ import { connect } from "#holon-ui";
46
48
 
47
- const { total } = await view.tools.total({ id: "A-1" });
48
- ```
49
+ const app = await connect();
49
50
 
50
- The host owns the tool catalog, so `listTools`, `exposeTools` and `watch` need an endpoint binding instead.
51
+ const { result } = await app.tools.greet({ name: "Ada" });
51
52
 
52
- ### Directly to an endpoint
53
+ await app.tools.great({ name: "Ada" });
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'?
53
55
 
54
- ```typescript
55
- const apps = createApps({
56
- checkout: { endpoint: new URL("/mcp", location.origin) },
57
- orders: { endpoint: "https://orders.example.com/mcp" },
58
- });
56
+ await app.tools.greet({ name: 42 });
57
+ // error TS2322: Type 'number' is not assignable to type 'string'.
59
58
 
60
- const order = await apps.orders.tools.lookup({ id: "A-1" }, { timeout: 5000 });
59
+ result.toFixed();
60
+ // error TS2551: Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?
61
61
  ```
62
62
 
63
- An endpoint binding takes `endpoint`, and optionally `authProvider`, `fetch`, and `scoped: true` to close the session after every call. Otherwise a client keeps one session open; call `close()` when the page no longer needs it.
63
+ ## Tools that run in the page
64
64
 
65
- A tool can stop and ask for input through an MCP elicitation. Bind `elicit` to answer it, and the call returns its usual typed output:
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
66
 
67
- ```typescript
68
- const apps = createApps({
69
- orders: {
70
- endpoint: "https://orders.example.com/mcp",
71
- elicit: async ({ params }) => ({ action: "accept", content: await showForm(params) }),
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
+ },
72
76
  },
73
77
  });
74
78
  ```
75
79
 
76
- ## Read and watch resources
77
-
78
- A server types a JSON resource by registering it with `mimeType: "application/json"` and an `"sh.holon/outputSchema"` JSON Schema in its `_meta`:
80
+ `execute` also receives a `signal` that aborts when the agent cancels.
79
81
 
80
- ```typescript
81
- const summary = await apps.orders.resources["orders://summary"].read();
82
-
83
- const lifetime = new AbortController();
84
- await apps.orders.resources["orders://summary"].watch(value => render(value.open), { signal: lifetime.signal });
85
- ```
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.
86
83
 
87
- `watch` calls back with the current value and then on every update, until the signal aborts; the server must support resource subscriptions.
84
+ ## The call that opened a view
88
85
 
89
- ## Give tools to the page's agent
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`.
90
87
 
91
- `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 the binding's `elicit` does not answer reaches it as a failed result naming the question. It returns `false` when the browser has no WebMCP context.
92
-
93
- ```typescript
94
- await exposeTools(apps.orders, { signal: lifetime.signal });
88
+ ```ts
89
+ const opened = await app.opened;
90
+ if (opened?.tool === "greet") greeting.value = opened.output.result;
95
91
  ```
96
92
 
97
- `registerPageTools` registers tools the page implements itself. Input schemas are Standard Schema validators that can produce JSON Schema, such as Zod 4. Pass `view` to register with the MCP Apps host; without it they go to WebMCP. Aborting the signal unregisters them.
98
-
99
- ```typescript
100
- import { z } from "zod";
93
+ Host-only features are on `app.view`, the ext-apps `App`:
101
94
 
102
- await registerPageTools(
103
- {
104
- highlight: {
105
- description: "Highlight an order on the page",
106
- inputSchema: z.object({ id: z.string() }),
107
- execute: ({ id }) => {
108
- select(id);
109
- return { content: [{ type: "text", text: `Highlighted ${id}` }] };
110
- },
111
- },
112
- },
113
- { view, signal: lifetime.signal },
114
- );
95
+ ```ts
96
+ if (app.view) app.view.onhostcontextchanged = ({ theme }) => { if (theme) document.documentElement.style.colorScheme = theme; };
115
97
  ```
116
98
 
117
- ## Build and serve a view
99
+ ## Building the page
118
100
 
119
- The server serves the view as one HTML file, so bundle it into a single file. With Vite, in the app root:
101
+ `holon-ui/vite` builds `ui/index.html` twice in one `vite build`: the web page into `dist/web`, and the view into `dist/mcp/index.html`, one self-contained file in which `holon-ui` calls through the host:
120
102
 
121
- ```typescript
122
- // vite.config.ts
103
+ ```ts
123
104
  import { defineConfig } from "vite";
124
- import { viteSingleFile } from "vite-plugin-singlefile";
105
+ import { holon } from "holon-ui/vite";
125
106
 
126
- export default defineConfig({ root: "ui", plugins: [viteSingleFile()], build: { outDir: "../dist", emptyOutDir: true } });
107
+ export default defineConfig({ plugins: [holon()] });
127
108
  ```
128
109
 
129
- ```sh
130
- npm install --save-dev vite vite-plugin-singlefile
131
- npm install @modelcontextprotocol/ext-apps
132
- npx vite build
133
- ```
134
-
135
- Then serve `dist/index.html` from the server with `appView` from `holon-sh/view` (Node.js) or `app_view` from `holon.view` (Python); both are documented in their runtime READMEs.
136
-
137
- ## Low-level runtime
138
-
139
- `holon-ui/runtime` exports what the generated module calls: `createApps(identity, contracts, bindings?, options?)`, `bindApps`, `appClass(identity, contracts, own)`, `exposeTools`, `registerPageTools`, `ToolCallError`, and the `EndpointBinding`, `View` and page-tool types. Apps use the generated module instead.
140
-
141
- ## Develop
142
-
143
- ```sh
144
- npm ci
145
- npm test
146
- ```
110
+ `create-holon-app` sets this up. With another bundler, build the view with the `mcp-app` export condition.
147
111
 
148
- ## License
112
+ ## Community
149
113
 
150
- [Apache License 2.0](LICENSE)
114
+ 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.2",
4
- "description": "Typed MCP clients for browser views: MCP Apps host bindings and WebMCP tool exposure.",
3
+ "version": "0.0.1-dev.20",
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"
@@ -12,44 +12,43 @@
12
12
  "publishConfig": {
13
13
  "access": "public"
14
14
  },
15
- "holon": {
16
- "slot": "generated",
17
- "contractVersion": 1
18
- },
19
15
  "exports": {
20
- ".": {
21
- "types": "./generated/index.d.ts",
22
- "import": "./generated/index.js"
23
- },
24
16
  "./runtime": {
25
17
  "types": "./runtime.d.ts",
26
- "import": "./runtime.mjs"
18
+ "mcp-app": "./runtime.host.mjs",
19
+ "default": "./runtime.web.mjs"
20
+ },
21
+ "./vite": {
22
+ "types": "./vite.d.ts",
23
+ "default": "./vite.mjs"
27
24
  }
28
25
  },
29
26
  "files": [
30
- "runtime.mjs",
31
27
  "runtime.d.ts",
32
- "generated/",
28
+ "runtime.host.mjs",
29
+ "runtime.web.mjs",
30
+ "vite.d.ts",
31
+ "vite.mjs",
33
32
  "README.md"
34
33
  ],
35
34
  "scripts": {
36
- "build": "node scripts/build.mjs",
37
- "prepack": "npm run build",
38
- "test": "npm run build && node --test tests/*.test.mjs",
35
+ "test": "node --test --test-timeout=30000 tests/*.test.mjs && node --conditions=mcp-app --test --test-timeout=30000 tests/mcp-app/*.test.mjs",
39
36
  "fixtures": "node scripts/fixtures.mjs"
40
37
  },
41
38
  "dependencies": {
42
- "holon-sh": "^0.0.1-dev.5"
39
+ "@modelcontextprotocol/client": "^2.3.1",
40
+ "holon-sh": "^0.0.1-dev.23"
43
41
  },
44
42
  "peerDependencies": {
45
- "@modelcontextprotocol/ext-apps": ">=1.0.0"
43
+ "@modelcontextprotocol/ext-apps": "^2.0.0"
46
44
  },
47
45
  "devDependencies": {
48
- "@modelcontextprotocol/ext-apps": "^1.7.5",
46
+ "@modelcontextprotocol/ext-apps": "^2.0.4",
49
47
  "@modelcontextprotocol/node": "2.1.1",
50
48
  "@modelcontextprotocol/server": "2.3.1",
51
49
  "@types/node": "^22.0.0",
52
50
  "typescript": "~5.9.3",
51
+ "vite": "8.3.8",
53
52
  "zod": "4.6.6"
54
53
  }
55
54
  }
package/runtime.d.ts CHANGED
@@ -1,21 +1,56 @@
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 } 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 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>;
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?: Parameters<App["connect"]>[0] };
24
+ /** 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. */
25
+ web?: EndpointBinding;
26
+ }
27
+ type Tools<C> = C extends { tools: infer T } ? T : never;
28
+ /** The tool call that opened a view: typed by its tool, or untyped when the host does not say which tool it was. */
29
+ export type Opened<C> =
30
+ | { [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]
31
+ | { tool: undefined; input: Record<string, unknown>; output: unknown };
32
+ type Resources<C> = C extends { readonly resources: infer R } ? R : never;
33
+ /** What a view can do with its app: call its tools and read its resources. */
34
+ type Relayed<C> = Pick<C, Extract<keyof C, "tools" | "callTool" | "close">> & {
35
+ readonly resources: { readonly [U in keyof Resources<C>]: Pick<Resources<C>[U], Extract<keyof Resources<C>[U], "read">> };
36
+ };
37
+ /** 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. */
38
+ export type Page<C> =
39
+ | (Relayed<C> & {
40
+ /** The connected ext-apps App, for host-only features. */
41
+ readonly view: App;
42
+ /** The tool call that opened the view, with the output its tool returns. */
43
+ readonly opened: Promise<Opened<C>>;
44
+ })
45
+ | (C & {
46
+ /** Undefined on a web page. */
47
+ readonly view: undefined;
48
+ readonly opened: undefined;
49
+ });
50
+ /** 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. */
51
+ export type Connect<C> = <S extends Record<string, unknown> = {}>(options?: ConnectOptions<S> & { tools?: { [K in keyof Tools<C>]?: never } }) => Promise<Page<C>>;
52
+ /** 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. */
53
+ export declare function connect<S extends Record<string, unknown> = {}>(
54
+ 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 },
55
+ options?: ConnectOptions<S>,
56
+ ): Promise<Page<RuntimeClient>>;
@@ -0,0 +1,58 @@
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
+ });
50
+ // Closing the view removes its tools from the host.
51
+ return Object.freeze({ tools: client.tools, callTool: client.callTool, resources: client.resources, view: app, opened, close: () => app.close() });
52
+ }
53
+
54
+ function toolResult(value) {
55
+ if (value === undefined) return { content: [] };
56
+ const structured = typeof value === "object" && value !== null && !Array.isArray(value);
57
+ return { content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(structured && { structuredContent: value }) };
58
+ }
@@ -0,0 +1,90 @@
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 = {}, web = { endpoint } } = {}) {
10
+ const client = bindApps(identity, contracts, { [own]: { ...web, endpoint: new URL(web.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
+ if (!(tool._meta?.ui?.visibility ?? ["model"]).includes("model") || !contracted(tool.name)) continue;
27
+ const inputSchema = withoutFiles(tool.inputSchema);
28
+ if (inputSchema !== FILE) offer(serverTool(own, client, tool, inputSchema));
29
+ }
30
+ },
31
+ error => signal.aborted || console.warn(`Could not list the tools of ${own} for WebMCP:`, error),
32
+ );
33
+ }
34
+ return Object.freeze({ ...client, view: undefined, opened: undefined, close: async () => { lifetime.abort(); await client.close(); } });
35
+ }
36
+
37
+ function pageTool(name, { description, inputSchema, annotations, execute }) {
38
+ const standard = inputSchema?.["~standard"];
39
+ return {
40
+ name, title: annotations?.title, description, annotations: hints(annotations),
41
+ inputSchema: standard?.jsonSchema.input({ target: "draft-2020-12" }),
42
+ execute: async (input, { signal }) => {
43
+ const parsed = standard ? await standard.validate(input) : { value: {} };
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 FILE = Symbol("schema requires a file");
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(node, key) {
79
+ if (Array.isArray(node)) {
80
+ const items = node.map(item => withoutFiles(item));
81
+ if (!items.includes(FILE)) return items;
82
+ if (key !== "anyOf" && key !== "oneOf") return FILE;
83
+ const kept = items.filter(item => item !== FILE);
84
+ return kept.length ? kept : FILE;
85
+ }
86
+ if (typeof node !== "object" || node === null) return node;
87
+ if (Object.hasOwn(node, "x-mcp-file")) return FILE;
88
+ const entries = Object.entries(node).map(([key, value]) => [key, withoutFiles(value, key)]);
89
+ return entries.some(([, value]) => value === FILE) ? FILE : Object.fromEntries(entries);
90
+ }
package/vite.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from "vite";
2
+
3
+ /** 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. */
4
+ export declare function holon(): Plugin;
package/vite.mjs ADDED
@@ -0,0 +1,39 @@
1
+ export function holon() {
2
+ return {
3
+ name: "holon",
4
+ config: () => ({
5
+ root: "ui",
6
+ base: "./",
7
+ builder: {},
8
+ build: { outDir: "../dist/web", emptyOutDir: true },
9
+ environments: {
10
+ mcp: {
11
+ consumer: "client",
12
+ build: {
13
+ outDir: "../dist/mcp",
14
+ copyPublicDir: false,
15
+ assetsInlineLimit: () => true,
16
+ rolldownOptions: { output: { codeSplitting: false } },
17
+ },
18
+ },
19
+ },
20
+ }),
21
+ applyToEnvironment: ({ name }) => name === "mcp",
22
+ resolveId: { order: "pre", handler: id => (id === "holon-ui/runtime" ? `${import.meta.dirname}/runtime.host.mjs` : null) },
23
+ generateBundle: {
24
+ order: "post",
25
+ handler(_, bundle) {
26
+ const { "index.html": page, ...files } = bundle;
27
+ for (const [name, file] of Object.entries(files)) {
28
+ const url = page.source.indexOf(`"./${name}"`);
29
+ if (url < 0) 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`);
30
+ const startTag = page.source.slice(page.source.lastIndexOf("<", url), page.source.indexOf(">", url) + 1);
31
+ page.source = page.source.replace(startTag, () => file.type === "chunk"
32
+ ? `<script type="module">${file.code.replaceAll("<!--", "\\x3C!--")}`
33
+ : `<style>${file.source.replaceAll("</", "<\\/")}</style>`);
34
+ delete bundle[name];
35
+ }
36
+ },
37
+ },
38
+ };
39
+ }
@@ -1,4 +0,0 @@
1
- {
2
- "marker": "holon-generated-apps-v1",
3
- "placeholder": true
4
- }
@@ -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;
@@ -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.mjs DELETED
@@ -1,74 +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
- if (result.resultType !== "input_required") return result;
37
- // An agent can only supply arguments, so a question it receives would end the call anyway. Bind elicit to answer it.
38
- const questions = Object.values(result.inputRequests ?? {}).flatMap(request => request.params?.message ?? []);
39
- return { isError: true, content: [{ type: "text", text: [`${name} needs input this page cannot provide`, ...questions].join(": ") }] };
40
- });
41
- const { tools } = await app.listTools({ signal });
42
- for (const tool of tools) {
43
- // MCP Apps: a tool whose visibility omits "model" must not reach the agent; absent means ["model", "app"].
44
- // https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx#resource-discovery
45
- if (!(tool._meta?.ui?.visibility ?? ["model"]).includes("model")) continue;
46
- await context.registerTool({
47
- name: tool.name, title: tool.title, description: tool.description ?? "", inputSchema: tool.inputSchema, annotations: tool.annotations,
48
- execute: args => execute(tool.name, args ?? {}),
49
- }, { signal });
50
- }
51
- return true;
52
- }
53
-
54
- export async function registerPageTools(tools, { view, signal } = {}) {
55
- const context = globalThis.document?.modelContext ?? globalThis.navigator?.modelContext;
56
- const removals = [];
57
- for (const [name, { description, inputSchema, annotations, execute }] of Object.entries(tools)) {
58
- if (view) {
59
- removals.push(view.registerTool(name, { description, inputSchema, annotations }, args => execute(args)).remove);
60
- } else if (context) {
61
- const standard = inputSchema["~standard"];
62
- await context.registerTool({
63
- name, description, annotations, inputSchema: standard.jsonSchema.input({ target: "draft-2020-12" }),
64
- execute: async args => {
65
- const parsed = await standard.validate(args ?? {});
66
- if (parsed.issues) throw new Error(`Invalid arguments for ${name}: ${JSON.stringify(parsed.issues)}`);
67
- return execute(parsed.value);
68
- },
69
- }, { signal });
70
- }
71
- }
72
- signal?.addEventListener("abort", () => { for (const remove of removals) remove(); }, { once: true });
73
- return Boolean(view || context);
74
- }