The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(conversations): sandboxed widget frame with MCP Apps bridge and Apps SDK shim
oxoxDev717a77284cc9
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsxindex 0884cadaf0..e20e0331a6 100644--- a/app/src/components/assistant-ui/thread.tsx+++ b/app/src/components/assistant-ui/thread.tsx@@ -30,6 +30,7 @@ import {useAuiEditCapabilities,useAuiReloadCapability,} from '@/features/conversations/components/aui/auiThreadState';+import { onComposerPrefill } from '@/features/conversations/tools/mcpUi/composerPrefill';import { useT } from '@/lib/i18n/I18nContext';import { CHAT_ERROR_METADATA_KEY } from '@/store/threadSlice';import { fullTimestamp, relativeTime } from '@/utils/relativeTime';@@ -679,6 +680,8 @@ const Composer: FC<{// composition before it runs. That stale write would rebuild the editor// mid-composition and cancel it -- #5763 again, one composition later.const isComposingTextRef = useRef(false);++ useEffect(() => onComposerPrefill(text => aui.composer.setText(text)), [aui]);// ArrowUp recall only fires on an empty composer, so a caret move inside a// multi-line draft is never hijacked.const composerIsEmpty = useAuiState(state => state.composer.text.length === 0);diff --git a/app/src/features/conversations/tools/mcpUi/McpAppFrame.tsx b/app/src/features/conversations/tools/mcpUi/McpAppFrame.tsxnew file mode 100644index 0000000000..4898a1de0c--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/McpAppFrame.tsx@@ -0,0 +1,168 @@+import debug from 'debug';+import { useEffect, useMemo, useRef, useState } from 'react';++import Button from '../../../../components/ui/Button';+import { ConfirmDialog } from '../../../../components/ui/ConfirmDialog';+import { useT } from '../../../../lib/i18n/I18nContext';+import { mcpUiApi } from '../../../../services/api/mcpUiApi';+import { openUrl } from '../../../../utils/openUrl';+import { requestComposerPrefill } from './composerPrefill';+import { QrHandoff } from './LinkActions';+import { McpAppBridge } from './mcpAppBridge';+import type { McpUiPresentation, McpUiResource } from './types';+import { isWindowsHost, widgetProxyUrl } from './widgetUrl';++const log = debug('mcp-ui:frame');++const DEFAULT_HEIGHT = 360;++interface PendingCall {+ name: string;+ args: Record<string, unknown>;+ resolve: (value: unknown) => void;+ reject: (error: Error) => void;+}++type LoadState =+ | { status: 'loading' }+ | { status: 'ready'; resource: McpUiResource }+ | { status: 'unavailable' };++function currentTheme(): 'light' | 'dark' {+ return document.documentElement.classList.contains('dark') ? 'dark' : 'light';+}++export function McpAppFrame({ presentation }: { presentation: McpUiPresentation }) {+ const { t, locale } = useT();+ const frameRef = useRef<HTMLIFrameElement>(null);+ const [state, setState] = useState<LoadState>({ status: 'loading' });+ const [height, setHeight] = useState(DEFAULT_HEIGHT);+ const [pending, setPending] = useState<PendingCall | null>(null);+ const [handoffUrl, setHandoffUrl] = useState<string | null>(null);+ const serverId = presentation.server_id;++ useEffect(() => {+ let cancelled = false;+ mcpUiApi+ .resourceRead({+ serverId,+ uri: presentation.inline_id ? undefined : presentation.resource_uri,+ inlineId: presentation.inline_id,+ })+ .then(resource => {+ if (!cancelled) setState({ status: 'ready', resource });+ })+ .catch(error => {+ log('widget document unavailable: %s', error instanceof Error ? error.message : error);+ if (!cancelled) setState({ status: 'unavailable' });+ });+ return () => {+ cancelled = true;+ };+ }, [serverId, presentation.resource_uri, presentation.inline_id]);++ const resource = state.status === 'ready' ? state.resource : null;+ const src = useMemo(+ () => (resource ? widgetProxyUrl(resource.csp, isWindowsHost()) : null),+ [resource]+ );++ useEffect(() => {+ if (!resource) return;+ const bridge = new McpAppBridge({+ presentation,+ html: resource.html,+ theme: currentTheme(),+ locale,+ source: () => frameRef.current?.contentWindow,+ handlers: {+ callTool: async (name, args) => {+ if (!serverId) throw new Error('No server for this view');+ const first = await mcpUiApi.toolCall(serverId, name, args, false);+ if (!first.requires_confirmation) return first.result;+ await new Promise<unknown>((resolve, reject) =>+ setPending({ name, args, resolve, reject })+ );+ const confirmed = await mcpUiApi.toolCall(serverId, name, args, true);+ return confirmed.result;+ },+ openExternal: url => openUrl(url),+ handOff: url => setHandoffUrl(url),+ prefillMessage: text => requestComposerPrefill(text),+ readResource: async uri => {+ if (!serverId) throw new Error('No server for this view');+ const read = await mcpUiApi.resourceRead({ serverId, uri });+ return { contents: [{ uri, mimeType: read.mime_type, text: read.html }] };+ },+ resize: next => setHeight(next),+ },+ });+ const onMessage = (event: MessageEvent) => {+ bridge.handleMessage(event);+ };+ window.addEventListener('message', onMessage);+ return () => window.removeEventListener('message', onMessage);+ }, [resource, presentation, serverId, locale]);++ if (state.status === 'unavailable') {+ return (+ <p className="text-xs text-content-muted" data-testid="mcp-ui-unavailable">+ {t('conversations.mcpUi.widgetUnavailable')}+ </p>+ );+ }++ return (+ <div className="flex flex-col gap-2" data-testid="mcp-ui-frame">+ {state.status === 'loading' || !src ? (+ <p className="text-xs text-content-muted">{t('conversations.mcpUi.widgetLoading')}</p>+ ) : (+ <iframe+ ref={frameRef}+ src={src}+ title={presentation.title ?? t('conversations.mcpUi.widgetTitle')}+ sandbox="allow-scripts allow-forms"+ referrerPolicy="no-referrer"+ allow=""+ className={+ resource?.prefers_border+ ? 'w-full rounded-lg border border-line bg-transparent'+ : 'w-full bg-transparent'+ }+ style={{ height }}+ data-testid="mcp-ui-iframe"+ />+ )}+ {handoffUrl ? (+ <div className="flex flex-col items-center gap-2 rounded-lg border border-line p-3">+ <QrHandoff url={handoffUrl} hint={t('conversations.mcpUi.scanToOpen')} />+ <Button+ size="xs"+ variant="tertiary"+ analyticsId="mcp-ui-close-qr"+ onClick={() => setHandoffUrl(null)}>+ {t('conversations.mcpUi.hideQr')}+ </Button>+ </div>+ ) : null}+ {pending ? (+ <ConfirmDialog+ titleId="mcp-ui-confirm-title"+ title={t('conversations.mcpUi.confirmTitle')}+ body={t('conversations.mcpUi.confirmBody').replace('{tool}', pending.name)}+ confirmLabel={t('conversations.mcpUi.confirmAllow')}+ cancelLabel={t('conversations.mcpUi.confirmDeny')}+ testId="mcp-ui-confirm"+ onConfirm={() => {+ pending.resolve(undefined);+ setPending(null);+ }}+ onCancel={() => {+ pending.reject(new Error('The user declined this action'));+ setPending(null);+ }}+ />+ ) : null}+ </div>+ );+}diff --git a/app/src/features/conversations/tools/mcpUi/McpUiBody.test.tsx b/app/src/features/conversations/tools/mcpUi/McpUiBody.test.tsxnew file mode 100644index 0000000000..4556fd21ba--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/McpUiBody.test.tsx@@ -0,0 +1,30 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { McpUiBody } from './McpUiBody';++vi.mock('../../../../utils/tauriCommands/common', () => ({ isTauri: () => false }));++describe('McpUiBody', () => {+ it('renders nothing for other structured payloads', () => {+ const { container } = render(<McpUiBody structured={{ kind: 'web_search' }} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('falls back to links when the widget cannot be sandboxed', () => {+ render(+ <McpUiBody+ structured={{+ kind: 'mcp_ui',+ flavor: 'mcp_apps',+ server_id: 'srv',+ tool: 'checkout',+ resource_uri: 'ui://checkout',+ links: [{ url: 'upi://pay?pa=shop@bank', kind: 'handoff' }],+ }}+ />+ );+ expect(screen.queryByTestId('mcp-ui-frame')).toBeNull();+ expect(screen.getByTestId('mcp-ui-link')).toBeInTheDocument();+ });+});diff --git a/app/src/features/conversations/tools/mcpUi/McpUiBody.tsx b/app/src/features/conversations/tools/mcpUi/McpUiBody.tsxnew file mode 100644index 0000000000..9513b5e973--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/McpUiBody.tsx@@ -0,0 +1,23 @@+import { isTauri } from '../../../../utils/tauriCommands/common';+import { LinkActions } from './LinkActions';+import { McpAppFrame } from './McpAppFrame';+import { hasWidget, readMcpUiPresentation } from './types';++/**+ * What a tool call that offered UI shows outside its collapsed card: the+ * widget, when there is one and this host can sandbox it, and the links the+ * result offered as a passive fallback.+ */+export function McpUiBody({ structured }: { structured: unknown }) {+ const presentation = readMcpUiPresentation(structured);+ if (!presentation) return null;+ const showFrame = hasWidget(presentation) && isTauri();+ const showLinks = presentation.links.length > 0;+ if (!showFrame && !showLinks) return null;+ return (+ <div className="flex flex-col gap-2" data-testid="mcp-ui-body">+ {showFrame ? <McpAppFrame presentation={presentation} /> : null}+ {showLinks ? <LinkActions links={presentation.links} /> : null}+ </div>+ );+}diff --git a/app/src/features/conversations/tools/mcpUi/appsSdkShim.test.ts b/app/src/features/conversations/tools/mcpUi/appsSdkShim.test.tsnew file mode 100644index 0000000000..070e53463a--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/appsSdkShim.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest';++import { APPS_SDK_SHIM_SOURCE, injectScript } from './appsSdkShim';++describe('injectScript', () => {+ it('runs the script before the document content', () => {+ expect(injectScript('<html><head><title>x</title></head></html>', 'A')).toBe(+ '<html><head><script>A</script><title>x</title></head></html>'+ );+ expect(injectScript('<!doctype html><p>hi</p>', 'A')).toBe(+ '<!doctype html><script>A</script><p>hi</p>'+ );+ expect(injectScript('<p>hi</p>', 'A')).toBe('<script>A</script><p>hi</p>');+ });++ it('cannot be closed early by the script body', () => {+ expect(injectScript('<p/>', 'x</script><b>')).toContain('x<\\/script><b>');+ });+});++describe('APPS_SDK_SHIM_SOURCE', () => {+ it('maps window.openai onto MCP Apps messages', () => {+ const posted: Array<Record<string, unknown>> = [];+ const listeners: Array<(event: { source: unknown; data: unknown }) => void> = [];+ const host = { postMessage: (message: Record<string, unknown>) => posted.push(message) };+ const fakeWindow: Record<string, unknown> = {+ parent: host,+ addEventListener: (type: string, fn: (event: { source: unknown; data: unknown }) => void) => {+ if (type === 'message') listeners.push(fn);+ },+ dispatchEvent: () => true,+ };+ const fakeDocument = { documentElement: { scrollHeight: 120 } };+ class FakeEvent {+ constructor(+ readonly type: string,+ readonly init?: unknown+ ) {}+ }+ new Function('window', 'document', 'CustomEvent', 'ResizeObserver', APPS_SDK_SHIM_SOURCE)(+ fakeWindow,+ fakeDocument,+ FakeEvent,+ undefined+ );+ const openai = fakeWindow.openai as {+ toolOutput: unknown;+ callTool: (name: string, args: unknown) => Promise<unknown>;+ openExternal: (o: { href: string }) => Promise<void>;+ };+ expect(posted[0]).toMatchObject({ method: 'ui/initialize' });++ const deliver = (data: unknown) => listeners.forEach(fn => fn({ source: host, data }));+ deliver({+ jsonrpc: '2.0',+ method: 'ui/notifications/tool-result',+ params: { structuredContent: { total: 120 } },+ });+ expect(openai.toolOutput).toEqual({ total: 120 });++ void openai.callTool('add_to_cart', { id: 1 });+ expect(posted.at(-1)).toMatchObject({+ method: 'tools/call',+ params: { name: 'add_to_cart', arguments: { id: 1 } },+ });+ void openai.openExternal({ href: 'https://pay.example.com' });+ expect(posted.at(-1)).toMatchObject({+ method: 'ui/open-link',+ params: { url: 'https://pay.example.com' },+ });++ const before = posted.length;+ listeners.forEach(fn =>+ fn({+ source: {},+ data: { jsonrpc: '2.0', method: 'ui/notifications/tool-input', params: {} },+ })+ );+ expect(posted.length).toBe(before);+ });+});diff --git a/app/src/features/conversations/tools/mcpUi/appsSdkShim.ts b/app/src/features/conversations/tools/mcpUi/appsSdkShim.tsnew file mode 100644index 0000000000..97892d9b5a--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/appsSdkShim.ts@@ -0,0 +1,134 @@+/**+ * `window.openai` for OpenAI Apps SDK widgets, implemented over the same+ * MCP Apps JSON-RPC channel the frame bridge speaks. Injected at the top of+ * the widget document, so it runs before the widget's own scripts.+ *+ * The documented subset: `toolInput`, `toolOutput`, `toolResponseMetadata`,+ * `widgetState`, `theme`, `locale`, `displayMode`, `maxHeight`, `callTool`,+ * `sendFollowUpMessage`, `openExternal`, `requestDisplayMode`,+ * `setWidgetState`, and the `openai:set_globals` event. Widget state lives in+ * memory only.+ */+export const APPS_SDK_SHIM_SOURCE = `(function () {+ 'use strict';+ var host = window.parent;+ if (!host || host === window || window.openai) return;+ var nextId = 1;+ var pending = {};+ var globals = {+ toolInput: null,+ toolOutput: null,+ toolResponseMetadata: null,+ widgetState: null,+ theme: 'light',+ locale: 'en',+ displayMode: 'inline',+ maxHeight: 640,+ userAgent: { device: { type: 'desktop' }, capabilities: { hover: true, touch: false } },+ safeArea: { insets: { top: 0, bottom: 0, left: 0, right: 0 } }+ };+ function send(message) { host.postMessage(message, '*'); }+ function request(method, params) {+ return new Promise(function (resolve, reject) {+ var id = 'openai-' + nextId++;+ pending[id] = { resolve: resolve, reject: reject };+ send({ jsonrpc: '2.0', id: id, method: method, params: params || {} });+ });+ }+ function notify(method, params) { send({ jsonrpc: '2.0', method: method, params: params || {} }); }+ function setGlobals(patch) {+ for (var key in patch) {+ if (Object.prototype.hasOwnProperty.call(patch, key)) globals[key] = patch[key];+ }+ window.dispatchEvent(new CustomEvent('openai:set_globals', { detail: { globals: patch } }));+ }+ function applyContext(context) {+ if (!context || typeof context !== 'object') return;+ var patch = {};+ if (context.theme === 'dark' || context.theme === 'light') patch.theme = context.theme;+ if (typeof context.locale === 'string') patch.locale = context.locale;+ setGlobals(patch);+ }+ window.addEventListener('message', function (event) {+ if (event.source !== host) return;+ var data = event.data;+ if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') return;+ if (data.id != null && !data.method) {+ var waiter = pending[data.id];+ if (!waiter) return;+ delete pending[data.id];+ if (data.error) waiter.reject(new Error((data.error && data.error.message) || 'Request failed'));+ else waiter.resolve(data.result);+ return;+ }+ var params = data.params || {};+ if (data.method === 'ui/notifications/tool-input') {+ setGlobals({ toolInput: params.arguments == null ? null : params.arguments });+ } else if (data.method === 'ui/notifications/tool-result') {+ setGlobals({+ toolOutput: params.structuredContent == null ? null : params.structuredContent,+ toolResponseMetadata: params._meta == null ? null : params._meta+ });+ } else if (data.method === 'ui/notifications/host-context-changed') {+ applyContext(params);+ }+ });+ var api = {+ callTool: function (name, args) {+ return request('tools/call', { name: String(name), arguments: args || {} });+ },+ sendFollowUpMessage: function (options) {+ var text = String((options && options.prompt) || '');+ return request('ui/message', { role: 'user', content: [{ type: 'text', text: text }] }).then(function () {});+ },+ openExternal: function (options) {+ return request('ui/open-link', { url: String((options && options.href) || '') }).then(function () {});+ },+ requestDisplayMode: function () { return Promise.resolve({ mode: 'inline' }); },+ setWidgetState: function (state) { setGlobals({ widgetState: state }); return Promise.resolve(); },+ notifyIntrinsicHeight: function () { reportSize(); }+ };+ var openai = {};+ Object.keys(globals).forEach(function (key) {+ Object.defineProperty(openai, key, { enumerable: true, get: function () { return globals[key]; } });+ });+ Object.keys(api).forEach(function (key) {+ Object.defineProperty(openai, key, { enumerable: true, value: api[key] });+ });+ Object.defineProperty(window, 'openai', { value: openai, configurable: false, writable: false });+ var lastHeight = 0;+ function reportSize() {+ var height = Math.ceil(document.documentElement.scrollHeight);+ if (height === lastHeight) return;+ lastHeight = height;+ notify('ui/notifications/size-changed', { height: height });+ }+ if (typeof ResizeObserver === 'function') {+ new ResizeObserver(reportSize).observe(document.documentElement);+ }+ window.addEventListener('load', reportSize);+ request('ui/initialize', {+ protocolVersion: '2025-06-18',+ appInfo: { name: 'openai-apps-sdk-shim', version: '1' },+ appCapabilities: {}+ }).then(function (result) {+ applyContext(result && result.hostContext);+ notify('ui/notifications/initialized', {});+ }, function () {});+})();`;++/** `html` with `script` run first: placed right after `<head>`, or at the top. */+export function injectScript(html: string, script: string): string {+ const tag = `<script>${script.replace(/<\/script/gi, '<\\/script')}</script>`;+ const head = /<head(\s[^>]*)?>/i.exec(html);+ if (head) {+ const at = head.index + head[0].length;+ return html.slice(0, at) + tag + html.slice(at);+ }+ const doctype = /^\s*<!doctype[^>]*>/i.exec(html);+ if (doctype) {+ const at = doctype[0].length;+ return html.slice(0, at) + tag + html.slice(at);+ }+ return tag + html;+}diff --git a/app/src/features/conversations/tools/mcpUi/composerPrefill.ts b/app/src/features/conversations/tools/mcpUi/composerPrefill.tsnew file mode 100644index 0000000000..038c846569--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/composerPrefill.ts@@ -0,0 +1,22 @@+/**+ * Puts text in the chat composer without sending it. A widget's+ * `ui/message` lands here so the user reads and sends it themselves.+ */+export const COMPOSER_PREFILL_EVENT = 'openhuman:composer-prefill';++const MAX_PREFILL_CHARS = 4000;++export function requestComposerPrefill(text: string): void {+ const value = text.slice(0, MAX_PREFILL_CHARS);+ window.dispatchEvent(new CustomEvent(COMPOSER_PREFILL_EVENT, { detail: { text: value } }));+}++/** Subscribes `apply` to prefill requests; returns the unsubscribe. */+export function onComposerPrefill(apply: (text: string) => void): () => void {+ const listener = (event: Event) => {+ const text = (event as CustomEvent<{ text?: unknown }>).detail?.text;+ if (typeof text === 'string' && text.trim()) apply(text);+ };+ window.addEventListener(COMPOSER_PREFILL_EVENT, listener);+ return () => window.removeEventListener(COMPOSER_PREFILL_EVENT, listener);+}diff --git a/app/src/features/conversations/tools/mcpUi/mcpAppBridge.test.ts b/app/src/features/conversations/tools/mcpUi/mcpAppBridge.test.tsnew file mode 100644index 0000000000..104417a341--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/mcpAppBridge.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it, vi } from 'vitest';++import {+ type BridgeHandlers,+ MAX_FRAME_HEIGHT,+ McpAppBridge,+ readRpcMessage,+} from './mcpAppBridge';+import type { McpUiPresentation } from './types';++const flush = () => new Promise(resolve => setTimeout(resolve, 0));++function setup(+ overrides: Partial<McpUiPresentation> = {},+ handlerOverrides: Partial<BridgeHandlers> = {}+) {+ const posted: Array<Record<string, unknown>> = [];+ const frame = {+ postMessage: (message: Record<string, unknown>) => posted.push(message),+ } as unknown as Window;+ const handlers: BridgeHandlers = {+ callTool: vi.fn(async () => ({ content: [], structuredContent: { ok: true } })),+ openExternal: vi.fn(async () => undefined),+ handOff: vi.fn(),+ prefillMessage: vi.fn(),+ readResource: vi.fn(async () => ({ contents: [] })),+ resize: vi.fn(),+ ...handlerOverrides,+ };+ let clock = 0;+ const bridge = new McpAppBridge({+ presentation: {+ kind: 'mcp_ui',+ flavor: 'mcp_apps',+ server_id: 'srv',+ tool: 'cart',+ resource_uri: 'ui://cart',+ tool_input: { item: 'dosa' },+ structured_content: { total: 120 },+ links: [],+ ...overrides,+ },+ html: '<html><head></head><body>cart</body></html>',+ theme: 'dark',+ locale: 'en',+ handlers,+ source: () => frame,+ now: () => clock,+ });+ const send = (data: unknown, source: unknown = frame) =>+ bridge.handleMessage({ source, data } as unknown as MessageEvent);+ return { bridge, posted, handlers, send, frame, tick: (ms: number) => (clock += ms) };+}++describe('readRpcMessage', () => {+ it('accepts JSON-RPC requests and notifications only', () => {+ expect(readRpcMessage({ jsonrpc: '2.0', method: 'ping', id: 1 })).not.toBeNull();+ expect(readRpcMessage({ jsonrpc: '2.0', method: 'x' })).not.toBeNull();+ expect(readRpcMessage({ method: 'ping', id: 1 })).toBeNull();+ expect(readRpcMessage({ jsonrpc: '2.0', method: 'x', params: [1] })).toBeNull();+ expect(readRpcMessage({ jsonrpc: '2.0', method: 'x', id: {} })).toBeNull();+ expect(readRpcMessage('{"jsonrpc":"2.0"}')).toBeNull();+ });+});++describe('McpAppBridge', () => {+ it('ignores messages from any other window', async () => {+ const { send, posted } = setup();+ expect(send({ jsonrpc: '2.0', method: 'ping', id: 1 }, window)).toBe(false);+ await flush();+ expect(posted).toHaveLength(0);+ });++ it('delivers the document once the proxy is ready, once', () => {+ const { send, posted } = setup();+ send({ jsonrpc: '2.0', method: 'ui/notifications/sandbox-proxy-ready', params: {} });+ send({ jsonrpc: '2.0', method: 'ui/notifications/sandbox-proxy-ready', params: {} });+ expect(posted).toHaveLength(1);+ expect(posted[0]).toMatchObject({+ method: 'ui/notifications/sandbox-resource-ready',+ params: { html: '<html><head></head><body>cart</body></html>' },+ });+ });++ it('injects the Apps SDK shim for Apps SDK widgets', () => {+ const { send, posted } = setup({ flavor: 'apps_sdk' });+ send({ jsonrpc: '2.0', method: 'ui/notifications/sandbox-proxy-ready' });+ const html = (posted[0].params as { html: string }).html;+ expect(html).toContain('window.openai');+ expect(html.indexOf('<script>')).toBeLessThan(html.indexOf('cart'));+ });++ it('answers ui/initialize with host context, then sends tool input and result', async () => {+ const { send, posted } = setup();+ send({ jsonrpc: '2.0', id: 1, method: 'ui/initialize', params: { protocolVersion: 'v1' } });+ await flush();+ expect(posted[0]).toMatchObject({+ id: 1,+ result: { protocolVersion: 'v1', hostContext: { theme: 'dark', displayMode: 'inline' } },+ });+ send({ jsonrpc: '2.0', method: 'ui/notifications/initialized' });+ expect(posted[1]).toMatchObject({+ method: 'ui/notifications/tool-input',+ params: { arguments: { item: 'dosa' } },+ });+ expect(posted[2]).toMatchObject({+ method: 'ui/notifications/tool-result',+ params: { structuredContent: { total: 120 } },+ });+ });++ it('routes tools/call through the handler', async () => {+ const { send, posted, handlers } = setup();+ send({+ jsonrpc: '2.0',+ id: 'a',+ method: 'tools/call',+ params: { name: 'add', arguments: { id: 2 } },+ });+ await flush();+ expect(handlers.callTool).toHaveBeenCalledWith('add', { id: 2 });+ expect(posted[0]).toMatchObject({ id: 'a', result: { structuredContent: { ok: true } } });+ });++ it('reports a declined tool call as an error', async () => {+ const { send, posted } = setup(+ {},+ {+ callTool: async () => {+ throw new Error('The user declined this action');+ },+ }+ );+ send({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'pay' } });+ await flush();+ expect(posted[0]).toMatchObject({ id: 2, error: { message: 'The user declined this action' } });+ });++ it('refuses tool calls and resource reads from host views', async () => {+ const { send, posted, handlers } = setup({ flavor: 'host_inline', server_id: undefined });+ send({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'x' } });+ send({ jsonrpc: '2.0', id: 2, method: 'resources/read', params: { uri: 'ui://x' } });+ await flush();+ expect(handlers.callTool).not.toHaveBeenCalled();+ expect(handlers.readResource).not.toHaveBeenCalled();+ expect(posted.every(message => 'error' in message)).toBe(true);+ });++ it('opens https links, hands off app links, and refuses the rest', async () => {+ const { send, posted, handlers, tick } = setup();+ send({+ jsonrpc: '2.0',+ id: 1,+ method: 'ui/open-link',+ params: { url: 'https://pay.example.com' },+ });+ send({ jsonrpc: '2.0', id: 2, method: 'ui/open-link', params: { url: 'phonepe://pay?id=1' } });+ send({ jsonrpc: '2.0', id: 3, method: 'ui/open-link', params: { url: 'javascript:alert(1)' } });+ await flush();+ expect(handlers.openExternal).toHaveBeenCalledWith('https://pay.example.com');+ expect(handlers.handOff).toHaveBeenCalledWith('phonepe://pay?id=1');+ expect(posted.find(message => message.id === 3)).toHaveProperty('error');++ send({+ jsonrpc: '2.0',+ id: 4,+ method: 'ui/open-link',+ params: { url: 'https://b.example.com' },+ });+ await flush();+ expect(posted.find(message => message.id === 4)).toHaveProperty('error');+ tick(1500);+ send({+ jsonrpc: '2.0',+ id: 5,+ method: 'ui/open-link',+ params: { url: 'https://b.example.com' },+ });+ await flush();+ expect(handlers.openExternal).toHaveBeenCalledTimes(2);+ });++ it('prefills the composer from ui/message without sending', async () => {+ const { send, handlers } = setup();+ send({+ jsonrpc: '2.0',+ id: 1,+ method: 'ui/message',+ params: { role: 'user', content: [{ type: 'text', text: 'Checkout please' }] },+ });+ await flush();+ expect(handlers.prefillMessage).toHaveBeenCalledWith('Checkout please');+ });++ it('only reads ui:// resources', async () => {+ const { send, handlers, posted } = setup();+ send({+ jsonrpc: '2.0',+ id: 1,+ method: 'resources/read',+ params: { uri: 'file:///etc/passwd' },+ });+ send({ jsonrpc: '2.0', id: 2, method: 'resources/read', params: { uri: 'ui://cart/2' } });+ await flush();+ expect(handlers.readResource).toHaveBeenCalledTimes(1);+ expect(handlers.readResource).toHaveBeenCalledWith('ui://cart/2');+ expect(posted.find(message => message.id === 1)).toHaveProperty('error');+ });++ it('clamps size changes', () => {+ const { send, handlers } = setup();+ send({ jsonrpc: '2.0', method: 'ui/notifications/size-changed', params: { height: 99999 } });+ expect(handlers.resize).toHaveBeenCalledWith(MAX_FRAME_HEIGHT);+ });++ it('rejects unknown requests', async () => {+ const { send, posted } = setup();+ send({ jsonrpc: '2.0', id: 9, method: 'ui/eval', params: {} });+ await flush();+ expect(posted[0]).toMatchObject({ id: 9, error: { code: -32601 } });+ });+});diff --git a/app/src/features/conversations/tools/mcpUi/mcpAppBridge.ts b/app/src/features/conversations/tools/mcpUi/mcpAppBridge.tsnew file mode 100644index 0000000000..4e1709aa08--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/mcpAppBridge.ts@@ -0,0 +1,279 @@+/**+ * The host side of the MCP Apps channel to one widget frame.+ *+ * The frame is the `ohwidget:` sandbox proxy, which relays JSON-RPC between+ * this window and the widget's inner sandboxed frame. Every message is+ * accepted only from that frame's window and only in JSON-RPC 2.0 shape; what+ * a widget may ask for is decided here and in the handlers, never by the+ * widget.+ */+import debug from 'debug';++import { classifyHref } from '../../utils/format';+import { APPS_SDK_SHIM_SOURCE, injectScript } from './appsSdkShim';+import type { McpUiPresentation } from './types';++const log = debug('mcp-ui:bridge');++export const MAX_FRAME_HEIGHT = 720;+export const MIN_FRAME_HEIGHT = 48;+const MAX_METHOD_LENGTH = 96;+const OPEN_LINK_INTERVAL_MS = 1000;+const PROTOCOL_VERSION = '2025-06-18';++export const RPC_METHOD_NOT_FOUND = -32601;+export const RPC_INVALID_PARAMS = -32602;+export const RPC_INTERNAL_ERROR = -32603;+export const RPC_DENIED = -32000;++export interface BridgeHandlers {+ /** Runs a tool call the widget asked for; rejects when refused. */+ callTool(name: string, args: Record<string, unknown>): Promise<unknown>;+ /** Opens an `http(s)` link in the browser. */+ openExternal(url: string): Promise<void>;+ /** Hands an app link (`upi://`, ...) to the user's phone. */+ handOff(url: string): void;+ /** Prefills the composer; never sends. */+ prefillMessage(text: string): void;+ /** Reads another `ui://` resource on the widget's server. */+ readResource(uri: string): Promise<unknown>;+ /** The widget asked for this content height. */+ resize(height: number): void;+}++export interface BridgeOptions {+ presentation: McpUiPresentation;+ html: string;+ theme: 'light' | 'dark';+ locale: string;+ handlers: BridgeHandlers;+ /** The proxy frame's window; messages from anything else are ignored. */+ source: () => Window | null | undefined;+ now?: () => number;+}++interface RpcMessage {+ jsonrpc: '2.0';+ id?: string | number;+ method?: string;+ params?: Record<string, unknown>;+}++class RpcError extends Error {+ constructor(+ readonly code: number,+ message: string+ ) {+ super(message);+ }+}++/** Whether `data` is a JSON-RPC 2.0 request or notification this host reads. */+export function readRpcMessage(data: unknown): RpcMessage | null {+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;+ const message = data as Record<string, unknown>;+ if (message.jsonrpc !== '2.0') return null;+ if (typeof message.method !== 'string' || message.method.length === 0) return null;+ if (message.method.length > MAX_METHOD_LENGTH) return null;+ if (+ 'id' in message &&+ message.id !== undefined &&+ typeof message.id !== 'string' &&+ typeof message.id !== 'number'+ ) {+ return null;+ }+ if (+ message.params !== undefined &&+ (message.params === null || typeof message.params !== 'object' || Array.isArray(message.params))+ ) {+ return null;+ }+ return message as unknown as RpcMessage;+}++function textOf(content: unknown): string {+ if (!Array.isArray(content)) return '';+ return content+ .filter(+ (block): block is { type: 'text'; text: string } =>+ !!block &&+ typeof block === 'object' &&+ (block as { type?: unknown }).type === 'text' &&+ typeof (block as { text?: unknown }).text === 'string'+ )+ .map(block => block.text)+ .join('\n');+}++export class McpAppBridge {+ private readonly options: BridgeOptions;+ private delivered = false;+ private initialized = false;+ private lastOpenAt = Number.NEGATIVE_INFINITY;++ constructor(options: BridgeOptions) {+ this.options = options;+ }++ private get flavor() {+ return this.options.presentation.flavor;+ }++ private post(message: Record<string, unknown>): void {+ const target = this.options.source();+ if (!target) return;+ target.postMessage({ jsonrpc: '2.0', ...message }, '*');+ }++ /** Feeds one `message` event; returns whether it was accepted. */+ handleMessage(event: MessageEvent): boolean {+ const source = this.options.source();+ if (!source || event.source !== source) return false;+ const message = readRpcMessage(event.data);+ if (!message) {+ log('dropped a malformed message');+ return false;+ }+ void this.dispatch(message);+ return true;+ }++ private async dispatch(message: RpcMessage): Promise<void> {+ const { method = '', id } = message;+ const params = message.params ?? {};+ if (id === undefined) {+ this.onNotification(method, params);+ return;+ }+ try {+ const result = await this.onRequest(method, params);+ this.post({ id, result });+ } catch (error) {+ const code = error instanceof RpcError ? error.code : RPC_INTERNAL_ERROR;+ const text = error instanceof Error ? error.message : 'Request failed';+ log('request %s failed: %s', method, text);+ this.post({ id, error: { code, message: text } });+ }+ }++ private onNotification(method: string, params: Record<string, unknown>): void {+ switch (method) {+ case 'ui/notifications/sandbox-proxy-ready':+ this.deliverDocument();+ return;+ case 'ui/notifications/initialized':+ this.sendToolData();+ return;+ case 'ui/notifications/size-changed': {+ const height = Number(params.height);+ if (Number.isFinite(height) && height > 0) {+ this.options.handlers.resize(+ Math.min(MAX_FRAME_HEIGHT, Math.max(MIN_FRAME_HEIGHT, Math.ceil(height)))+ );+ }+ return;+ }+ default:+ return;+ }+ }++ private deliverDocument(): void {+ if (this.delivered) return;+ this.delivered = true;+ const html =+ this.flavor === 'apps_sdk'+ ? injectScript(this.options.html, APPS_SDK_SHIM_SOURCE)+ : this.options.html;+ log('delivering widget document (%s)', this.flavor);+ this.post({ method: 'ui/notifications/sandbox-resource-ready', params: { html } });+ }++ private sendToolData(): void {+ if (this.initialized) return;+ this.initialized = true;+ const { presentation } = this.options;+ this.post({+ method: 'ui/notifications/tool-input',+ params: { arguments: presentation.tool_input ?? {} },+ });+ const result: Record<string, unknown> = { content: [] };+ if (presentation.structured_content !== undefined) {+ result.structuredContent = presentation.structured_content;+ }+ if (presentation.result_meta !== undefined) result._meta = presentation.result_meta;+ this.post({ method: 'ui/notifications/tool-result', params: result });+ }++ private async onRequest(method: string, params: Record<string, unknown>): Promise<unknown> {+ const { handlers } = this.options;+ switch (method) {+ case 'ui/initialize':+ return {+ protocolVersion:+ typeof params.protocolVersion === 'string' ? params.protocolVersion : PROTOCOL_VERSION,+ hostInfo: { name: 'OpenHuman', version: '1' },+ hostCapabilities: {+ openLinks: {},+ ...(this.flavor === 'host_inline' ? {} : { serverTools: {}, serverResources: {} }),+ },+ hostContext: {+ theme: this.options.theme,+ displayMode: 'inline',+ availableDisplayModes: ['inline'],+ locale: this.options.locale,+ platform: 'desktop',+ },+ };+ case 'ping':+ return {};+ case 'ui/request-display-mode':+ return { mode: 'inline' };+ case 'tools/call': {+ if (this.flavor === 'host_inline') {+ throw new RpcError(RPC_METHOD_NOT_FOUND, 'Tool calls are not available to this view');+ }+ const name = params.name;+ const args = params.arguments ?? {};+ if (typeof name !== 'string' || !name || typeof args !== 'object' || Array.isArray(args)) {+ throw new RpcError(RPC_INVALID_PARAMS, 'tools/call needs a name and an arguments object');+ }+ return handlers.callTool(name, args as Record<string, unknown>);+ }+ case 'ui/open-link': {+ const url = typeof params.url === 'string' ? params.url.trim() : '';+ const kind = classifyHref(url);+ if (kind !== 'external' && kind !== 'handoff') {+ throw new RpcError(RPC_DENIED, 'This link cannot be opened');+ }+ if (kind === 'handoff') {+ handlers.handOff(url);+ return {};+ }+ const now = (this.options.now ?? Date.now)();+ if (now - this.lastOpenAt < OPEN_LINK_INTERVAL_MS) {+ throw new RpcError(RPC_DENIED, 'Too many links opened');+ }+ this.lastOpenAt = now;+ await handlers.openExternal(url);+ return {};+ }+ case 'ui/message': {+ const text = textOf(params.content).trim();+ if (!text) throw new RpcError(RPC_INVALID_PARAMS, 'ui/message needs text content');+ handlers.prefillMessage(text);+ return {};+ }+ case 'resources/read': {+ const uri = typeof params.uri === 'string' ? params.uri : '';+ if (this.flavor === 'host_inline' || !/^ui:\/\/./i.test(uri)) {+ throw new RpcError(RPC_DENIED, 'Only ui:// resources on this server can be read');+ }+ return handlers.readResource(uri);+ }+ default:+ throw new RpcError(RPC_METHOD_NOT_FOUND, `Unsupported method ${method}`);+ }+ }+}diff --git a/app/src/features/conversations/tools/mcpUi/widgetUrl.test.ts b/app/src/features/conversations/tools/mcpUi/widgetUrl.test.tsnew file mode 100644index 0000000000..789e4dc839--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/widgetUrl.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { widgetProxyUrl } from './widgetUrl';++describe('widgetProxyUrl', () => {+ it('uses the platform origin and carries the declared origins', () => {+ expect(widgetProxyUrl(undefined, false)).toBe('ohwidget://localhost/proxy');+ expect(+ widgetProxyUrl(+ {+ connect_domains: ['https://api.example.com'],+ resource_domains: ['https://cdn.example.com'],+ },+ true+ )+ ).toBe(+ 'http://ohwidget.localhost/proxy?connect=https%3A%2F%2Fapi.example.com&resource=https%3A%2F%2Fcdn.example.com'+ );+ });+});diff --git a/app/src/features/conversations/tools/mcpUi/widgetUrl.ts b/app/src/features/conversations/tools/mcpUi/widgetUrl.tsnew file mode 100644index 0000000000..9556f04de9--- /dev/null+++ b/app/src/features/conversations/tools/mcpUi/widgetUrl.ts@@ -0,0 +1,15 @@+import type { McpUiResource } from './types';++/** The sandbox proxy URL on the widget origin, carrying the declared CSP. */+export function widgetProxyUrl(csp: McpUiResource['csp'] | undefined, windows: boolean): string {+ const base = windows ? 'http://ohwidget.localhost/proxy' : 'ohwidget://localhost/proxy';+ const query = new URLSearchParams();+ for (const origin of csp?.connect_domains ?? []) query.append('connect', origin);+ for (const origin of csp?.resource_domains ?? []) query.append('resource', origin);+ const encoded = query.toString();+ return encoded ? `${base}?${encoded}` : base;+}++export function isWindowsHost(): boolean {+ return typeof navigator !== 'undefined' && /Windows/i.test(navigator.userAgent);+}