Skip to content

add option for MCP apps support - #69039

Merged
steipete merged 1 commit into
openclaw:mainfrom
sallyom:mcp-apps-bridge
Jul 12, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
sallyom:mcp-apps-bridge

Conversation

@sallyom

@sallyom sallyom commented Apr 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: OpenClaw calls MCP servers, but ignores MCP Apps UI metadata/resources
  • Why it matters: MCP Apps turns trusted MCP servers into richer tool providers with purpose-built UI. Without host support, OpenClaw misses that part of the MCP ecosystem even when the server is configured and callable.
  • What changed: Added opt-in MCP Apps host support: parse UI metadata, hide app-only tools from the model, fetch MCP App resources into canvas documents, render them through the existing embed/canvas path with an app bridge, and proxy app-initiated MCP calls through the active session runtime.
  • What changed: Added restart/reload hardening for restored app views, wider assistant canvas layout, docs, config schema support,tests, and a security-audit warning when mcp.apps.enabled=true.
  • What did NOT change (scope boundary): Normal MCP tool execution still works without MCP Apps. MCP Apps are default-off behind mcp.apps.enabled; this does not add a marketplace, new MCP server examples, or plugin-only architecture.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Regression Test Plan (if applicable)

  • MCP app-only tools are not materialized for the model.

  • MCP Apps UI payloads are only fetched/rendered when mcp.apps.enabled=true.

  • App bridge calls are rejected when MCP Apps are disabled.

  • App bridge calls enforce app-callable tool visibility.

  • Persisted/restored app views can recreate an MCP runtime after gateway restart.

  • Existing [embed] canvas rendering remains the fallback path when MCP Apps metadata is absent or disabled.

  • Target test or file:

    • New opt-in config: mcp.apps.enabled.
    • Default behavior is unchanged for normal MCP tools; MCP Apps UI rendering is disabled by default.
    • When enabled, trusted MCP servers can render interactive app views in chat using the existing canvas/embed path.
    • MCP Apps views may call app-visible MCP tools through the active session runtime.
    • App-only MCP tools are hidden from the model.
    • openclaw security audit now warns when MCP Apps are enabled.
    • Docs now describe MCP Apps setup, scope, and security considerations.
  • Scenario the test should lock in:

    • MCP Apps metadata is preserved from MCP tool catalogs through tool results and chat rendering.
    • App-only tools are hidden from the model.
    • Model-only tools are blocked from app bridge calls.
    • MCP Apps UI rendering and bridge proxy calls require mcp.apps.enabled=true.
    • Restored app views can recreate an MCP runtime after gateway restart.
    • Existing canvas/embed rendering remains the fallback when MCP Apps are disabled or metadata is absent.
  • Why this is the smallest reliable guardrail:

    • The feature crosses runtime materialization, gateway proxying, config/bootstrap, and UI rendering. Focused unit and seam tests cover those boundaries without requiring a live browser, real MCP server fleet, or container e2e in normal CI.
  • Existing test that already covers this (if any):

    • Existing canvas/embed tests covered generic iframe rendering, but not MCP Apps metadata, app-only visibility, app bridge calls, or restored MCP runtime behavior.

    User-visible / Behavior Changes

    • New opt-in config: mcp.apps.enabled.
    • Default behavior is unchanged for normal MCP tools; MCP Apps UI rendering is disabled by default.
    • When enabled, trusted MCP servers can render interactive app views in chat using the existing canvas/embed path.
    • MCP Apps views may call app-visible MCP tools through the active session runtime.
    • App-only MCP tools are hidden from the model.
    • openclaw security audit now warns when MCP Apps are enabled.
    • Docs now describe MCP Apps setup, scope, and security considerations.

Diagram (if applicable)

flowchart LR
  A[MCP server tool] --> B[Tool result with UI metadata]
  B --> C[OpenClaw MCP runtime]
  C --> D[Fetch MCP App HTML resource]
  D --> E[Canvas document / existing embed path]
  E --> F[Control UI mcp-app-view iframe]
  F --> G[AppBridge]
  G --> H[Gateway mcp.* proxy]
  H --> C
Loading

