Skip to content

Commit bbbc8c3

Browse files
steipetetzy-17
andcommitted
fix(gateway): own standalone MCP App request lifetimes
Keep initial loading and individual MCP requests bounded without applying a derived single-request timeout to composed App operations. Carry caller cancellation through the HTTP request owner, isolate shared catalog waits, and preserve bounded graceful cleanup before terminal document teardown. Retire stale document/bootstrap responses and observe asynchronous catalog rejections without changing authorization, public SDK contracts, or retry behavior. Add serialized-owner regressions and real Chromium conformance. Rewrites #119388 while preserving the contributor's report and credit. Co-authored-by: 唐梓夷0668001293 <[email protected]>
1 parent 648d0c4 commit bbbc8c3

19 files changed

Lines changed: 2868 additions & 1049 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ Docs: https://docs.openclaw.ai
6969

7070
### Fixes
7171

72+
- MCP Apps: let standalone operations finish across catalog refreshes within per-request server budgets, propagate App cancellation without cancelling shared catalog work, and reload restored history views without replaying interrupted operations. Thanks @tzy-17. (#119388)
73+
7274
- **Control UI command palette:** keep keyboard selection and Enter usable when reconnects or catalog refreshes replace search results, preserving the selected command while it remains available.
7375
- **Control UI Gateway labels:** keep the discovered machine name through recovery initialization and refresh open folder-browser labels when name discovery finishes.
7476
- **Android settings:** keep form fields and actions reachable above the keyboard, and respect bottom system insets without duplicating navigation padding.

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2875,7 +2875,6 @@ src/gateway/local-request-context.ts 2
28752875
src/gateway/managed-image-attachments.ts 8
28762876
src/gateway/mcp-app-operations.ts 3
28772877
src/gateway/mcp-app-reconstruction.ts 3
2878-
src/gateway/mcp-app-standalone.ts 7
28792878
src/gateway/mcp-grant-store.ts 2
28802879
src/gateway/mcp-http.handlers.ts 4
28812880
src/gateway/mcp-http.request.ts 2

‎docs/cli/mcp.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -954,6 +954,9 @@ Behavior and security boundaries:
954954
- In channel conversations, the latest successful App view in a turn adds one **Open App**-style action to the final assistant reply. Telegram DMs use a native Mini App button; Slack and Discord render the same portable action as a link. Other channels keep the original reply text and append an understandable HTTPS link.
955955
- Channel launch links are available only when Gateway Tailscale exposure has prepared a published HTTPS origin. `gateway.tailscale.mode: "serve"` is reachable only from the tailnet; password-authenticated `"funnel"` is reachable from the public internet. Externally managed Funnel routes targeting the ordinary Gateway listener must migrate to managed `"funnel"` mode before OpenClaw can publish an internet-reachable origin. See [Tailscale](/gateway/tailscale).
956956
- Launch tickets are opaque, minted only while materializing the final channel reply, and expire after at most two minutes or when the underlying view lease expires, whichever comes first. The URL does not contain Gateway bearer credentials, session keys, view metadata, App HTML, tool input, or tool results.
957+
- Standalone App windows allow 30 seconds to load the view. Each server's `requestTimeoutMs` applies to individual MCP requests, not to a complete App operation that may refresh the catalog before calling a tool. App request cancellation or closing the window aborts its browser request and propagates to the managed MCP runtime; other callers can still finish a shared catalog refresh. Cancellation cannot undo side effects already performed by the server.
958+
- When an App requests teardown, existing calls and authorized cleanup calls can finish until the App acknowledges shutdown or the one-second grace period expires. Closing or navigating away from the window cancels immediately.
959+
- Returning to a standalone App restored from the browser's back/forward cache reloads and revalidates the view instead of reviving its torn-down connection. This resets transient App state and does not automatically retry interrupted operations. If the launch ticket has expired, open a fresh App link.
957960
- If no published origin or ticket capacity is available, the view or ticket has expired, or the transport cannot render native controls, the original assistant text remains available. The Control UI keeps its existing inline App canvas and does not receive a duplicate launch action.
958961
- `openclaw security audit` warns while the bridge is enabled. Disable it with `openclaw config set mcp.apps.enabled false --strict-json` when it is not needed.
959962

‎scripts/check-coercion-helper-declarations.mts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ const EXCEPTIONAL_COERCION_HELPER_CARVE_OUTS = [
227227
reason: "Serialized mock Gateway closure cannot capture module imports.",
228228
},
229229
{
230-
file: "src/gateway/mcp-app-standalone.ts",
230+
file: "src/gateway/mcp-app-standalone-host.ts",
231231
name: "asStandaloneRecord",
232232
kind: "variable",
233233
reason: "Serialized standalone app closure cannot capture module imports.",

‎scripts/lib/type-assertion-guard-scope.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ export const CHAINED_ASSERTION_EXCLUDED_ROOTS = [
130130
"src/config/schema.hints.ts", // Zod pipe internals cross its public type namespace.
131131
"src/config/sessions/store-entry-shape.ts", // Legacy projection accepts partially validated session records.
132132
"src/gateway/cli-session-history.claude.ts", // External CLI messages cross the canonical transcript redactor.
133-
"src/gateway/mcp-app-standalone.ts", // Generated standalone browser code bridges the DOM namespace.
133+
"src/gateway/mcp-app-standalone-host.ts", // Generated standalone browser code bridges the DOM namespace.
134134
"src/gateway/server-methods/chat-transcript-inject.ts", // Gateway media blocks exceed the canonical message content union.
135135
"src/gateway/test-http-response.ts", // Test support.
136136
"src/infra/backup-volatile-stat-cache.ts", // node-tar's cache expects full Stats for a synthetic sentinel.

‎src/agents/agent-bundle-mcp-combined.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
/** Combined session MCP runtime facade for static + requester partitions. */
2+
import { racePromiseWithAbortSignal } from "../infra/abort-signal.js";
3+
import { getSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context.js";
24
import type {
35
McpCatalogTool,
46
McpServerCatalog,
@@ -141,8 +143,10 @@ export function createCombinedSessionMcpRuntime(params: {
141143
// Fresh combined facades have an empty owner map until the catalog is loaded.
142144
// Share one in-flight getCatalog so concurrent tool/resource calls do not fan out.
143145
const ownerForServer = async (serverName: string): Promise<SessionMcpRuntime> => {
146+
const signal = getSessionMcpRequestSignal();
147+
signal?.throwIfAborted();
144148
if (serverOwner.size === 0) {
145-
await loadCatalog();
149+
await racePromiseWithAbortSignal(loadCatalog(), signal);
146150
}
147151
const owner = serverOwner.get(serverName);
148152
if (owner) {

‎src/agents/agent-bundle-mcp-runtime.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
useAutoCleanupTempDirTracker,
1515
} from "../../test/helpers/temp-dir.js";
1616
import { createCombinedSessionMcpRuntime } from "./agent-bundle-mcp-combined.js";
17+
import { runWithSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context.js";
1718
import {
1819
completeDeferredSessionMcpRuntimeRetirement,
1920
createBundleMcpJsonSchemaValidator,
@@ -2235,6 +2236,67 @@ process.on("SIGINT", shutdown);`,
22352236
}
22362237
});
22372238

2239+
it.each(["managed", "combined"] as const)(
2240+
"cancels a %s catalog waiter without cancelling the shared producer",
2241+
async (kind) => {
2242+
const tempDir = tempDirTracker.make("bundle-mcp-catalog-cancel-");
2243+
const serverPath = path.join(tempDir, "server.mjs");
2244+
const logPath = path.join(tempDir, "server.log");
2245+
const releasePath = path.join(tempDir, "release-list");
2246+
await writeListToolsMcpServer({
2247+
filePath: serverPath,
2248+
logPath,
2249+
listToolsReleasePath: releasePath,
2250+
});
2251+
const managed = createSessionMcpRuntime({
2252+
sessionId: `catalog-cancel-${kind}`,
2253+
workspaceDir: tempDir,
2254+
cfg: { mcp: { servers: { shared: { command: process.execPath, args: [serverPath] } } } },
2255+
});
2256+
const runtime =
2257+
kind === "managed"
2258+
? managed
2259+
: createCombinedSessionMcpRuntime({
2260+
sessionId: "combined-catalog-cancel",
2261+
workspaceDir: tempDir,
2262+
parts: [managed, makeRuntime([], "other")],
2263+
});
2264+
const controller = new AbortController();
2265+
let cancelled = false;
2266+
let failure: unknown;
2267+
const reason = new Error("cancelled one catalog waiter");
2268+
const first = runWithSessionMcpRequestSignal(controller.signal, () =>
2269+
runtime.callTool("shared", "slow_tool", {}),
2270+
).catch((error: unknown) => {
2271+
cancelled = true;
2272+
failure = error;
2273+
return error;
2274+
});
2275+
let other: Promise<CallToolResult> | undefined;
2276+
try {
2277+
await waitForFileText(logPath, "recv tools/list", LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
2278+
expect(cancelled).toBe(false);
2279+
other = runtime.callTool("shared", "slow_tool", {});
2280+
controller.abort(reason);
2281+
await vi.waitFor(() => expect(cancelled).toBe(true));
2282+
expect(failure).toMatchObject({ name: "AbortError", cause: reason });
2283+
expect(await fs.readFile(logPath, "utf8")).not.toContain("recv notifications/cancelled");
2284+
await fs.writeFile(releasePath, "release");
2285+
await expect(other).resolves.toMatchObject({ isError: false });
2286+
await first;
2287+
const log = await fs.readFile(logPath, "utf8");
2288+
expect(log.match(/recv tools\/list/g)).toHaveLength(1);
2289+
expect(log.match(/recv tools\/call/g)).toHaveLength(1);
2290+
expect(log).not.toContain("recv notifications/cancelled");
2291+
expect(managed.peekCatalog()?.tools.map((tool) => tool.toolName)).toContain("slow_tool");
2292+
} finally {
2293+
await fs.writeFile(releasePath, "release");
2294+
await Promise.allSettled([first, other]);
2295+
await runtime.dispose();
2296+
}
2297+
},
2298+
);
2299+
22382300
it("cancels materialized MCP calls without pausing the healthy server", async () => {
22392301
const tempDir = tempDirTracker.make("bundle-mcp-caller-cancel-");
22402302
const serverPath = path.join(tempDir, "caller-cancel.mjs");

‎src/agents/agent-bundle-mcp-runtime.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { isRecord } from "@openclaw/normalization-core/record-coerce";
1414
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
1515
import type { SessionToolOverrides } from "../config/sessions/types.js";
1616
import type { OpenClawConfig } from "../config/types.openclaw.js";
17+
import { racePromiseWithAbortSignal } from "../infra/abort-signal.js";
1718
import { logWarn } from "../logger.js";
1819
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
1920
import { runTasksWithConcurrency } from "../utils/run-with-concurrency.js";
@@ -966,7 +967,9 @@ export function createSessionMcpRuntime(params: {
966967
return staleCatalog;
967968
};
968969
const getActiveSession = async (serverName: string) => {
969-
await getCatalog();
970+
const signal = getSessionMcpRequestSignal();
971+
signal?.throwIfAborted();
972+
await racePromiseWithAbortSignal(getCatalog(), signal);
970973
return requireConnectedSession(serverName);
971974
};
972975

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ describe("MCP App UI resources", () => {
194194
releases.slice(1).forEach((entry) => entry());
195195
});
196196

197-
it("normalizes CSP and snapshots the session deadline before retaining the view", async () => {
197+
it("normalizes CSP before retaining the view", async () => {
198198
const sessionRuntime = runtime(async () => ({
199199
contents: [
200200
{
@@ -212,10 +212,6 @@ describe("MCP App UI resources", () => {
212212
},
213213
],
214214
}));
215-
const peekCatalog = vi.fn(() => null);
216-
sessionRuntime.peekCatalog = peekCatalog;
217-
sessionRuntime.getServerRequestTimeoutMs = (serverName) =>
218-
serverName === "demo" ? 120_000 : undefined;
219215
const result = await fetchMcpAppView({
220216
runtime: sessionRuntime,
221217
serverName: "demo",
@@ -230,8 +226,6 @@ describe("MCP App UI resources", () => {
230226
resourceDomains: ["https://cdn.example.com"],
231227
});
232228
expect(view?.html.startsWith("<!doctype html>")).toBe(true);
233-
expect(view?.requestTimeoutMs).toBe(120_000);
234-
expect(peekCatalog).not.toHaveBeenCalled();
235229
expect(buildMcpAppSandboxPath(view?.csp)).toContain("?csp=");
236230
});
237231

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

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ export type McpAppViewLease = {
3939
readOnly?: true;
4040
toolInput: unknown;
4141
toolResult: CallToolResult;
42-
requestTimeoutMs?: number;
4342
expiresAtMs: number;
4443
requestWindowStartedAtMs: number;
4544
requestCount: number;
@@ -276,9 +275,6 @@ export async function fetchMcpAppView(params: {
276275
const permissions = normalizePermissions(uiMeta?.permissions);
277276
const title = `${params.toolName} UI`;
278277
const viewId = params.viewId ?? `mcp-app-${randomUUID()}`;
279-
// resources/read established the authoritative server session above. Carry
280-
// its deadline into the view so catalog invalidation cannot change it later.
281-
const requestTimeoutMs = params.runtime.getServerRequestTimeoutMs?.(params.serverName);
282278
releaseRuntimeLease = params.runtime.acquireLease?.();
283279
deleteView(viewId);
284280
pruneViewStore(byteSize, { reserveEntry: true });
@@ -303,7 +299,6 @@ export async function fetchMcpAppView(params: {
303299
...(params.readOnly ? { readOnly: true as const } : {}),
304300
toolInput: params.toolInput,
305301
toolResult: params.toolResult,
306-
...(requestTimeoutMs !== undefined ? { requestTimeoutMs } : {}),
307302
expiresAtMs: Date.now() + MCP_APP_VIEW_TTL_MS,
308303
requestWindowStartedAtMs: Date.now(),
309304
requestCount: 0,

0 commit comments

Comments
 (0)