Skip to content

fix(mcp-app): pass trusted toolMeta to session resource tool policy checks (#186775, #186777) - #186793

Open
xuilen wants to merge 4 commits into
openclaw:mainfrom
xuilen:fix/186775-186777-mcp-app-toolmeta
Open

xuilen wants to merge 4 commits into
openclaw:mainfrom
xuilen:fix/186775-186777-mcp-app-toolmeta

Conversation

@xuilen

@xuilen xuilen commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #186775
Closes #186777

What Problem This Solves

Fixes: MCP App tool calls are rejected by session tool policy when invoking permitted plugin tools (such as bundle-mcp), and standalone apps filter out allowed plugin tools.

User Impact

User impact: Model-created and standalone MCP App tool calls can reliably execute permitted plugin tools according to the session's tool capability profile without false policy rejections.

Why This Change Was Made

Both prepareModelCreatedAppToolCall (in src/gateway/mcp-app-operations.ts) and prepareMcpAppExtensionRuntime.assertTool (in src/gateway/mcp-app-extension-runtime.ts) invoke resolveSessionResourceToolPolicy, but previously passed only the string toolName while omitting toolMeta.

Consequently, the downstream policy evaluator (isConversationToolAllowed) cannot determine the tool's plugin ownership (such as pluginId: "bundle-mcp"), causing tools allowed under plugin policy profiles (such as the default coding profile) to fail session policy checks with SESSION_RESOURCE_TOOL_POLICY.

This change:

  1. Retains projected tools in the standalone runtime map and passes toolMeta: getPluginToolMeta(projectedTool) to resolveSessionResourceToolPolicy in mcp-app-extension-runtime.ts.
  2. Passes toolMeta: getPluginToolMeta(projected) to resolveSessionResourceToolPolicy in mcp-app-operations.ts.
  3. Preserves all existing authorization gates: view allowlists, server/session restrictions, explicit tool denials, requester checks, and execution-time approval revalidations.

Evidence

  • Verified unit test suite src/gateway/mcp-app-extension-runtime.test.ts: all 12 tests pass, including new assertions confirming toolMeta propagation.
  • Code style and TypeScript checks cleanly adhere to repository standards.

CI maintenance (2026-10-30)

The mock-isolation annotation removes one factory from the unannotated-mock inventory. Regenerated the shrink-only baseline with the repository's check-test-mock-exports.mts --prune; it removes exactly that stale entry (6565 -> 6564), with no new allowance.

Before regeneration, the check reproduced the same stale-entry failure as CI. After regeneration: Mock factory ratchet OK: 6564 grandfathered factories. git diff --check also passes. The local command used the repository-declared TypeScript 7.1.0-dev.20261016.1 from an isolated dependency directory because the shared local install had an older version without typescript/ast exports; the checker source was unchanged.

This maintenance changes only the generated baseline. It does not change production behavior. Other checks previously passed on head 3abaa2e; those are prior-head CI evidence, not a result for the proposed next commit. The new commit still needs its own CI run.

@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Oct 28, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 28, 2026
@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

Passes trusted plugin ownership into session tool-policy checks for model-created and standalone MCP Apps.

Example: An MCP App calls notes__write_note with tools.profile set to coding.

  • Before: The permitted tool is rejected because the policy check receives no bundle-mcp ownership.
  • After: The tool executes when allowed, while explicit denials and current requester authority still apply.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The narrow production repair has strong supplied behavior evidence, but the mock baseline still blocks validation and the added assertion provides little regression value.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied built-Gateway proof exercises both changed App owners over real MCP transport; the matching production repair in #186790 has inspected terminal output showing successful writes, denial and approval-time revocation preventing writes, plus real-transport requester-isolation and preparation-time revocation evidence. The current PR's later changes affect only its mocked test fixture and annotation.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: MCP Apps hide or reject plugin tools that the session's configured capability profile permits.
Reason: Restores the documented policy contract without adding configuration, widening an API, or bypassing explicit denial.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR fixes a current MCP App policy bug, but the latest mock annotation leaves an obsolete baseline entry that still blocks CI.

Priority: P2
Reviewed head: 3abaa2ed2b5b9bdea4c7f6defd7d9c6e4e3b01c8

Before merge

  • Remove the obsolete mock baseline entry (P2) - The new mock-isolation annotation makes the scanner skip this factory, but config/test-mock-exports-baseline.txt:4553 still records its original fingerprint. check-test-mock-exports.mts rejects delta.removed and exits 1 until that entry is removed, matching the exact-head mock-exports failure. The previous unbaselined-factory problem has changed into a stale-baseline problem. Prune that exact entry if retaining the annotation, or restore the original factory when removing the mock-forwarding assertion.

Findings

  • [P2] Remove the obsolete mock baseline entry — src/gateway/mcp-app-extension-runtime.test.ts:69-72

Tests

  • Low-value test src/gateway/mcp-app-extension-runtime.test.ts: Remove the added mocks.toolPolicy call-shape assertion: materialization, metadata, and policy are all mocked, so it only echoes fixture fields; use a focused real-policy regression from the supplied supplement instead.
Agent review details

How this fits together

The Gateway projects MCP catalog tools, checks session policy and App authority, obtains approval when needed, and sends permitted calls through the session-owned MCP transport.

flowchart LR
  A[App request] --> B[Trusted catalog projection]
  B --> C[Session tool policy]
  C --> D[App authority and approval]
  D --> E[Execution revalidation]
  E --> F[MCP transport]
Loading

Technical review

Best possible solution:

Keep the production metadata repair, replace the mock-forwarding assertion with focused real-policy coverage, and restore the original mock factory or prune its obsolete baseline entry.

Do we have a high-confidence way to reproduce the issue?

Current-main source shows both callers losing trusted ownership, and supplied real-Gateway comparisons demonstrate the resulting coding-profile rejection; this review executed no target code.

Is this the best way to solve the issue?

The production patch is the smallest complete repair: preserve the existing projection and pass its metadata into the existing policy owner at both affected callers.

Full review comments:

  • [P2] Remove the obsolete mock baseline entry — src/gateway/mcp-app-extension-runtime.test.ts:69-72
    The new mock-isolation annotation makes the scanner skip this factory, but config/test-mock-exports-baseline.txt:4553 still records its original fingerprint. check-test-mock-exports.mts rejects delta.removed and exits 1 until that entry is removed, matching the exact-head mock-exports failure. The previous unbaselined-factory problem has changed into a stale-baseline problem. Prune that exact entry if retaining the annotation, or restore the original factory when removing the mock-forwarding assertion.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against bde3017359ed.

Provenance checked

  • Standalone and model-created App policy checks keeps the original intent (6046d4f: Expanded MCP Apps while preserving existing session, requester, approval, and transport owners.)
  • Trusted ownership-aware session policy keeps the original intent (40ec02f: Preserve registered plugin allowances across policy checks while maintaining explicit denial and current authority.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm check:test-mock-exports --base a74f408
  • pnpm test src/gateway/mcp-app-extension-runtime.test.ts --maxWorkers=1
  • git diff --check

What I checked:

PR surface

Source +2, Tests +13. Total +15 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 7 5 +2
Tests 1 15 2 +13
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 22 7 +15

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Restores permitted MCP App interactions under plugin-aware tool profiles, with limited scope and no demonstrated urgent runtime outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-28T14:16:09.580Z sha 1ec7439 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-29T08:24:07.961Z sha 2f64fea :: needs maintainer review before merge. :: none
  • reviewed 2026-10-29T08:32:23.396Z sha 2f64fea :: needs changes before merge. :: [P2] Restore the baselined policy mock or preserve its real exports

Reviewed October 29, 2026, 5:28 AM ET / 09:28 UTC (Revision 4).

hualia2009 commented Oct 28, 2026 •

Copy link
Copy Markdown

The tests-only supplement is now available as xuilen/openclaw#2, targeting your fix/186775-186777-mcp-app-toolmeta branch at 1ec7439e3e297b0adaf8733ee428d1e0afbb022a. It adds two files and leaves your production repair and existing tests unchanged.

Published head: a58f13632a1eb6eb4f3c8d693c5a60fa6ef551be. A fresh fetch verifies that its complete tree matches the locally validated supplement (72a393e83b0f6920da492b6ac9facad8b37e008c); both trees are d62342095082a751ad71c6eea8ae163ee9f3a93d.

The 10-case policy regression uses the real materializer, trusted plugin metadata, and policy evaluator through both App entry points. It covers the coding allowance, explicit plugin/group denials despite an exact-name allowance, denial added after preparation, and revoked request authority before execution.

The isolated Gateway E2E uses a deterministic local model protocol fixture and real MCP HTTP transport. It proves standalone discovery/launch/call, creates a model App through an actual tool call and retrieves its view from chat history, and checks that session denial and subsequent server/tool revocation cause no additional upstream calls.

Validation on the supplement based on your head:

  • 22 focused tests pass (10 new policy cases + 12 existing extension-runtime cases).
  • The Gateway E2E passes: 1 test, 11.377s test execution / 19.13s total. It reuses the earlier built candidate after verifying identical production source, dependencies, build scripts, and test helpers.
  • Both affected test TypeScript projects, targeted lint, formatting, commit hooks, and git diff --check pass.
  • The patch passes git apply --check against your pinned head.

Earlier red/green evidence: all 10 new cases fail on unmodified main 2d81657852da10f5c03b8143417ec571e2e645d7; its built Gateway also returns an empty standalone discovery result under coding. The same repair and tests pass, including 82 distinct focused cases on that earlier candidate. This broader count is prior-candidate evidence, not 82 additional cases rerun on your branch.

Remaining coverage limits: this does not prove the complete cross-requester or revocation-during-await matrix requested above. It does not exercise external models, native harnesses, browser rendering, or an existing user's installation. I am not claiming all upstream review requirements are resolved.

The complete patch is retained below as an alternative to merging the supplement PR. Copy only the diff block into mcp-app-policy-tests.patch, then apply it on your branch:

git apply --check mcp-app-policy-tests.patch
git apply mcp-app-policy-tests.patch
OPENCLAW_VITEST_RUNTIME=node pnpm test src/gateway/mcp-app-tool-policy.test.ts src/gateway/mcp-app-extension-runtime.test.ts --maxWorkers=1
OPENCLAW_VITEST_RUNTIME=node pnpm test test/gateway-mcp-app-tool-policy.e2e.test.ts --maxWorkers=1

The Node setting matches the validated runtime; automatic Bun selection could not start on this macOS host because a compatible SQLite library is unavailable.

Complete tests-only patch (2 files, 510 added lines)
diff --git a/src/gateway/mcp-app-tool-policy.test.ts b/src/gateway/mcp-app-tool-policy.test.ts
new file mode 100644
index 0000000..6de958f
--- /dev/null
+++ b/src/gateway/mcp-app-tool-policy.test.ts
@@ -0,0 +1,200 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SessionEntry } from "../config/sessions/types.js";
+import type { OpenClawConfig } from "../config/types.openclaw.js";
+import { prepareMcpAppExtensionRuntime } from "./mcp-app-extension-runtime.js";
+import { prepareModelCreatedAppToolCall } from "./mcp-app-operations.js";
+import { appCatalog, appView, runtime } from "./server-methods/mcp-app.test-support.js";
+import type { GatewayRequestHandlerOptions } from "./server-methods/types.js";
+import { createGatewayRequestContext } from "./server-request-context.js";
+import { makeContextParams } from "./server-request-context.test-support.js";
+import { gatewayConnect, gatewayProfile } from "./server/client-fixtures.test-support.js";
+
+const mocks = vi.hoisted(() => ({
+  acquire: vi.fn(),
+  loadConfig: vi.fn(),
+  projection: vi.fn(),
+  approval: vi.fn(),
+  storageRead: vi.fn(() => {
+    throw new Error("Unexpected synchronous session storage read");
+  }),
+}));
+
+// mock-isolation: Supply the already acquired MCP transport, without opening external servers.
+vi.mock("../agents/agent-bundle-mcp-manager-api.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("../agents/agent-bundle-mcp-manager-api.js")>()),
+  acquireSessionMcpRuntime: mocks.acquire,
+}));
+// mock-isolation: The fixture owns the borrowed runtime lease.
+vi.mock("../agents/agent-bundle-mcp-manager-cleanup.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("../agents/agent-bundle-mcp-manager-cleanup.js")>()),
+  releaseSessionMcpRuntime: async (lease: { releaseLease: () => void }) => lease.releaseLease(),
+}));
+// mock-isolation: Configuration loading is external; policy evaluation consumes the real config.
+vi.mock("../agents/agent-bundle-mcp-runtime-config.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("../agents/agent-bundle-mcp-runtime-config.js")>()),
+  loadSessionMcpConfig: mocks.loadConfig,
+}));
+// mock-isolation: Select the built-in transport without preparing native harness credentials.
+vi.mock("../agents/thinking-runtime.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("../agents/thinking-runtime.js")>()),
+  resolveEffectiveAgentRuntime: () => "openclaw",
+}));
+// mock-isolation: No installed-plugin snapshot is needed for the built-in coding profile.
+vi.mock("../plugins/current-plugin-metadata-state.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("../plugins/current-plugin-metadata-state.js")>()),
+  getGatewayPluginMetadataSnapshot: () => undefined,
+}));
+// mock-isolation: Session facts are prepared in memory, as they are at this retained-resource boundary.
+vi.mock("./session-row-projection-access.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("./session-row-projection-access.js")>()),
+  getSessionRowProjection: mocks.projection,
+}));
+// mock-isolation: Guard against accidentally replacing prepared facts with synchronous disk reads.
+vi.mock("../config/sessions/session-accessor.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("../config/sessions/session-accessor.js")>()),
+  loadExactSessionEntryReadOnly: mocks.storageRead,
+  loadSessionEntryByIdReadOnly: mocks.storageRead,
+  loadSessionEntryReadOnly: mocks.storageRead,
+}));
+// mock-isolation: Approval delivery is external; approval requirements and rechecks remain real.
+vi.mock("./mcp-app-tool-approval.js", async (importOriginal) => ({
+  ...(await importOriginal<typeof import("./mcp-app-tool-approval.js")>()),
+  requestMcpAppToolApproval: mocks.approval,
+}));
+
+type AppPath = "model-created" | "standalone";
+const sessionKey = "agent:main:app-policy";
+const toolName = "read_progress";
+const projectedName = "fixture__read_progress";
+const dispose: Array<() => Promise<void>> = [];
+
+function fixture() {
+  const config: OpenClawConfig = {
+    agents: { defaults: { model: "openai/test-model", workspace: "/test/app-policy" } },
+    tools: { profile: "coding" },
+    mcp: {
+      apps: { enabled: true },
+      servers: { fixture: { command: "fixture-mcp", codex: { defaultToolsApprovalMode: "auto" } } },
+    },
+  };
+  const entry: SessionEntry = { sessionId: "session-1", updatedAt: 1, lifecycleRevision: "first" };
+  const target = {
+    agentId: "main",
+    canonicalKey: sessionKey,
+    entry,
+    generation: Symbol("database"),
+    storeKey: sessionKey,
+    storeKeys: [sessionKey],
+    storePath: "/test/main/sessions",
+  };
+  const projection = { sharingTarget: () => target };
+  const controller = new AbortController();
+  const assertCurrent = () => controller.signal.throwIfAborted();
+  const retain = () => ({ signal: controller.signal, assertCurrent, release: () => {} });
+  const contextParams = makeContextParams();
+  const context = createGatewayRequestContext(contextParams);
+  context.getRuntimeConfig = () => config;
+  dispose.push(() => contextParams.runtime.scheduler.stop());
+  const catalog = appCatalog("fixture", [
+    {
+      toolName,
+      uiVisibility: ["app"],
+      codexAnnotations: { readOnlyHint: true },
+    },
+  ]);
+  const owner = runtime();
+  owner.sessionKey = sessionKey;
+  owner.getCatalog.mockResolvedValue(catalog);
+  owner.peekCatalog.mockReturnValue(catalog);
+  const options: GatewayRequestHandlerOptions = {
+    req: { type: "req", id: "app-policy", method: "mcp.app.callTool" },
+    params: {},
+    respond: vi.fn(),
+    isWebchatConnect: () => true,
+    client: {
+      connect: gatewayConnect(["operator.write"]),
+      authenticatedUserProfile: gatewayProfile("reviewer", "Reviewer"),
+    },
+    context,
+    sessionAccessAuthority: {
+      target: { agentId: "main", sessionKey, sessionId: entry.sessionId },
+      sandboxRequired: false,
+      assertCurrent,
+      retain,
+      retainSession: retain,
+      release: () => {},
+    },
+  };
+  const request = { options, toolName, input: {}, assertCurrent };
+  mocks.projection.mockReturnValue(projection);
+  mocks.loadConfig.mockReturnValue({ loaded: { mcpServers: config.mcp!.servers } });
+  mocks.acquire.mockResolvedValue({ runtime: owner, releaseLease: () => {} });
+
+  async function openStandalone() {
+    const active = await prepareMcpAppExtensionRuntime(options);
+    dispose.push(() => active.dispose());
+    return active;
+  }
+  async function prepare(path: AppPath) {
+    if (path === "model-created") {
+      const view = appView(owner, {
+        serverName: "fixture",
+        requesterId: "reviewer",
+        allowedAppToolNames: new Set([toolName]),
+      });
+      return prepareModelCreatedAppToolCall({ runtime: owner, view }, request);
+    }
+    const active = await openStandalone();
+    expect(active.catalog.tools.map((tool) => tool.toolName)).toEqual([toolName]);
+    const retained = active.retainViewAuthority(active.catalog.tools);
+    dispose.push(async () => retained.release());
+    return retained.prepareToolCall(request);
+  }
+  return { config, controller, prepare, openStandalone };
+}
+
+beforeEach(() => vi.clearAllMocks());
+afterEach(async () => {
+  for (const release of dispose.splice(0).toReversed()) {
+    await release();
+  }
+  expect(mocks.storageRead).not.toHaveBeenCalled();
+});
+
+describe.each<AppPath>(["model-created", "standalone"])("MCP App policy via %s", (path) => {
+  it("admits an App-only tool through the coding profile's plugin allowance", async () => {
+    const test = fixture();
+    const assertExecutionCurrent = await test.prepare(path);
+    expect(assertExecutionCurrent).toBeTypeOf("function");
+    expect(() => assertExecutionCurrent?.()).not.toThrow();
+    expect(mocks.approval).not.toHaveBeenCalled();
+  });
+
+  it.each(["bundle-mcp", "group:plugins"])("preserves explicit %s denial", async (deny) => {
+    const test = fixture();
+    // Admit the exact name so this regression isolates ownership-based denial.
+    test.config.tools!.alsoAllow = [projectedName];
+    test.config.tools!.deny = [deny];
+    if (path === "standalone") {
+      expect((await test.openStandalone()).catalog.tools).toEqual([]);
+    } else {
+      await expect(test.prepare(path)).rejects.toThrow("current tool policy");
+    }
+    expect(mocks.approval).not.toHaveBeenCalled();
+  });
+
+  it("rechecks plugin denial after preparation", async () => {
+    const test = fixture();
+    test.config.tools!.alsoAllow = [projectedName];
+    const assertExecutionCurrent = await test.prepare(path);
+    test.config.tools!.deny = ["group:plugins"];
+    expect(() => assertExecutionCurrent?.()).toThrow("current tool policy");
+  });
+
+  it("rejects revoked request authority before execution", async () => {
+    const test = fixture();
+    const assertExecutionCurrent = await test.prepare(path);
+    test.controller.abort(new Error("fixture authority revoked"));
+    expect(() => assertExecutionCurrent?.()).toThrow("fixture authority revoked");
+  });
+});
diff --git a/test/gateway-mcp-app-tool-policy.e2e.test.ts b/test/gateway-mcp-app-tool-policy.e2e.test.ts
new file mode 100644
index 0000000..391bd1e
--- /dev/null
+++ b/test/gateway-mcp-app-tool-policy.e2e.test.ts
@@ -0,0 +1,310 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import http from "node:http";
+import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
+import { Server } from "@modelcontextprotocol/server";
+import { asRecord } from "@openclaw/normalization-core/record-coerce";
+import { expect, it } from "vitest";
+import type { McpAppDiscoverResult } from "../src/shared/mcp-app-extensions.js";
+import { reserveTestPortListener } from "../src/test-utils/port-claims.js";
+import { withBuiltGateway } from "./helpers/built-gateway-proof.js";
+import { readRequestText } from "./helpers/gateway-integration-fixtures.js";
+import {
+  createOpenAiResponsesModelConfig,
+  startOpenAiResponsesModelServer,
+} from "./helpers/openai-responses-model-fixture.js";
+import {
+  writeOpenAiResponsesSse,
+  writeOpenAiResponsesText,
+} from "./helpers/openai-responses-sse.js";
+import { runQaGatewayFixture } from "./helpers/qa-gateway-cleanup.js";
+
+const RESOURCE = "ui://policy-proof/app";
+const PROGRESS = { content: [{ type: "text" as const, text: "Progress: 42%" }] };
+
+async function startMcpServer(signal: AbortSignal) {
+  const calls: string[] = [];
+  const sessions = new Map<string, NodeStreamableHTTPServerTransport>();
+  const servers: Server[] = [];
+  const listener = await reserveTestPortListener({
+    offsets: [0],
+    signal,
+    createListener: () =>
+      http.createServer((request, response) => {
+        void (async () => {
+          const sessionId = request.headers["mcp-session-id"];
+          let transport = typeof sessionId === "string" ? sessions.get(sessionId) : undefined;
+          if (!transport && !sessionId && request.method === "POST") {
+            const server = new Server(
+              { name: "policy-proof", version: "1" },
+              { capabilities: { tools: {}, resources: {} } },
+            );
+            server.setRequestHandler("tools/list", async () => ({
+              tools: [
+                {
+                  name: "show_app",
+                  description: "Show the policy proof App.",
+                  inputSchema: { type: "object", properties: {} },
+                  annotations: { readOnlyHint: true },
+                  _meta: {
+                    ui: { resourceUri: RESOURCE, visibility: ["model", "app"] },
+                    "openai/ui": { entrypoints: [{ type: "global" }, { type: "thread" }] },
+                  },
+                },
+                {
+                  name: "read_progress",
+                  inputSchema: { type: "object", properties: {} },
+                  annotations: { readOnlyHint: true },
+                  _meta: { ui: { visibility: ["app"] } },
+                },
+              ],
+            }));
+            server.setRequestHandler("resources/read", async ({ params }) => ({
+              contents: [
+                {
+                  uri: params.uri,
+                  mimeType: "text/html;profile=mcp-app",
+                  text: "<p>Progress App</p>",
+                },
+              ],
+            }));
+            server.setRequestHandler("tools/call", async ({ params }) => {
+              calls.push(params.name);
+              if (params.name === "read_progress") {
+                return PROGRESS;
+              }
+              return { content: [{ type: "text", text: "Progress App opened" }] };
+            });
+            const created = new NodeStreamableHTTPServerTransport({
+              sessionIdGenerator: randomUUID,
+              onsessioninitialized: (id) => {
+                sessions.set(id, created);
+              },
+            });
+            servers.push(server);
+            await server.connect(created);
+            transport = created;
+          }
+          if (!transport) {
+            response.writeHead(404).end();
+            return;
+          }
+          await transport.handleRequest(request, response);
+        })().catch(() => {
+          if (!response.headersSent) {
+            response.writeHead(500).end();
+          }
+        });
+      }),
+  });
+  return {
+    url: `http://127.0.0.1:${listener.claim.port}/mcp`,
+    calls,
+    close: () =>
+      runQaGatewayFixture(
+        async () => {
+          await Promise.all(servers.map((server) => server.close()));
+        },
+        () => listener.listener.closeAllConnections(),
+        listener.releaseListener,
+        listener.claim.release,
+      ),
+  };
+}
+
+it(
+  "enforces coding policy for standalone and model-created Apps over real MCP HTTP",
+  { timeout: 120_000 },
+  async ({ signal }) => {
+    const mcp = await startMcpServer(signal);
+    await runQaGatewayFixture(async () => {
+      let modelToolCalls = 0;
+      const modelId = "mcp-app-policy-model";
+      const provider = await startOpenAiResponsesModelServer({
+        modelId,
+        bindError: "MCP App model fixture did not bind",
+        onRequest: async (request, response) => {
+          const body = asRecord(JSON.parse(await readRequestText(request)));
+          const tools = Array.isArray(body.tools) ? body.tools.map(asRecord) : [];
+          const show = tools.find((tool) => tool.name === "proof__show_app");
+          if (show && modelToolCalls++ === 0) {
+            expect(tools.some((tool) => tool.name === "proof__read_progress")).toBe(false);
+            const item = {
+              type: "function_call",
+              id: "fc_show_app",
+              call_id: "call_show_app",
+              name: "proof__show_app",
+              arguments: "{}",
+            };
+            writeOpenAiResponsesSse(response, [
+              {
+                type: "response.output_item.added",
+                output_index: 0,
+                item: { ...item, arguments: "" },
+              },
+              {
+                type: "response.function_call_arguments.delta",
+                output_index: 0,
+                item_id: item.id,
+                delta: item.arguments,
+              },
+              { type: "response.output_item.done", output_index: 0, item },
+              {
+                type: "response.completed",
+                response: {
+                  id: "resp_show_app",
+                  status: "completed",
+                  output: [item],
+                  usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
+                },
+              },
+            ]);
+            return;
+          }
+          writeOpenAiResponsesText(response, {
+            text: "The progress App is ready.",
+            messageId: "msg_done",
+            responseId: "resp_done",
+          });
+        },
+      });
+      await runQaGatewayFixture(async () => {
+        const config = createOpenAiResponsesModelConfig({
+          baseUrl: provider.baseUrl,
+          providerId: "mock-openai",
+          modelId,
+          reasoning: false,
+          toolProfile: "coding",
+        });
+        // Expose the selected tools directly; neither presentation option adds authority.
+        config.tools = { ...config.tools, codeMode: false, toolSearch: false };
+        config.mcp = {
+          apps: { enabled: true },
+          servers: {
+            proof: {
+              url: mcp.url,
+              transport: "streamable-http",
+              codex: { defaultToolsApprovalMode: "auto" },
+            },
+          },
+        };
+        await withBuiltGateway(
+          {
+            name: "mcp-app-tool-policy",
+            signal,
+            config,
+            env: {
+              OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
+              OPENCLAW_SKIP_PROVIDERS: undefined,
+              OPENCLAW_TEST_MINIMAL_GATEWAY: undefined,
+              HTTP_PROXY: "",
+              HTTPS_PROXY: "",
+              ALL_PROXY: "",
+              http_proxy: "",
+              https_proxy: "",
+              all_proxy: "",
+              NO_PROXY: "127.0.0.1,localhost",
+              no_proxy: "127.0.0.1,localhost",
+            },
+          },
+          async (client) => {
+            const sessionKey = "agent:main:mcp-app-standalone-policy";
+            await client.request("sessions.create", { agentId: "main", key: sessionKey });
+            const discovered = await client.request<McpAppDiscoverResult>("mcp.app.discover", {
+              sessionKey,
+            });
+            expect(discovered.servers).toEqual([
+              expect.objectContaining({
+                serverName: "proof",
+                entrypoints: expect.arrayContaining([
+                  expect.objectContaining({ toolName: "show_app", entrypoint: { type: "global" } }),
+                  expect.objectContaining({ toolName: "show_app", entrypoint: { type: "thread" } }),
+                ]),
+              }),
+            ]);
+            const launch = (key: string) =>
+              client.request<{ viewId: string }>("mcp.app.launch", {
+                sessionKey: key,
+                serverName: "proof",
+                toolName: "show_app",
+                entrypointType: "global",
+              });
+            const read = (key: string, viewId: string) =>
+              client.request("mcp.app.callTool", {
+                sessionKey: key,
+                viewId,
+                toolName: "read_progress",
+                arguments: {},
+              });
+            const standalone = await launch(sessionKey);
+            expect(await read(sessionKey, standalone.viewId)).toMatchObject(PROGRESS);
+            expect(mcp.calls).toEqual(["show_app", "read_progress"]);
+
+            const deniedKey = "agent:main:mcp-app-explicit-deny";
+            await client.request("sessions.create", {
+              agentId: "main",
+              key: deniedKey,
+              toolOverrides: { mcpToolsDeny: { proof: ["read_progress"] } },
+            });
+            const denied = await launch(deniedKey);
+            await expect(read(deniedKey, denied.viewId)).rejects.toThrow(
+              /denied|not app-callable|not granted/i,
+            );
+            expect(mcp.calls).toEqual(["show_app", "read_progress", "show_app"]);
+            await client.request("sessions.patch", {
+              key: sessionKey,
+              toolOverrides: { mcpServers: { proof: false } },
+            });
+            await expect(read(sessionKey, standalone.viewId)).rejects.toThrow(
+              /denied|expired|unavailable|revoked/i,
+            );
+            expect(mcp.calls).toHaveLength(3);
+
+            const modelKey = "agent:main:mcp-app-model-policy";
+            await client.request("sessions.create", { agentId: "main", key: modelKey });
+            await client.request(
+              "agent",
+              {
+                agentId: "main",
+                sessionKey: modelKey,
+                idempotencyKey: randomUUID(),
+                message: "Show the progress App.",
+                deliver: false,
+              },
+              { expectFinal: true, timeoutMs: 60_000 },
+            );
+            const history = await client.request<{ messages: unknown[] }>("chat.history", {
+              sessionKey: modelKey,
+            });
+            const views = history.messages.flatMap((message) => {
+              const details = asRecord(asRecord(message).details);
+              const view = asRecord(asRecord(details.mcpAppPreview).mcpApp);
+              return typeof view.viewId === "string" ? [view.viewId] : [];
+            });
+            expect(views).toHaveLength(1);
+            const modelViewId = views[0];
+            assert(modelViewId, "The model tool result must contain a real App view");
+            expect(modelToolCalls).toBeGreaterThanOrEqual(2);
+            expect(await read(modelKey, modelViewId)).toMatchObject(PROGRESS);
+            expect(mcp.calls).toEqual([
+              "show_app",
+              "read_progress",
+              "show_app",
+              "show_app",
+              "read_progress",
+            ]);
+            await client.request("sessions.patch", {
+              key: modelKey,
+              toolOverrides: { mcpToolsDeny: { proof: ["read_progress"] } },
+            });
+            await expect(read(modelKey, modelViewId)).rejects.toThrow(
+              /denied|expired|unavailable|revoked/i,
+            );
+            expect(mcp.calls).toHaveLength(5);
+          },
+          { role: "operator", scopes: ["operator.admin", "operator.read", "operator.write"] },
+        );
+      }, provider.close);
+    }, mcp.close);
+  },
+);

@xuilen

xuilen commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Updated in 2f64fea: fixture metadata now specifies \pluginId: 'bundle-mcp'\ and asserts exact ownership propagation.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Oct 29, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 29, 2026
@xuilen

xuilen commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Updated in 3abaa2e: added // mock-isolation:\ annotation on ./session-resource-tool-policy.js\ mock to satisfy the \check:test-mock-exports\ baseline ratchet.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026

This branch has not been deployed

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

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

2 participants