Skip to content

Commit 6f4b9a2

Browse files
fix(gateway): preserve standalone MCP app HEAD response metadata (#120905)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent e5cc191 commit 6f4b9a2

2 files changed

Lines changed: 115 additions & 35 deletions

File tree

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

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { IncomingMessage } from "node:http";
1+
import { createServer, type IncomingMessage } from "node:http";
2+
import type { AddressInfo } from "node:net";
23
import { Readable } from "node:stream";
34
import { runInNewContext } from "node:vm";
45
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -221,6 +222,84 @@ describe("MCP App standalone host", () => {
221222
);
222223
});
223224

225+
it.each([
226+
{ label: "public shell", path: "/__openclaw__/mcp-app", expectedStatus: 200 },
227+
{
228+
label: "authenticated multibyte view",
229+
path: "/__openclaw__/mcp-app/view",
230+
expectedStatus: 200,
231+
authorized: true,
232+
},
233+
{
234+
label: "unauthorized view",
235+
path: "/__openclaw__/mcp-app/view",
236+
expectedStatus: 401,
237+
},
238+
{
239+
label: "saturated view",
240+
path: "/__openclaw__/mcp-app/view",
241+
expectedStatus: 429,
242+
authorized: true,
243+
saturated: true,
244+
},
245+
])(
246+
"keeps GET and HEAD metadata aligned over HTTP for $label",
247+
async ({ path, expectedStatus, authorized, saturated }) => {
248+
const originalHtml = view.html;
249+
view.html = "<!doctype html><p>caf\u00e9 \ud83e\udd9e</p>";
250+
const ticket = authorized
251+
? issueTicket({ sessionKey: "agent:main:main", view, nowMs, secret }).ticket
252+
: undefined;
253+
view.activeRequests = saturated ? 4 : 0;
254+
const server = createServer((req, res) => {
255+
void handleMcpAppStandaloneHttpRequest(req, res, {
256+
sandboxPort: 18_790,
257+
nowMs,
258+
ticketSecret: secret,
259+
}).catch((error: unknown) => {
260+
res.statusCode = 500;
261+
res.end(String(error));
262+
});
263+
});
264+
await new Promise<void>((resolve, reject) => {
265+
server.once("error", reject);
266+
server.listen(0, "127.0.0.1", resolve);
267+
});
268+
269+
try {
270+
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
271+
const headers = ticket ? { Authorization: `MCP-App ${ticket}` } : undefined;
272+
const get = await fetch(`${origin}${path}`, { headers });
273+
const body = Buffer.from(await get.arrayBuffer());
274+
const head = await fetch(`${origin}${path}`, { method: "HEAD", headers });
275+
276+
expect(get.status).toBe(expectedStatus);
277+
expect(head.status).toBe(expectedStatus);
278+
expect(get.headers.get("content-length")).toBe(String(body.byteLength));
279+
expect(head.headers.get("content-length")).toBe(String(body.byteLength));
280+
expect((await head.arrayBuffer()).byteLength).toBe(0);
281+
expect(head.headers.get("cache-control")).toBe("no-store");
282+
283+
if (path.endsWith("/view")) {
284+
expect(head.headers.get("vary")).toBe("Authorization");
285+
}
286+
if (expectedStatus === 401) {
287+
expect(head.headers.get("www-authenticate")).toBe("MCP-App");
288+
}
289+
if (authorized && !saturated) {
290+
expect(body.toString()).toContain("caf\u00e9 \ud83e\udd9e");
291+
expect(JSON.parse(body.toString())).toMatchObject({ operationTimeoutMs: 65_000 });
292+
}
293+
} finally {
294+
view.html = originalHtml;
295+
view.activeRequests = 0;
296+
await new Promise<void>((resolve, reject) => {
297+
server.close((error) => (error ? reject(error) : resolve()));
298+
});
299+
}
300+
},
301+
);
302+
224303
it("executes serialized fetch deadlines with visible outcomes", async () => {
225304
const shell = await request({ url: "/__openclaw__/mcp-app" });
226305
const html = String(shell.end.mock.calls[0]?.[0]);

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

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { buildMcpAppSandboxPath, resolveMcpAppSandboxPort } from "../agents/mcp-
66
import { getMcpAppViewLease, type McpAppViewLease } from "../agents/mcp-ui-resource.js";
77
import { formatErrorMessage } from "../infra/errors.js";
88
import { safeEqualSecret } from "../security/secret-equal.js";
9+
import { respondPlainText } from "./control-ui-http-utils.js";
910
import {
1011
classifyMcpAppStandalonePath,
1112
MCP_APP_STANDALONE_PATH,
@@ -210,10 +211,17 @@ function supportsStandaloneToolOperations(
210211
return view.allowedAppToolNames !== undefined && view.readOnly !== true;
211212
}
212213

213-
function sendText(res: ServerResponse, statusCode: number, body: string): void {
214+
function sendJsonRepresentation(
215+
req: IncomingMessage,
216+
res: ServerResponse,
217+
statusCode: number,
218+
body: unknown,
219+
): void {
220+
const serialized = JSON.stringify(body);
214221
res.statusCode = statusCode;
215-
res.setHeader("Content-Type", "text/plain; charset=utf-8");
216-
res.end(body);
222+
res.setHeader("Content-Type", "application/json; charset=utf-8");
223+
res.setHeader("Content-Length", String(Buffer.byteLength(serialized)));
224+
res.end(req.method === "HEAD" ? undefined : serialized);
217225
}
218226

219227
function runStandaloneMcpAppHost(config: {
@@ -593,20 +601,20 @@ export async function handleMcpAppStandaloneHttpRequest(
593601
req.method !== "HEAD" &&
594602
!(url.pathname === MCP_APP_STANDALONE_VIEW_PATH && req.method === "POST")
595603
) {
596-
sendText(res, 404, "Not Found");
604+
respondPlainText(res, 404, "Not Found");
597605
return true;
598606
}
599607

600608
const gatewayPort = options.gatewayPort ?? req.socket.localPort;
601609
if (!gatewayPort) {
602-
sendText(res, 503, "MCP App host unavailable");
610+
respondPlainText(res, 503, "MCP App host unavailable");
603611
return true;
604612
}
605613
let sandboxPort: number;
606614
try {
607615
sandboxPort = resolveMcpAppSandboxPort(gatewayPort, options.sandboxPort);
608616
} catch {
609-
sendText(res, 503, "MCP App host unavailable");
617+
respondPlainText(res, 503, "MCP App host unavailable");
610618
return true;
611619
}
612620

@@ -622,6 +630,7 @@ export async function handleMcpAppStandaloneHttpRequest(
622630
const shell = standaloneHostHtml();
623631
res.statusCode = 200;
624632
res.setHeader("Content-Type", "text/html; charset=utf-8");
633+
res.setHeader("Content-Length", String(Buffer.byteLength(shell.html)));
625634
res.setHeader(
626635
"Content-Security-Policy",
627636
`default-src 'none'; script-src 'sha256-${shell.scriptHash}'; style-src 'unsafe-inline'; connect-src 'self'; frame-src ${frameOrigin}; base-uri 'none'; form-action 'none'; object-src 'none'`,
@@ -639,7 +648,7 @@ export async function handleMcpAppStandaloneHttpRequest(
639648
const active = ticket ? resolveTicketActiveView(ticket, nowMs, secret) : undefined;
640649
if (!active) {
641650
res.setHeader("WWW-Authenticate", "MCP-App");
642-
sendText(res, 401, "Unauthorized");
651+
respondPlainText(res, 401, "Unauthorized");
643652
return true;
644653
}
645654
if (req.method === "POST") {
@@ -678,36 +687,28 @@ export async function handleMcpAppStandaloneHttpRequest(
678687
try {
679688
return await withMcpAppActiveView(active, "read", () => {
680689
const { runtime, view } = active;
681-
res.statusCode = 200;
682-
res.setHeader("Content-Type", "application/json; charset=utf-8");
683-
res.end(
684-
req.method === "HEAD"
685-
? undefined
686-
: JSON.stringify({
687-
sandboxUrl: buildMcpAppSandboxPath(view.csp),
688-
sandboxPort,
689-
...(options.sandboxOrigin
690-
? { sandboxOrigin: new URL(options.sandboxOrigin).origin }
691-
: {}),
692-
html: view.html,
693-
...(view.csp ? { csp: view.csp } : {}),
694-
toolInput: view.toolInput,
695-
toolResult: view.toolResult,
696-
serverTools: supportsStandaloneToolOperations(view),
697-
serverResources: runtime.readResource !== undefined,
698-
...(view.requestTimeoutMs !== undefined
699-
? {
700-
// Keep the browser's outer deadline behind the SDK request
701-
// so a valid near-deadline response can reach the App.
702-
operationTimeoutMs: addTimerTimeoutGraceMs(view.requestTimeoutMs),
703-
}
704-
: {}),
705-
}),
706-
);
690+
sendJsonRepresentation(req, res, 200, {
691+
sandboxUrl: buildMcpAppSandboxPath(view.csp),
692+
sandboxPort,
693+
...(options.sandboxOrigin ? { sandboxOrigin: new URL(options.sandboxOrigin).origin } : {}),
694+
html: view.html,
695+
...(view.csp ? { csp: view.csp } : {}),
696+
toolInput: view.toolInput,
697+
toolResult: view.toolResult,
698+
serverTools: supportsStandaloneToolOperations(view),
699+
serverResources: runtime.readResource !== undefined,
700+
...(view.requestTimeoutMs !== undefined
701+
? {
702+
// Keep the browser's outer deadline behind the SDK request
703+
// so a valid near-deadline response can reach the App.
704+
operationTimeoutMs: addTimerTimeoutGraceMs(view.requestTimeoutMs),
705+
}
706+
: {}),
707+
});
707708
return true;
708709
});
709710
} catch (error) {
710-
sendJson(res, 429, { ok: false, error: formatErrorMessage(error) });
711+
sendJsonRepresentation(req, res, 429, { ok: false, error: formatErrorMessage(error) });
711712
return true;
712713
}
713714
}

0 commit comments

Comments
 (0)