@agimon-ai/po-native 0.0.1-alpha.3 → 0.0.1-alpha.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-native",
3
- "version": "0.0.1-alpha.3",
3
+ "version": "0.0.1-alpha.4",
4
4
  "description": "Po for iOS and Android",
5
5
  "homepage": "https://agimon.ai",
6
6
  "bugs": {
@@ -29,15 +29,15 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@agimon-ai/po-core": "0.0.0-alpha.123",
33
- "@agimon-ai/po-expo-signing": "0.0.1-alpha.3",
34
- "@agimon-ai/po-identity": "0.0.2-alpha.70",
35
- "@agimon-ai/po-native-components": "0.0.0-alpha.123",
36
- "@agimon-ai/po-template-advanced": "0.0.0-alpha.123",
37
- "@agimon-ai/po-voice": "0.0.0-alpha.123",
38
- "@agimon-ai/po-web-components": "0.0.0-alpha.123",
39
- "@agimon-ai/po-web-dashboard": "0.0.0-alpha.123",
40
- "@agimon-ai/po-web-security": "0.0.0-alpha.123",
32
+ "@agimon-ai/po-core": "0.0.0-alpha.124",
33
+ "@agimon-ai/po-expo-signing": "0.0.1-alpha.4",
34
+ "@agimon-ai/po-identity": "0.0.2-alpha.71",
35
+ "@agimon-ai/po-native-components": "0.0.0-alpha.124",
36
+ "@agimon-ai/po-template-advanced": "0.0.0-alpha.124",
37
+ "@agimon-ai/po-voice": "0.0.0-alpha.124",
38
+ "@agimon-ai/po-web-components": "0.0.0-alpha.124",
39
+ "@agimon-ai/po-web-dashboard": "0.0.0-alpha.124",
40
+ "@agimon-ai/po-web-security": "0.0.0-alpha.124",
41
41
  "@better-auth/expo": "1.7.12",
42
42
  "@config-plugins/react-native-webrtc": "15.0.2",
43
43
  "@earendil-works/chord": "1.5.0",
package/src/app/App.tsx CHANGED
@@ -136,6 +136,7 @@ import {
136
136
  cropAuthorImage,
137
137
  } from '../components/richActivity/AuthorMediaHost';
138
138
  import { createRichActivityRenderers, nativeSaveFile } from '../components/richActivity/createRichActivityRenderers';
139
+ import { McpAppView } from '../components/richActivity/McpAppView';
139
140
  import { NativeAuthorCaptureSurface } from '../components/richActivity/NativeAuthorCaptureSurface';
140
141
  import { NativeAuthorHtmlView } from '../components/richActivity/NativeAuthorHtmlView';
141
142
  import { SessionOptionsSheet } from '../components/SessionOptionsSheet';
@@ -737,6 +738,7 @@ function SessionRoute({
737
738
  },
738
739
  {
739
740
  ...richRenderers,
741
+ renderMcpApp: ({ key, toolCallId }) => <McpAppView key={key} toolCallId={toolCallId} sessionId={sessionId} />,
740
742
  nativeSaveFile,
741
743
  nativeAudio,
742
744
  runNativeVoice,
@@ -0,0 +1,62 @@
1
+ import { NATIVE_THEMES, type PoNativeTheme } from '@agimon-ai/po-web-components/nativeTheme';
2
+ import { View } from 'react-native';
3
+ import { StyleSheet, UnistylesRuntime } from 'react-native-unistyles';
4
+
5
+ import { PhoneFrame } from '../../screens/designFrame';
6
+ import { McpAppChrome, type McpAppStatus } from './McpAppChrome';
7
+
8
+ function Target({
9
+ status,
10
+ scheme = 'light',
11
+ large = false,
12
+ }: {
13
+ status: McpAppStatus;
14
+ scheme?: 'light' | 'dark';
15
+ large?: boolean;
16
+ }) {
17
+ const base = NATIVE_THEMES[scheme];
18
+ const scaled = (ramp: PoNativeTheme['fontSize']) =>
19
+ Object.fromEntries(
20
+ Object.entries(ramp).map(([key, value]) => [key, value * (large ? 1.5 : 1)]),
21
+ ) as PoNativeTheme['fontSize'];
22
+ UnistylesRuntime.updateTheme(scheme, () => ({
23
+ ...base,
24
+ fontSize: scaled(base.fontSize),
25
+ lineHeight: scaled(base.lineHeight),
26
+ lineHeightRelaxed: scaled(base.lineHeightRelaxed),
27
+ }));
28
+ return (
29
+ <PhoneFrame scheme={scheme}>
30
+ <View style={styles.canvas}>
31
+ <McpAppChrome status={status} enable={() => undefined} reopen={() => undefined} />
32
+ </View>
33
+ </PhoneFrame>
34
+ );
35
+ }
36
+ const styles = StyleSheet.create((theme) => ({
37
+ canvas: { flex: 1, backgroundColor: theme.colors.rail, padding: theme.spacing(4) },
38
+ }));
39
+ const meta = { title: 'Native/Design/McpAppChrome', component: Target, tags: ['style-system', 'mockup', 'native'] };
40
+ export default meta;
41
+ export const Playground = { render: () => <Target status="readOnly" /> };
42
+ export const LoadingLight = { render: () => <Target status="loading" /> };
43
+ export const LoadingDark = { render: () => <Target status="loading" scheme="dark" /> };
44
+ export const LoadingLargeText = { render: () => <Target status="loading" large /> };
45
+ export const ReadOnlyLight = { render: () => <Target status="readOnly" /> };
46
+ export const ReadOnlyDark = { render: () => <Target status="readOnly" scheme="dark" /> };
47
+ export const ReadOnlyLargeText = { render: () => <Target status="readOnly" large /> };
48
+ export const EnablingLight = { render: () => <Target status="enabling" /> };
49
+ export const EnablingDark = { render: () => <Target status="enabling" scheme="dark" /> };
50
+ export const EnablingLargeText = { render: () => <Target status="enabling" large /> };
51
+ export const EnabledLight = { render: () => <Target status="enabled" /> };
52
+ export const EnabledDark = { render: () => <Target status="enabled" scheme="dark" /> };
53
+ export const EnabledLargeText = { render: () => <Target status="enabled" large /> };
54
+ export const FailureLight = { render: () => <Target status="failure" /> };
55
+ export const FailureDark = { render: () => <Target status="failure" scheme="dark" /> };
56
+ export const FailureLargeText = { render: () => <Target status="failure" large /> };
57
+ export const ClosedLight = { render: () => <Target status="closed" /> };
58
+ export const ClosedDark = { render: () => <Target status="closed" scheme="dark" /> };
59
+ export const ClosedLargeText = { render: () => <Target status="closed" large /> };
60
+ export const UnsupportedLight = { render: () => <Target status="unsupported" /> };
61
+ export const UnsupportedDark = { render: () => <Target status="unsupported" scheme="dark" /> };
62
+ export const UnsupportedLargeText = { render: () => <Target status="unsupported" large /> };
@@ -0,0 +1,54 @@
1
+ import { Button, fontOf } from '@agimon-ai/po-native-components';
2
+ import type { ReactNode } from 'react';
3
+ import { Text, View } from 'react-native';
4
+ import { StyleSheet } from 'react-native-unistyles';
5
+
6
+ export type McpAppStatus = 'loading' | 'readOnly' | 'enabling' | 'enabled' | 'failure' | 'closed' | 'unsupported';
7
+ export interface McpAppChromeProps {
8
+ status: McpAppStatus;
9
+ error?: string;
10
+ enable: () => void;
11
+ reopen: () => void;
12
+ children?: ReactNode;
13
+ }
14
+ const LABELS: Record<McpAppStatus, string> = {
15
+ loading: 'Loading App…',
16
+ readOnly: 'Read-only App. Enable interactions whenever you are ready.',
17
+ enabling: 'Waiting for your approval…',
18
+ enabled: 'Interactions enabled. Tool calls still ask for approval.',
19
+ failure: 'This App could not be displayed.',
20
+ closed: 'App closed.',
21
+ unsupported: 'This device cannot securely display this App.',
22
+ };
23
+ /** Shared deterministic story target and native controls. The container owns all effects. */
24
+ export function McpAppChrome({ status, error, enable, reopen, children }: McpAppChromeProps) {
25
+ return (
26
+ <View style={styles.root}>
27
+ <View style={styles.controls}>
28
+ <Text
29
+ accessibilityRole={status === 'failure' ? 'alert' : undefined}
30
+ accessibilityLiveRegion="polite"
31
+ style={status === 'failure' ? styles.error : styles.text}
32
+ >
33
+ {error || LABELS[status]}
34
+ </Text>
35
+ {status === 'readOnly' || status === 'enabling' ? (
36
+ <Button variant="secondary" disabled={status === 'enabling'} onPress={enable}>
37
+ Enable interactions
38
+ </Button>
39
+ ) : status === 'closed' || status === 'failure' ? (
40
+ <Button variant="secondary" onPress={reopen}>
41
+ Reopen App
42
+ </Button>
43
+ ) : null}
44
+ </View>
45
+ {children}
46
+ </View>
47
+ );
48
+ }
49
+ const styles = StyleSheet.create((theme) => ({
50
+ root: { borderWidth: 1, borderColor: theme.colors.border, borderRadius: theme.borderRadius.md, overflow: 'hidden' },
51
+ controls: { padding: theme.spacing(3), gap: theme.spacing(2), alignItems: 'flex-start' },
52
+ text: { fontFamily: fontOf(theme.fontFamily.sans), fontSize: theme.fontSize.sm, color: theme.colors.dim },
53
+ error: { fontFamily: fontOf(theme.fontFamily.sans), fontSize: theme.fontSize.sm, color: theme.colors.red },
54
+ }));
@@ -0,0 +1,289 @@
1
+ import type { McpAppFrameOptions } from '@agimon-ai/po-web-components/mcpAppHost';
2
+ import { splitHostId, transportForHost } from '@agimon-ai/po-web-dashboard/core';
3
+ import * as WebBrowser from 'expo-web-browser';
4
+ import { useEffect, useRef, useState, type ComponentProps, type ComponentType, type RefAttributes } from 'react';
5
+ import { Alert, Platform, View } from 'react-native';
6
+ import { useUnistyles } from 'react-native-unistyles';
7
+ import { WebView } from 'react-native-webview';
8
+
9
+ import type { McpAppHostConfig } from '../../../scripts/mcpAppHost';
10
+ import { loadCloudHosts } from '../../services/cloudHosts';
11
+ import { loadHost } from '../../services/deviceTrust';
12
+ import { isolatedWebViewProps, useVisible } from './createRichActivityRenderers';
13
+ import {
14
+ allowMcpAppNavigation,
15
+ createMcpAppMessageGate,
16
+ declaresFrameDomains,
17
+ isMcpAppLink,
18
+ MCP_APP_METHODS,
19
+ } from './mcpAppBridge';
20
+ import { McpAppChrome, type McpAppStatus } from './McpAppChrome';
21
+ import { mcpAppHostDocument, scriptValue } from './offlineDocuments';
22
+
23
+ type Handle = { injectJavaScript(script: string): void };
24
+ const AppWebView = WebView as ComponentType<ComponentProps<typeof WebView> & RefAttributes<Handle>>;
25
+ type Opened = McpAppFrameOptions['data'] & { leaseId: string; state: unknown };
26
+ function errorText(error: unknown): string {
27
+ return error instanceof Error ? error.message : 'This App could not be displayed.';
28
+ }
29
+ function confirmLink(url: string): Promise<boolean> {
30
+ return new Promise((resolve) =>
31
+ Alert.alert(
32
+ 'Open this external link?',
33
+ url,
34
+ [
35
+ { text: 'Cancel', style: 'cancel', onPress: () => resolve(false) },
36
+ { text: 'Open link', onPress: () => resolve(true) },
37
+ ],
38
+ { cancelable: true, onDismiss: () => resolve(false) },
39
+ ),
40
+ );
41
+ }
42
+ interface Mount {
43
+ live: boolean;
44
+ lease?: Opened;
45
+ config?: McpAppHostConfig;
46
+ gate?: ReturnType<typeof createMcpAppMessageGate>;
47
+ timer?: ReturnType<typeof setTimeout>;
48
+ invoke(method: string, input: Record<string, unknown>): Promise<unknown>;
49
+ stop(status: McpAppStatus, error?: string): void;
50
+ show(data: Opened, origin: string): void;
51
+ }
52
+
53
+ /** Host-owned App surface. Only RN holds the lease and the owning session's transport. */
54
+ export function McpAppView({ sessionId, toolCallId }: { sessionId: string; toolCallId: string }) {
55
+ const visible = useVisible();
56
+ const { rt } = useUnistyles();
57
+ const theme = rt.themeName === 'dark' ? 'dark' : 'light';
58
+ const themeRef = useRef<'light' | 'dark'>(theme);
59
+ themeRef.current = theme;
60
+ const web = useRef<Handle>(null);
61
+ const mount = useRef<Mount | undefined>(undefined);
62
+ const [status, setStatus] = useState<McpAppStatus>('loading');
63
+ const [error, setError] = useState('');
64
+ const [page, setPage] = useState<{ html: string; token: string }>();
65
+ const [height, setHeight] = useState(320);
66
+ const [retry, setRetry] = useState(0);
67
+ useEffect(() => {
68
+ setPage(undefined);
69
+ if (!visible) return;
70
+ setStatus('loading');
71
+ setError('');
72
+ setHeight(320);
73
+ const owner = splitHostId(sessionId);
74
+ if (!owner) {
75
+ setStatus('failure');
76
+ setError('This App requires an owning host.');
77
+ return;
78
+ }
79
+ const transport = transportForHost(owner.hostId);
80
+ const invoke = (method: string, input: Record<string, unknown>) =>
81
+ transport.invokeServerMethod({ mount: { scope: 'session', sessionId }, service: 'mcp.apps', method, input });
82
+ const current: Mount = {
83
+ live: true,
84
+ invoke,
85
+ stop(next, failure) {
86
+ if (!current.live) return;
87
+ current.live = false;
88
+ current.gate?.dispose();
89
+ clearTimeout(current.timer);
90
+ setPage(undefined);
91
+ setStatus(next);
92
+ setError(failure ?? '');
93
+ if (current.lease)
94
+ void invoke('close', { leaseId: current.lease.leaseId }).catch((reason: unknown) => {
95
+ if (mount.current === current) setError(`Closing the App failed: ${errorText(reason)}`);
96
+ });
97
+ },
98
+ show(data, hostOrigin) {
99
+ if (!current.live) return;
100
+ current.gate?.dispose();
101
+ const token = Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>
102
+ byte.toString(16).padStart(2, '0'),
103
+ ).join('');
104
+ current.gate = createMcpAppMessageGate(token);
105
+ // Explicit projection: leaseId and any future server-only fields never enter the document.
106
+ const config: McpAppHostConfig = {
107
+ token,
108
+ platform: Platform.OS === 'ios' ? 'ios' : 'android',
109
+ toolCallId,
110
+ savedState: data.state,
111
+ hostOrigin,
112
+ theme: themeRef.current,
113
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
114
+ data: {
115
+ html: data.html,
116
+ protocol: data.protocol,
117
+ resourceMeta: data.resourceMeta,
118
+ args: data.args,
119
+ result: data.result,
120
+ tool: data.tool,
121
+ readOnly: data.readOnly,
122
+ },
123
+ };
124
+ current.config = config;
125
+ setPage({ html: mcpAppHostDocument(config), token });
126
+ clearTimeout(current.timer);
127
+ current.timer = setTimeout(() => current.stop('failure', 'This App took too long to open.'), 15000);
128
+ },
129
+ };
130
+ mount.current = current;
131
+ current.timer = setTimeout(() => current.stop('failure', 'This App took too long to open.'), 15000);
132
+ void (async () => {
133
+ const host =
134
+ (await loadHost(owner.hostId)) ?? (await loadCloudHosts()).find((candidate) => candidate.id === owner.hostId);
135
+ if (!current.live) return;
136
+ if (!host) throw new Error('The owning host is unavailable.');
137
+ const opened = (await invoke('open', { toolCallId })) as Opened;
138
+ if (!current.live) {
139
+ await invoke('close', { leaseId: opened.leaseId });
140
+ return;
141
+ }
142
+ current.lease = opened;
143
+ current.show(opened, new URL(host.origin).origin);
144
+ })().catch((reason: unknown) => {
145
+ if (current.live) current.stop('failure', errorText(reason));
146
+ else if (mount.current === current) setError(errorText(reason));
147
+ });
148
+ return () => {
149
+ current.stop('closed');
150
+ if (mount.current === current) mount.current = undefined;
151
+ };
152
+ }, [sessionId, toolCallId, visible, retry]);
153
+ useEffect(() => {
154
+ web.current?.injectJavaScript(`window.poMcpHost?.setTheme(${scriptValue(theme)});true;`);
155
+ }, [theme]);
156
+ const enable = async () => {
157
+ const current = mount.current;
158
+ if (!current?.live || !current.lease || !current.config || status !== 'readOnly') return;
159
+ setStatus('enabling');
160
+ setError('');
161
+ const gate = current.gate;
162
+ try {
163
+ const result = (await current.invoke('activate', { leaseId: current.lease.leaseId })) as { readOnly: boolean };
164
+ if (!current.live || current.gate !== gate) return;
165
+ if (result.readOnly !== false) throw new Error('App interactions were not enabled.');
166
+ current.lease = { ...current.lease, readOnly: false };
167
+ current.show(current.lease, current.config.hostOrigin);
168
+ } catch (reason) {
169
+ if (current.live) {
170
+ setStatus('readOnly');
171
+ setError(errorText(reason));
172
+ }
173
+ }
174
+ };
175
+ const receive = (text: string) => {
176
+ const current = mount.current;
177
+ if (!current?.live || !current.gate || !current.lease || current.config?.token !== page?.token) return;
178
+ const gate = current.gate;
179
+ const { message, revoke } = gate.accept(text);
180
+ if (revoke) {
181
+ current.stop('failure', 'This App sent an invalid request.');
182
+ return;
183
+ }
184
+ if (!message) return;
185
+ switch (message.type) {
186
+ case 'ready':
187
+ clearTimeout(current.timer);
188
+ setStatus(current.lease.readOnly ? 'readOnly' : 'enabled');
189
+ return;
190
+ case 'resize':
191
+ setHeight(message.height);
192
+ return;
193
+ case 'unsupported':
194
+ current.stop('unsupported');
195
+ return;
196
+ case 'revoked':
197
+ current.stop('failure', 'App navigation was blocked. Reopen it to continue.');
198
+ return;
199
+ case 'fail':
200
+ current.stop('failure', message.message);
201
+ return;
202
+ case 'closed':
203
+ current.stop('closed');
204
+ return;
205
+ case 'request': {
206
+ const { id, method, input } = message;
207
+ void (async () => {
208
+ if (method === 'openLink') {
209
+ const url = input.url;
210
+ if (!isMcpAppLink(url) || !(await confirmLink(url))) throw new Error('Opening the link was declined.');
211
+ if (!current.live || current.gate !== gate) throw new Error('App is closed.');
212
+ await WebBrowser.openBrowserAsync(url);
213
+ return {};
214
+ }
215
+ if (current.lease!.readOnly && (method === 'callTool' || method === 'followUp'))
216
+ throw new Error('Enable interactions first.');
217
+ const result = await current.invoke(MCP_APP_METHODS[method].slice('mcp.apps.'.length), {
218
+ ...input,
219
+ leaseId: current.lease!.leaseId,
220
+ });
221
+ if (method === 'setState' && current.live) current.lease!.state = input.state;
222
+ if (method === 'close') {
223
+ current.lease = undefined;
224
+ current.stop('closed');
225
+ }
226
+ return result;
227
+ })().then(
228
+ (result) => {
229
+ if (current.live && current.gate === gate && gate.finish(id))
230
+ web.current?.injectJavaScript(`window.poMcpHost?.reply(${id},${scriptValue(result ?? null)});true;`);
231
+ },
232
+ (reason: unknown) => {
233
+ if (current.live && current.gate === gate && gate.finish(id))
234
+ web.current?.injectJavaScript(
235
+ `window.poMcpHost?.reply(${id},null,${scriptValue(errorText(reason))});true;`,
236
+ );
237
+ },
238
+ );
239
+ }
240
+ }
241
+ };
242
+ const stopFrame = (failure: string) => {
243
+ if (mount.current?.config?.token === page?.token) mount.current?.stop('failure', failure);
244
+ };
245
+ return (
246
+ <McpAppChrome
247
+ status={visible ? status : 'closed'}
248
+ error={error}
249
+ enable={() => void enable()}
250
+ reopen={() => setRetry((value) => value + 1)}
251
+ >
252
+ {visible && page ? (
253
+ <View style={{ height }}>
254
+ <AppWebView
255
+ {...isolatedWebViewProps}
256
+ key={page.token}
257
+ ref={web}
258
+ source={{ html: page.html }}
259
+ javaScriptEnabled
260
+ onMessage={(event) => receive(event.nativeEvent.data)}
261
+ onShouldStartLoadWithRequest={(request) => {
262
+ const current = mount.current;
263
+ if (current?.config?.token !== page.token) return false;
264
+ const allowed = allowMcpAppNavigation(
265
+ request.url,
266
+ request.isTopFrame !== false,
267
+ Platform.OS === 'ios' ? 'ios' : 'android',
268
+ declaresFrameDomains(current?.lease?.resourceMeta),
269
+ );
270
+ if (!allowed) current?.stop('failure', 'App navigation was blocked.');
271
+ return allowed;
272
+ }}
273
+ onLoadStart={(event) => {
274
+ if (
275
+ mount.current?.config?.token === page.token &&
276
+ !['about:blank', 'about:srcdoc'].includes(event.nativeEvent.url)
277
+ )
278
+ mount.current?.stop('failure', 'App navigation was blocked.');
279
+ }}
280
+ onOpenWindow={() => stopFrame('App navigation was blocked.')}
281
+ onError={(event) => stopFrame(event.nativeEvent.description)}
282
+ onContentProcessDidTerminate={() => stopFrame('The App process stopped.')}
283
+ onRenderProcessGone={() => stopFrame('The App process stopped.')}
284
+ />
285
+ </View>
286
+ ) : null}
287
+ </McpAppChrome>
288
+ );
289
+ }
@@ -53,7 +53,7 @@ export const isolatedWebViewProps = {
53
53
  function message(reason: unknown): string {
54
54
  return reason instanceof Error ? reason.message : 'This preview could not be displayed.';
55
55
  }
56
- function useVisible(): boolean {
56
+ export function useVisible(): boolean {
57
57
  const focused = useIsFocused();
58
58
  const [active, setActive] = useState(AppState.currentState === 'active');
59
59
  useEffect(() => {
@@ -0,0 +1,165 @@
1
+ const MAX_BYTES = 64 * 1024;
2
+ const MAX_MESSAGES = 128;
3
+ const MAX_PENDING = 16;
4
+
5
+ export const MCP_APP_METHODS = {
6
+ callTool: 'mcp.apps.callTool',
7
+ setState: 'mcp.apps.setState',
8
+ followUp: 'mcp.apps.followUp',
9
+ close: 'mcp.apps.close',
10
+ } as const;
11
+
12
+ function record(value: unknown): value is Record<string, unknown> {
13
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
14
+ }
15
+ function keys(value: Record<string, unknown>, expected: string[]): boolean {
16
+ return Object.keys(value).length === expected.length && expected.every((key) => key in value);
17
+ }
18
+ export type McpAppMessage =
19
+ | {
20
+ token: string;
21
+ type: 'request';
22
+ id: number;
23
+ method: keyof typeof MCP_APP_METHODS | 'openLink';
24
+ input: Record<string, unknown>;
25
+ }
26
+ | { token: string; type: 'ready' | 'closed' | 'unsupported' | 'revoked' }
27
+ | { token: string; type: 'resize'; height: number }
28
+ | { token: string; type: 'fail'; message: string };
29
+
30
+ /** Validates the entire envelope before native can dispatch anything. The lease is never supplied by a page. */
31
+ export function parseMcpAppMessage(text: string, token: string): McpAppMessage | undefined {
32
+ if (text.length > MAX_BYTES || new TextEncoder().encode(text).byteLength > MAX_BYTES) return undefined;
33
+ let value: unknown;
34
+ try {
35
+ value = JSON.parse(text);
36
+ } catch {
37
+ return undefined; // Malformed, untrusted bridge input is refused.
38
+ }
39
+ if (!record(value) || value.token !== token) return undefined;
40
+ switch (value.type) {
41
+ case 'ready':
42
+ case 'closed':
43
+ case 'unsupported':
44
+ case 'revoked':
45
+ return keys(value, ['token', 'type']) ? (value as McpAppMessage) : undefined;
46
+ case 'resize':
47
+ return keys(value, ['token', 'type', 'height']) &&
48
+ typeof value.height === 'number' &&
49
+ Number.isFinite(value.height)
50
+ ? { token, type: 'resize', height: Math.min(1200, Math.max(80, Math.ceil(value.height))) }
51
+ : undefined;
52
+ case 'fail':
53
+ return keys(value, ['token', 'type', 'message']) &&
54
+ typeof value.message === 'string' &&
55
+ value.message.length <= 4096
56
+ ? (value as McpAppMessage)
57
+ : undefined;
58
+ case 'request': {
59
+ if (
60
+ !keys(value, ['token', 'type', 'id', 'method', 'input']) ||
61
+ !Number.isSafeInteger(value.id) ||
62
+ (value.id as number) < 1 ||
63
+ !record(value.input)
64
+ )
65
+ return undefined;
66
+ const input = value.input;
67
+ const valid =
68
+ value.method === 'callTool'
69
+ ? keys(input, ['name', 'arguments']) &&
70
+ typeof input.name === 'string' &&
71
+ input.name.length > 0 &&
72
+ input.name.length <= 256 &&
73
+ record(input.arguments)
74
+ : value.method === 'setState'
75
+ ? keys(input, ['state'])
76
+ : value.method === 'followUp'
77
+ ? keys(input, ['prompt']) &&
78
+ typeof input.prompt === 'string' &&
79
+ input.prompt.length > 0 &&
80
+ input.prompt.length <= 16000
81
+ : value.method === 'close'
82
+ ? keys(input, [])
83
+ : value.method === 'openLink' && keys(input, ['url']) && isMcpAppLink(input.url);
84
+ return valid ? (value as McpAppMessage) : undefined;
85
+ }
86
+ default:
87
+ return undefined;
88
+ }
89
+ }
90
+
91
+ /** Per-mount accounting. Disposing invalidates replies and every subsequent message. */
92
+ export function createMcpAppMessageGate(token: string, now: () => number = Date.now) {
93
+ let live = true;
94
+ let invalid = 0;
95
+ let count = 0;
96
+ let start = now();
97
+ const pending = new Set<number>();
98
+ return {
99
+ accept(text: string): { message?: McpAppMessage; revoke: boolean } {
100
+ if (!live) return { revoke: true };
101
+ const time = now();
102
+ if (time - start >= 1000) {
103
+ start = time;
104
+ count = 0;
105
+ }
106
+ if (++count > MAX_MESSAGES) {
107
+ live = false;
108
+ return { revoke: true };
109
+ }
110
+ const message = parseMcpAppMessage(text, token);
111
+ if (!message) {
112
+ if (++invalid >= 2) live = false;
113
+ return { revoke: !live };
114
+ }
115
+ if (message.type === 'request') {
116
+ if (pending.size >= MAX_PENDING || pending.has(message.id)) {
117
+ live = false;
118
+ return { revoke: true };
119
+ }
120
+ pending.add(message.id);
121
+ }
122
+ return { message, revoke: false };
123
+ },
124
+ finish(id: number): boolean {
125
+ return live && pending.delete(id);
126
+ },
127
+ dispose(): void {
128
+ live = false;
129
+ pending.clear();
130
+ },
131
+ };
132
+ }
133
+
134
+ export function isMcpAppLink(value: unknown): value is string {
135
+ if (typeof value !== 'string' || value.length > 2048) return false;
136
+ try {
137
+ const url = new URL(value);
138
+ return url.protocol === 'https:' && !url.username && !url.password;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ /** Present standard CSP fields win, even when empty or malformed. */
145
+ export function declaresFrameDomains(metadata: unknown): boolean {
146
+ if (!record(metadata)) return false;
147
+ const ui = record(metadata.ui) ? metadata.ui : undefined;
148
+ if (metadata.ui !== undefined && !ui) return false;
149
+ const standard = ui !== undefined && 'csp' in ui;
150
+ const csp = standard ? ui.csp : metadata['openai/widgetCSP'];
151
+ if (!record(csp)) return false;
152
+ const domains = csp[standard ? 'frameDomains' : 'frame_domains'];
153
+ return Array.isArray(domains) && domains.length > 0 && domains.every((domain) => typeof domain === 'string');
154
+ }
155
+
156
+ export function allowMcpAppNavigation(
157
+ url: string,
158
+ topFrame: boolean,
159
+ platform: 'ios' | 'android',
160
+ frameDomains: boolean,
161
+ ): boolean {
162
+ if (url === 'about:blank' || url === 'about:srcdoc') return true;
163
+ // Android does not report inner navigation reliably. Its iframe CSP is mandatory in the browser host.
164
+ return !topFrame && platform === 'ios' && frameDomains && isMcpAppLink(url);
165
+ }
@@ -1,6 +1,7 @@
1
1
  import type { PoNativeTheme } from '@agimon-ai/po-web-components/nativeTheme';
2
2
 
3
3
  import assets from '../../../generated/richAssets.json';
4
+ import type { McpAppHostConfig } from '../../../scripts/mcpAppHost';
4
5
  import { mediaDataUri } from './isolatedContent';
5
6
 
6
7
  const POLICY =
@@ -18,6 +19,14 @@ function document(body: string, code: string, theme: PoNativeTheme): string {
18
19
  return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${POLICY}"><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:${colors.panel};color:${colors.text};font-family:sans-serif}button,input{font:inherit;color:inherit;background:${colors.bg};border:1px solid ${colors.border};border-radius:8px;min-height:44px;padding:0 12px}button:disabled{opacity:.4}nav{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:12px}img,video,canvas{max-width:100%}audio,video{width:100%}#status{padding:12px}#page{overflow:auto}canvas{display:block;margin:auto}</style></head><body>${body}${script(code)}</body></html>`;
19
20
  }
20
21
 
22
+ /** Trusted shell only. No lease, transport or credentials belong in this config. */
23
+ export function mcpAppHostDocument(config: McpAppHostConfig): string {
24
+ // The shell admits declared remote resources. Shared relay and App CSPs narrow these permissions.
25
+ const policy =
26
+ "default-src 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; script-src 'unsafe-inline' https:; style-src 'unsafe-inline' https:; img-src data: blob: https:; media-src blob: https:; font-src data: https:; connect-src https: wss:; frame-src about: https:; worker-src 'none'";
27
+ return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${policy}"><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;overflow:hidden}</style></head><body>${script(`window.poMcpConfig=${scriptValue(config)};document.currentScript.remove();`)}${script(assets.mcpAppHost)}</body></html>`;
28
+ }
29
+
21
30
  export function terminalDocument(session: string, theme: PoNativeTheme): string {
22
31
  return document(
23
32
  `<style>${assets.xtermCss}</style><div id="terminal" style="height:100%;background:${theme.colors.deep}"></div>`,
@@ -23,6 +23,7 @@ export type NativeSlotHost = Partial<
23
23
  | 'nativeAuthor'
24
24
  | 'renderStoryPreview'
25
25
  | 'renderFilePreview'
26
+ | 'renderMcpApp'
26
27
  | 'renderRunnerTerminal'
27
28
  | 'attachComposerCapture'
28
29
  | 'submitCapture'