Skip to content

Commit 923d92b

Browse files
feat(ui): complete Control UI MCP App bridge (#109807)
* feat(ui): complete MCP App message bridge * fix(ui): gate reconstructed MCP App messaging * fix(ui): register MCP message handler without suppression * fix(ui): use public MCP Apps message schema export * chore: realign PR branch with canonical main * fix(ui): register MCP messages through public bridge API
1 parent f31de78 commit 923d92b

9 files changed

Lines changed: 416 additions & 99 deletions

File tree

‎src/agents/mcp-ui-resource.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export type McpAppViewLease = {
2929
csp?: McpAppCsp;
3030
permissions?: McpAppPermissions;
3131
allowedAppToolNames?: ReadonlySet<string>;
32+
readOnly?: true;
3233
toolInput: unknown;
3334
toolResult: CallToolResult;
3435
expiresAtMs: number;
@@ -201,6 +202,7 @@ export async function fetchMcpAppView(params: {
201202
toolInput: unknown;
202203
toolResult: CallToolResult;
203204
allowedAppToolNames?: ReadonlySet<string>;
205+
readOnly?: true;
204206
viewId?: string;
205207
}): Promise<
206208
| {
@@ -260,6 +262,7 @@ export async function fetchMcpAppView(params: {
260262
...(params.allowedAppToolNames
261263
? { allowedAppToolNames: new Set(params.allowedAppToolNames) }
262264
: {}),
265+
...(params.readOnly ? { readOnly: true as const } : {}),
263266
toolInput: params.toolInput,
264267
toolResult: params.toolResult,
265268
expiresAtMs: Date.now() + MCP_APP_VIEW_TTL_MS,

‎src/gateway/mcp-app-reconstruction.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ describe("MCP App transcript reconstruction", () => {
124124
},
125125
viewId: "mcp-app-1",
126126
allowedAppToolNames: new Set(),
127+
readOnly: true,
127128
});
128129
});
129130

‎src/gateway/mcp-app-reconstruction.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ async function restoreMcpAppViewOnce(params: {
275275
// A reconstructed preview can render and read its owning server resources,
276276
// but cannot call tools without a fresh run carrying current effective policy.
277277
allowedAppToolNames: new Set(),
278+
readOnly: true,
278279
});
279280
const view = getMcpAppViewLease(params.viewId, runtime);
280281
return view ? { runtime, view } : undefined;

‎src/gateway/server-methods/mcp-app.test.ts‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ const view = {
3636
toolName: "show",
3737
uiResourceUri: "ui://demo/app",
3838
html: "<html>demo</html>",
39-
allowedAppToolNames: undefined as ReadonlySet<string> | undefined,
39+
allowedAppToolNames: new Set(["shared", "app-only"]) as ReadonlySet<string> | undefined,
40+
readOnly: undefined as boolean | undefined,
4041
toolInput: { city: "Paris" },
4142
toolResult: { content: [{ type: "text", text: "ok" }] },
4243
expiresAtMs: Date.now() + 60_000,
@@ -108,7 +109,8 @@ describe("MCP App gateway bridge", () => {
108109
view.requestCount = 0;
109110
view.toolCallCount = 0;
110111
view.activeRequests = 0;
111-
view.allowedAppToolNames = undefined;
112+
view.allowedAppToolNames = new Set(["shared", "app-only"]);
113+
view.readOnly = undefined;
112114
mocks.getMcpAppViewLease.mockReset().mockReturnValue(view);
113115
mocks.completeDeferredSessionMcpRuntimeRetirement.mockReset().mockResolvedValue(false);
114116
mocks.peekSessionMcpRuntime.mockReset().mockReturnValue(runtime());
@@ -135,6 +137,7 @@ describe("MCP App gateway bridge", () => {
135137
toolInput: { city: "Paris" },
136138
standaloneUrl: "/__openclaw__/mcp-app#ticket",
137139
standaloneExpiresAtMs: 1_800_000_120_000,
140+
messageSupported: true,
138141
}),
139142
);
140143
expect(mocks.getMcpAppViewLease).toHaveBeenCalledWith("cv_app", expect.any(Object));
@@ -178,6 +181,26 @@ describe("MCP App gateway bridge", () => {
178181
});
179182
});
180183

184+
it("keeps message support disabled without fresh run authority", async () => {
185+
view.allowedAppToolNames = undefined;
186+
const respond = await invoke("mcp.app.view", {
187+
sessionKey: "agent:main:main",
188+
viewId: "cv_app",
189+
});
190+
191+
expect(respond.mock.calls[0]?.[1]).toMatchObject({ messageSupported: false });
192+
});
193+
194+
it("supports messages for a fresh view with no app-callable tools", async () => {
195+
view.allowedAppToolNames = new Set();
196+
const respond = await invoke("mcp.app.view", {
197+
sessionKey: "agent:main:main",
198+
viewId: "cv_app",
199+
});
200+
201+
expect(respond.mock.calls[0]?.[1]).toMatchObject({ messageSupported: true });
202+
});
203+
181204
it("filters model-only tools from app discovery and execution", async () => {
182205
const params = { sessionKey: "agent:main:main", viewId: "cv_app" };
183206
const listed = await invoke("mcp.app.listTools", params);
@@ -233,7 +256,12 @@ describe("MCP App gateway bridge", () => {
233256

234257
it("restores a transcript-backed view after a Gateway restart", async () => {
235258
const restoredRuntime = runtime();
236-
const restoredView = { ...view, runtime: restoredRuntime, allowedAppToolNames: new Set() };
259+
const restoredView = {
260+
...view,
261+
runtime: restoredRuntime,
262+
allowedAppToolNames: new Set(),
263+
readOnly: true,
264+
};
237265
mocks.peekSessionMcpRuntime.mockReturnValue(undefined);
238266
mocks.restoreMcpAppView.mockResolvedValue({
239267
runtime: restoredRuntime,
@@ -246,6 +274,9 @@ describe("MCP App gateway bridge", () => {
246274
});
247275

248276
expect(respond.mock.calls[0]?.[0]).toBe(true);
249-
expect(respond.mock.calls[0]?.[1]).toMatchObject({ html: "<html>demo</html>" });
277+
expect(respond.mock.calls[0]?.[1]).toMatchObject({
278+
html: "<html>demo</html>",
279+
messageSupported: false,
280+
});
250281
});
251282
});

‎src/gateway/server-methods/mcp-app.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,8 @@ export const mcpAppHandlers: GatewayRequestHandlers = {
171171
standaloneExpiresAtMs: standalone.expiresAtMs,
172172
}
173173
: {}),
174+
// Reconstruction marks views read-only; fresh runs may legitimately grant zero App tools.
175+
messageSupported: view.allowedAppToolNames !== undefined && view.readOnly !== true,
174176
};
175177
},
176178
context.getRuntimeConfig(),

‎ui/src/components/mcp-app-security.ts‎

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,105 @@ export type McpAppHostSandboxCsp = NonNullable<
55
NonNullable<McpAppHostCapabilities["sandbox"]>["csp"]
66
>;
77

8-
export function buildMcpAppHostCapabilities(csp?: McpAppHostSandboxCsp): McpAppHostCapabilities {
8+
/** Bubbling event handled by the owning chat pane through its normal send path. */
9+
export const WIDGET_PROMPT_EVENT = "openclaw-widget-prompt";
10+
export type WidgetPromptEventDetail = { text: string };
11+
12+
const WIDGET_PROMPT_MAX_CHARS = 4_000;
13+
const WIDGET_PROMPT_RATE_WINDOW_MS = 60_000;
14+
const WIDGET_PROMPT_RATE_MAX = 10;
15+
const WIDGET_PROMPT_RATE_KEYS_MAX = 100;
16+
const widgetPromptTimestampsByKey = new Map<string, number[]>();
17+
18+
function resolveWidgetPromptText(raw: unknown): string | null {
19+
if (typeof raw !== "string") {
20+
return null;
21+
}
22+
const text = raw.trim();
23+
if (!text || text.length > WIDGET_PROMPT_MAX_CHARS || text.startsWith("/")) {
24+
return null;
25+
}
26+
return text;
27+
}
28+
29+
function allowWidgetPrompt(key: string, nowMs: number): boolean {
30+
const cutoff = nowMs - WIDGET_PROMPT_RATE_WINDOW_MS;
31+
const timestamps = (widgetPromptTimestampsByKey.get(key) ?? []).filter((ts) => ts > cutoff);
32+
if (
33+
!widgetPromptTimestampsByKey.has(key) &&
34+
widgetPromptTimestampsByKey.size >= WIDGET_PROMPT_RATE_KEYS_MAX
35+
) {
36+
const oldest = widgetPromptTimestampsByKey.keys().next().value;
37+
if (oldest !== undefined) {
38+
widgetPromptTimestampsByKey.delete(oldest);
39+
}
40+
}
41+
if (timestamps.length >= WIDGET_PROMPT_RATE_MAX) {
42+
widgetPromptTimestampsByKey.set(key, timestamps);
43+
return false;
44+
}
45+
timestamps.push(nowMs);
46+
widgetPromptTimestampsByKey.set(key, timestamps);
47+
return true;
48+
}
49+
50+
function isWidgetFrameInteractable(frame: HTMLIFrameElement): boolean {
51+
if (!frame.isConnected) {
52+
return false;
53+
}
54+
const visible =
55+
typeof frame.checkVisibility === "function"
56+
? frame.checkVisibility()
57+
: frame.getClientRects().length > 0;
58+
if (!visible) {
59+
return false;
60+
}
61+
let active: Element | null = frame.ownerDocument.activeElement;
62+
while (active?.shadowRoot?.activeElement) {
63+
active = active.shadowRoot.activeElement;
64+
}
65+
return active === frame;
66+
}
67+
68+
/**
69+
* Agent-authored frames may submit only user-focused conversational text.
70+
* The shared event preserves pane routing and prevents privileged shortcuts.
71+
*/
72+
export function dispatchWidgetPrompt(
73+
frame: HTMLIFrameElement,
74+
raw: unknown,
75+
rateKey: string,
76+
confirmPrompt?: (text: string) => boolean,
77+
): boolean {
78+
const text = resolveWidgetPromptText(raw);
79+
if (
80+
!text ||
81+
!isWidgetFrameInteractable(frame) ||
82+
!allowWidgetPrompt(rateKey, Date.now()) ||
83+
(confirmPrompt && !confirmPrompt(text))
84+
) {
85+
return false;
86+
}
87+
frame.dispatchEvent(
88+
new CustomEvent<WidgetPromptEventDetail>(WIDGET_PROMPT_EVENT, {
89+
bubbles: true,
90+
composed: true,
91+
detail: { text },
92+
}),
93+
);
94+
return true;
95+
}
96+
97+
export function buildMcpAppHostCapabilities(
98+
csp?: McpAppHostSandboxCsp,
99+
supportsMessage = false,
100+
): McpAppHostCapabilities {
9101
return {
10102
openLinks: {},
11103
serverResources: {},
12104
serverTools: {},
13105
sandbox: { csp: csp ?? {} },
106+
...(supportsMessage ? { message: { text: {} } } : {}),
14107
};
15108
}
16109

0 commit comments

Comments
 (0)