@guuey/mcp-apps-host 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The Host half of the MCP Apps (SEP-1865) App handshake, as a PURE state
3
+ * machine — message in, `{state, effects}` out, zero DOM (guuey#186 Gap 1).
4
+ *
5
+ * ## Why the view hangs without this
6
+ *
7
+ * A spec-following App (ggui's iframe-runtime included) opens with
8
+ * `ui/initialize` posted to its parent and BLOCKS — the handshake runs
9
+ * before the view reads any seeded boot data, so a frame whose parent
10
+ * never answers stays blank forever. `toolResultViewMount` prepares the
11
+ * document; THIS module answers the document. The two halves together are
12
+ * the Host role the package is named for.
13
+ *
14
+ * ## Why a pure machine
15
+ *
16
+ * Only a real browser runs the postMessage/sandbox physics, but the
17
+ * publish gate (guuey-sdks mirror CI) is Node-only — the exact blind spot
18
+ * that let the missing-host gap ship (mount-material assertions run in
19
+ * Node; nothing ran the negotiation). So the protocol logic lives here,
20
+ * exhaustively unit-tested against scripted message sequences, and the DOM
21
+ * glue in `view-host.ts` stays thin enough to carry no decisions. Even the
22
+ * negotiation timeout is a machine INPUT ({@link viewHostElapsed}), not a
23
+ * timer here.
24
+ *
25
+ * ## Spec posture
26
+ *
27
+ * Types and method names come from `@modelcontextprotocol/ext-apps` — the
28
+ * SEP-1865 surface itself, someone else's frozen contract. Zero ggui
29
+ * imports, deliberately (guuey#123): this host answers ANY spec-following
30
+ * view; everything ggui-specific stays in `ggui-render.ts` behind ggui's
31
+ * own published protocol package.
32
+ */
33
+ import { type McpUiHostCapabilities, type McpUiHostContext, type McpUiInitializeResult } from "@modelcontextprotocol/ext-apps";
34
+ import type { McpToolStructuredContent } from "./action.js";
35
+ import type { McpResourceReadResult } from "./reader.js";
36
+ /**
37
+ * The host identity in the initialize result — structurally the spec's
38
+ * `Implementation` (which the ext-apps root does not re-export), narrowed
39
+ * to the two fields a host must supply.
40
+ */
41
+ export interface ViewHostInfo {
42
+ name: string;
43
+ version: string;
44
+ }
45
+ /** The standard MCP method a view uses to reach host-proxied tools. */
46
+ export declare const TOOLS_CALL_METHOD = "tools/call";
47
+ /**
48
+ * The standard MCP method a view uses to read host-proxied resources —
49
+ * `ReadResourceRequest` in the spec's App→Host request union
50
+ * (`@modelcontextprotocol/ext-apps` `AppRequest`). A local constant, same
51
+ * as {@link TOOLS_CALL_METHOD}: the string is MCP-core vocabulary the
52
+ * ext-apps root does not re-export, and this package deliberately carries
53
+ * no `@modelcontextprotocol/sdk` dependency.
54
+ */
55
+ export declare const RESOURCES_READ_METHOD = "resources/read";
56
+ /** A JSON-RPC id as the wire allows it. */
57
+ export type ViewRequestId = number | string;
58
+ /** The messages this host posts INTO the view frame. */
59
+ export interface ViewHostOutbound {
60
+ jsonrpc: "2.0";
61
+ id?: ViewRequestId;
62
+ method?: string;
63
+ params?: {
64
+ [key: string]: unknown;
65
+ };
66
+ result?: {
67
+ [key: string]: unknown;
68
+ };
69
+ error?: {
70
+ code: number;
71
+ message: string;
72
+ };
73
+ }
74
+ /**
75
+ * Where the negotiation stands, from the host's side of the boundary.
76
+ *
77
+ * - `"negotiating"` — attached; no `ui/initialize` seen yet. A plain-HTML
78
+ * inline card may stay here forever, legitimately: the handshake is how
79
+ * a spec App boots, not an obligation on arbitrary tenant HTML.
80
+ * - `"connected"` — `ui/initialize` was answered. The view owns its own
81
+ * pixels (and its own failures) from here on.
82
+ * - `"no-handshake"` — the caller declared the negotiation window over
83
+ * ({@link viewHostElapsed}) before any `ui/initialize` arrived. What
84
+ * that MEANS depends on the mount channel and is the renderer's call:
85
+ * a `"ggui"` shell always handshakes, so this phase is a boot failure
86
+ * there; an `"inline"` card may simply not be an App.
87
+ *
88
+ * A renderer binds to this — the failure mode must be a labeled state,
89
+ * never a blank page (guuey#186 audit).
90
+ */
91
+ export type ViewHostPhase = "negotiating" | "connected" | "no-handshake";
92
+ /** The machine's whole state. Immutable — every transition returns a new one. */
93
+ export interface ViewHostState {
94
+ phase: ViewHostPhase;
95
+ /** `ui/notifications/initialized` seen (the App's post-handshake ack). */
96
+ initializedSeen: boolean;
97
+ }
98
+ export declare function initialViewHostState(): ViewHostState;
99
+ /**
100
+ * What the glue must DO after a transition. Effects are data so the machine
101
+ * stays synchronous and Node-testable; the glue performs them.
102
+ */
103
+ export type ViewHostEffect = {
104
+ kind: "respond";
105
+ message: ViewHostOutbound;
106
+ } | {
107
+ /**
108
+ * A `tools/call` the config accepted for relaying. The glue runs the
109
+ * (async) relay hook and posts {@link toolCallResponse} with the
110
+ * result. Only ever emitted when {@link ViewHostBehavior.toolRelay}
111
+ * is true — with no relay wired, the machine refuses the call
112
+ * in-band instead (an honest `method_not_supported`).
113
+ */
114
+ kind: "relay-tool-call";
115
+ id: ViewRequestId;
116
+ name: string;
117
+ arguments?: McpToolStructuredContent;
118
+ } | {
119
+ /**
120
+ * A `resources/read` the config accepted for relaying (spec surface:
121
+ * `ReadResourceRequest` rides the App→Host union, and the matching
122
+ * advertisement is `hostCapabilities.serverResources`). The glue runs
123
+ * the read hook and posts {@link resourceReadResponse}. Only emitted
124
+ * when {@link ViewHostBehavior.resourceRelay} is true — unwired, the
125
+ * machine refuses in-band like every other unsupported request.
126
+ */
127
+ kind: "relay-resource-read";
128
+ id: ViewRequestId;
129
+ uri: string;
130
+ } | {
131
+ /**
132
+ * The view reported its content size (`ui/notifications/size-changed`
133
+ * — spec notification, App → Host). At least one of the two fields is
134
+ * a finite number; a notification carrying neither is consumed
135
+ * silently instead. The glue forwards this to the embedder
136
+ * ({@link AttachViewHostConfig.onSizeChanged} in `view-host.ts`) —
137
+ * whether/how to resize the frame is the embedder's layout decision,
138
+ * never the machine's.
139
+ */
140
+ kind: "size-changed";
141
+ width?: number;
142
+ height?: number;
143
+ };
144
+ /**
145
+ * The host identity/behavior the machine answers with. Everything here is
146
+ * explicit config — the machine assumes nothing about the embedder.
147
+ */
148
+ export interface ViewHostBehavior {
149
+ hostInfo: ViewHostInfo;
150
+ /**
151
+ * The capabilities to advertise. Empty is a correct, honest default for
152
+ * views that ride their own live channel (ggui views do — they boot from
153
+ * their seeded envelope and talk to their pod directly, so the host's
154
+ * whole job is unblocking the handshake). Advertise ONLY what the
155
+ * embedder actually implements: a capability the host does not honor
156
+ * makes the view attribute later failures to the wrong layer.
157
+ */
158
+ hostCapabilities: McpUiHostCapabilities;
159
+ /** The context handed to the view in the initialize result. */
160
+ hostContext: McpUiHostContext;
161
+ /** Whether a `tools/call` relay hook is wired (see `view-host.ts`). */
162
+ toolRelay: boolean;
163
+ /** Whether a `resources/read` relay hook is wired (see `view-host.ts`). */
164
+ resourceRelay: boolean;
165
+ }
166
+ /** The result of feeding one inbound frame (or the timeout) to the machine. */
167
+ export interface ViewHostTransition {
168
+ state: ViewHostState;
169
+ effects: ViewHostEffect[];
170
+ }
171
+ /** The spec-canonical answer to `ui/initialize`. Exported for the glue/tests. */
172
+ export declare function initializeResult(behavior: ViewHostBehavior, requestedProtocolVersion: unknown): McpUiInitializeResult;
173
+ /** Build the in-band response for a relayed `tools/call`'s settled result. */
174
+ export declare function toolCallResponse(id: ViewRequestId, result: {
175
+ [key: string]: unknown;
176
+ }): ViewHostOutbound;
177
+ /**
178
+ * Build the in-band response for a relayed `resources/read`. An entry
179
+ * becomes the spec's `ReadResourceResult` (`contents: [entry]`); `undefined`
180
+ * — a miss, a deny, or a relay failure alike — becomes the one
181
+ * `Resource not found` error (deny == miss, {@link RESOURCE_NOT_FOUND}).
182
+ */
183
+ export declare function resourceReadResponse(id: ViewRequestId, entry: McpResourceReadResult | undefined): ViewHostOutbound;
184
+ /**
185
+ * The spec-mannered farewell a detaching host posts (`ui/resource-teardown`).
186
+ * Sent WITHOUT an id — a host that is tearing the frame down cannot await a
187
+ * response, and an id-less JSON-RPC message is a notification the view may
188
+ * use for cleanup or ignore.
189
+ */
190
+ export declare function teardownMessage(): ViewHostOutbound;
191
+ /**
192
+ * Feed one inbound postMessage payload to the machine.
193
+ *
194
+ * The contract, exactly:
195
+ * - non-RPC data → ignored (not ours);
196
+ * - notifications (no id) → consumed silently, JSON-RPC-correctly; the
197
+ * `ui/notifications/initialized` ack is remembered on the state;
198
+ * - `ui/initialize` → answered spec-canonically; phase → `"connected"`
199
+ * (also from `"no-handshake"` — a late handshake still gets answered:
200
+ * the timeout labels a state, it does not close the door);
201
+ * - `tools/call` with a relay wired → `relay-tool-call` effect;
202
+ * - every other REQUEST → `method_not_supported`, honestly.
203
+ */
204
+ export declare function viewHostReceive(state: ViewHostState, behavior: ViewHostBehavior, data: unknown): ViewHostTransition;
205
+ /**
206
+ * Declare the negotiation window over. Meaningful only while
207
+ * `"negotiating"`: a connected view stays connected, and an already-lapsed
208
+ * one stays lapsed. The caller owns the clock — this machine has none.
209
+ */
210
+ export declare function viewHostElapsed(state: ViewHostState): ViewHostState;
211
+ //# sourceMappingURL=view-host-protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view-host-protocol.d.ts","sourceRoot":"","sources":["../src/view-host-protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,OAAO,EAKL,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC3B,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAKD,uEAAuE;AACvE,eAAO,MAAM,iBAAiB,eAAe,CAAC;AAE9C;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,mBAAmB,CAAC;AAStD,2CAA2C;AAC3C,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,CAAC;AAE5C,wDAAwD;AACxD,MA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EAAE,YAAY,CAAC;IACvB;;;;;;;OAOG;IACH,gBAAgB,EAAE,qBAAqB,CAAC;IACxC,+DAA+D;IAC/D,WAAW,EAAE,gBAAgB,CAAC;IAC9B,uEAAuE;IACvE,SAAS,EAAE,OAAO,CAAC;IACnB,2EAA2E;IAC3E,aAAa,EAAE,OAAO,CAAC;CACxB;AAED,+EAA+E;AAC/E,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,aAAa,CAAC;IACrB,OAAO,EAAE,cAAc,EAAE,CAAC;CAC3B;AAiCD,iFAAiF;AACjF,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,gBAAgB,EAC1B,wBAAwB,EAAE,OAAO,GAChC,qBAAqB,CAcvB;AAED,8EAA8E;AAC9E,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,aAAa,EACjB,MAAM,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,GACjC,gBAAgB,CAElB;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,aAAa,EACjB,KAAK,EAAE,qBAAqB,GAAG,SAAS,GACvC,gBAAgB,CASlB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,IAAI,gBAAgB,CAElD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,aAAa,EACpB,QAAQ,EAAE,gBAAgB,EAC1B,IAAI,EAAE,OAAO,GACZ,kBAAkB,CAuFpB;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,aAAa,GAAG,aAAa,CAEnE"}
@@ -0,0 +1,230 @@
1
+ /**
2
+ * The Host half of the MCP Apps (SEP-1865) App handshake, as a PURE state
3
+ * machine — message in, `{state, effects}` out, zero DOM (guuey#186 Gap 1).
4
+ *
5
+ * ## Why the view hangs without this
6
+ *
7
+ * A spec-following App (ggui's iframe-runtime included) opens with
8
+ * `ui/initialize` posted to its parent and BLOCKS — the handshake runs
9
+ * before the view reads any seeded boot data, so a frame whose parent
10
+ * never answers stays blank forever. `toolResultViewMount` prepares the
11
+ * document; THIS module answers the document. The two halves together are
12
+ * the Host role the package is named for.
13
+ *
14
+ * ## Why a pure machine
15
+ *
16
+ * Only a real browser runs the postMessage/sandbox physics, but the
17
+ * publish gate (guuey-sdks mirror CI) is Node-only — the exact blind spot
18
+ * that let the missing-host gap ship (mount-material assertions run in
19
+ * Node; nothing ran the negotiation). So the protocol logic lives here,
20
+ * exhaustively unit-tested against scripted message sequences, and the DOM
21
+ * glue in `view-host.ts` stays thin enough to carry no decisions. Even the
22
+ * negotiation timeout is a machine INPUT ({@link viewHostElapsed}), not a
23
+ * timer here.
24
+ *
25
+ * ## Spec posture
26
+ *
27
+ * Types and method names come from `@modelcontextprotocol/ext-apps` — the
28
+ * SEP-1865 surface itself, someone else's frozen contract. Zero ggui
29
+ * imports, deliberately (guuey#123): this host answers ANY spec-following
30
+ * view; everything ggui-specific stays in `ggui-render.ts` behind ggui's
31
+ * own published protocol package.
32
+ */
33
+ import { INITIALIZE_METHOD, LATEST_PROTOCOL_VERSION, RESOURCE_TEARDOWN_METHOD, SIZE_CHANGED_METHOD, } from "@modelcontextprotocol/ext-apps";
34
+ /** JSON-RPC `method not found` — the spec's code, not an invented one. */
35
+ const METHOD_NOT_SUPPORTED = -32601;
36
+ /** The standard MCP method a view uses to reach host-proxied tools. */
37
+ export const TOOLS_CALL_METHOD = "tools/call";
38
+ /**
39
+ * The standard MCP method a view uses to read host-proxied resources —
40
+ * `ReadResourceRequest` in the spec's App→Host request union
41
+ * (`@modelcontextprotocol/ext-apps` `AppRequest`). A local constant, same
42
+ * as {@link TOOLS_CALL_METHOD}: the string is MCP-core vocabulary the
43
+ * ext-apps root does not re-export, and this package deliberately carries
44
+ * no `@modelcontextprotocol/sdk` dependency.
45
+ */
46
+ export const RESOURCES_READ_METHOD = "resources/read";
47
+ /**
48
+ * MCP's `Resource not found` JSON-RPC code — the one answer for a miss, a
49
+ * transport deny, AND a relay failure (deny == miss: the reader discipline,
50
+ * `reader.ts` — the view gets no oracle for which locators resolve).
51
+ */
52
+ const RESOURCE_NOT_FOUND = -32002;
53
+ export function initialViewHostState() {
54
+ return { phase: "negotiating", initializedSeen: false };
55
+ }
56
+ /** Plain-object narrowing, same idiom as `action.ts`'s `isJsonObjectLike`. */
57
+ function isPlainObject(value) {
58
+ return typeof value === "object" && value !== null && !Array.isArray(value);
59
+ }
60
+ /**
61
+ * Narrow untrusted postMessage data to a JSON-RPC envelope this host could
62
+ * answer. Anything else — other windows' chatter, the view's own non-RPC
63
+ * messages — is silently not ours (`undefined`), NOT an error: a shared
64
+ * `message` listener hears the whole page.
65
+ */
66
+ function asInboundEnvelope(data) {
67
+ if (!isPlainObject(data))
68
+ return undefined;
69
+ if (data["jsonrpc"] !== "2.0")
70
+ return undefined;
71
+ const method = data["method"];
72
+ if (typeof method !== "string")
73
+ return undefined;
74
+ const id = data["id"];
75
+ const params = data["params"];
76
+ return {
77
+ ...(typeof id === "number" || typeof id === "string" ? { id } : {}),
78
+ method,
79
+ ...(isPlainObject(params) ? { params } : {}),
80
+ };
81
+ }
82
+ /** The spec-canonical answer to `ui/initialize`. Exported for the glue/tests. */
83
+ export function initializeResult(behavior, requestedProtocolVersion) {
84
+ // Echo the version the view asked for when it names one — the view is
85
+ // the side with a fixed runtime; the host has no version-specific
86
+ // behavior to defend. Absent/malformed, answer with the spec's latest.
87
+ const protocolVersion = typeof requestedProtocolVersion === "string" && requestedProtocolVersion.length > 0
88
+ ? requestedProtocolVersion
89
+ : LATEST_PROTOCOL_VERSION;
90
+ return {
91
+ protocolVersion,
92
+ hostInfo: behavior.hostInfo,
93
+ hostCapabilities: behavior.hostCapabilities,
94
+ hostContext: behavior.hostContext,
95
+ };
96
+ }
97
+ /** Build the in-band response for a relayed `tools/call`'s settled result. */
98
+ export function toolCallResponse(id, result) {
99
+ return { jsonrpc: "2.0", id, result };
100
+ }
101
+ /**
102
+ * Build the in-band response for a relayed `resources/read`. An entry
103
+ * becomes the spec's `ReadResourceResult` (`contents: [entry]`); `undefined`
104
+ * — a miss, a deny, or a relay failure alike — becomes the one
105
+ * `Resource not found` error (deny == miss, {@link RESOURCE_NOT_FOUND}).
106
+ */
107
+ export function resourceReadResponse(id, entry) {
108
+ if (entry === undefined) {
109
+ return {
110
+ jsonrpc: "2.0",
111
+ id,
112
+ error: { code: RESOURCE_NOT_FOUND, message: "resource unavailable" },
113
+ };
114
+ }
115
+ return { jsonrpc: "2.0", id, result: { contents: [entry] } };
116
+ }
117
+ /**
118
+ * The spec-mannered farewell a detaching host posts (`ui/resource-teardown`).
119
+ * Sent WITHOUT an id — a host that is tearing the frame down cannot await a
120
+ * response, and an id-less JSON-RPC message is a notification the view may
121
+ * use for cleanup or ignore.
122
+ */
123
+ export function teardownMessage() {
124
+ return { jsonrpc: "2.0", method: RESOURCE_TEARDOWN_METHOD, params: {} };
125
+ }
126
+ /**
127
+ * Feed one inbound postMessage payload to the machine.
128
+ *
129
+ * The contract, exactly:
130
+ * - non-RPC data → ignored (not ours);
131
+ * - notifications (no id) → consumed silently, JSON-RPC-correctly; the
132
+ * `ui/notifications/initialized` ack is remembered on the state;
133
+ * - `ui/initialize` → answered spec-canonically; phase → `"connected"`
134
+ * (also from `"no-handshake"` — a late handshake still gets answered:
135
+ * the timeout labels a state, it does not close the door);
136
+ * - `tools/call` with a relay wired → `relay-tool-call` effect;
137
+ * - every other REQUEST → `method_not_supported`, honestly.
138
+ */
139
+ export function viewHostReceive(state, behavior, data) {
140
+ const req = asInboundEnvelope(data);
141
+ if (req === undefined)
142
+ return { state, effects: [] };
143
+ if (req.id === undefined) {
144
+ // A notification. Track the one the handshake defines, surface the one
145
+ // the embedder may act on; consume the rest.
146
+ if (req.method === "ui/notifications/initialized" && !state.initializedSeen) {
147
+ return { state: { ...state, initializedSeen: true }, effects: [] };
148
+ }
149
+ if (req.method === SIZE_CHANGED_METHOD) {
150
+ const width = req.params?.["width"];
151
+ const height = req.params?.["height"];
152
+ const validWidth = typeof width === "number" && Number.isFinite(width);
153
+ const validHeight = typeof height === "number" && Number.isFinite(height);
154
+ if (validWidth || validHeight) {
155
+ return {
156
+ state,
157
+ effects: [
158
+ {
159
+ kind: "size-changed",
160
+ ...(validWidth ? { width } : {}),
161
+ ...(validHeight ? { height } : {}),
162
+ },
163
+ ],
164
+ };
165
+ }
166
+ }
167
+ return { state, effects: [] };
168
+ }
169
+ if (req.method === INITIALIZE_METHOD) {
170
+ const result = initializeResult(behavior, req.params?.["protocolVersion"]);
171
+ return {
172
+ state: { ...state, phase: "connected" },
173
+ effects: [{ kind: "respond", message: { jsonrpc: "2.0", id: req.id, result } }],
174
+ };
175
+ }
176
+ if (req.method === TOOLS_CALL_METHOD && behavior.toolRelay) {
177
+ const name = req.params?.["name"];
178
+ if (typeof name === "string") {
179
+ const args = req.params?.["arguments"];
180
+ return {
181
+ state,
182
+ effects: [
183
+ {
184
+ kind: "relay-tool-call",
185
+ id: req.id,
186
+ name,
187
+ ...(isPlainObject(args) ? { arguments: args } : {}),
188
+ },
189
+ ],
190
+ };
191
+ }
192
+ // fall through: a nameless tools/call is not a call we can relay.
193
+ }
194
+ if (req.method === RESOURCES_READ_METHOD && behavior.resourceRelay) {
195
+ const uri = req.params?.["uri"];
196
+ if (typeof uri === "string") {
197
+ return { state, effects: [{ kind: "relay-resource-read", id: req.id, uri }] };
198
+ }
199
+ // fall through: a uri-less read is not a read we can relay.
200
+ }
201
+ const answered = [
202
+ INITIALIZE_METHOD,
203
+ ...(behavior.toolRelay ? [TOOLS_CALL_METHOD] : []),
204
+ ...(behavior.resourceRelay ? [RESOURCES_READ_METHOD] : []),
205
+ ];
206
+ return {
207
+ state,
208
+ effects: [
209
+ {
210
+ kind: "respond",
211
+ message: {
212
+ jsonrpc: "2.0",
213
+ id: req.id,
214
+ error: {
215
+ code: METHOD_NOT_SUPPORTED,
216
+ message: `method_not_supported: ${req.method} — this host answers ${answered.join(", ")} only`,
217
+ },
218
+ },
219
+ },
220
+ ],
221
+ };
222
+ }
223
+ /**
224
+ * Declare the negotiation window over. Meaningful only while
225
+ * `"negotiating"`: a connected view stays connected, and an already-lapsed
226
+ * one stays lapsed. The caller owns the clock — this machine has none.
227
+ */
228
+ export function viewHostElapsed(state) {
229
+ return state.phase === "negotiating" ? { ...state, phase: "no-handshake" } : state;
230
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * `attachViewHost` — the DOM glue around `view-host-protocol.ts`'s pure
3
+ * machine (guuey#186 Gap 1). Framework-agnostic: any embedder with an
4
+ * iframe can play the MCP Apps Host role with one call; `react.tsx` is one
5
+ * convenience composition of exactly this, and a future full transcript
6
+ * renderer composes the same primitive differently.
7
+ *
8
+ * This module is glue by DESIGN — every decision (what to answer, what to
9
+ * refuse, when the negotiation window lapses) lives in the machine, which
10
+ * the Node-only publish gate can test. What genuinely needs a browser is
11
+ * this file's five moves: listen, identity-filter, post, time, detach —
12
+ * covered by the monorepo's Playwright leg (`e2e/`), which the guuey-sdks
13
+ * mirror deliberately does not carry.
14
+ *
15
+ * ## The identity filter (security invariant)
16
+ *
17
+ * Messages are matched by `event.source === frame.contentWindow`, NEVER by
18
+ * `event.origin`: a view frame runs `sandbox="allow-scripts"` WITHOUT
19
+ * `allow-same-origin`, so its origin is opaque — every message it posts
20
+ * carries `"null"`, a value every other sandboxed frame on the page
21
+ * shares, identifying nobody. The window handle is the only identity that
22
+ * names the frame; a frame with no `contentWindow` matches nothing rather
23
+ * than everything. Responses target `'*'` for the same reason: an opaque
24
+ * origin is not addressable by name, and the handshake payload carries no
25
+ * secrets — it is the result the spec defines for any host.
26
+ *
27
+ * Seeded from ggui's console `surface-host.ts` (donated, guuey#186 audit);
28
+ * re-derived here against the pure machine + our own tests.
29
+ */
30
+ import { type ViewHostPhase } from "./view-host-protocol.js";
31
+ import type { McpResourceReadResult } from "./reader.js";
32
+ import { type McpToolCallResult, type UiActionRequest } from "./action.js";
33
+ import type { McpUiResourcePayload } from "./block-ui.js";
34
+ import type { McpUiHostCapabilities, McpUiHostContext } from "@modelcontextprotocol/ext-apps";
35
+ import type { ViewHostInfo } from "./view-host-protocol.js";
36
+ /**
37
+ * The slice of an `HTMLIFrameElement` this host actually touches — a
38
+ * structural type so Node tests (and non-DOM hosts) can hand in a fake
39
+ * without a single cast, same injection idiom as the package's readers and
40
+ * relays. A real iframe element satisfies it as-is.
41
+ */
42
+ export interface ViewFrameLike {
43
+ readonly contentWindow: {
44
+ postMessage(message: unknown, targetOrigin: string): void;
45
+ } | null;
46
+ readonly clientWidth: number;
47
+ readonly clientHeight: number;
48
+ }
49
+ /** The inbound side: what this host needs from `window`. */
50
+ export interface ViewHostEvents {
51
+ addEventListener(type: "message", listener: (event: {
52
+ data: unknown;
53
+ source: unknown;
54
+ }) => void): void;
55
+ removeEventListener(type: "message", listener: (event: {
56
+ data: unknown;
57
+ source: unknown;
58
+ }) => void): void;
59
+ }
60
+ export interface AttachViewHostConfig {
61
+ /**
62
+ * Capabilities to advertise in the initialize result. Default: `{}` —
63
+ * correct for views that ride their own live channel (ggui views do;
64
+ * they boot from their seeded envelope and talk to their pod directly),
65
+ * and the honest floor for everyone else: advertise only what the
66
+ * embedder implements. Exception: wiring {@link onCallTool} advertises
67
+ * `serverTools` automatically — a wired relay IS the implementation —
68
+ * and an explicit `hostCapabilities.serverTools` still wins.
69
+ */
70
+ hostCapabilities?: McpUiHostCapabilities;
71
+ /** Host identity for the initialize result. */
72
+ hostInfo?: ViewHostInfo;
73
+ /**
74
+ * Extra context merged over the derived defaults (locale from
75
+ * `navigator`, container dimensions from the frame when it has laid
76
+ * out — a 0×0 pre-layout reading is a lie the spec type shouldn't be
77
+ * told). Keys given here win.
78
+ */
79
+ hostContext?: McpUiHostContext;
80
+ /**
81
+ * The `tools/call` relay — a PRIVILEGE boundary, default off: with no
82
+ * hook, the machine refuses `tools/call` in-band and advertises no
83
+ * `serverTools`. Wire `createMcpUiActionRelay` (or your own) to let the
84
+ * mounted view reach tools over a transport the embedder owns. The
85
+ * request's `name`/`arguments` are VIEW-CONTROLLED wire data — the hook
86
+ * owns allowlisting and validation (`createMcpUiActionRelay` does both).
87
+ */
88
+ onCallTool?: (request: UiActionRequest) => Promise<McpToolCallResult>;
89
+ /**
90
+ * The mounted resource's `ui://` locator — the scope stamped on every
91
+ * relayed {@link UiActionRequest}. Required for the relay to fire;
92
+ * `<GuueyView>` fills it from the mount automatically.
93
+ */
94
+ resourceUri?: string;
95
+ /**
96
+ * The `resources/read` relay — a PRIVILEGE boundary like
97
+ * {@link onCallTool}, default off: with no hook, the machine refuses
98
+ * `resources/read` in-band and advertises no `serverResources`. The hook
99
+ * is structurally the SAME transport `createMcpUiResourceReader`
100
+ * assembles over ({@link CreateMcpUiResourceReaderDeps.readResource}) —
101
+ * a host with a locator reader wires the identical function here. Trust
102
+ * rules ride the reader discipline (`reader.ts`): enforcement lives
103
+ * INSIDE the transport; a miss, a deny, and a throw all answer the view
104
+ * with the one `Resource not found` error (deny == miss — no oracle).
105
+ */
106
+ onReadResource?: (uri: string) => Promise<McpResourceReadResult | undefined>;
107
+ /**
108
+ * The view reported its content size (`ui/notifications/size-changed` —
109
+ * spec notification). Whether and how to resize the frame is the
110
+ * embedder's layout decision; `<GuueyView autoResize>` is one wiring of
111
+ * exactly this callback.
112
+ */
113
+ onSizeChanged?: (size: {
114
+ width?: number;
115
+ height?: number;
116
+ }) => void;
117
+ /** Observe phase transitions (see {@link ViewHostPhase}). */
118
+ onPhaseChange?: (phase: ViewHostPhase) => void;
119
+ /**
120
+ * How long to wait for `ui/initialize` before declaring
121
+ * `"no-handshake"` (ms). `0` disables the timer. Default 8000 — a view
122
+ * runtime negotiates immediately after parse; this bound exists to turn
123
+ * "blank forever" into a labeled state, not to race slow networks.
124
+ */
125
+ negotiationTimeoutMs?: number;
126
+ /** Message-event source, injectable for tests. Default: `window`. */
127
+ events?: ViewHostEvents;
128
+ }
129
+ /**
130
+ * Attach the Host role to a mounted view frame. Returns a detach function;
131
+ * call it before the frame unmounts — it stops listening and posts the
132
+ * spec-mannered `ui/resource-teardown` farewell through the CACHED window
133
+ * handle (post-removal, `frame.contentWindow` is already null).
134
+ */
135
+ export declare function attachViewHost(frame: ViewFrameLike, config?: AttachViewHostConfig): () => void;
136
+ /**
137
+ * The document a {@link McpUiResourcePayload} mounts: `text` verbatim, or
138
+ * `blob` base64-decoded as UTF-8. `undefined` when the payload carries
139
+ * neither — nothing to put in `srcdoc`.
140
+ */
141
+ export declare function viewDocumentHtml(resource: McpUiResourcePayload): string | undefined;
142
+ //# sourceMappingURL=view-host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view-host.d.ts","sourceRoot":"","sources":["../src/view-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EASL,KAAK,aAAa,EAEnB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAEL,KAAK,iBAAiB,EAEtB,KAAK,eAAe,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,KAAK,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAC9F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAE5D;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,aAAa,EAAE;QAAE,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC;IAC7F,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC/B;AAED,4DAA4D;AAC5D,MAAM,WAAW,cAAc;IAC7B,gBAAgB,CACd,IAAI,EAAE,SAAS,EACf,QAAQ,E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