Add mcp-apps module: Spring AI 2.1.0 MCP server with MCP Apps HTML views, app-only tool callbacks, CSP declarations, SDK client tests and a Chromium harness on the official AppBridge

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4RzcCS5JCAgcxLz7T
This commit is contained in:
Claude
2026-12-05 16:43:24 +05:30
parent 8fa3c5d682
commit 508fed3b98
46 changed files with 1730 additions and 0 deletions
+163
View File
@@ -0,0 +1,163 @@
// Drives the Java server through the harness host in a real Chromium and writes output/05..07.
// Usage: node run.mjs (the jar must already be built: mvn -pl mcp-apps package)
import { build } from "esbuild";
import { chromium } from "playwright";
import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import assert from "node:assert/strict";
import { buildCsp } from "./csp.mjs";
const here = dirname(fileURLToPath(import.meta.url));
const jar = join(here, "../target/mcp-apps.jar");
const outDir = join(here, "../output");
const MCP = "http://localhost:3001/mcp";
const SANDBOX = "http://127.0.0.1:7002/sandbox.html";
const SDK_FILE = join(here, "node_modules/@modelcontextprotocol/ext-apps/dist/src/app-with-deps.js");
const bundle = (await build({ entryPoints: [join(here, "host.js")], bundle: true, format: "iife", write: false,
logLevel: "error", absWorkingDir: here })).outputFiles[0].text;
const hostServer = createServer((req, res) => {
if (req.url === "/host.bundle.js") return res.writeHead(200, { "Content-Type": "text/javascript" }).end(bundle);
res.writeHead(200, { "Content-Type": "text/html" }).end(readFileSync(join(here, "host.html")));
}).listen(7001);
const sandboxServer = createServer((req, res) => {
const url = new URL(req.url, SANDBOX);
res.writeHead(200, { "Content-Type": "text/html", "Content-Security-Policy": buildCsp(JSON.parse(url.searchParams.get("csp") ?? "{}")) })
.end(readFileSync(join(here, "sandbox.html")));
}).listen(7002, "127.0.0.1");
async function startJava(profiles) {
const proc = spawn("java", ["-jar", jar, "--app.cors-origins=http://localhost:7001", "--logging.level.root=warn",
...(profiles ? ["--spring.profiles.active=" + profiles] : [])], { stdio: "ignore" });
for (let i = 0; i < 120; i++) {
try { await fetch(MCP); return proc; } catch { await new Promise((r) => setTimeout(r, 500)); }
}
throw new Error("server did not start");
}
const stop = (proc) => new Promise((r) => { proc.once("exit", r); proc.kill(); });
const addInlineScript = (code) => { const s = document.createElement("script"); s.textContent = code; document.body.append(s); };
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined });
async function open(toolName, extra = {}) {
const page = await browser.newPage({ viewport: { width: 700, height: 420 } });
const consoleLines = [];
page.on("console", (m) => consoleLines.push(m.text()));
page.on("pageerror", (e) => consoleLines.push("pageerror: " + e.message));
// unpkg.com is answered from the pinned npm package, so the run does not depend on the CDN.
// The browser still applies the CSP before the request is made.
await page.route("https://unpkg.com/**", (route) => route.fulfill({ status: 200, body: readFileSync(SDK_FILE),
contentType: "text/javascript", headers: { "Access-Control-Allow-Origin": "*" } }));
await page.goto("http://localhost:7001/");
await page.evaluate((a) => window.runApp(a), { mcpUrl: MCP, sandboxUrl: SANDBOX, toolName, ...extra });
const view = page.frameLocator("#sandbox").frameLocator("#view");
const log = () => page.evaluate(() => window.hostLog);
return { page, view, log, consoleLines };
}
const inner = (page) => page.frames().find((f) => f.url() === "about:srcdoc");
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
const rowText = async (view) => (await view.locator("#rows tr").allInnerTexts()).map((t) => t.replace(/\s+/g, " ").trim());
const violations = (lines) => lines.filter((l) => /Content Security Policy/i.test(l))
.map((l) => l.replace(/\s+/g, " ").replace(/\. Note that .*$/, "."));
const write = (name, lines) => { writeFileSync(join(outDir, name), lines.join("\n") + "\n"); console.log("wrote", name); };
let java;
try {
// ---------- 05: the hand-written view, end to end ----------
java = await startJava();
{
const out = ["# Hand-written view (board.html) in Chromium, AppBridge as the host, strict CSP", ""];
const { page, view, log } = await open("show_inventory");
await view.locator("tr[data-sku=KB-01]").waitFor();
out.push("## rows after the tool result", ...(await rowText(view)));
await view.locator("tr[data-sku=KB-01] button").click();
await view.getByText("Restocked KB-01").waitFor();
await pause(500);
out.push("", "## rows after clicking +10 on KB-01", ...(await rowText(view)), "", "status line: " + await view.locator("#status").innerText());
const seen = (await log()).filter((l, i, a) => !(l.includes("size-changed") && a.indexOf(l) !== i));
out.push("", "## host log (repeated size-changed lines removed)", ...seen);
await page.screenshot({ path: join(outDir, "board.png") });
const frame = inner(page);
const probes = await frame.evaluate(async () => {
const r = [];
try { window.top.document.title; r.push("read host page DOM: ALLOWED"); } catch (e) { r.push("read host page DOM: " + e.name); }
try { await fetch("https://api.example.com/stock"); r.push("fetch undeclared origin: ALLOWED"); } catch (e) { r.push("fetch undeclared origin: " + e.name + ": " + e.message); }
try { await fetch("http://localhost:3001/mcp"); r.push("fetch the MCP server directly: ALLOWED"); } catch (e) { r.push("fetch the MCP server directly: " + e.name + ": " + e.message); }
const ask = (params) => new Promise((resolve) => {
const id = Math.floor(Math.random() * 1e6) + 5000;
addEventListener("message", function on(e) { if (e.data.id === id && !e.data.method) { removeEventListener("message", on); resolve(e.data); } });
parent.postMessage({ jsonrpc: "2.0", id, method: "ui/message", params }, "*");
});
const text = { type: "text", text: "hi" };
for (const [label, content] of [["ui/message, content as one object (spec text)", text], ["ui/message, content as an array (SDK types)", [text]]]) {
const reply = await ask({ role: "user", content });
r.push(label + ": " + (reply.error ? "error " + reply.error.code : "ok"));
}
return r;
});
await frame.evaluate(addInlineScript, readFileSync(join(here, "probes.js"), "utf8"));
await frame.waitForFunction(() => window.__probes);
out.push("", "## probes run inside the view's frame", ...probes, ...await frame.evaluate(() => window.__probes));
assert.ok(probes[0].endsWith("SecurityError"));
assert.ok(probes[1].includes("TypeError") && probes[2].includes("TypeError"));
assert.ok((await rowText(view))[0].includes(" 14 "));
write("05-browser-board.txt", out);
await page.close();
}
await stop(java);
// ---------- 06: the SDK view and its CSP declaration ----------
java = await startJava();
{
const out = ["# SDK view (board-sdk.html), strict CSP", ""];
const good = await open("show_inventory_sdk");
await good.view.locator("li", { hasText: "KB-01" }).waitFor();
await good.view.locator("#ask").click();
await good.view.getByText("Sent to the chat.").waitFor();
out.push("## with _meta.ui.csp.resourceDomains = [https://unpkg.com]", ...(await good.view.locator("li").allInnerTexts()),
...(await good.log()).filter((l) => l.startsWith("host:")));
await good.page.screenshot({ path: join(outDir, "board-sdk.png") });
await good.page.close();
const bad = await open("show_inventory_sdk", { dropCsp: true });
await pause(4000);
out.push("", "## the same view when no domains are declared, 4 seconds later",
"view shows: " + (await bad.view.locator("#rows").innerText()).trim(),
...(await bad.log()), "browser console:", ...violations(bad.consoleLines));
assert.ok(violations(bad.consoleLines).length > 0);
assert.ok(!(await bad.log()).some((l) => l.includes("ui/initialize")));
write("06-browser-csp.txt", out);
await bad.page.close();
}
await stop(java);
// ---------- 07: a poisoned product name ----------
const out = ["# A product name carrying <img onerror=...>, rendered two ways", ""];
for (const [profile, label] of [["poisoned", "textContent (the shipped view)"], ["unsafe", "innerHTML (app.unsafe-render=true)"]]) {
java = await startJava(profile);
const { page, view, log } = await open("show_inventory");
await view.locator("tr[data-sku=CB-99]").waitFor();
await pause(2500);
const calls = (await log()).filter((l) => l.includes("tools/call"));
const stock = await inner(page).evaluate(() => new Promise((resolve) => {
addEventListener("message", function on(e) { if (e.data.id === 777) { removeEventListener("message", on); resolve(e.data.result.structuredContent.items[0].stock); } });
parent.postMessage({ jsonrpc: "2.0", id: 777, method: "tools/call", params: { name: "show_inventory", arguments: {} } }, "*");
}));
out.push("## " + label, "CB-99 row text: " + (await view.locator("tr[data-sku=CB-99] td").nth(1).innerText()).slice(0, 60), "clicks by the user: 0",
"tools/call sent by the view: " + (calls.length ? "" : "none"), ...calls, "KB-01 stock on the server afterwards: " + stock, "");
assert.equal(stock, profile === "unsafe" ? 103 : 4);
await page.close();
await stop(java);
}
write("07-browser-injection.txt", out);
java = undefined;
} finally {
java?.kill();
await browser.close();
hostServer.close();
sandboxServer.close();
}