Security Impact (required)

  • New permissions/capabilities? (Yes/No): Yes

  • Secrets/tokens handling changed? (Yes/No): No

  • New/changed network calls? (Yes/No): No for normal MCP transport; Yes in the sense that enabled MCP Apps can make app-initiated MCP calls back through the existing MCP session runtime.

  • Command/tool execution surface changed? (Yes/No): Yes

  • Data access scope changed? (Yes/No): Yes

  • If any Yes, explain risk + mitigation:

    • Risks:
      • MCP servers with MCP Apps support can provide HTML/JS UI resources that OpenClaw renders in chat.
      • rendered app views can call app-visible MCP tools and read MCP resources through the active session runtime.
      • app views receive the tool input/result payload they are rendering.
    • Mitigations:
      • MCP Apps are default-off behind mcp.apps.enabled=true.
      • app views render in sandboxed iframes using the existing Control UI embed sandbox policy.
      • app-only tools are hidden from the model, and model-only tools are blocked from app bridge calls.
      • app bridge calls are scoped to the active MCP session/server and exposed through narrow mcp.* gateway methods.
      • openclaw security audit warns when MCP Apps are enabled.
  • Trust model: enabling MCP Apps means trusting the configured MCP servers not only as tool providers, but also as UI code providers.

    Repro + Verification

    Environment

    • OS: macOS
    • Runtime/container: local OpenClaw container via Podman
    • Model/provider: Claude Sonnet 4.6
    • Integration/channel (if any): Control UI chat with configured MCP servers
    • Relevant config (redacted):
  {
    "mcp": {
      "apps": {
        "enabled": true
      },
      "servers": {
        "system-monitor": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-system-monitor", "--stdio"]
        },
        "pdf": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-pdf", "--stdio"]
        },
        "qr": {
          "url": "http://127.0.0.1:3108/mcp",
          "transport": "streamable-http"
        }
      }
    }
  }

Steps

  1. Build and run an OpenClaw image from this branch.
  2. Enable MCP Apps with openclaw config set mcp.apps.enabled true --strict-json.
  3. Configure the system-monitor, pdf, and qr MCP servers.
  4. Start the QR MCP sidecar if using the QR example.
  5. Start a fresh chat/session in the Control UI.
  6. Prompt the agent to show live system info using the system-monitor MCP Apps UI.
  7. Prompt the agent to generate a QR code using the QR MCP Apps UI.
  8. Prompt the agent to display https://arxiv.org/pdf/1706.03762 using the PDF MCP Apps UI.
  9. Restart the OpenClaw container and reload the Control UI.
  10. Confirm the persisted PDF app view reloads and reconnects.

Expected

  • Normal MCP tools still work.
  • With mcp.apps.enabled=true, MCP Apps UI resources render as interactive embedded app views.
  • System monitor renders a live monitor UI.
  • QR renders an embedded QR UI.
  • PDF renders an interactive PDF viewer.
  • Restored app views can reconnect after gateway/container restart.
  • With mcp.apps.enabled=false, app bridge calls are rejected and MCP Apps render through the normal fallback path instead of the app bridge.

Actual

  • Verified locally with system-monitor, QR, and PDF MCP Apps examples.
  • Verified upstream image comparison: upstream can call the MCP servers but does not render the MCP Apps UI resources.
  • Verified restart/reload behavior for the PDF app view.

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

poc-mcp-apps.mp4

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) Yes
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:
    • No migration is required for existing installs. MCP Apps support is default-off.
    • To enable it, set:
      openclaw config set mcp.apps.enabled true --strict-json
    • Configure MCP servers that expose MCP Apps / mcp-ui resources.
    • Restart OpenClaw so the updated config is loaded.

Risks and Mitigations

  • Risk: Enabling MCP Apps allows configured MCP servers to provide HTML/JS UI that renders inside OpenClaw.
    • Mitigation: Feature is opt-in via mcp.apps.enabled; app UI renders in a sandboxed iframe; docs and security audit call out the trust boundary.
  • Risk: App views can call app-visible MCP tools/resources through the bridge, increasing the practical surface area of a trusted MCP server.
    • Mitigation: Bridge is scoped to MCP app methods only; model-only tools are blocked from app bridge calls; app-only tools are hidden from the model.
  • Risk: Restored chat views may need to reconnect to MCP runtimes after a container restart.
    • Mitigation: Gateway proxy lazily recreates the session MCP runtime from config when an app bridge call arrives and no runtime is currently active.
  • Risk: Servers without MCP Apps support, or installs with the feature disabled, should not regress.
    • Mitigation: Existing MCP tool execution path remains unchanged; UI falls back to the existing embed/canvas rendering behavior when MCP Apps are disabled or metadata is absent.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Apr 19, 2026
