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:
@@ -0,0 +1,55 @@
|
||||
# mcp-apps
|
||||
|
||||
Companion code for *MCP Apps in Java: Serve Interactive HTML UIs from a Spring AI MCP Server* on
|
||||
[ankurm.com](https://ankurm.com). A Spring AI MCP server whose tools come with an HTML view
|
||||
(the MCP Apps extension, `io.modelcontextprotocol/ui`, spec `2026-01-26`).
|
||||
|
||||
```bash
|
||||
mvn -pl mcp-apps package # tests write output/01-04, builds target/mcp-apps.jar
|
||||
java -jar mcp-apps/target/mcp-apps.jar # Streamable HTTP on http://localhost:3001/mcp
|
||||
./mcp-apps/scripts/run-all.sh # output/01-07 and 09 (needs Node 20+ and Chromium)
|
||||
./mcp-apps/scripts/basic-host.sh # output/08: the official ext-apps basic-host (clones it, needs the network)
|
||||
```
|
||||
|
||||
Set `CHROMIUM_PATH` to use an installed Chromium; otherwise run `npx playwright install chromium` in `harness/`.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `UiMeta` | The `_meta.ui` blocks as `MetaProvider` classes: tool link, visibility, CSP |
|
||||
| `InventoryTools` | `show_inventory`, `show_inventory_sdk`, and the app-only `restock_item`; text fallback by client capability |
|
||||
| `UiResources` | The two `ui://` resources |
|
||||
| `resources/ui/board.html` | A view with no library: `postMessage` JSON-RPC by hand |
|
||||
| `resources/ui/board-sdk.html` | A view on `@modelcontextprotocol/ext-apps` loaded from unpkg, so it declares a CSP domain |
|
||||
| `VisibilityFilter` | `McpToolFilter` logic for a Java host: keeps app-only tools away from the model |
|
||||
| `CorsConfig` | Off by default; for hosts that call `/mcp` from the browser |
|
||||
| `McpAppsServerTest` | Raw HTTP and MCP Java SDK clients, Spring AI `SyncMcpToolCallbackProvider` |
|
||||
| `harness/` | A web host on the official `AppBridge` with a second-origin sandbox proxy and a strict CSP, driven by Playwright |
|
||||
|
||||
Profiles: `browserhost` (CORS for the basic-host), `poisoned` (a product name carrying markup),
|
||||
`unsafe` (the same, rendered with `innerHTML`; never ship it).
|
||||
|
||||
## Captured output
|
||||
|
||||
| File | Shows |
|
||||
|---|---|
|
||||
| `output/01-wire.txt` | capabilities, `tools/list`, `resources/list`, `resources/read` and where `_meta` ends up |
|
||||
| `output/02-capability.txt` | the same tool for a client with and without the UI extension |
|
||||
| `output/03-callback.txt` | `restock_item`, its errors, and that any client can call an "app-only" tool |
|
||||
| `output/04-spring-ai-client.txt` | Spring AI as host offers app-only tools to the model unless filtered |
|
||||
| `output/05-browser-board.txt`, `board.png` | the hand-written view in Chromium, sandbox probes, `ui/message` shapes |
|
||||
| `output/06-browser-csp.txt`, `board-sdk.png` | the SDK view with and without the CSP declaration |
|
||||
| `output/07-browser-injection.txt` | script injection through tool data |
|
||||
| `output/08-basic-host.txt`, `basic-host.png` | the official reference host |
|
||||
| `output/09-jar-search.txt` | no MCP Apps specific API in the Spring AI 2.1.0 / SDK 2.2.0 MCP jars |
|
||||
|
||||
## Versions
|
||||
|
||||
Spring Boot 4.2.0, Spring AI 2.1.0, MCP Java SDK 2.2.0, JDK 25 (Temurin 25.0.5.1), JUnit 6.1.3,
|
||||
`@modelcontextprotocol/ext-apps` 2.0.4, `@modelcontextprotocol/client` 2.4.0, Playwright 1.65.2 driving
|
||||
Chrome for Testing 158, Node 22. The basic-host is from `modelcontextprotocol/ext-apps` commit `87bcdc8`.
|
||||
|
||||
## Not covered
|
||||
|
||||
Nothing here was run in Claude, ChatGPT, VS Code or another production host, and no model was involved.
|
||||
The server was run with the `streamable` protocol only, not the stateless one. In the browser runs
|
||||
`unpkg.com` is answered from the pinned npm package.
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,58 @@
|
||||
// Drives the official ext-apps basic-host (already running on :8080, see scripts/basic-host.sh) and writes output/08.
|
||||
import { chromium } from "playwright";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const outDir = join(here, "../output");
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined });
|
||||
const out = ["# The official ext-apps basic-host against the Spring AI server", ""];
|
||||
const consoleLines = [];
|
||||
const wire = [];
|
||||
|
||||
async function open(toolName) {
|
||||
const page = await browser.newPage({ viewport: { width: 900, height: 900 } });
|
||||
page.on("console", (m) => consoleLines.push(m.text()));
|
||||
page.on("request", (r) => { if (r.url().endsWith("/mcp") && r.postData()) wire.push(r.postData()); });
|
||||
await page.route("https://unpkg.com/**", (route) => route.fulfill({ status: 200, contentType: "text/javascript",
|
||||
headers: { "Access-Control-Allow-Origin": "*" },
|
||||
body: readFileSync(join(here, "node_modules/@modelcontextprotocol/ext-apps/dist/src/app-with-deps.js")) }));
|
||||
await page.goto("http://localhost:8080/");
|
||||
await page.locator("option[value=show_inventory]").waitFor({ state: "attached" });
|
||||
const tools = await page.locator("select").nth(1).locator("option").allTextContents();
|
||||
await page.locator("select").nth(1).selectOption(toolName);
|
||||
await page.getByRole("button", { name: "Call Tool" }).click();
|
||||
await page.waitForTimeout(5000);
|
||||
let view;
|
||||
for (const f of page.frames()) if (await f.locator("#rows").count().catch(() => 0)) view = f;
|
||||
assert.ok(view, "view frame not found");
|
||||
return { page, view, tools };
|
||||
}
|
||||
|
||||
const first = await open("show_inventory");
|
||||
out.push("tools offered in basic-host's tool list: " + JSON.stringify(first.tools));
|
||||
await first.view.locator("tr[data-sku=KB-01] button").click();
|
||||
await first.view.getByText("Restocked KB-01").waitFor();
|
||||
out.push("show_inventory, after clicking +10 on KB-01: " + await first.view.locator("#status").innerText());
|
||||
await first.view.evaluate((code) => { const s = document.createElement("script"); s.textContent = code; document.body.append(s); }, readFileSync(join(here, "probes.js"), "utf8"));
|
||||
await first.view.waitForFunction(() => window.__probes);
|
||||
out.push("", "probes in a view that declares no CSP domains:", ...await first.view.evaluate(() => window.__probes));
|
||||
await first.page.waitForTimeout(1000);
|
||||
await first.page.screenshot({ path: join(outDir, "basic-host.png"), fullPage: true });
|
||||
const body = await first.page.locator("body").innerText();
|
||||
out.push("", "basic-host Model Context panel shows: " + body.match(/The user restocked[^\n]*/)?.[0]);
|
||||
await first.page.close();
|
||||
|
||||
const second = await open("show_inventory_sdk");
|
||||
out.push("", "show_inventory_sdk renders: " + (await second.view.locator("#rows li").allInnerTexts()).join(" | "));
|
||||
await second.page.close();
|
||||
|
||||
const requests = wire.map((w) => JSON.parse(w));
|
||||
const init = requests.find((r) => r.method === "initialize");
|
||||
out.push("", "initialize sent by basic-host: " + JSON.stringify(init.params),
|
||||
"methods basic-host sent while loading and running the first tool: " + [...new Set(requests.map((r) => r.method))].join(", "));
|
||||
writeFileSync(join(outDir, "08-basic-host.txt"), out.join("\n") + "\n");
|
||||
console.log(out.join("\n"));
|
||||
await browser.close();
|
||||
@@ -0,0 +1,18 @@
|
||||
// The Content-Security-Policy a strict host builds, following "Restrictive Default" in the 2026-01-26 spec.
|
||||
const clean = (list) => (list ?? []).filter((d) => typeof d === "string" && !/[;\r\n'" ]/.test(d)).join(" ");
|
||||
|
||||
export function buildCsp(csp = {}) {
|
||||
const resources = clean(csp.resourceDomains);
|
||||
return [
|
||||
"default-src 'none'",
|
||||
`script-src 'self' 'unsafe-inline' ${resources}`,
|
||||
`style-src 'self' 'unsafe-inline' ${resources}`,
|
||||
`img-src 'self' data: ${resources}`,
|
||||
`media-src 'self' data: ${resources}`,
|
||||
`font-src ${resources || "'none'"}`,
|
||||
`connect-src ${clean(csp.connectDomains) || "'none'"}`,
|
||||
`frame-src ${clean(csp.frameDomains) || "'none'"}`,
|
||||
"object-src 'none'",
|
||||
`base-uri ${clean(csp.baseUriDomains) || "'self'"}`,
|
||||
].map((d) => d.trim().replace(/\s+/g, " ")).join("; ");
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><meta charset="utf-8"><title>harness host</title><body style="font:14px system-ui"><script src="/host.bundle.js"></script>
|
||||
@@ -0,0 +1,54 @@
|
||||
// A small web host built on the official AppBridge. It is a test harness, not a chat client: there is no model.
|
||||
import { AppBridge, PostMessageTransport, getToolUiResourceUri } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
||||
|
||||
const MIME = "text/html;profile=mcp-app";
|
||||
window.hostLog = [];
|
||||
const log = (line) => window.hostLog.push(line);
|
||||
|
||||
window.runApp = async ({ mcpUrl, sandboxUrl, toolName, dropCsp }) => {
|
||||
const client = new Client({ name: "harness-host", version: "1.0.0" },
|
||||
{ capabilities: { extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [MIME] } } } });
|
||||
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));
|
||||
|
||||
const tool = (await client.listTools()).tools.find((t) => t.name === toolName);
|
||||
const uri = getToolUiResourceUri(tool);
|
||||
const [content] = (await client.readResource({ uri })).contents;
|
||||
if (content.mimeType !== MIME) throw new Error("not an MCP App: " + content.mimeType);
|
||||
// dropCsp simulates a server that forgot to declare its domains.
|
||||
const csp = dropCsp ? undefined : content._meta?.ui?.csp;
|
||||
log(`host: tool ${toolName} -> ${uri}, declared csp ${JSON.stringify(csp) ?? "none"}`);
|
||||
|
||||
const frame = document.createElement("iframe");
|
||||
frame.id = "sandbox";
|
||||
frame.setAttribute("sandbox", "allow-scripts allow-same-origin");
|
||||
frame.style.cssText = "width:640px;height:260px;border:1px solid #ccc";
|
||||
document.body.append(frame);
|
||||
|
||||
const bridge = new AppBridge(client, { name: "harness-host", version: "1.0.0" },
|
||||
{ serverTools: {}, updateModelContext: { text: {} }, message: { text: {} } },
|
||||
{ hostContext: { theme: "light" } });
|
||||
|
||||
bridge.onsandboxready = () => bridge.sendSandboxResourceReady({ html: content.text, csp });
|
||||
bridge.oninitialized = async () => {
|
||||
await bridge.sendToolInput({ arguments: {} });
|
||||
await bridge.sendToolResult(await client.callTool({ name: toolName, arguments: {} }));
|
||||
log("host: tool-input and tool-result delivered");
|
||||
};
|
||||
bridge.onsizechange = ({ height }) => { if (height) frame.style.height = height + "px"; };
|
||||
bridge.onupdatemodelcontext = async (p) => { log("host: model context = " + p.content[0].text); return {}; };
|
||||
bridge.onmessage = async (p) => { log("host: chat message = " + p.content[0].text); return {}; };
|
||||
|
||||
// Wire log of what the view side sends, in order.
|
||||
window.addEventListener("message", (e) => {
|
||||
if (e.source !== frame.contentWindow) return;
|
||||
const m = e.data;
|
||||
if (m.method) {
|
||||
const detail = m.method === "tools/call" ? ` ${m.params.name} ${JSON.stringify(m.params.arguments)} (id ${m.id})` : "";
|
||||
log("view -> host: " + m.method + detail);
|
||||
}
|
||||
});
|
||||
|
||||
await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow));
|
||||
frame.src = sandboxUrl + "?csp=" + encodeURIComponent(JSON.stringify(csp ?? {}));
|
||||
};
|
||||
Generated
+252
@@ -0,0 +1,252 @@
|
||||
{
|
||||
"name": "mcp-apps-harness",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mcp-apps-harness",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/client": "2.4.0",
|
||||
"@modelcontextprotocol/ext-apps": "2.0.4",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "0.28.2",
|
||||
"playwright": "1.65.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.28.2",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/client": {
|
||||
"version": "2.4.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.4.0",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.8",
|
||||
"jose": "^6.1.3",
|
||||
"pkce-challenge": "^5.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/core": {
|
||||
"version": "2.4.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/ext-apps": {
|
||||
"version": "2.0.4",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"examples/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@modelcontextprotocol/server": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@standard-schema/spec": {
|
||||
"version": "1.1.0",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.1.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^3.1.0",
|
||||
"shebang-command": "^2.0.0",
|
||||
"which": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.28.2",
|
||||
"@esbuild/android-arm": "0.28.2",
|
||||
"@esbuild/android-arm64": "0.28.2",
|
||||
"@esbuild/android-x64": "0.28.2",
|
||||
"@esbuild/darwin-arm64": "0.28.2",
|
||||
"@esbuild/darwin-x64": "0.28.2",
|
||||
"@esbuild/freebsd-arm64": "0.28.2",
|
||||
"@esbuild/freebsd-x64": "0.28.2",
|
||||
"@esbuild/linux-arm": "0.28.2",
|
||||
"@esbuild/linux-arm64": "0.28.2",
|
||||
"@esbuild/linux-ia32": "0.28.2",
|
||||
"@esbuild/linux-loong64": "0.28.2",
|
||||
"@esbuild/linux-mips64el": "0.28.2",
|
||||
"@esbuild/linux-ppc64": "0.28.2",
|
||||
"@esbuild/linux-riscv64": "0.28.2",
|
||||
"@esbuild/linux-s390x": "0.28.2",
|
||||
"@esbuild/linux-x64": "0.28.2",
|
||||
"@esbuild/netbsd-arm64": "0.28.2",
|
||||
"@esbuild/netbsd-x64": "0.28.2",
|
||||
"@esbuild/openbsd-arm64": "0.28.2",
|
||||
"@esbuild/openbsd-x64": "0.28.2",
|
||||
"@esbuild/openharmony-arm64": "0.28.2",
|
||||
"@esbuild/sunos-x64": "0.28.2",
|
||||
"@esbuild/win32-arm64": "0.28.2",
|
||||
"@esbuild/win32-ia32": "0.28.2",
|
||||
"@esbuild/win32-x64": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource": {
|
||||
"version": "3.0.7",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"eventsource-parser": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource-parser": {
|
||||
"version": "3.1.1",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/jose": {
|
||||
"version": "6.3.0",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/pkce-challenge": {
|
||||
"version": "5.0.2",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.65.2",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.65.2"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.65.2",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"shebang-regex": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-regex": {
|
||||
"version": "3.0.0",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"node-which": "bin/node-which"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.6.7",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "mcp-apps-harness",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": { "test": "node run.mjs" },
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/client": "2.4.0",
|
||||
"@modelcontextprotocol/ext-apps": "2.0.4",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"devDependencies": { "esbuild": "0.28.2", "playwright": "1.65.2" }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Runs inside the view's frame as a real inline script, so the page's CSP applies to it (DevTools evaluate would not).
|
||||
(async () => {
|
||||
const r = [];
|
||||
// Wait for a new task: while a DevTools call is still on the stack, Chromium lets eval through whatever the CSP says.
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
try { eval("1"); r.push("eval(): ALLOWED"); } catch (e) { r.push("eval(): " + e.name); }
|
||||
try { await fetch(location.ancestorOrigins[0] + "/sandbox.html"); r.push("fetch from the sandbox origin ('self'): ALLOWED"); }
|
||||
catch (e) { r.push("fetch from the sandbox origin ('self'): " + 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); }
|
||||
window.__probes = r;
|
||||
})();
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8">
|
||||
<title>sandbox proxy</title>
|
||||
<style>html,body,iframe{margin:0;border:0;width:100%;height:100%}</style>
|
||||
<body>
|
||||
<script>
|
||||
// The proxy of the spec: a second origin between the host and the view. It loads the HTML and relays messages.
|
||||
const inner = document.createElement("iframe");
|
||||
inner.id = "view";
|
||||
inner.setAttribute("sandbox", "allow-scripts allow-same-origin");
|
||||
const HOST = "http://localhost:7001";
|
||||
window.addEventListener("message", (event) => {
|
||||
if (event.source === window.parent && event.origin === HOST) {
|
||||
if (event.data.method === "ui/notifications/sandbox-resource-ready") {
|
||||
inner.srcdoc = event.data.params.html; // srcdoc inherits this page's CSP header
|
||||
document.body.append(inner);
|
||||
} else {
|
||||
inner.contentWindow?.postMessage(event.data, "*");
|
||||
}
|
||||
} else if (event.source === inner.contentWindow) {
|
||||
window.parent.postMessage(event.data, HOST);
|
||||
}
|
||||
});
|
||||
window.parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/sandbox-proxy-ready", params: {} }, HOST);
|
||||
</script>
|
||||
@@ -0,0 +1,37 @@
|
||||
# Raw Streamable HTTP against the Spring AI 2.1.0 server
|
||||
|
||||
## initialize: server capabilities
|
||||
{"completions":{},"logging":{},"prompts":{"listChanged":true},"resources":{"subscribe":false,"listChanged":true},"tools":{"listChanged":true}}
|
||||
|
||||
## tools/list: name and _meta of each tool
|
||||
restock_item _meta={"ui":{"visibility":["app"],"resourceUri":"ui://inventory/board.html"}}
|
||||
show_inventory _meta={"ui":{"visibility":["model","app"],"resourceUri":"ui://inventory/board.html"}}
|
||||
show_inventory_sdk _meta={"ui":{"visibility":["model","app"],"resourceUri":"ui://inventory/board-sdk.html"}}
|
||||
|
||||
## resources/list
|
||||
ui://inventory/board-sdk.html mimeType=text/html;profile=mcp-app _meta={"ui":{"prefersBorder":true,"csp":{"resourceDomains":["https://unpkg.com"]}}}
|
||||
ui://inventory/board.html mimeType=text/html;profile=mcp-app _meta={"ui":{"prefersBorder":true}}
|
||||
ui://probe/explicit.html mimeType=text/html;profile=mcp-app _meta={"ui":{"prefersBorder":true}}
|
||||
|
||||
## resources/templates/list (the {theme} probe lands here)
|
||||
ui://probe/{theme}.html
|
||||
|
||||
## resources/read ui://inventory/board.html
|
||||
mimeType=text/html;profile=mcp-app
|
||||
_meta={"ui":{"prefersBorder":true}}
|
||||
text starts: <!DOCTYPE html>
|
||||
|
||||
## resources/read ui://inventory/board-sdk.html
|
||||
mimeType=text/html;profile=mcp-app
|
||||
_meta={"ui":{"prefersBorder":true,"csp":{"resourceDomains":["https://unpkg.com"]}}}
|
||||
text starts: <!DOCTYPE html>
|
||||
|
||||
## resources/read ui://probe/dark.html
|
||||
mimeType=text/html;profile=mcp-app
|
||||
_meta=(absent)
|
||||
text starts: <!DOCTYPE html><title>dark</title>
|
||||
|
||||
## resources/read ui://probe/explicit.html
|
||||
mimeType=text/html;profile=mcp-app
|
||||
_meta=(absent)
|
||||
text starts: <!DOCTYPE html><title>explicit</title>
|
||||
@@ -0,0 +1,13 @@
|
||||
# show_inventory seen by two MCP Java SDK clients
|
||||
|
||||
## client that declares io.modelcontextprotocol/ui: content
|
||||
2 of 3 items are below their reorder level.
|
||||
|
||||
## client that does not: content
|
||||
2 of 3 items are below their reorder level.
|
||||
KB-01 Mechanical keyboard: 4 in stock, reorder at 10
|
||||
MN-27 27 inch monitor: 25 in stock, reorder at 8
|
||||
HB-04 USB4 hub: 0 in stock, reorder at 15
|
||||
|
||||
## structuredContent (same for both)
|
||||
{"items":[{"name":"Mechanical keyboard","reorderAt":10,"sku":"KB-01","stock":4},{"name":"27 inch monitor","reorderAt":8,"sku":"MN-27","stock":25},{"name":"USB4 hub","reorderAt":15,"sku":"HB-04","stock":0}]}
|
||||
@@ -0,0 +1,18 @@
|
||||
# restock_item, the tool the view calls back into
|
||||
|
||||
## tools/list from a client with no UI support
|
||||
[restock_item, show_inventory, show_inventory_sdk]
|
||||
|
||||
## restock_item sku=KB-01 quantity=10
|
||||
isError=false
|
||||
Restocked KB-01 by 10, now 14 in stock.
|
||||
|
||||
## restock_item sku=KB-01 quantity=500
|
||||
isError=true
|
||||
quantity must be between 1 and 100, got 500
|
||||
quantity must be between 1 and 100, got 500
|
||||
|
||||
## restock_item sku=ZZ-00 quantity=1
|
||||
isError=true
|
||||
unknown sku ZZ-00
|
||||
unknown sku ZZ-00
|
||||
@@ -0,0 +1,10 @@
|
||||
# Spring AI 2.1.0 SyncMcpToolCallbackProvider as the host
|
||||
|
||||
## tools offered to the model, no filter
|
||||
[restock_item, show_inventory, show_inventory_sdk]
|
||||
|
||||
## tools offered to the model, with VisibilityFilter
|
||||
[show_inventory, show_inventory_sdk]
|
||||
|
||||
## string that SyncMcpToolCallback hands back to the model for show_inventory
|
||||
[{"text":"2 of 3 items are below their reorder level.\nKB-01 Mechanical keyboard: 4 in stock, reorder at 10\nMN-27 27 inch monitor: 25 in stock, reorder at 8\nHB-04 USB4 hub: 0 in stock, reorder at 15"}]
|
||||
@@ -0,0 +1,34 @@
|
||||
# Hand-written view (board.html) in Chromium, AppBridge as the host, strict CSP
|
||||
|
||||
## rows after the tool result
|
||||
KB-01 Mechanical keyboard 4 +10
|
||||
MN-27 27 inch monitor 25 +10
|
||||
HB-04 USB4 hub 0 +10
|
||||
|
||||
## rows after clicking +10 on KB-01
|
||||
KB-01 Mechanical keyboard 14 +10
|
||||
MN-27 27 inch monitor 25 +10
|
||||
HB-04 USB4 hub 0 +10
|
||||
|
||||
status line: Restocked KB-01 by 10, now 14 in stock.
|
||||
|
||||
## host log (repeated size-changed lines removed)
|
||||
host: tool show_inventory -> ui://inventory/board.html, declared csp none
|
||||
view -> host: ui/notifications/sandbox-proxy-ready
|
||||
view -> host: ui/initialize
|
||||
view -> host: ui/notifications/initialized
|
||||
view -> host: ui/notifications/size-changed
|
||||
host: tool-input and tool-result delivered
|
||||
view -> host: tools/call restock_item {"sku":"KB-01","quantity":10} (id 2)
|
||||
view -> host: ui/update-model-context
|
||||
host: model context = The user restocked KB-01 by 10 from the stock board.
|
||||
|
||||
## probes run inside the view's frame
|
||||
read host page DOM: SecurityError
|
||||
fetch undeclared origin: TypeError: Failed to fetch
|
||||
fetch the MCP server directly: TypeError: Failed to fetch
|
||||
ui/message, content as one object (spec text): error -32602
|
||||
ui/message, content as an array (SDK types): ok
|
||||
eval(): EvalError
|
||||
fetch from the sandbox origin ('self'): TypeError
|
||||
fetch undeclared origin: TypeError
|
||||
@@ -0,0 +1,16 @@
|
||||
# SDK view (board-sdk.html), strict CSP
|
||||
|
||||
## with _meta.ui.csp.resourceDomains = [https://unpkg.com]
|
||||
KB-01 Mechanical keyboard: 4
|
||||
MN-27 27 inch monitor: 25
|
||||
HB-04 USB4 hub: 0
|
||||
host: tool show_inventory_sdk -> ui://inventory/board-sdk.html, declared csp {"resourceDomains":["https://unpkg.com"]}
|
||||
host: tool-input and tool-result delivered
|
||||
host: chat message = Which items should I reorder first?
|
||||
|
||||
## the same view when no domains are declared, 4 seconds later
|
||||
view shows: Waiting for the tool result…
|
||||
host: tool show_inventory_sdk -> ui://inventory/board-sdk.html, declared csp none
|
||||
view -> host: ui/notifications/sandbox-proxy-ready
|
||||
browser console:
|
||||
Loading the script 'https://unpkg.com/@modelcontextprotocol/[email protected]/dist/src/app-with-deps.js' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline'".
|
||||
@@ -0,0 +1,15 @@
|
||||
# A product name carrying <img onerror=...>, rendered two ways
|
||||
|
||||
## textContent (the shipped view)
|
||||
CB-99 row text: Cable <img src="x" onerror="parent.postMessage({jsonrpc:'2.0
|
||||
clicks by the user: 0
|
||||
tools/call sent by the view: none
|
||||
KB-01 stock on the server afterwards: 4
|
||||
|
||||
## innerHTML (app.unsafe-render=true)
|
||||
CB-99 row text: Cable
|
||||
clicks by the user: 0
|
||||
tools/call sent by the view:
|
||||
view -> host: tools/call restock_item {"sku":"KB-01","quantity":99} (id 666)
|
||||
KB-01 stock on the server afterwards: 103
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# The official ext-apps basic-host against the Spring AI server
|
||||
|
||||
tools offered in basic-host's tool list: ["show_inventory","show_inventory_sdk"]
|
||||
show_inventory, after clicking +10 on KB-01: Restocked KB-01 by 10, now 14 in stock.
|
||||
|
||||
probes in a view that declares no CSP domains:
|
||||
eval(): ALLOWED
|
||||
fetch from the sandbox origin ('self'): ALLOWED
|
||||
fetch undeclared origin: TypeError
|
||||
|
||||
basic-host Model Context panel shows: The user restocked KB-01 by 10 from the stock board.
|
||||
|
||||
show_inventory_sdk renders: KB-01 Mechanical keyboard: 14 | MN-27 27 inch monitor: 25 | HB-04 USB4 hub: 0
|
||||
|
||||
initialize sent by basic-host: {"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"MCP Apps Host","version":"1.0.0"}}
|
||||
methods basic-host sent while loading and running the first tool: initialize, notifications/initialized, tools/list, resources/list, tools/call, resources/read
|
||||
@@ -0,0 +1,24 @@
|
||||
# Strings searched in every class file: mcp-app | io.modelcontextprotocol/ui | McpUi | ui://
|
||||
mcp-spring-webmvc-2.1.0.jar: 0 class files match
|
||||
spring-ai-autoconfigure-mcp-client-common-2.1.0.jar: 0 class files match
|
||||
spring-ai-autoconfigure-mcp-client-httpclient-2.1.0.jar: 0 class files match
|
||||
spring-ai-autoconfigure-mcp-server-common-2.1.0.jar: 0 class files match
|
||||
spring-ai-autoconfigure-mcp-server-webmvc-2.1.0.jar: 0 class files match
|
||||
spring-ai-mcp-annotations-2.1.0.jar: 0 class files match
|
||||
spring-ai-mcp-2.1.0.jar: 0 class files match
|
||||
spring-ai-starter-mcp-client-2.1.0.jar: 0 class files match
|
||||
spring-ai-starter-mcp-server-webmvc-2.1.0.jar: 0 class files match
|
||||
mcp-core-2.2.0.jar: 0 class files match
|
||||
|
||||
# javap: what the Java SDK does offer, a generic extensions map
|
||||
public java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.lang.Object>> extensions();
|
||||
|
||||
# javap: the attributes of @McpTool in spring-ai-mcp-annotations 2.1.0
|
||||
java.lang.String name();
|
||||
java.lang.String description();
|
||||
org.springframework.ai.mcp.annotation.McpTool$McpAnnotations annotations();
|
||||
boolean generateOutputSchema();
|
||||
java.lang.String title();
|
||||
java.lang.Class<? extends org.springframework.ai.mcp.annotation.context.MetaProvider> metaProvider();
|
||||
org.springframework.ai.mcp.annotation.McpIcon[] icons();
|
||||
org.springframework.ai.mcp.annotation.McpClientCapability[] requiredCapabilities();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ankurm.agents</groupId>
|
||||
<artifactId>java-ai-agents</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>mcp-apps</artifactId>
|
||||
<name>MCP Apps: interactive HTML UIs from a Spring AI MCP server</name>
|
||||
|
||||
<properties>
|
||||
<!-- Verified on Maven Central 2026-12-05. These override the parent's older values for this module only. -->
|
||||
<spring-boot.version>4.2.0</spring-boot.version>
|
||||
<spring-ai.version>2.1.0</spring-ai.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bom</artifactId>
|
||||
<version>${spring-ai.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-starter-mcp-client</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>mcp-apps</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals><goal>repackage</goal></goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Writes output/08: builds the official ext-apps basic-host, points it at this server and drives it in Chromium.
|
||||
# Needs the jar (mvn -pl mcp-apps package) and harness/node_modules (npm install in harness/).
|
||||
set -euo pipefail
|
||||
MODULE="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
WORK="$(mktemp -d)"
|
||||
git clone -q https://github.com/modelcontextprotocol/ext-apps.git "$WORK/ext-apps"
|
||||
git -C "$WORK/ext-apps" checkout -q 87bcdc8
|
||||
cp -r "$WORK/ext-apps/examples/basic-host" "$WORK/basic-host"
|
||||
cd "$WORK/basic-host"
|
||||
sed -i 's/"@modelcontextprotocol\/ext-apps": "\^2.1.0"/"@modelcontextprotocol\/ext-apps": "2.0.4"/' package.json
|
||||
npm install --silent
|
||||
npm install --silent tsx
|
||||
INPUT=index.html npx vite build >/dev/null
|
||||
INPUT=sandbox.html npx vite build >/dev/null
|
||||
|
||||
java -jar "$MODULE/target/mcp-apps.jar" --spring.profiles.active=browserhost --logging.level.root=warn &
|
||||
JAVA_PID=$!
|
||||
SERVERS='["http://localhost:3001/mcp"]' node_modules/.bin/tsx serve.ts &
|
||||
HOST_PID=$!
|
||||
trap 'kill $JAVA_PID $HOST_PID 2>/dev/null || true' EXIT
|
||||
sleep 15
|
||||
cd "$MODULE/harness" && node basic-host.mjs
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Writes output/09: does anything in the MCP jars of Spring AI 2.1.0 or the Java SDK 2.2.0 know about MCP Apps?
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
M="${M2_REPO:-$HOME/.m2/repository}"
|
||||
TMP="$(mktemp -d)"
|
||||
OUT=output/09-jar-search.txt
|
||||
{
|
||||
echo "# Strings searched in every class file: mcp-app | io.modelcontextprotocol/ui | McpUi | ui://"
|
||||
for jar in "$M"/org/springframework/ai/*mcp*/2.1.0/*-2.1.0.jar "$M"/io/modelcontextprotocol/sdk/mcp-core/2.2.0/mcp-core-2.2.0.jar; do
|
||||
dir="$TMP/$(basename "$jar" .jar)"
|
||||
mkdir -p "$dir" && unzip -q -o "$jar" -d "$dir"
|
||||
echo "$(basename "$jar"): $( { grep -rlaE 'mcp-app|io\.modelcontextprotocol/ui|McpUi|ui://' "$dir" || true; } | wc -l) class files match"
|
||||
done
|
||||
echo
|
||||
echo "# javap: what the Java SDK does offer, a generic extensions map"
|
||||
javap -cp "$M/io/modelcontextprotocol/sdk/mcp-core/2.2.0/mcp-core-2.2.0.jar" 'io.modelcontextprotocol.spec.McpSchema$ClientCapabilities' 2>/dev/null | grep -E 'extensions\(\)' | sed 's/^ *//'
|
||||
echo
|
||||
echo "# javap: the attributes of @McpTool in spring-ai-mcp-annotations 2.1.0"
|
||||
javap -cp "$M/org/springframework/ai/spring-ai-mcp-annotations/2.1.0/spring-ai-mcp-annotations-2.1.0.jar" org.springframework.ai.mcp.annotation.McpTool 2>/dev/null | grep abstract | sed -E 's/^ *public abstract //'
|
||||
} > "$OUT"
|
||||
rm -rf "$TMP"
|
||||
cat "$OUT"
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates output/01-07. Needs JDK 25, Maven, Node 20+ and Chromium (set CHROMIUM_PATH to use an installed one,
|
||||
# otherwise run "npx playwright install chromium" inside harness/ first). output/08 comes from scripts/basic-host.sh.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mvn -q -B -f ../pom.xml -pl mcp-apps clean package # tests write output/01-04
|
||||
cd harness
|
||||
npm install --silent
|
||||
node run.mjs # writes output/05-07 and two screenshots
|
||||
../scripts/jar-search.sh # writes output/09
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Only needed for hosts that call the MCP endpoint from the browser (the ext-apps basic-host does). Empty by default.
|
||||
*/
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
|
||||
private final List<String> origins;
|
||||
|
||||
public CorsConfig(@Value("${app.cors-origins:}") List<String> origins) {
|
||||
this.origins = origins;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
if (!origins.isEmpty()) {
|
||||
registry.addMapping("/mcp")
|
||||
.allowedOrigins(origins.toArray(String[]::new))
|
||||
.allowedMethods("GET", "POST", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.exposedHeaders("Mcp-Session-Id");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** In-memory stock list. Enough state to show that a button in the view really changes something on the server. */
|
||||
@Service
|
||||
public class Inventory {
|
||||
|
||||
public record Item(String sku, String name, int stock, int reorderAt) {
|
||||
public boolean low() {
|
||||
return stock < reorderAt;
|
||||
}
|
||||
}
|
||||
|
||||
/** A product name written by an attacker, for example through a supplier import. Enabled by app.poisoned-item. */
|
||||
static final String POISONED_NAME = "Cable <img src=\"x\" onerror=\"parent.postMessage({jsonrpc:'2.0',id:666,"
|
||||
+ "method:'tools/call',params:{name:'restock_item',arguments:{sku:'KB-01',quantity:99}}},'*')\">";
|
||||
|
||||
private final Map<String, Item> items = new LinkedHashMap<>();
|
||||
private final boolean poisoned;
|
||||
|
||||
public Inventory(@Value("${app.poisoned-item:false}") boolean poisoned) {
|
||||
this.poisoned = poisoned;
|
||||
reset();
|
||||
}
|
||||
|
||||
public synchronized void reset() {
|
||||
items.clear();
|
||||
add(new Item("KB-01", "Mechanical keyboard", 4, 10));
|
||||
add(new Item("MN-27", "27 inch monitor", 25, 8));
|
||||
add(new Item("HB-04", "USB4 hub", 0, 15));
|
||||
if (poisoned) {
|
||||
add(new Item("CB-99", POISONED_NAME, 1, 5));
|
||||
}
|
||||
}
|
||||
|
||||
private void add(Item item) {
|
||||
items.put(item.sku(), item);
|
||||
}
|
||||
|
||||
public synchronized List<Item> all() {
|
||||
return new ArrayList<>(items.values());
|
||||
}
|
||||
|
||||
public synchronized Item restock(String sku, int quantity) {
|
||||
if (quantity < 1 || quantity > 100) {
|
||||
throw new IllegalArgumentException("quantity must be between 1 and 100, got " + quantity);
|
||||
}
|
||||
Item old = items.get(sku);
|
||||
if (old == null) {
|
||||
throw new IllegalArgumentException("unknown sku " + sku);
|
||||
}
|
||||
Item updated = new Item(old.sku(), old.name(), old.stock() + quantity, old.reorderAt());
|
||||
items.put(sku, updated);
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
|
||||
import io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.ai.mcp.annotation.McpTool;
|
||||
import org.springframework.ai.mcp.annotation.McpToolParam;
|
||||
import org.springframework.ai.mcp.annotation.context.McpSyncRequestContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class InventoryTools {
|
||||
|
||||
private final Inventory inventory;
|
||||
|
||||
public InventoryTools(Inventory inventory) {
|
||||
this.inventory = inventory;
|
||||
}
|
||||
|
||||
@McpTool(name = "show_inventory", description = "Show warehouse stock levels and which items are low",
|
||||
metaProvider = UiMeta.ShowBoard.class)
|
||||
public CallToolResult showInventory(McpSyncRequestContext context) {
|
||||
return board(supportsUi(context.clientCapabilities()));
|
||||
}
|
||||
|
||||
@McpTool(name = "show_inventory_sdk", description = "Show warehouse stock levels (view built with the ext-apps SDK)",
|
||||
metaProvider = UiMeta.ShowSdkBoard.class)
|
||||
public CallToolResult showInventorySdk(McpSyncRequestContext context) {
|
||||
return board(supportsUi(context.clientCapabilities()));
|
||||
}
|
||||
|
||||
@McpTool(name = "restock_item", description = "Add units to one stock item", metaProvider = UiMeta.AppOnly.class)
|
||||
public CallToolResult restock(
|
||||
@McpToolParam(description = "Stock keeping unit, for example KB-01") String sku,
|
||||
@McpToolParam(description = "Units to add, 1 to 100") int quantity) {
|
||||
Inventory.Item item = inventory.restock(sku, quantity);
|
||||
return CallToolResult.builder()
|
||||
.addTextContent("Restocked " + item.sku() + " by " + quantity + ", now " + item.stock() + " in stock.")
|
||||
.structuredContent(snapshot())
|
||||
.build();
|
||||
}
|
||||
|
||||
/** True when the connected client said it can render MCP Apps. */
|
||||
static boolean supportsUi(ClientCapabilities capabilities) {
|
||||
if (capabilities == null || capabilities.extensions() == null) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Object> ui = capabilities.extensions().get(UiMeta.EXTENSION);
|
||||
return ui != null && ui.get("mimeTypes") instanceof List<?> types && types.contains(UiMeta.MIME_TYPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* content is what the model reads, structuredContent is what the view draws. A client without UI support gets
|
||||
* the whole table as text, because the text is all it will ever show.
|
||||
*/
|
||||
private CallToolResult board(boolean uiSupported) {
|
||||
List<Inventory.Item> items = inventory.all();
|
||||
long low = items.stream().filter(Inventory.Item::low).count();
|
||||
String text = low + " of " + items.size() + " items are below their reorder level.";
|
||||
if (!uiSupported) {
|
||||
text += "\n" + items.stream()
|
||||
.map(i -> i.sku() + " " + i.name() + ": " + i.stock() + " in stock, reorder at " + i.reorderAt())
|
||||
.collect(Collectors.joining("\n"));
|
||||
}
|
||||
return CallToolResult.builder().addTextContent(text).structuredContent(snapshot()).build();
|
||||
}
|
||||
|
||||
private Map<String, Object> snapshot() {
|
||||
return Map.of("items", inventory.all());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/** A Spring AI MCP server whose tools come with an HTML view (the MCP Apps extension, io.modelcontextprotocol/ui). */
|
||||
@SpringBootApplication
|
||||
public class McpAppsApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(McpAppsApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.ai.mcp.annotation.context.MetaProvider;
|
||||
|
||||
/**
|
||||
* The _meta blocks of the MCP Apps extension. Spring AI 2.1.0 has no dedicated annotation for them, so they are
|
||||
* plain maps returned by a {@link MetaProvider}.
|
||||
*/
|
||||
public final class UiMeta {
|
||||
|
||||
public static final String MIME_TYPE = "text/html;profile=mcp-app";
|
||||
public static final String EXTENSION = "io.modelcontextprotocol/ui";
|
||||
public static final String BOARD_URI = "ui://inventory/board.html";
|
||||
public static final String SDK_URI = "ui://inventory/board-sdk.html";
|
||||
public static final String CDN = "https://unpkg.com";
|
||||
|
||||
private UiMeta() {
|
||||
}
|
||||
|
||||
static Map<String, Object> tool(String resourceUri, String... visibility) {
|
||||
return Map.of("ui", Map.of("resourceUri", resourceUri, "visibility", List.of(visibility)));
|
||||
}
|
||||
|
||||
/** Model and view may call it. */
|
||||
public static class ShowBoard implements MetaProvider {
|
||||
public Map<String, Object> getMeta() {
|
||||
return tool(BOARD_URI, "model", "app");
|
||||
}
|
||||
}
|
||||
|
||||
/** Same data, rendered by the view that uses the ext-apps SDK. */
|
||||
public static class ShowSdkBoard implements MetaProvider {
|
||||
public Map<String, Object> getMeta() {
|
||||
return tool(SDK_URI, "model", "app");
|
||||
}
|
||||
}
|
||||
|
||||
/** Only the view may call it; a conforming host hides it from the model. */
|
||||
public static class AppOnly implements MetaProvider {
|
||||
public Map<String, Object> getMeta() {
|
||||
return tool(BOARD_URI, "app");
|
||||
}
|
||||
}
|
||||
|
||||
/** The hand-written view loads nothing from outside, so it declares no CSP domains at all. */
|
||||
public static class BoardResource implements MetaProvider {
|
||||
public Map<String, Object> getMeta() {
|
||||
return Map.of("ui", Map.of("prefersBorder", true));
|
||||
}
|
||||
}
|
||||
|
||||
/** The SDK view imports a script from a CDN, so that origin has to be declared. */
|
||||
public static class SdkResource implements MetaProvider {
|
||||
public Map<String, Object> getMeta() {
|
||||
return Map.of("ui", Map.of("csp", Map.of("resourceDomains", List.of(CDN)), "prefersBorder", true));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.springframework.ai.mcp.annotation.McpResource;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** The HTML views, served as ordinary MCP resources under the ui:// scheme. */
|
||||
@Component
|
||||
public class UiResources {
|
||||
|
||||
private final boolean unsafeRender;
|
||||
|
||||
public UiResources(@Value("${app.unsafe-render:false}") boolean unsafeRender) {
|
||||
this.unsafeRender = unsafeRender;
|
||||
}
|
||||
|
||||
@McpResource(uri = UiMeta.BOARD_URI, name = "inventory_board", description = "Stock board view",
|
||||
mimeType = UiMeta.MIME_TYPE, metaProvider = UiMeta.BoardResource.class)
|
||||
public String board() throws IOException {
|
||||
// app.unsafe-render=true switches the view to innerHTML, to demonstrate script injection. Never ship that.
|
||||
return load("ui/board.html").replace("__UNSAFE_RENDER__", Boolean.toString(unsafeRender));
|
||||
}
|
||||
|
||||
@McpResource(uri = UiMeta.SDK_URI, name = "inventory_board_sdk", description = "Stock board view (ext-apps SDK)",
|
||||
mimeType = UiMeta.MIME_TYPE, metaProvider = UiMeta.SdkResource.class)
|
||||
public String sdkBoard() throws IOException {
|
||||
return load("ui/board-sdk.html");
|
||||
}
|
||||
|
||||
private static String load(String path) throws IOException {
|
||||
return new ClassPathResource(path).getContentAsString(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import io.modelcontextprotocol.spec.McpSchema.Tool;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* For a Java application that plays the host with the Spring AI MCP client: the MCP Apps spec says tools whose
|
||||
* _meta.ui.visibility does not include "model" must not reach the model. Spring AI 2.1.0 does not apply that
|
||||
* rule itself, so pass this as the McpToolFilter.
|
||||
*/
|
||||
public final class VisibilityFilter {
|
||||
|
||||
private VisibilityFilter() {
|
||||
}
|
||||
|
||||
public static boolean visibleToModel(Tool tool) {
|
||||
if (tool.meta() == null || !(tool.meta().get("ui") instanceof Map<?, ?> ui)
|
||||
|| !(ui.get("visibility") instanceof List<?> visibility)) {
|
||||
return true; // the spec default is ["model", "app"]
|
||||
}
|
||||
return visibility.contains("model");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# The ext-apps basic-host runs on http://localhost:8080 and calls /mcp from the browser.
|
||||
app.cors-origins=http://localhost:8080
|
||||
@@ -0,0 +1 @@
|
||||
app.poisoned-item=true
|
||||
@@ -0,0 +1,2 @@
|
||||
app.unsafe-render=true
|
||||
app.poisoned-item=true
|
||||
@@ -0,0 +1,4 @@
|
||||
server.port=3001
|
||||
spring.ai.mcp.server.name=inventory-mcp-apps
|
||||
spring.ai.mcp.server.version=1.0.0
|
||||
spring.ai.mcp.server.protocol=streamable
|
||||
@@ -0,0 +1,51 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Stock board (SDK)</title>
|
||||
<style>
|
||||
body { font: 14px system-ui, sans-serif; margin: 12px; }
|
||||
li.low { color: #b3261e; }
|
||||
#status { margin-top: 8px; min-height: 1.2em; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<ul id="rows"><li>Waiting for the tool result…</li></ul>
|
||||
<button id="reload">Reload</button>
|
||||
<button id="ask">Ask the assistant</button>
|
||||
<div id="status" role="status"></div>
|
||||
<script type="module">
|
||||
// Allowed only because the resource declares https://unpkg.com in _meta.ui.csp.resourceDomains.
|
||||
import { App, applyHostStyleVariables } from "https://unpkg.com/@modelcontextprotocol/[email protected]/dist/src/app-with-deps.js";
|
||||
|
||||
const app = new App({ name: "stock-board-sdk", version: "1.0.0" }, {});
|
||||
const status = document.getElementById("status");
|
||||
|
||||
function render(result) {
|
||||
document.getElementById("rows").replaceChildren(...result.structuredContent.items.map((item) => {
|
||||
const li = document.createElement("li");
|
||||
li.className = item.stock < item.reorderAt ? "low" : "";
|
||||
li.textContent = item.sku + " " + item.name + ": " + item.stock;
|
||||
return li;
|
||||
}));
|
||||
}
|
||||
|
||||
// Register handlers before connect(), so no early notification is missed.
|
||||
app.ontoolresult = render;
|
||||
app.onhostcontextchanged = (context) => context.styles?.variables && applyHostStyleVariables(context.styles.variables);
|
||||
|
||||
document.getElementById("reload").onclick = async () => {
|
||||
render(await app.callServerTool({ name: "show_inventory_sdk", arguments: {} }));
|
||||
status.textContent = "Reloaded.";
|
||||
};
|
||||
document.getElementById("ask").onclick = async () => {
|
||||
const reply = await app.sendMessage({
|
||||
role: "user", content: [{ type: "text", text: "Which items should I reorder first?" }],
|
||||
});
|
||||
status.textContent = reply.isError ? "The host declined the message." : "Sent to the chat.";
|
||||
};
|
||||
|
||||
await app.connect();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,112 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Stock board</title>
|
||||
<style>
|
||||
body { font: 14px var(--font-sans, system-ui, sans-serif); margin: 12px;
|
||||
color: var(--color-text-primary, #1a1a1a); background: var(--color-background-primary, #fff); }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
td, th { text-align: left; padding: 4px 8px; border-bottom: 1px solid var(--color-border-primary, #ddd); }
|
||||
tr.low td { color: var(--color-text-danger, #b3261e); }
|
||||
#status { margin-top: 8px; min-height: 1.2em; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<table>
|
||||
<thead><tr><th>SKU</th><th>Item</th><th>Stock</th><th></th></tr></thead>
|
||||
<tbody id="rows"><tr><td colspan="4">Waiting for the tool result…</td></tr></tbody>
|
||||
</table>
|
||||
<div id="status" role="status"></div>
|
||||
<script>
|
||||
"use strict";
|
||||
const UNSAFE_RENDER = __UNSAFE_RENDER__; // replaced by the server; true only in the "unsafe" demo profile
|
||||
|
||||
// ---- 1. A tiny JSON-RPC over postMessage client. No library needed. ----
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
const post = (message) => window.parent.postMessage({ jsonrpc: "2.0", ...message }, "*");
|
||||
const notify = (method, params = {}) => post({ method, params });
|
||||
function request(method, params) {
|
||||
const id = nextId++;
|
||||
post({ id, method, params });
|
||||
return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
|
||||
}
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
if (event.source !== window.parent) return; // only the host may talk to us
|
||||
const msg = event.data;
|
||||
if (!msg || msg.jsonrpc !== "2.0") return;
|
||||
if (msg.method === undefined) { // a response to one of our requests
|
||||
const waiting = pending.get(msg.id);
|
||||
if (!waiting) return;
|
||||
pending.delete(msg.id);
|
||||
msg.error ? waiting.reject(new Error(msg.error.message)) : waiting.resolve(msg.result);
|
||||
} else if (msg.id !== undefined) { // a request from the host: it expects an answer
|
||||
if (msg.method === "ping" || msg.method === "ui/resource-teardown") post({ id: msg.id, result: {} });
|
||||
else post({ id: msg.id, error: { code: -32601, message: "Method not found" } });
|
||||
} else if (msg.method === "ui/notifications/tool-result") {
|
||||
render(msg.params.structuredContent);
|
||||
} else if (msg.method === "ui/notifications/host-context-changed") {
|
||||
applyContext(msg.params);
|
||||
}
|
||||
});
|
||||
|
||||
// ---- 2. Drawing. textContent, never innerHTML: the data is not trusted. ----
|
||||
function render(data) {
|
||||
const rows = document.getElementById("rows");
|
||||
rows.replaceChildren();
|
||||
for (const item of data.items) {
|
||||
const tr = rows.insertRow();
|
||||
tr.className = item.stock < item.reorderAt ? "low" : "";
|
||||
tr.dataset.sku = item.sku;
|
||||
tr.insertCell().textContent = item.sku;
|
||||
const name = tr.insertCell();
|
||||
if (UNSAFE_RENDER) name.innerHTML = item.name; else name.textContent = item.name;
|
||||
tr.insertCell().textContent = item.stock;
|
||||
const button = document.createElement("button");
|
||||
button.textContent = "+10";
|
||||
button.addEventListener("click", () => restock(item.sku, 10));
|
||||
tr.insertCell().append(button);
|
||||
}
|
||||
}
|
||||
|
||||
function applyContext(context) {
|
||||
if (context.theme) document.documentElement.style.colorScheme = context.theme;
|
||||
for (const [name, value] of Object.entries(context.styles?.variables ?? {})) {
|
||||
if (value) document.documentElement.style.setProperty(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 3. The view calls a tool, then tells the model what happened. ----
|
||||
async function restock(sku, quantity) {
|
||||
const status = document.getElementById("status");
|
||||
try {
|
||||
const result = await request("tools/call", { name: "restock_item", arguments: { sku, quantity } });
|
||||
status.textContent = result.content[0].text;
|
||||
if (result.isError) return;
|
||||
render(result.structuredContent);
|
||||
await request("ui/update-model-context", {
|
||||
content: [{ type: "text", text: "The user restocked " + sku + " by " + quantity + " from the stock board." }],
|
||||
});
|
||||
} catch (error) {
|
||||
status.textContent = "Host refused: " + error.message;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 4. Handshake: ui/initialize, then initialized. The host sends nothing before that. ----
|
||||
(async () => {
|
||||
const init = await request("ui/initialize", {
|
||||
protocolVersion: "2026-01-26",
|
||||
appInfo: { name: "stock-board", version: "1.0.0" },
|
||||
appCapabilities: { availableDisplayModes: ["inline"] },
|
||||
});
|
||||
applyContext(init.hostContext ?? {});
|
||||
notify("ui/notifications/initialized");
|
||||
new ResizeObserver(() => notify("ui/notifications/size-changed",
|
||||
{ height: Math.ceil(document.documentElement.getBoundingClientRect().height) }))
|
||||
.observe(document.documentElement);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import io.modelcontextprotocol.client.McpClient;
|
||||
import io.modelcontextprotocol.client.McpSyncClient;
|
||||
import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
|
||||
import io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;
|
||||
import io.modelcontextprotocol.spec.McpSchema.Implementation;
|
||||
import io.modelcontextprotocol.spec.McpSchema.TextContent;
|
||||
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** MCP Java SDK clients: one that says it can render MCP Apps, one that does not. */
|
||||
final class Clients {
|
||||
|
||||
static McpSyncClient connect(int port, boolean supportsUi) {
|
||||
ClientCapabilities.Builder capabilities = ClientCapabilities.builder();
|
||||
if (supportsUi) {
|
||||
capabilities.extensions(Map.of(UiMeta.EXTENSION, Map.of("mimeTypes", List.of(UiMeta.MIME_TYPE))));
|
||||
}
|
||||
McpSyncClient client = McpClient
|
||||
.sync(HttpClientStreamableHttpTransport.builder("http://localhost:" + port).endpoint("/mcp").build())
|
||||
.clientInfo(Implementation.builder(supportsUi ? "ui-client" : "text-client", "1").build())
|
||||
.capabilities(capabilities.build())
|
||||
.build();
|
||||
client.initialize();
|
||||
return client;
|
||||
}
|
||||
|
||||
static String text(CallToolResult result) {
|
||||
return ((TextContent) result.content().get(0)).text();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import io.modelcontextprotocol.client.McpSyncClient;
|
||||
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
|
||||
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
|
||||
import io.modelcontextprotocol.spec.McpSchema.ReadResourceRequest;
|
||||
import io.modelcontextprotocol.spec.McpSchema.Resource;
|
||||
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
|
||||
import io.modelcontextprotocol.spec.McpSchema.Tool;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
|
||||
import org.springframework.ai.mcp.McpToolFilter;
|
||||
import org.springframework.ai.tool.ToolCallback;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = {"spring.ai.mcp.client.enabled=false", "logging.level.root=warn"})
|
||||
@Import(ProbeResources.class)
|
||||
class McpAppsServerTest {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Autowired
|
||||
Inventory inventory;
|
||||
|
||||
@BeforeEach
|
||||
void freshStock() {
|
||||
inventory.reset();
|
||||
}
|
||||
|
||||
/** Raw HTTP, so the transcript is the wire and not a client's idea of it. */
|
||||
private String rpc(HttpClient http, String session, String body, String[] sessionOut) throws Exception {
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/mcp"))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body));
|
||||
if (session != null) {
|
||||
request.header("Mcp-Session-Id", session);
|
||||
}
|
||||
HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
|
||||
if (sessionOut != null) {
|
||||
sessionOut[0] = response.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
}
|
||||
return response.body().lines()
|
||||
.map(l -> l.startsWith("data:") ? l.substring(5) : l)
|
||||
.filter(l -> l.stripLeading().startsWith("{"))
|
||||
.findFirst().orElse("");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whatTheServerPutsOnTheWire() throws Exception {
|
||||
Transcript t = new Transcript("01-wire.txt", "Raw Streamable HTTP against the Spring AI 2.1.0 server");
|
||||
HttpClient http = HttpClient.newHttpClient();
|
||||
String[] session = new String[1];
|
||||
String init = rpc(http, null, """
|
||||
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25",
|
||||
"capabilities":{"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},
|
||||
"clientInfo":{"name":"wire","version":"1"}}}""", session);
|
||||
var initResult = Transcript.JSON.readTree(init).get("result");
|
||||
t.section("initialize: server capabilities");
|
||||
t.line(Transcript.json(initResult.get("capabilities")));
|
||||
rpc(http, session[0], "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", null);
|
||||
|
||||
var tools = Transcript.JSON.readTree(rpc(http, session[0],
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\"}", null)).get("result").get("tools");
|
||||
t.section("tools/list: name and _meta of each tool");
|
||||
tools.valueStream().sorted(Comparator.comparing(n -> n.get("name").asString()))
|
||||
.forEach(n -> t.line(n.get("name").asString() + " _meta=" + Transcript.json(n.get("_meta"))));
|
||||
|
||||
var resources = Transcript.JSON.readTree(rpc(http, session[0],
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/list\"}", null)).get("result").get("resources");
|
||||
t.section("resources/list");
|
||||
resources.valueStream().sorted(Comparator.comparing(n -> n.get("uri").asString()))
|
||||
.forEach(n -> t.line(n.get("uri").asString() + " mimeType=" + n.get("mimeType").asString()
|
||||
+ " _meta=" + Transcript.json(n.get("_meta"))));
|
||||
|
||||
var templates = Transcript.JSON.readTree(rpc(http, session[0],
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"resources/templates/list\"}", null))
|
||||
.get("result").get("resourceTemplates");
|
||||
t.section("resources/templates/list (the {theme} probe lands here)");
|
||||
templates.valueStream().forEach(n -> t.line(n.get("uriTemplate").asString()));
|
||||
|
||||
int id = 5;
|
||||
for (String uri : List.of(UiMeta.BOARD_URI, UiMeta.SDK_URI, "ui://probe/dark.html", "ui://probe/explicit.html")) {
|
||||
var content = Transcript.JSON.readTree(rpc(http, session[0], "{\"jsonrpc\":\"2.0\",\"id\":" + id++
|
||||
+ ",\"method\":\"resources/read\",\"params\":{\"uri\":\"" + uri + "\"}}", null))
|
||||
.get("result").get("contents").get(0);
|
||||
t.section("resources/read " + uri);
|
||||
t.line("mimeType=" + content.get("mimeType").asString());
|
||||
t.line("_meta=" + (content.has("_meta") ? Transcript.json(content.get("_meta")) : "(absent)"));
|
||||
t.line("text starts: " + content.get("text").asString().lines().findFirst().orElse(""));
|
||||
}
|
||||
t.write();
|
||||
|
||||
assertThat(initResult.get("capabilities").has("extensions")).isFalse();
|
||||
assertThat(tools.size()).isEqualTo(3);
|
||||
assertThat(templates.valueStream().map(n -> n.get("uriTemplate").asString())).containsExactly("ui://probe/{theme}.html");
|
||||
}
|
||||
|
||||
@Test
|
||||
void textFallbackDependsOnTheClientCapability() {
|
||||
Transcript t = new Transcript("02-capability.txt", "show_inventory seen by two MCP Java SDK clients");
|
||||
try (McpSyncClient ui = Clients.connect(port, true); McpSyncClient plain = Clients.connect(port, false)) {
|
||||
CallToolResult withUi = ui.callTool(CallToolRequest.builder("show_inventory").arguments(Map.of()).build());
|
||||
CallToolResult without = plain.callTool(CallToolRequest.builder("show_inventory").arguments(Map.of()).build());
|
||||
t.section("client that declares io.modelcontextprotocol/ui: content");
|
||||
t.line(Clients.text(withUi));
|
||||
t.section("client that does not: content");
|
||||
t.line(Clients.text(without));
|
||||
t.section("structuredContent (same for both)");
|
||||
t.line(Transcript.json(withUi.structuredContent()));
|
||||
t.write();
|
||||
|
||||
assertThat(Clients.text(withUi)).isEqualTo("2 of 3 items are below their reorder level.");
|
||||
assertThat(Clients.text(without)).contains("HB-04 USB4 hub: 0 in stock");
|
||||
assertThat(withUi.structuredContent()).isEqualTo(without.structuredContent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCallbackToolAndWhatVisibilityDoesNotDo() {
|
||||
Transcript t = new Transcript("03-callback.txt", "restock_item, the tool the view calls back into");
|
||||
try (McpSyncClient client = Clients.connect(port, false)) {
|
||||
t.section("tools/list from a client with no UI support");
|
||||
List<String> names = client.listTools().tools().stream().map(Tool::name).sorted().toList();
|
||||
t.line(names.toString());
|
||||
for (var args : List.of(Map.<String, Object>of("sku", "KB-01", "quantity", 10),
|
||||
Map.<String, Object>of("sku", "KB-01", "quantity", 500),
|
||||
Map.<String, Object>of("sku", "ZZ-00", "quantity", 1))) {
|
||||
CallToolResult r = client.callTool(CallToolRequest.builder("restock_item").arguments(args).build());
|
||||
t.section("restock_item sku=" + args.get("sku") + " quantity=" + args.get("quantity"));
|
||||
t.line("isError=" + r.isError());
|
||||
t.line(Clients.text(r));
|
||||
}
|
||||
t.write();
|
||||
assertThat(names).contains("restock_item");
|
||||
assertThat(inventory.all().get(0).stock()).isEqualTo(14);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void springAiAsTheHostGivesTheModelAppOnlyTools() {
|
||||
Transcript t = new Transcript("04-spring-ai-client.txt", "Spring AI 2.1.0 SyncMcpToolCallbackProvider as the host");
|
||||
try (McpSyncClient client = Clients.connect(port, false)) {
|
||||
ToolCallback[] all = SyncMcpToolCallbackProvider.builder().mcpClients(client).build().getToolCallbacks();
|
||||
t.section("tools offered to the model, no filter");
|
||||
t.line(names(all).toString());
|
||||
|
||||
McpToolFilter modelVisible = (connection, tool) -> VisibilityFilter.visibleToModel(tool);
|
||||
ToolCallback[] filtered = SyncMcpToolCallbackProvider.builder().mcpClients(client)
|
||||
.toolFilter(modelVisible).build().getToolCallbacks();
|
||||
t.section("tools offered to the model, with VisibilityFilter");
|
||||
t.line(names(filtered).toString());
|
||||
|
||||
ToolCallback show = java.util.Arrays.stream(filtered)
|
||||
.filter(c -> c.getToolDefinition().name().equals("show_inventory")).findFirst().orElseThrow();
|
||||
String toModel = show.call("{}");
|
||||
t.section("string that SyncMcpToolCallback hands back to the model for show_inventory");
|
||||
t.line(toModel);
|
||||
t.write();
|
||||
|
||||
assertThat(names(all)).contains("restock_item");
|
||||
assertThat(names(filtered)).containsExactly("show_inventory", "show_inventory_sdk");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> names(ToolCallback[] callbacks) {
|
||||
return java.util.Arrays.stream(callbacks).map(c -> c.getToolDefinition().name()).sorted().toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import io.modelcontextprotocol.spec.McpSchema.ReadResourceResult;
|
||||
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.ai.mcp.annotation.McpResource;
|
||||
|
||||
/** Test-only resources that answer two questions about Spring AI 2.1.0. */
|
||||
class ProbeResources {
|
||||
|
||||
/** A URI with a variable: where does it get listed? */
|
||||
@McpResource(uri = "ui://probe/{theme}.html", name = "probe_template", mimeType = UiMeta.MIME_TYPE)
|
||||
public String templated(String theme) {
|
||||
return "<!DOCTYPE html><title>" + theme + "</title>";
|
||||
}
|
||||
|
||||
/** The method builds the result itself: whose _meta wins? */
|
||||
@McpResource(uri = "ui://probe/explicit.html", name = "probe_explicit", mimeType = UiMeta.MIME_TYPE,
|
||||
metaProvider = UiMeta.BoardResource.class)
|
||||
public ReadResourceResult explicit() {
|
||||
return ReadResourceResult.builder(List.of(TextResourceContents
|
||||
.builder("ui://probe/explicit.html", "<!DOCTYPE html><title>explicit</title>")
|
||||
.mimeType(UiMeta.MIME_TYPE)
|
||||
.build())).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.ankurm.mcpapps;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import tools.jackson.databind.SerializationFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Writes output/NN-name.txt. The tests that fill a transcript assert the same facts. */
|
||||
final class Transcript {
|
||||
|
||||
static final JsonMapper JSON = JsonMapper.builder().enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).build();
|
||||
|
||||
private final StringBuilder out = new StringBuilder();
|
||||
private final String file;
|
||||
|
||||
Transcript(String file, String title) {
|
||||
this.file = file;
|
||||
out.append("# ").append(title).append('\n');
|
||||
}
|
||||
|
||||
Transcript section(String title) {
|
||||
out.append("\n## ").append(title).append('\n');
|
||||
return this;
|
||||
}
|
||||
|
||||
Transcript line(String text) {
|
||||
out.append(text).append('\n');
|
||||
return this;
|
||||
}
|
||||
|
||||
static String json(Object value) {
|
||||
return JSON.writeValueAsString(value);
|
||||
}
|
||||
|
||||
static String pretty(Object value) {
|
||||
return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(value);
|
||||
}
|
||||
|
||||
void write() {
|
||||
try {
|
||||
Path dir = Path.of(System.getProperty("user.dir"), "output");
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve(file), out.toString(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user