@saga-a2ui/lit-mcp-stack 0.0.0-stage → 0.8.0-rc.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @saga-a2ui/lit-mcp-stack
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Lit renderer and MCP Apps delivery in one application dependency. Install the stack plus `lit@^3.3.3`, and import from the stack only: the root starts an application-owned catalog with `startA2uiView`; `/faithful-card` starts a card application with `startFaithfulCardApp`; `/content-policy` supplies content policies; `/server` supplies server composition. The server entry stays out of browser bundles.
4
+
5
+ The stack declares core, components, MCP and the Lit renderer as dependencies. Your application owns its domain values, catalog, actions, verified identity and authorization.
6
+
7
+ Requires Node >=22.12.0 and a TypeScript-aware bundler; exports are TypeScript source. Apache-2.0, with dependency licenses retained separately.
8
+
9
+ Release candidates use the npm `next` tag. Pin exact published SAGA versions. At the consumer root, override `@a2ui/markdown-it` to `0.2.1`; keep A2UI's Zod 3 and MCP's Zod 4 contexts separate.
10
+
11
+ See [public installation](https://github.com/MachineWisdomAI/saga-a2ui/blob/main/docs/public-install.md) and [release preparation](https://github.com/MachineWisdomAI/saga-a2ui/blob/main/docs/release-packages.md). Source versions and candidate tarballs do not establish registry availability.
package/package.json CHANGED
@@ -1,6 +1 @@
1
- {
2
- "name": "@saga-a2ui/lit-mcp-stack",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {"name":"@saga-a2ui/lit-mcp-stack","private":false,"description":"The Lit and MCP Apps stack for SAGA A2UI: starts a view for an application's own catalog, and a FaithfulCard application from one validated definition","license":"Apache-2.0","type":"module","sideEffects":false,"exports":{".":"./src/index.ts","./faithful-card":"./src/faithful-card/index.ts","./content-policy":"./src/content-policy/index.ts","./server":"./src/server/index.ts"},"files":["src","!src/**/*.test.ts","!src/**/*.test-support.ts"],"scripts":{"typecheck":"tsc --noEmit"},"dependencies":{"@a2ui/lit":"0.13.0","@a2ui/web_core":"0.13.0","@modelcontextprotocol/ext-apps":"2.0.3","@saga-a2ui/components":"0.8.0-rc.1","@saga-a2ui/core":"0.8.0-rc.1","@saga-a2ui/lit":"0.8.0-rc.1","@saga-a2ui/mcp":"0.8.0-rc.1","zod":"4.6.7"},"peerDependencies":{"lit":"^3.3.3"},"devDependencies":{"@modelcontextprotocol/client":"2.3.1","jsdom":"28.1.0","lit":"^3.3.3","typescript":"^5.9.0","vitest":"^5.0.4"},"version":"0.8.0-rc.1","engines":{"node":">=22.12.0"},"repository":{"type":"git","url":"https://github.com/MachineWisdomAI/saga-a2ui.git","directory":"packages/lit-mcp-stack"},"publishConfig":{"access":"public","tag":"next"}}
@@ -0,0 +1,31 @@
1
+ // An application callback that runs while the stack is still setting up (before there is a running
2
+ // view to report through). A throw from it must not escape `start`: the stack cleans up what it had
3
+ // made and returns a handle whose `ready` rejects with `StartFailure('application')`. Marking the
4
+ // throw keeps that apart from a misuse or a defect of the stack itself, which still throws.
5
+
6
+ class ApplicationCallFailure {
7
+ constructor(readonly cause: unknown) {}
8
+ }
9
+
10
+ /** Runs one application callback of the synchronous part of a start. */
11
+ export function callApplication<T>(call: () => T): T {
12
+ try {
13
+ return call();
14
+ } catch (cause) {
15
+ throw new ApplicationCallFailure(cause);
16
+ }
17
+ }
18
+
19
+ /** Ends the synchronous part of a start as the application's own failure (it threw, if not here). */
20
+ export function failApplication(cause: unknown): never {
21
+ throw new ApplicationCallFailure(cause);
22
+ }
23
+
24
+ /** The application's own throw, when `error` came out of {@link callApplication}. */
25
+ export function applicationFailureOf(
26
+ error: unknown,
27
+ ): { readonly cause: unknown } | undefined {
28
+ return error instanceof ApplicationCallFailure
29
+ ? { cause: error.cause }
30
+ : undefined;
31
+ }
@@ -0,0 +1,19 @@
1
+ import { StartError } from './start-failure.js';
2
+
3
+ // One view per container. A start claims the container; the claim ends when that view is gone from
4
+ // the screen (disposed, or ended by the host). A view that failed to start keeps its failure text in
5
+ // the container and so keeps the claim until the application disposes it. This is state about the
6
+ // container, not about the module: it is the one thing two starts of different entries must agree on.
7
+ const claimed = new WeakSet<Element>();
8
+
9
+ /** Claims `container` for one view, or throws `StartError` and changes nothing. Returns the release. */
10
+ export function claimContainer(container: unknown): {
11
+ readonly container: Element;
12
+ release(): void;
13
+ } {
14
+ if (!(container instanceof Element) || !container.isConnected)
15
+ throw new StartError('container-missing');
16
+ if (claimed.has(container)) throw new StartError('container-busy');
17
+ claimed.add(container);
18
+ return { container, release: () => void claimed.delete(container) };
19
+ }
@@ -0,0 +1,12 @@
1
+ // The content-policy entry of the stack: how a server states and embeds the content policy that
2
+ // the card application reads back from its document at startup. The policy is the owner's
3
+ // (`@saga-a2ui/components`); this entry only names it for an application that installs the stack.
4
+ // It carries no renderer and no delivery, and the own-catalog entry does not import it.
5
+ export {
6
+ createContentPolicy,
7
+ embedContentPolicy,
8
+ type ContentPolicy,
9
+ type CreatePolicyResult,
10
+ type PolicyConfiguration,
11
+ type PolicyFailure,
12
+ } from '@saga-a2ui/components/faithful-card';
@@ -0,0 +1,32 @@
1
+ import {
2
+ CONTENT_POLICY_ELEMENT_ID,
3
+ contentPolicyFromEmbedded,
4
+ type CreatePolicyResult,
5
+ } from '@saga-a2ui/components/faithful-card';
6
+
7
+ // Where a view finds what its server embedded in the document it served. The format belongs to
8
+ // `@saga-a2ui/components` (`embedContentPolicy`, `contentPolicyFromEmbedded`); reading the
9
+ // document is the stack’s, because components and the renderers take no document.
10
+
11
+ /**
12
+ * The content policy embedded in `doc`, validated again: no embedded policy means the Standard
13
+ * policy with empty lists, and anything that does not validate is a failure, so a view is never
14
+ * mounted on a guessed policy.
15
+ */
16
+ export function contentPolicyFromDocument(doc: Document): CreatePolicyResult {
17
+ return contentPolicyFromEmbedded(
18
+ doc.getElementById(CONTENT_POLICY_ELEMENT_ID)?.textContent ?? null,
19
+ );
20
+ }
21
+
22
+ /**
23
+ * The Content-Security-Policy values `doc` carries in `<meta http-equiv>` elements: the restrictions
24
+ * image loading relies on. They are passed to `createFaithfulCardView` with the policy; images
25
+ * load only when the document carries exactly what that policy derives.
26
+ */
27
+ export function documentContentSecurityPolicies(doc: Document): string[] {
28
+ return Array.from(
29
+ doc.querySelectorAll('meta[http-equiv="Content-Security-Policy" i]'),
30
+ (meta) => meta.getAttribute('content') ?? '',
31
+ );
32
+ }
@@ -0,0 +1,40 @@
1
+ // The Lit and MCP Apps stack, card entry: a FaithfulCard application started from one validated
2
+ // definition. The Lit card styles itself; there is no stylesheet to import.
3
+ export { FaithfulCardApp } from '@saga-a2ui/components/faithful-card';
4
+ export type {
5
+ CardContent,
6
+ CardResultOutcome,
7
+ CardResultReader,
8
+ FaithfulCardAppDefinition,
9
+ } from '@saga-a2ui/components/faithful-card';
10
+ // What an application's `result` reader receives: the delivery-neutral whole result.
11
+ export type { DeliveredResult } from '@saga-a2ui/core/delivered-result';
12
+ export {
13
+ startFaithfulCardApp,
14
+ type CardChrome,
15
+ type CardChromeParts,
16
+ type CardViewState,
17
+ type StartFaithfulCardOptions,
18
+ } from './start-faithful-card-app.js';
19
+ export {
20
+ contentPolicyFromDocument,
21
+ documentContentSecurityPolicies,
22
+ } from './document-policy.js';
23
+ // The failures `startFaithfulCardApp` reports, and the phase its `onError` callback is told: the
24
+ // same values the main entry exports, so one `catch` serves an application that uses both.
25
+ export {
26
+ StartError,
27
+ StartFailure,
28
+ type ErrorPhase,
29
+ type StartFailureKind,
30
+ type StartMisuse,
31
+ } from '../start-failure.js';
32
+ export type { RunningView } from '../running-view.js';
33
+ // A link the card's host can be asked to open, for the application's own chrome.
34
+ export {
35
+ bindHostLink,
36
+ type HostLinkBinding,
37
+ type HostLinkOutcome,
38
+ } from '@saga-a2ui/lit/faithful-card';
39
+ // How the reader meets the host (device or desktop), for an application that maps its own tokens.
40
+ export { readingProfile, type ReadingProfile } from '@saga-a2ui/mcp/view';
@@ -0,0 +1,253 @@
1
+ import {
2
+ readCardResult,
3
+ type CardResultOutcome,
4
+ type FaithfulCardAppDefinition,
5
+ } from '@saga-a2ui/components/faithful-card';
6
+ import {
7
+ createFaithfulCardView,
8
+ openFaithfulCardSurface,
9
+ provideContentView,
10
+ registerFaithfulCard,
11
+ } from '@saga-a2ui/lit/faithful-card';
12
+ import type { CardSurface, ContentView } from '@saga-a2ui/lit/faithful-card';
13
+ import {
14
+ deliveredResultFromToolResult,
15
+ hostLinksFromApp,
16
+ } from '@saga-a2ui/mcp/view';
17
+ import type { HostContext, ToolResult } from '@saga-a2ui/mcp/view';
18
+ import { html, render, type TemplateResult } from 'lit';
19
+ import { applicationFailureOf, callApplication } from '../application-call.js';
20
+ import { claimContainer } from '../container-claim.js';
21
+ import { connectToHost, type HostConnection } from '../host-connection.js';
22
+ import {
23
+ runView,
24
+ viewFailedBeforeConnecting,
25
+ viewThatNeverStarted,
26
+ type RunningView,
27
+ } from '../running-view.js';
28
+ import { StartFailure, type ErrorPhase } from '../start-failure.js';
29
+ import {
30
+ contentPolicyFromDocument,
31
+ documentContentSecurityPolicies,
32
+ } from './document-policy.js';
33
+
34
+ /** What the application’s chrome is told about the card, and what to say beside it. */
35
+ export type CardViewState =
36
+ | { readonly kind: 'waiting'; readonly text: string }
37
+ | {
38
+ readonly kind: 'answer';
39
+ readonly heading: string | undefined;
40
+ /** Advances with every presented answer, including one whose text equals the last. */
41
+ readonly presentation: number;
42
+ }
43
+ | { readonly kind: 'problem'; readonly text: string };
44
+
45
+ /** What the chrome function receives: the card to place, and the state to word around it. */
46
+ export interface CardChromeParts {
47
+ /** The card. Place it exactly once; it is empty until the first answer. */
48
+ readonly card: Node;
49
+ readonly state: CardViewState;
50
+ }
51
+
52
+ /** The application’s chrome: renders the card and the words around it. Called again on every change of state. */
53
+ export type CardChrome = (parts: CardChromeParts) => TemplateResult;
54
+
55
+ export interface StartFaithfulCardOptions {
56
+ /** The element the view is rendered into. Must be attached to the document and free. */
57
+ readonly container: Element;
58
+ /** `own`: the view tells the host its size. `host`: the bridge reports it. */
59
+ readonly sizing: 'own' | 'host';
60
+ /** Optional. Work the view needs before it shows anything (for example fonts); `signal` aborts when the view ends. */
61
+ readonly readyWhen?: (signal: AbortSignal) => Promise<void>;
62
+ /** Optional. The negotiated host context and the host’s name, before the first answer and on change. */
63
+ readonly hostContext?: (
64
+ context: HostContext | undefined,
65
+ hostName: string | undefined,
66
+ ) => void;
67
+ /** Optional. The application’s chrome around the card. By default the status text, then the card. */
68
+ readonly chrome?: CardChrome;
69
+ /**
70
+ * Optional. The application's constructable stylesheets for the card. The card sits inside shadow
71
+ * roots a page stylesheet cannot select into; each connected card adopts these into the root it
72
+ * lives in (see `createFaithfulCardView`). Custom properties need none of this: they inherit.
73
+ */
74
+ readonly styles?: readonly CSSStyleSheet[];
75
+ /** Optional. Receives a throw from a callback after the view was ready. Defaults to `console.error`. */
76
+ readonly onError?: (error: unknown, phase: ErrorPhase) => void;
77
+ }
78
+
79
+ const defaultChrome: CardChrome = ({ card, state }) =>
80
+ html`${
81
+ state.kind === 'answer'
82
+ ? state.heading === undefined
83
+ ? ''
84
+ : html`<h2>${state.heading}</h2>`
85
+ : html`<p role="status">${state.text}</p>`
86
+ }${card}`;
87
+
88
+ /**
89
+ * Starts a card application in `options.container` and returns it at once. The embedded policy is
90
+ * read from the container’s document, the host is connected with its handlers installed first,
91
+ * and each delivered result is read by the definition’s one `result` reader and shown in the card: a new
92
+ * presentation each time, even for equal text. Throws `StartError` (`container-missing`,
93
+ * `container-busy`) before connecting to anything.
94
+ * An application callback that throws while the view is being set up (the initial `chrome` call) does not
95
+ * throw out of `start`: the stack takes back what it made, frees the container and returns a
96
+ * view whose `ready` rejects with `StartFailure` of kind `application`.
97
+ */
98
+ export function startFaithfulCardApp(
99
+ definition: FaithfulCardAppDefinition,
100
+ options: StartFaithfulCardOptions,
101
+ ): RunningView {
102
+ return startFaithfulCardAppOn(
103
+ () => connectToHost(definition.identity, options.sizing),
104
+ definition,
105
+ options,
106
+ );
107
+ }
108
+
109
+ /** {@link startFaithfulCardApp} over a connection the caller supplies: the seam the stack’s own tests use. */
110
+ export function startFaithfulCardAppOn(
111
+ connect: () => HostConnection,
112
+ definition: FaithfulCardAppDefinition,
113
+ options: StartFaithfulCardOptions,
114
+ ): RunningView {
115
+ const claim = claimContainer(options.container);
116
+ // The view renders into an element of its own, so removing it leaves the container as it was.
117
+ const mount = document.createElement('div');
118
+ mount.style.display = 'contents';
119
+ let stopProviding: (() => void) | undefined;
120
+ let view: ContentView | undefined;
121
+ let surface: CardSurface | undefined;
122
+ try {
123
+ const { texts } = definition;
124
+ const chrome = options.chrome ?? defaultChrome;
125
+ let state: CardViewState = { kind: 'waiting', text: texts.waiting };
126
+ let card: Node = document.createDocumentFragment();
127
+ const show = (next: CardViewState): void => {
128
+ state = next;
129
+ render(chrome({ card, state }), mount);
130
+ };
131
+ const unmount = (): void => {
132
+ stopProviding?.();
133
+ mount.remove();
134
+ };
135
+ claim.container.append(mount);
136
+
137
+ const policy = contentPolicyFromDocument(claim.container.ownerDocument);
138
+ if (!policy.ok) {
139
+ callApplication(() =>
140
+ show({ kind: 'problem', text: texts.policyFailure }),
141
+ );
142
+ return viewFailedBeforeConnecting({
143
+ failure: new StartFailure('policy', policy.failure),
144
+ unmount,
145
+ releaseContainer: claim.release,
146
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
147
+ });
148
+ }
149
+
150
+ const connection = connect();
151
+ const lifetime = new AbortController();
152
+ const cardView = (view = createFaithfulCardView({
153
+ ...definition.reader,
154
+ policy: policy.policy,
155
+ contentSecurityPolicies: documentContentSecurityPolicies(
156
+ claim.container.ownerDocument,
157
+ ),
158
+ hostLinks: hostLinksFromApp(connection.app, lifetime.signal),
159
+ ...(options.styles === undefined ? {} : { styles: options.styles }),
160
+ }));
161
+ registerFaithfulCard();
162
+ const opened = (surface = openFaithfulCardSurface());
163
+ card = opened.element;
164
+ // The card asks the nearest view for its settings when it connects, so the view is provided first.
165
+ stopProviding = provideContentView(mount, cardView);
166
+ callApplication(() => show(state));
167
+
168
+ const report =
169
+ options.onError ?? ((error: unknown) => console.error(error));
170
+ let presentation = 0;
171
+ const problem = (text: string): void => {
172
+ opened.clear();
173
+ show({ kind: 'problem', text });
174
+ };
175
+ /**
176
+ * The definition's one reader decides what the whole result means. A throw from the reader or
177
+ * from mapping the delivery's result is reported (phase `result`) and rejects the result.
178
+ */
179
+ const read = (result: ToolResult): CardResultOutcome =>
180
+ readCardResult(
181
+ definition,
182
+ () => deliveredResultFromToolResult(result),
183
+ (error) => {
184
+ try {
185
+ report(error, 'result');
186
+ } catch {
187
+ // A reporter that throws must not stop the answer from clearing.
188
+ }
189
+ },
190
+ );
191
+
192
+ return runView({
193
+ connection,
194
+ lifetime,
195
+ releaseContainer: claim.release,
196
+ sizing: options.sizing,
197
+ ...(options.readyWhen === undefined
198
+ ? {}
199
+ : { readyWhen: options.readyWhen }),
200
+ ...(options.hostContext === undefined
201
+ ? {}
202
+ : { hostContext: options.hostContext }),
203
+ // Every result is a new selection: `present` ends the earlier presentation, image consent
204
+ // included, even when the Markdown equals the previous one.
205
+ onToolResult(result) {
206
+ const outcome = read(result);
207
+ if (outcome.kind === 'rejected') {
208
+ // The application's wording for this rejection, else the definition's.
209
+ problem(outcome.text ?? texts.problem);
210
+ return;
211
+ }
212
+ if (!opened.present(outcome.content).ok) {
213
+ problem(texts.problem);
214
+ return;
215
+ }
216
+ presentation += 1;
217
+ show({
218
+ kind: 'answer',
219
+ heading: outcome.content.heading,
220
+ presentation,
221
+ });
222
+ },
223
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
224
+ retire() {
225
+ cardView.consent.retire();
226
+ opened.dispose();
227
+ },
228
+ unmount,
229
+ showFailure(failure) {
230
+ const text = {
231
+ policy: texts.policyFailure,
232
+ connect: texts.connectFailure,
233
+ ready: texts.readyFailure,
234
+ application: texts.problem,
235
+ disposed: texts.problem,
236
+ }[failure.kind];
237
+ show({ kind: 'problem', text });
238
+ return true;
239
+ },
240
+ });
241
+ } catch (error) {
242
+ // Nothing connected: take back what this start made and free the container.
243
+ stopProviding?.();
244
+ mount.remove();
245
+ view?.consent.retire();
246
+ surface?.dispose();
247
+ claim.release();
248
+ const failed = applicationFailureOf(error);
249
+ if (failed === undefined) throw error;
250
+ // The application's chrome threw before a view existed: `ready` carries the failure.
251
+ return viewThatNeverStarted(failed.cause);
252
+ }
253
+ }
@@ -0,0 +1,39 @@
1
+ import { App, PostMessageTransport } from '@modelcontextprotocol/ext-apps';
2
+
3
+ /**
4
+ * The two halves of a connection to the MCP Apps host: the bridge and the transport it will connect
5
+ * over. Making them is the stack’s job so that no application imports the bridge package; a start
6
+ * takes the pair as a value so a test can supply a bridge joined to an in-memory host.
7
+ */
8
+ export interface HostConnection {
9
+ readonly app: App;
10
+ readonly transport: NonNullable<Parameters<App['connect']>[0]>;
11
+ }
12
+
13
+ /** What a server tool call answers: the reply type of the bridge’s own `callServerTool`. */
14
+ export type ServerReply = Awaited<ReturnType<App['callServerTool']>>;
15
+
16
+ export interface HostIdentity {
17
+ readonly name: string;
18
+ readonly version: string;
19
+ }
20
+
21
+ /**
22
+ * The connection a view uses in a host’s iframe: a bridge named for the application and the
23
+ * `postMessage` transport to the embedding window. With `own` sizing the view tells the host its
24
+ * size itself (`startOwnSizing`), so the bridge’s automatic resizing is turned off and sizing has
25
+ * exactly one owner.
26
+ */
27
+ export function connectToHost(
28
+ identity: HostIdentity,
29
+ sizing: 'own' | 'host',
30
+ ): HostConnection {
31
+ return {
32
+ app: new App(
33
+ { name: identity.name, version: identity.version },
34
+ {},
35
+ sizing === 'own' ? { autoResize: false } : undefined,
36
+ ),
37
+ transport: new PostMessageTransport(window.parent, window.parent),
38
+ };
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,58 @@
1
+ // The Lit and MCP Apps stack, main entry: an application's own catalog and nothing else. It
2
+ // imports nothing from `@saga-a2ui/components`, so an own-catalog application's emitted browser
3
+ // bundle holds neither the FaithfulCard nor a Markdown parser. (Its installed tree does include
4
+ // them, as declared dependencies of the stack; the card application's entry is `/faithful-card`.)
5
+ //
6
+ // An application that installs this stack and Lit writes its view, its catalog and its actions
7
+ // against the names below and declares no other SDK or upstream package for them. The list is
8
+ // what the qualifying consumers use, no more.
9
+ export {
10
+ startA2uiView,
11
+ type BoundSurface,
12
+ type RunningA2uiView,
13
+ type StartA2uiViewOptions,
14
+ type ViewHost,
15
+ } from './start-a2ui-view.js';
16
+ // What a start can fail with and the phase an `onError` callback is told; the card entry shares them.
17
+ export {
18
+ StartError,
19
+ StartFailure,
20
+ type ErrorPhase,
21
+ type StartFailureKind,
22
+ type StartMisuse,
23
+ } from './start-failure.js';
24
+ export type { RunningView } from './running-view.js';
25
+ // The shapes of the two notifications an application's handlers receive.
26
+ export type { ToolInput, ToolResult } from '@saga-a2ui/mcp/view';
27
+ // How the reader meets the host (device or desktop), for an application that maps its own tokens.
28
+ export { readingProfile, type ReadingProfile } from '@saga-a2ui/mcp/view';
29
+ // The link opener a running view hands its actions, for an optional card the catalog includes.
30
+ export type { HostLinks } from '@saga-a2ui/core/host-links';
31
+ // The conversation a running view hands its actions, and the results of adding a message to it.
32
+ export type {
33
+ AppendResult,
34
+ Conversation,
35
+ RequestOutcome,
36
+ } from '@saga-a2ui/core/conversation';
37
+ // The authoring surface of an own-catalog application: the layout and its schemas.
38
+ export { defineSurface } from '@saga-a2ui/core/protocols/a2ui/v0_9';
39
+ export type { SurfaceLayout } from '@saga-a2ui/core/protocols/a2ui/v0_9';
40
+ export { z } from '@saga-a2ui/core/protocols/a2ui/zod3';
41
+ // The catalog an application builds: its components over upstream's component API, and the
42
+ // catalog value and schemas it declares them with.
43
+ export {
44
+ A2uiLitElement,
45
+ basicCatalog,
46
+ Catalog,
47
+ CommonSchemas,
48
+ type LitComponentApi,
49
+ } from '@saga-a2ui/lit';
50
+ // The actions an application attaches to the controls it renders.
51
+ export {
52
+ ActionButton,
53
+ actionButtonEntry,
54
+ createLitActions,
55
+ type ActionButtonActivation,
56
+ type LitActionsOptions,
57
+ } from '@saga-a2ui/lit/actions';
58
+ export { Action, type ActionBinding } from '@saga-a2ui/core/actions';
@@ -0,0 +1,215 @@
1
+ import {
2
+ runToolResultView,
3
+ startOwnSizing,
4
+ ViewStartFailure,
5
+ type HostContext,
6
+ type ToolInput,
7
+ type ToolResult,
8
+ } from '@saga-a2ui/mcp/view';
9
+ import type { HostConnection } from './host-connection.js';
10
+ import { StartFailure, type ErrorPhase } from './start-failure.js';
11
+
12
+ // What both entries of the stack share once they have something to show: one view in one container
13
+ // whose lifetime is `runToolResultView`'s. It adds what is the stack’s alone: the typed failure,
14
+ // own sizing that starts only once the host can be told, the claim on the container, and when a
15
+ // view that has ended leaves the screen. It decides nothing about what is shown.
16
+
17
+ /** The handle both entries return, synchronously. */
18
+ export interface RunningView {
19
+ /**
20
+ * Settles when the embedded policy was valid, the host connected with the handlers installed
21
+ * first, the latest host context was applied and the application's readiness work finished.
22
+ * Rejects with a {@link StartFailure} otherwise. Ignoring it never causes an unhandled rejection.
23
+ */
24
+ readonly ready: Promise<void>;
25
+ /**
26
+ * Ends the view and removes what it showed, whatever state it is in: ready, still starting, or
27
+ * failed (a failed view keeps its failure text on screen until it is disposed). Idempotent;
28
+ * settles after cleanup and never rejects. Afterwards the container may be started again.
29
+ */
30
+ dispose(): Promise<void>;
31
+ }
32
+
33
+ export interface RunViewOptions {
34
+ readonly connection: HostConnection;
35
+ /** Aborts when the view ends. Anything the view started for the host (links, sizing) listens to it. */
36
+ readonly lifetime: AbortController;
37
+ /** Frees the container; called once, after `unmount`. */
38
+ readonly releaseContainer: () => void;
39
+ readonly sizing: 'own' | 'host';
40
+ readonly readyWhen?: (signal: AbortSignal) => Promise<void>;
41
+ readonly hostContext?: (
42
+ context: HostContext | undefined,
43
+ hostName: string | undefined,
44
+ ) => void;
45
+ /** Called for each delivered result once the view is ready (the held one at that moment). */
46
+ readonly onToolResult: (result: ToolResult) => void;
47
+ /** Called for the tool call that is starting, once the view is ready and before the held result. */
48
+ readonly onToolInput?: (input: ToolInput) => void;
49
+ readonly onError?: (error: unknown, phase: ErrorPhase) => void;
50
+ /** The first step of ending, once, before the connection ends: retire consent and the surface. */
51
+ readonly retire: () => void;
52
+ /** Removes everything the view rendered. Called once. */
53
+ readonly unmount: () => void;
54
+ /**
55
+ * Shows why the view did not start. Returns true when the failure is now on screen, which keeps
56
+ * the view mounted until it is disposed. Not asked for `disposed`, which shows nothing.
57
+ */
58
+ readonly showFailure?: (failure: StartFailure) => boolean;
59
+ }
60
+
61
+ function startFailureOf(failure: unknown): StartFailure {
62
+ return failure instanceof ViewStartFailure
63
+ ? new StartFailure(failure.kind, failure.cause)
64
+ : new StartFailure('application', failure);
65
+ }
66
+
67
+ export function runView(options: RunViewOptions): RunningView {
68
+ const { app, transport } = options.connection;
69
+ const report = options.onError ?? ((error: unknown) => console.error(error));
70
+ let onScreen = true;
71
+ let failureShown = false;
72
+ let sizingStarted = false;
73
+
74
+ const reportError = (error: unknown, phase: ErrorPhase): void => {
75
+ try {
76
+ report(error, phase);
77
+ } catch {
78
+ // A reporter that throws must not stop cleanup.
79
+ }
80
+ };
81
+
82
+ /** The view is gone from the screen: unmount, then free the container, whatever unmount did. */
83
+ const leave = (): void => {
84
+ if (!onScreen) return;
85
+ onScreen = false;
86
+ try {
87
+ options.unmount();
88
+ } finally {
89
+ options.releaseContainer();
90
+ }
91
+ };
92
+
93
+ const running = runToolResultView({
94
+ app,
95
+ transport,
96
+ ...(options.readyWhen === undefined
97
+ ? {}
98
+ : { readyWhen: options.readyWhen }),
99
+ onToolResult: options.onToolResult,
100
+ ...(options.onToolInput === undefined
101
+ ? {}
102
+ : { onToolInput: options.onToolInput }),
103
+ onHostContext(context, hostName) {
104
+ // Told only once the host can hear it: sizing before the handshake would be dropped, and the
105
+ // size it measured would then count as sent.
106
+ if (options.sizing === 'own' && !sizingStarted) {
107
+ sizingStarted = true;
108
+ startOwnSizing(app, options.lifetime.signal);
109
+ }
110
+ options.hostContext?.(context, hostName);
111
+ },
112
+ onTeardown(startupFailure) {
113
+ options.lifetime.abort();
114
+ const failures: unknown[] = [];
115
+ try {
116
+ options.retire();
117
+ } catch (error) {
118
+ failures.push(error);
119
+ }
120
+ // Whatever ended the view, nothing it showed may outlast its connection. Only a start that
121
+ // failed keeps something on screen: the failure, which is known only after the connection
122
+ // has ended (see below).
123
+ if (startupFailure === undefined) {
124
+ try {
125
+ leave();
126
+ } catch (error) {
127
+ reportError(error, 'teardown');
128
+ }
129
+ }
130
+ queueMicrotask(() => {
131
+ void running.dispose().then(() => {
132
+ if (!failureShown) {
133
+ try {
134
+ leave();
135
+ } catch (error) {
136
+ reportError(error, 'teardown');
137
+ }
138
+ }
139
+ });
140
+ });
141
+ // Every step ran; the runner reports the first thing that threw and still ends the connection.
142
+ if (failures.length > 0) throw failures[0];
143
+ },
144
+ onFailure(failure) {
145
+ const startFailure = startFailureOf(failure);
146
+ if (startFailure.kind !== 'disposed')
147
+ failureShown = options.showFailure?.(startFailure) ?? false;
148
+ },
149
+ onError: options.onError ?? ((error, phase) => reportError(error, phase)),
150
+ });
151
+
152
+ const readiness = running.ready.then(
153
+ () => undefined,
154
+ (failure: unknown) => {
155
+ throw startFailureOf(failure);
156
+ },
157
+ );
158
+ readiness.catch(() => undefined);
159
+
160
+ return {
161
+ ready: readiness,
162
+ async dispose() {
163
+ await running.dispose();
164
+ try {
165
+ leave();
166
+ } catch (error) {
167
+ reportError(error, 'teardown');
168
+ }
169
+ },
170
+ };
171
+ }
172
+
173
+ /**
174
+ * The view of a start that failed before it connected to anything (an invalid embedded policy):
175
+ * its failure is already on screen, `ready` rejects with it, and disposing it removes it.
176
+ */
177
+ export function viewFailedBeforeConnecting(options: {
178
+ readonly failure: StartFailure;
179
+ readonly unmount: () => void;
180
+ readonly releaseContainer: () => void;
181
+ readonly onError?: (error: unknown, phase: ErrorPhase) => void;
182
+ }): RunningView {
183
+ let onScreen = true;
184
+ const ready = Promise.reject<void>(options.failure);
185
+ ready.catch(() => undefined);
186
+ return {
187
+ ready,
188
+ async dispose() {
189
+ if (!onScreen) return;
190
+ onScreen = false;
191
+ try {
192
+ options.unmount();
193
+ } catch (error) {
194
+ try {
195
+ (options.onError ?? ((e) => console.error(e)))(error, 'teardown');
196
+ } catch {
197
+ // Nothing more to do for a reporter that throws.
198
+ }
199
+ } finally {
200
+ options.releaseContainer();
201
+ }
202
+ },
203
+ };
204
+ }
205
+
206
+ /**
207
+ * The view of a start whose application callback threw before anything ran: the stack already took
208
+ * back what it had made and freed the container, so `ready` rejects with the failure and there is
209
+ * nothing left to dispose.
210
+ */
211
+ export function viewThatNeverStarted(cause: unknown): RunningView {
212
+ const ready = Promise.reject<void>(new StartFailure('application', cause));
213
+ ready.catch(() => undefined);
214
+ return { ready, dispose: () => Promise.resolve() };
215
+ }
@@ -0,0 +1,15 @@
1
+ // The server entry of the stack: what an application's MCP server composes to serve a card or an
2
+ // own-catalog view, from the same package it installs for the view. It re-exports the delivery
3
+ // owner's named operations and nothing from a renderer, `@saga-a2ui/components` or the browser
4
+ // entries, so a server never loads a renderer and a browser bundle never loads a server module.
5
+ // The operations, their failures and their lifetimes are specified in `@saga-a2ui/mcp/server`.
6
+ export {
7
+ attachRequestLifetime,
8
+ createServerBudgets,
9
+ operationViewFromHtml,
10
+ registerProtectedOperation,
11
+ registerPublicOperation,
12
+ viewUriForHtml,
13
+ type OperationView,
14
+ type RequestLifetime,
15
+ } from '@saga-a2ui/mcp/server';
@@ -0,0 +1,268 @@
1
+ import type { LitComponentApi } from '@a2ui/lit/v0_9';
2
+ import type { Catalog } from '@a2ui/web_core/v0_9';
3
+ import type { ServerTransport } from '@saga-a2ui/core/actions';
4
+ import { type SurfaceLayout } from '@saga-a2ui/core/protocols/a2ui/v0_9';
5
+ import {
6
+ createA2uiAppElement,
7
+ defineElements,
8
+ type A2uiActions,
9
+ type A2uiUpdateResult,
10
+ } from '@saga-a2ui/lit';
11
+ import type { Conversation } from '@saga-a2ui/core/conversation';
12
+ import type { HostLinks } from '@saga-a2ui/core/host-links';
13
+ import {
14
+ conversationFromApp,
15
+ hostLinksFromApp,
16
+ type HostContext,
17
+ type ToolInput,
18
+ type ToolResult,
19
+ } from '@saga-a2ui/mcp/view';
20
+ import {
21
+ applicationFailureOf,
22
+ callApplication,
23
+ failApplication,
24
+ } from './application-call.js';
25
+ import { claimContainer } from './container-claim.js';
26
+ import {
27
+ connectToHost,
28
+ type HostConnection,
29
+ type HostIdentity,
30
+ type ServerReply,
31
+ } from './host-connection.js';
32
+ import {
33
+ runView,
34
+ viewThatNeverStarted,
35
+ type RunningView,
36
+ } from './running-view.js';
37
+ import type { ErrorPhase } from './start-failure.js';
38
+
39
+ /** What the application may use of the host while it states its actions. */
40
+ export interface ViewHost {
41
+ /** The way an action reaches the application’s server, through the host. */
42
+ readonly server: ServerTransport<ServerReply>;
43
+ /** The one way to ask the host to open a link, for an optional card the application's catalog includes. Ends with the view. */
44
+ readonly links: HostLinks;
45
+ /** The one way to add a message to the conversation, optionally with context for the assistant. Ends with the view. */
46
+ readonly conversation: Conversation;
47
+ }
48
+
49
+ /** The typed way to change what a running view shows. */
50
+ export interface BoundSurface<TData> {
51
+ /**
52
+ * Validates `data` against the layout and applies it in place: no remount, so the mounted
53
+ * controls, their action bindings and focus survive. Never throws. A rejection (data the layout’s
54
+ * schema refuses, or a view that has ended) returns the failure and changes nothing.
55
+ */
56
+ update(data: TData): A2uiUpdateResult;
57
+ }
58
+
59
+ export interface StartA2uiViewOptions<TData> {
60
+ /** The element the view is rendered into. Must be attached to the document and free. */
61
+ readonly container: Element;
62
+ /** The one surface the view presents: its identity, its data type and how it opens. */
63
+ readonly layout: SurfaceLayout<TData>;
64
+ /**
65
+ * The application's own catalog. The stack defines each component's custom element (repeating
66
+ * that for a catalog that is already defined is harmless).
67
+ */
68
+ readonly catalog: Catalog<LitComponentApi>;
69
+ /**
70
+ * Optional. The application’s action setup (`createLitActions`), or a function that makes it
71
+ * from the host when the setup needs the server (`host.server`).
72
+ */
73
+ readonly actions?:
74
+ A2uiActions | ((host: ViewHost) => A2uiActions | undefined);
75
+ /** Optional. Work the view needs before it shows anything; `signal` aborts when the view ends. */
76
+ readonly readyWhen?: (signal: AbortSignal) => Promise<void>;
77
+ /** `own`: the view tells the host its size. `host` (the default): the bridge reports it. */
78
+ readonly sizing?: 'own' | 'host';
79
+ /** Optional. The negotiated host context and the host’s name, before the first result and on change. */
80
+ readonly hostContext?: (
81
+ context: HostContext | undefined,
82
+ hostName: string | undefined,
83
+ ) => void;
84
+ /**
85
+ * Optional. The tool call that is starting, with its own arguments: the only place the host
86
+ * announces them. Delivered once the view is ready, before the held result. It is not that
87
+ * call's response and authenticates nothing.
88
+ */
89
+ readonly onToolInput?: (input: ToolInput) => void;
90
+ /** Each delivered result, once the view is ready. Update the surface through `view.surface`. */
91
+ readonly onToolResult: (
92
+ result: ToolResult,
93
+ view: RunningA2uiView<TData>,
94
+ ) => void;
95
+ /**
96
+ * Optional. Called once, whichever way the view ends (host teardown request, `dispose()`,
97
+ * `pagehide` or a startup failure), after the surface has been retired and before the connection
98
+ * ends. For an application that holds something outside the page's own rendering. It must
99
+ * tolerate being called on a view that never showed anything; a throw is reported and never
100
+ * skips the connection's disposal.
101
+ */
102
+ readonly onTeardown?: () => void;
103
+ /** Optional. Receives a throw from a callback after the view was ready. Defaults to `console.error`. */
104
+ readonly onError?: (error: unknown, phase: ErrorPhase) => void;
105
+ /** Optional. Who the host sees. Defaults to the layout’s surface id at version `0.0.0`. */
106
+ readonly identity?: HostIdentity;
107
+ }
108
+
109
+ /** The running view of an own-catalog application, and the typed way to update what it shows. */
110
+ export interface RunningA2uiView<TData> extends RunningView {
111
+ readonly surface: BoundSurface<TData>;
112
+ }
113
+
114
+ /** Each view is its own custom element, so each needs a tag of its own. */
115
+ let views = 0;
116
+
117
+ /**
118
+ * Starts an own-catalog view in `options.container` and returns it at once. The view connects to
119
+ * the MCP Apps host, holds results that arrive before it is ready, presents the layout over the
120
+ * catalog and gives each result to `onToolResult` with the bound surface to update. Throws
121
+ * `StartError` (`container-missing`, `container-busy`) before connecting to anything.
122
+ * An application callback that throws while the view is being set up (the `actions` factory) does not
123
+ * throw out of `start`: the stack takes back what it made, frees the container and returns a
124
+ * view whose `ready` rejects with `StartFailure` of kind `application`. Imports
125
+ * nothing from `@saga-a2ui/components`.
126
+ */
127
+ export function startA2uiView<TData>(
128
+ options: StartA2uiViewOptions<TData>,
129
+ ): RunningA2uiView<TData> {
130
+ return startA2uiViewOn(
131
+ () =>
132
+ connectToHost(
133
+ options.identity ?? {
134
+ name: options.layout.surfaceId,
135
+ version: '0.0.0',
136
+ },
137
+ options.sizing ?? 'host',
138
+ ),
139
+ options,
140
+ );
141
+ }
142
+
143
+ /** {@link startA2uiView} over a connection the caller supplies: the seam the stack’s own tests use. */
144
+ export function startA2uiViewOn<TData>(
145
+ connect: () => HostConnection,
146
+ options: StartA2uiViewOptions<TData>,
147
+ ): RunningA2uiView<TData> {
148
+ const claim = claimContainer(options.container);
149
+ let element: Element | undefined;
150
+ try {
151
+ const connection = connect();
152
+ const { app } = connection;
153
+ const lifetime = new AbortController();
154
+ const { actions: makeActions } = options;
155
+ const actions =
156
+ typeof makeActions === 'function'
157
+ ? callApplication(() =>
158
+ makeActions({
159
+ server: {
160
+ callServerTool: (request, requestOptions) =>
161
+ app.callServerTool(request, requestOptions),
162
+ },
163
+ links: hostLinksFromApp(app, lifetime.signal),
164
+ conversation: conversationFromApp(app, lifetime.signal),
165
+ }),
166
+ )
167
+ : makeActions;
168
+
169
+ // The app element presents the surface, and so starts the actions, as it connects. A setup
170
+ // that throws there is swallowed into the element's safe fallback after the application's sink
171
+ // heard it; the stack notes it here, so the start fails as `application` instead of reporting
172
+ // a view that shows nothing. Only the first presentation, made as the element connects, counts.
173
+ let connecting = true;
174
+ let setupFailure: { readonly cause: unknown } | undefined;
175
+ const watched: A2uiActions | undefined =
176
+ actions === undefined
177
+ ? undefined
178
+ : {
179
+ begin(mount) {
180
+ try {
181
+ return actions.begin(mount);
182
+ } catch (error) {
183
+ if (connecting) setupFailure ??= { cause: error };
184
+ throw error;
185
+ }
186
+ },
187
+ };
188
+
189
+ defineElements([...options.catalog.components.values()]);
190
+ const AppElement = createA2uiAppElement({
191
+ catalog: options.catalog,
192
+ layout: options.layout,
193
+ ...(watched === undefined ? {} : { actions: watched }),
194
+ });
195
+ views += 1;
196
+ customElements.define(`saga-a2ui-view-${views}`, AppElement);
197
+ const shown = new AppElement();
198
+ element = shown;
199
+ try {
200
+ claim.container.append(shown);
201
+ } finally {
202
+ connecting = false;
203
+ }
204
+ if (setupFailure !== undefined) failApplication(setupFailure.cause);
205
+
206
+ const surface: BoundSurface<TData> = {
207
+ update: (data) => shown.updateData(data),
208
+ };
209
+ const remove = (): void => shown.remove();
210
+
211
+ const running = runView({
212
+ connection,
213
+ lifetime,
214
+ releaseContainer: claim.release,
215
+ sizing: options.sizing ?? 'host',
216
+ ...(options.readyWhen === undefined
217
+ ? {}
218
+ : { readyWhen: options.readyWhen }),
219
+ ...(options.hostContext === undefined
220
+ ? {}
221
+ : { hostContext: options.hostContext }),
222
+ onToolResult: (result) => options.onToolResult(result, view),
223
+ ...(options.onToolInput === undefined
224
+ ? {}
225
+ : { onToolInput: options.onToolInput }),
226
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
227
+ retire() {
228
+ try {
229
+ remove();
230
+ } finally {
231
+ options.onTeardown?.();
232
+ }
233
+ },
234
+ unmount: remove,
235
+ });
236
+ const view: RunningA2uiView<TData> = { ...running, surface };
237
+ return view;
238
+ } catch (error) {
239
+ element?.remove();
240
+ claim.release();
241
+ const failed = applicationFailureOf(error);
242
+ if (failed === undefined) throw error;
243
+ // The application's own callback threw before a view existed: nothing connected, so what was
244
+ // made is gone and the view ends as it would for any other startup failure, with `onTeardown`
245
+ // told once. `ready` carries the failure; the container is free for another start.
246
+ try {
247
+ options.onTeardown?.();
248
+ } catch (teardownError) {
249
+ try {
250
+ (options.onError ?? ((e) => console.error(e)))(
251
+ teardownError,
252
+ 'teardown',
253
+ );
254
+ } catch {
255
+ // A reporter that throws must not turn a typed startup failure into a throw.
256
+ }
257
+ }
258
+ return {
259
+ ...viewThatNeverStarted(failed.cause),
260
+ surface: {
261
+ update: () => ({
262
+ ok: false,
263
+ failure: { kind: 'rejected', message: 'The app is not connected.' },
264
+ }),
265
+ },
266
+ };
267
+ }
268
+ }
@@ -0,0 +1,41 @@
1
+ import type { ViewErrorPhase, ViewFailureKind } from '@saga-a2ui/mcp/view';
2
+
3
+ /**
4
+ * Why a view did not become ready.
5
+ *
6
+ * - `policy`: the embedded content policy is malformed or not valid; no connection was made.
7
+ * - `connect`: the handshake with the host failed.
8
+ * - `ready`: the application's own readiness work rejected.
9
+ * - `application`: an application callback threw while the view was starting. Cleanup completed
10
+ * before this was reported.
11
+ * - `disposed`: the view was ended (dispose, host teardown or `pagehide`) before it was ready.
12
+ */
13
+ export type StartFailureKind = 'policy' | ViewFailureKind;
14
+
15
+ /** The reason `ready` rejects. */
16
+ export class StartFailure extends Error {
17
+ constructor(
18
+ readonly kind: StartFailureKind,
19
+ readonly cause?: unknown,
20
+ ) {
21
+ super(`The view did not become ready (${kind}).`);
22
+ this.name = 'StartFailure';
23
+ }
24
+ }
25
+
26
+ /** Where an application callback threw after the view was ready. */
27
+ export type ErrorPhase = ViewErrorPhase;
28
+
29
+ /** Misuse of `start`, thrown before any connection is made. */
30
+ export type StartMisuse = 'container-missing' | 'container-busy';
31
+
32
+ export class StartError extends Error {
33
+ constructor(readonly code: StartMisuse) {
34
+ super(
35
+ code === 'container-busy'
36
+ ? 'container-busy: a view is already running in this container; dispose it first.'
37
+ : 'container-missing: the container is missing or not attached to the document.',
38
+ );
39
+ this.name = 'StartError';
40
+ }
41
+ }