@sallyom
sallyom marked this pull request as ready for review April 19, 2026 19:05
@sallyom
sallyom requested a review from a team as a code owner April 19, 2026 19:05
@greptile-apps

greptile-apps Bot commented Apr 19, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds opt-in MCP Apps host support (mcp.apps.enabled) that lets configured MCP servers provide HTML/JS UI resources rendered in sandboxed iframes within the chat canvas. It introduces a gateway proxy for app-initiated MCP calls (mcp.callTool, mcp.readResource, etc.), hides app-only tools from the model, adds restart/reload hardening for persisted app views, and wires a security-audit warning when the feature is enabled.

The visibility-enforcement logic (three-state uiVisibility: undefined = both, [\"model\"] = model-only, [\"app\"] = app-only) is consistent across requireAppCallableTool, isAppCallableTool, and isAppOnlyTool, and is backed by focused unit and integration tests. The main non-blocking finding is that the McpAppView component does not call _teardown() inside the catch block of _setupBridge, leaving the bridge and transport alive when the iframe load or handshake times out.

Confidence Score: 4/5

Safe to merge with minor cleanup; the bridge resource-leak in the error path is the only non-trivial finding.

All P0/P1 security controls (feature flag, tool visibility enforcement, sandboxed iframe, security audit warning) are in place and tested. The two findings are P2: a resource leak when the bridge handshake fails, and a readability note on the default-allow visibility logic. Neither blocks correct behaviour under the normal success path.

ui/src/ui/components/mcp-app-view.ts — catch block in _setupBridge should call _teardown() to avoid leaving the bridge/transport alive on connect failure.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: ui/src/ui/components/mcp-app-view.ts
Line: 232-236

Comment:
**Bridge and transport not torn down on connect failure**

When `Promise.all([loadPromise, connectPromise])` rejects (e.g., the 15 s iframe-load timeout fires, or the bridge handshake fails), `this._bridge` and `this._closeTransport` are left set but the catch block only records the error string — it does not call `_teardown()`. The dangling bridge will keep its internal listeners alive until the next `_setupBridge` call or `disconnectedCallback`.

```suggestion
    } catch (err) {
      if (!this._disposed) {
        this._error = err instanceof Error ? err.message : String(err);
        this._teardown();
        this._disposed = false; // keep component alive to show error
      }
    }
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/gateway/server-methods/mcp-app-proxy.ts
Line: 51-68

Comment:
**Implicit default-allow for tools with no `uiVisibility` annotation**

The guard `tool.uiVisibility?.includes("app") === false` throws only when `uiVisibility` is defined and excludes `"app"`. When `uiVisibility` is `undefined` the optional-chain short-circuits to `undefined`, and `undefined === false` is `false`, so the tool silently passes through. This is the same logic as `isAppCallableTool`, so the behavior is internally consistent, but the intent ("default-allow" for unannotated tools) is easy to misread.

A comment or a named helper that spells out the three-state semantics (undefined = both, ["model"] = model-only, ["app"] = app-only) would help reviewers and future maintainers avoid accidentally tightening this in a way that breaks unlabeled tools.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "add option for MCP apps support" | Re-trigger Greptile

Comment thread ui/src/ui/components/mcp-app-view.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a3a1489046

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread ui/src/ui/components/mcp-app-view.ts Resolved
Comment thread src/agents/pi-bundle-mcp-runtime.ts Resolved
@aisle-research-bot

aisle-research-bot Bot commented Apr 19, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 7 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Session key (bearer capability) and tool data embedded into MCP App canvas JSON and propagated to UI
2 🟠 High Default-allow app access to unannotated MCP tools via mcp-app proxy
3 🟠 High Unbounded MCP UI resource decoding and persistence can cause memory/disk exhaustion (DoS)
4 🟠 High IDOR/broken access control: MCP app proxy methods accept arbitrary sessionKey and recreate runtimes
5 🟠 High Unrestricted MCP resource URI proxy allows untrusted MCP Apps to read arbitrary resources (SSRF/LFI)
6 🟠 High MCP App iframe can be rendered with allow-same-origin, enabling same-origin XSS/privilege escalation
7 🟡 Medium MCP UI resource response is not strictly validated (content substitution / confused deputy)
1. 🟠 Session key (bearer capability) and tool data embedded into MCP App canvas JSON and propagated to UI
Property Value
Severity High
CWE CWE-922
Location src/agents/mcp-ui-resource.ts:69-107

Description

The MCP App canvas metadata includes sessionKey plus toolInput/toolResult, and this JSON is embedded into the canvas shortcode/preview that gets stored and rendered in chat UI.

Security impact:

  • sessionKey appears to function as a bearer credential (used by the UI to authenticate gateway requests in mcp-app-proxy), so embedding it into message content risks unintended disclosure via:
    • persistence in chat history / logs / exports
    • exposure to any other same-origin scripts (e.g., compromised UI dependency/XSS) that can read rendered message data
    • potential inclusion in model-visible transcripts if chat content is re-sent to the LLM
  • toolInput/toolResult may include sensitive user data and are similarly embedded and propagated.

Vulnerable code:

const mcpApp: McpAppViewMeta = {
  serverName: params.serverName,
  toolName: params.toolName,
  uiResourceUri: params.uiResourceUri,
  ...(params.runtime.sessionKey ? { sessionKey: params.runtime.sessionKey } : {}),
};
...
const mcpApp = {
  ...params.view.mcpApp,
  toolInput: params.toolInput,
  toolResult: params.toolResult,
};
return JSON.stringify({ ..., mcpApp });

Even though the iframe is sandboxed, the app does not need the sessionKey value at rest; the host can keep the session key only in memory (UI context) and use it for proxying. Persisting it in message content creates an avoidable credential leakage surface.

Recommendation

Do not serialize bearer credentials or sensitive tool payloads into chat/canvas JSON.

  • Remove sessionKey from McpAppViewMeta and from the serialized mcpApp field.
  • If the UI host needs a session key, obtain it from in-memory UI context (getMcpAppContext()) rather than persisted message content.
  • Consider redacting or omitting toolInput/toolResult from persisted canvas metadata; if needed for UX, store a minimal, explicitly-redacted subset.

Example (server-side):

​// Do not include sessionKey in view metadata
const mcpApp: McpAppViewMeta = {
  serverName: params.serverName,
  toolName: params.toolName,
  uiResourceUri: params.uiResourceUri,
};

​// Persist only non-sensitive metadata
return JSON.stringify({
  kind: "canvas",
  ...,
  mcpApp,
});

Example (client-side):

​// In mcp-app-view.ts
const sessionKey = ctx.sessionKey; // only from in-memory context

Additionally: add automated tests/audits to ensure sessionKey never appears in stored chat transcripts or rendered message JSON.

2. 🟠 Default-allow app access to unannotated MCP tools via mcp-app proxy
Property Value
Severity High
CWE CWE-284
Location src/gateway/server-methods/mcp-app-proxy.ts:70-73

Description

The MCP app proxy gateway methods allow an app UI to list and invoke MCP tools based on isAppCallableTool(). The policy currently defaults to allowing app calls when tool.uiVisibility is undefined (legacy/unannotated tools):

  • uiVisibility is populated from tool _meta.ui.visibility in the MCP catalog; when absent, it becomes undefined
  • isAppCallableTool() treats undefined as app-callable, so any legacy tool (including potentially dangerous tools that were only intended for model invocation) becomes callable by an app UI
  • This violates least privilege for untrusted/third-party app UIs and can expand the attack surface to arbitrary tool execution

Vulnerable code:

function isAppCallableTool(tool: McpCatalogTool): boolean {
  ​// Unannotated tools predate MCP Apps and remain visible to both model and app callers.
  return tool.uiVisibility === undefined || tool.uiVisibility.includes("app");
}

Recommendation

Change the policy to default-deny for app callers, requiring an explicit app visibility annotation.

Suggested fix:

function isAppCallableTool(tool: McpCatalogTool): boolean {
  ​// Safer default: only explicitly app-visible tools can be called by apps.
  return tool.uiVisibility?.includes("app") === true;
}

If backward compatibility is required, gate legacy/default-allow behavior behind a config flag (e.g., mcp.apps.allowLegacyTools: false by default) and provide a migration path to annotate existing tools with _meta.ui.visibility: ["app"] where appropriate.

3. 🟠 Unbounded MCP UI resource decoding and persistence can cause memory/disk exhaustion (DoS)
Property Value
Severity High
CWE CWE-400
Location src/agents/mcp-ui-resource.ts:37-82

Description

fetchMcpAppView decodes and persists MCP server-provided UI resources without any size limits:

  • An MCP server can return arbitrarily large content.text or base64 content.blob.
  • Buffer.from(content.blob, "base64") will allocate memory proportional to the decoded size.
  • The resulting html string is then written to disk via createCanvasDocument (which uses fs.writeFile), potentially exhausting disk.

Vulnerable code:

const html =
  "text" in content && typeof content.text === "string"
    ? content.text
    : "blob" in content && typeof content.blob === "string"
      ? Buffer.from(content.blob, "base64").toString("utf8")
      : undefined;
...
entrypoint: { type: "html", value: html },

Recommendation

Enforce strict maximum sizes for MCP UI resources before decoding and before writing to disk.

Suggested approach:

  1. Reject responses whose declared/observed size exceeds a configured limit (e.g. 1–5 MB for HTML).
  2. For base64 blobs, reject if content.blob.length exceeds a safe bound (base64 overhead ~4/3), and/or decode with a hard cap.
  3. Add a cap in createCanvasDocument for entrypoint.type === "html" payload size.

Example:

const MAX_HTML_BYTES = 2 * 1024 * 1024; // 2MB

function assertMaxBytesUtf8(s: string, max: number) {
  if (Buffer.byteLength(s, "utf8") > max) {
    throw new Error(`MCP UI resource too large (${Buffer.byteLength(s, "utf8")} bytes)`);
  }
}

let html: string | undefined;
if ("text" in content && typeof content.text === "string") {
  assertMaxBytesUtf8(content.text, MAX_HTML_BYTES);
  html = content.text;
} else if ("blob" in content && typeof content.blob === "string") {
  ​// base64 length check (~4/3 expansion)
  if (content.blob.length > Math.ceil(MAX_HTML_BYTES * 4 / 3) + 16) {
    throw new Error("MCP UI resource blob too large");
  }
  const decoded = Buffer.from(content.blob, "base64");
  if (decoded.length > MAX_HTML_BYTES) throw new Error("MCP UI resource too large");
  html = decoded.toString("utf8");
}
4. 🟠 IDOR/broken access control: MCP app proxy methods accept arbitrary sessionKey and recreate runtimes
Property Value
Severity High
CWE CWE-639
Location src/gateway/server-methods/mcp-app-proxy.ts:84-108

Description

In mcpAppProxyHandlers, the gateway methods (mcp.callTool, mcp.readResource, mcp.listTools, mcp.listResources, mcp.listResourceTemplates) take a sessionKey directly from untrusted request parameters and use it to resolve or create an MCP runtime.

  • Input: sessionKey comes from params.sessionKey (client-controlled)
  • Authorization missing: there is no server-side check that the provided sessionKey is the caller’s current/authorized session (or even an existing session belonging to the authenticated client)
  • Impact: a client with gateway access and appropriate scopes can potentially:
    • access another session’s MCP runtime if they can obtain/guess its sessionKey
    • create/target a runtime for a different agent by supplying a crafted sessionKey (since resolveSessionAgentId derives agentId from the sessionKey)
    • read resources and enumerate tools/resources across sessions/agents

Vulnerable flow:

const sessionKey = requireString(params, "sessionKey");
const runtime = await resolveRuntime(sessionKey);
...
const result = await runtime.readResource(serverName, uri);

and in resolveRuntime:

const agentId = resolveSessionAgentId({ sessionKey, config: cfg });
...
return await getOrCreateSessionMcpRuntime({
  sessionId: `mcp-app:${sessionKey}`,
  sessionKey,
  ...
});

requireMcpAppsEnabled() only checks a feature flag and does not restrict which session/runtime can be accessed.

Recommendation

Bind sessionKey to the authenticated caller context and enforce authorization before resolving/creating a runtime.

Recommended approaches (pick what matches your architecture):

  1. Do not accept sessionKey from the client for MCP app proxy calls; instead, derive it from the already-authenticated gateway connection/session state (e.g., from client, a server-side session, or an issued capability token).

  2. If sessionKey must be provided, validate access:

    • ensure the session exists and is owned by/issued to the current authenticated principal
    • ensure the session’s agent/workspace matches what the caller is allowed to access
    • reject unknown session keys (do not create new runtimes from arbitrary keys)

Example pattern (illustrative):

"mcp.readResource": async ({ respond, params, client, context }) => {
  const sessionKey = requireString(params, "sessionKey");

  ​// 1) Verify sessionKey belongs to this authenticated client/principal
  const allowed = await context.sessionAuth.canAccessSessionKey({
    principal: client.connect?.principalId,
    sessionKey,
  });
  if (!allowed) {
    respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized session"));
    return;
  }

  ​// 2) Only then resolve runtime
  const runtime = await resolveRuntime(sessionKey);
  requireMcpAppsEnabled(runtime);
  ...
}

Additionally:

  • Use a server-generated, unguessable session identifier (capability) rather than a user-controlled string.
  • Avoid sessionId: \mcp-app:${sessionKey}`ifsessionKey` is not guaranteed secret/unpredictable and authenticated.
5. 🟠 Unrestricted MCP resource URI proxy allows untrusted MCP Apps to read arbitrary resources (SSRF/LFI)
Property Value
Severity High
CWE CWE-918
Location src/gateway/server-methods/mcp-app-proxy.ts:100-108

Description

The gateway handler mcp.readResource forwards an arbitrary, app-controlled uri directly to the MCP runtime without enforcing that it is a safe UI resource (e.g., ui://...) or checking it against advertised resource templates.

This is dangerous because MCP Apps are rendered as untrusted HTML/JS in an iframe and can invoke the AppBridge methods:

  • Input: params.uri originates from the embedded MCP App via the browser AppBridge.onreadresource call.
  • Sink: runtime.readResource(serverName, uri) forwards the URI to the MCP server.
  • If the MCP server supports resource handlers for http(s)://, file://, ssh://, gopher://, cloud-metadata URLs, or other custom schemes, a malicious app could:
    • trigger SSRF to internal services/metadata endpoints
    • trigger local file reads or other sensitive resource access supported by that server
    • fetch very large blobs causing memory/CPU/transfer DoS

Vulnerable code:

const uri = requireString(params, "uri");
...
const result = await runtime.readResource(serverName, uri);

Recommendation

Enforce a strict allowlist for app-initiated resource reads.

At minimum, only allow ui:// resources for MCP Apps (or only URIs that were previously advertised by listResources/listResourceTemplates for that server and match expected UI MIME types).

Example (scheme allowlist + optional length limit):

function requireUiResourceUri(uri: string): string {
  if (!uri.startsWith("ui://")) {
    throw new Error("only ui:// resources may be read by MCP Apps");
  }
  if (uri.length > 2048) {
    throw new Error("resource URI too long");
  }
  return uri;
}

​// in handler
const uri = requireUiResourceUri(requireString(params, "uri"));
const result = await runtime.readResource(serverName, uri);

Additionally consider:

  • enforcing maximum response size / streaming limits when returning ReadResourceResult
  • validating that returned content types for app UI are only text/html;profile=mcp-app (or other explicitly allowed UI types)
6. 🟠 MCP App iframe can be rendered with `allow-same-origin`, enabling same-origin XSS/privilege escalation
Property Value
Severity High
CWE CWE-79
Location ui/src/ui/components/mcp-app-view.ts:249-257

Description

The Control UI renders MCP server-supplied HTML inside an iframe. The iframe sandbox flags are derived from embedSandboxMode and may include allow-same-origin when the mode is set to "trusted".

When allow-same-origin is combined with allow-scripts, the sandbox no longer origin-isolates the embedded document. If the canvas document is served from the same origin as the Control UI (e.g., resolveCanvasIframeUrl() returns a relative /_ _openclaw_ _/canvas/... URL), the untrusted MCP App HTML can:

  • Run arbitrary JS (intended)
  • Become same-origin with the Control UI (in trusted mode)
  • Directly access window.top / parent DOM, read sensitive data, and invoke privileged UI actions

Vulnerable code paths:

  • resolveEmbedSandbox("trusted") returns "allow-scripts allow-same-origin"
  • mcp-app-view uses that value to build the iframe sandbox string

Vulnerable code:

​// ui/src/ui/embed-sandbox.ts
case "trusted":
  return "allow-scripts allow-same-origin";

​// ui/src/ui/components/mcp-app-view.ts
iframe.setAttribute(
  "sandbox",
  `${resolveEmbedSandbox(this.sandboxMode)} allow-forms allow-popups`,
);

Because the embedded content is explicitly fetched from an MCP server resource and stored as an HTML canvas document, treating it as "trusted" creates an XSS-equivalent condition (arbitrary script running with the app/control UI origin).

Recommendation

Prevent untrusted MCP App HTML from ever being embedded with allow-same-origin.

Options:

  1. Force a safe sandbox for MCP Apps regardless of global embedSandboxMode:
​// Always origin-isolate MCP apps
const sandbox = `allow-scripts allow-forms allow-popups`; // no allow-same-origin
iframe.setAttribute("sandbox", sandbox);
  1. If you must support a "trusted" mode for other embeds, disallow it when mcpAppsEnabled is true or when rendering preview.mcpApp.

  2. Defense-in-depth: serve canvas documents from a separate origin (different scheme/host/port) and/or apply restrictive response headers (CSP) on the canvas host to reduce impact if same-origin isolation is accidentally lost.

At minimum, ensure MCP Apps never receive allow-same-origin unless the content is locally produced and verified.

7. 🟡 MCP UI resource response is not strictly validated (content substitution / confused deputy)
Property Value
Severity Medium
CWE CWE-20
Location src/agents/mcp-ui-resource.ts:37-55

Description

fetchMcpAppView does not strictly verify that the MCP server returned content for the requested uiResourceUri:

  • If no entry matches item.uri === uiResourceUri, it falls back to resource.contents[0].
  • It also allows missing/empty mimeType (only rejects when a non-empty mimeType is present and not equal to the expected type).

This lets a malicious/compromised MCP server return a different resource than requested (or omit mimeType) and have it rendered/persisted as the UI for the tool.

Vulnerable code:

const content =
  resource.contents.find((item) => item.uri === params.uiResourceUri) ?? resource.contents[0];
...
if (
  typeof content.mimeType === "string" &&
  content.mimeType.trim() &&
  content.mimeType !== MCP_APP_RESOURCE_MIME_TYPE
) {
  return undefined;
}

Recommendation

Tighten validation of the readResource response:

  • Require an entry whose uri exactly matches the requested uiResourceUri; do not fall back to contents[0].
  • Require mimeType === "text/html;profile=mcp-app" (do not accept empty/undefined mimeType for UI rendering).
  • Consider also enforcing contents.length === 1 for ui:// resources to reduce ambiguity.

Example:

const content = resource.contents.find((item) => item.uri === params.uiResourceUri);
if (!content) throw new Error(`Resource response missing requested uri: ${params.uiResourceUri}`);
if (content.mimeType !== MCP_APP_RESOURCE_MIME_TYPE) {
  throw new Error(`Unexpected mimeType: ${String(content.mimeType)}`);
}

Analyzed PR: #69039 at commit bb2e842

Last updated on: 2026-04-20T01:56:00Z

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 34f609af9f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8a5a40f8d4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/pi-bundle-mcp-runtime.ts Resolved
Comment thread ui/src/ui/components/mcp-app-view.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb2e8428d6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@sallyom
sallyom marked this pull request as draft April 25, 2026 13:39
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: 🎥 video Contributor real behavior proof includes video or recording evidence. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 14, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4f391fe898

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/mcp-ui-resource.ts Resolved
Comment thread src/agents/mcp-ui-resource.ts Resolved
@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps specification support on exact head 381acc2a1afd4d27399b7cf10cf9dc4bc43422b8.

@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps specification support on exact head 495b882213f6f11e176889bcb170b3991edfb31e.

@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps specification support on exact head 8989d992d3840082af2dec07b5efd56e7f182b02.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8989d992d3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ui/src/components/mcp-app-view.ts Resolved
@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps specification support on exact head e8d5123dd5703a63b269865a7f6541bb5b07b740.

@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps specification support on exact head 5b56267baff43c08d3aabf0dd80fa6af4ef85e2a.

@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps specification support on exact head 3076a015bd1ec787391ac2ea4c9669a46d34810d.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3076a015bd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/mcp-ui-resource.ts Resolved
@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps support on exact head 3076a015bd1ec787391ac2ea4c9669a46d34810d.

@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps support on rebased exact head 0687d5387fcf17856d056d54cd08da5d4f882e35.

@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps support on consolidated exact head 1a2c400ee92c1134a737439206e0ed27980afdee.

@steipete

steipete commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Land-ready maintainer proof

Reviewed and consolidated on exact head f08d45e78a1e3939cd38a1049272f77f37f819ce. The final commit preserves @sallyom as co-author.

  • Spec: audited against the stable MCP Apps 2026-01-26 contract and official @modelcontextprotocol/[email protected] demo.
  • Review: fresh autoreview completed with no accepted or actionable findings; repo review artifacts validate as READY FOR /prepare-pr with zero findings.
  • Focused proof: Crabbox run run_d075122f7542 passed 830 gateway/config/agent/UI tests and all changed gates until the known current-main SQLite test-type baseline.
  • Build/docs proof: Crabbox run run_c21d7fd8d1fe passed pnpm build, pnpm ui:build, pnpm docs:list, and docs-map validation.
  • Exact-head hosted CI run 29180448535 passed build artifacts, UI, lint, prod and test types, Windows, security scans, CodeQL, QA smoke, and every runtime test shard.
  • Repo-native OPENCLAW_TESTBOX=1 scripts/pr prepare-run 69039 passed the authoritative hosted exact-head gate.
  • Live browser: the official app rendered through a distinct-origin outer sandbox plus opaque inner App iframe; one Get Server Time click made one owning-server bridge call and advanced the timestamp; cache-bypassing refresh restored exactly one app; external navigation opened separately; current console had no runtime errors.
  • Source-blind validation: official-demo render, bridge-call, refresh, bounded-frame, and separate-link clauses passed. Disabled-mode, caller-denial, and invalid-resource clauses require a hostile fixture and are covered by exact-head automated tests rather than inferred from the valid demo.

Official app rendered

Official MCP App rendered in OpenClaw chat

App-to-server bridge call updated live data

MCP App after owning-server tool call

Refresh restored one app instance

MCP App restored after refresh

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a2c400ee9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gateway/server-runtime-state.ts Resolved
Comment thread src/gateway/server-methods/mcp-app.ts Resolved
Implement stable opt-in MCP Apps negotiation, caller-specific tool
visibility, bounded ephemeral UI resources, a dedicated-origin double
iframe host, restrictive CSP, configuration, docs, and regression tests.

Co-authored-by: Sally O'Malley <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

/allow-dependencies-change Required official @modelcontextprotocol/ext-apps bridge dependency for stable MCP Apps support on final rebased exact head f08d45e.

@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f08d45e78a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +125 to +126
if (hostOrigin === null) hostOrigin = event.origin;
if (event.origin !== hostOrigin) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate MCP App sandbox messages to the Control UI

When mcp.apps.enabled exposes the sandbox listener on localhost or a LAN address, any unrelated web page that can iframe /mcp-app-sandbox becomes the first parent here, because the proxy records that page's event.origin and later accepts sandbox-resource-ready HTML from it without a nonce, auth check, or frame-ancestors restriction. That turns the dedicated listener into an arbitrary-origin HTML execution gadget rather than a Control-UI-only MCP App host; require an unguessable token from mcp.app.view or restrict allowed parent origins before trusting the first message.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui dependencies-changed PR changes dependency-related files docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants