diff --git a/README.md b/README.md index 203a2bd..c878ea8 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ facts, so the build fails when a claim stops being true. | `log-anomaly` | AI Log Anomaly Detection for Spring Boot: Embeddings and Clustering | a parser for Spring Boot's own log layout, template mining, an `Embedder` seam (offline hashing or any `/v1/embeddings` endpoint), k-means over normal templates, a novel-template detector and a rate-spike detector with their measured blind spots, incidents, and a summary prompt that is 0.4% of the raw window; tested on seeded synthetic logs and on a log file Spring Boot 4.2.0 wrote itself | | `classic-ml-vs-llm` | Text Classification in Java Without an LLM: Tribuo vs Smile vs a Zero-Shot LLM | 3000 seeded synthetic support tickets in five categories; Tribuo and Smile logistic regression and Smile naive Bayes against a majority baseline, with accuracy, macro-F1, latency and model size; skewed classes, train/test duplicates, vocabulary drift and the three different answers to a ticket of unseen words; a zero-shot LLM client tested against a fake endpoint (no model was called) and a cost formula with assumed prices | | `pr-reviewer` | Build an AI Pull Request Reviewer in Java: Spring AI, Gitea Webhooks and Inline Comments | signed webhooks, hunk-aware chunking, Spring AI structured output, a quote-based guard against wrong line numbers, de-duplication across pushes and cleanup of Gitea's leftover pending reviews; tested against a real Gitea 1.27.3 in Docker, with a scripted model and two small local models; computed cost estimates | +| `mcp-apps` | MCP Apps in Java: Serve Interactive HTML UIs from a Spring AI MCP Server | `ui://` HTML resources linked to tools through `MetaProvider`, a view that calls an app-only tool back, CSP declarations, script injection through tool data, MCP Java SDK client tests, a Playwright harness on the official `AppBridge` and a run against the ext-apps basic-host; no production host and no model involved | ## Versions (verified on Maven Central, 2026-10-11) @@ -52,6 +53,7 @@ facts, so the build fails when a claim stops being true. | Spring Boot (`log-anomaly`) | 4.2.0 | verified on Maven Central 2026-12-01; `log-anomaly` only. No Spring AI and no model download: the embedder and the summariser are seams, tested offline | | Tribuo `tribuo-classification-sgd` / Smile `smile-core` | 4.3.2 / 7.3.0 | verified on Maven Central 2026-12-01; `classic-ml-vs-llm` only. Tribuo is Apache-2.0 and Java 8 bytecode; Smile 7.3.0 is GPL-3.0-or-later or a commercial licence, and its bytecode needs Java 25 | | Spring Boot / Spring AI (`pr-reviewer`) | 4.2.0 / 2.1.0 | verified on Maven Central 2026-12-03; `pr-reviewer` only; live tests need Docker with Gitea 1.27.3 | +| Spring Boot / Spring AI / MCP Java SDK / `@modelcontextprotocol/ext-apps` (`mcp-apps`) | 4.2.0 / 2.1.0 / 2.2.0 / 2.0.4 | verified on Maven Central and npm 2026-12-05; `mcp-apps` only. The browser harness needs Node 20+ and Chromium | | JDK | 25 LTS | | | JUnit | 6.1.3 | | diff --git a/mcp-apps/README.md b/mcp-apps/README.md new file mode 100644 index 0000000..c8d7092 --- /dev/null +++ b/mcp-apps/README.md @@ -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. diff --git a/mcp-apps/harness/.gitignore b/mcp-apps/harness/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/mcp-apps/harness/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/mcp-apps/harness/basic-host.mjs b/mcp-apps/harness/basic-host.mjs new file mode 100644 index 0000000..6bf6231 --- /dev/null +++ b/mcp-apps/harness/basic-host.mjs @@ -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(); diff --git a/mcp-apps/harness/csp.mjs b/mcp-apps/harness/csp.mjs new file mode 100644 index 0000000..6b0dc1f --- /dev/null +++ b/mcp-apps/harness/csp.mjs @@ -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("; "); +} diff --git a/mcp-apps/harness/host.html b/mcp-apps/harness/host.html new file mode 100644 index 0000000..d18da64 --- /dev/null +++ b/mcp-apps/harness/host.html @@ -0,0 +1 @@ +harness host diff --git a/mcp-apps/harness/host.js b/mcp-apps/harness/host.js new file mode 100644 index 0000000..db0db22 --- /dev/null +++ b/mcp-apps/harness/host.js @@ -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 ?? {})); +}; diff --git a/mcp-apps/harness/package-lock.json b/mcp-apps/harness/package-lock.json new file mode 100644 index 0000000..ae863c4 --- /dev/null +++ b/mcp-apps/harness/package-lock.json @@ -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" + } + } + } +} diff --git a/mcp-apps/harness/package.json b/mcp-apps/harness/package.json new file mode 100644 index 0000000..89036a1 --- /dev/null +++ b/mcp-apps/harness/package.json @@ -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" } +} diff --git a/mcp-apps/harness/probes.js b/mcp-apps/harness/probes.js new file mode 100644 index 0000000..80e1911 --- /dev/null +++ b/mcp-apps/harness/probes.js @@ -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; +})(); diff --git a/mcp-apps/harness/run.mjs b/mcp-apps/harness/run.mjs new file mode 100644 index 0000000..d9f3c59 --- /dev/null +++ b/mcp-apps/harness/run.mjs @@ -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 , 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(); +} diff --git a/mcp-apps/harness/sandbox.html b/mcp-apps/harness/sandbox.html new file mode 100644 index 0000000..516f660 --- /dev/null +++ b/mcp-apps/harness/sandbox.html @@ -0,0 +1,25 @@ + + +sandbox proxy + + + diff --git a/mcp-apps/output/01-wire.txt b/mcp-apps/output/01-wire.txt new file mode 100644 index 0000000..789fe62 --- /dev/null +++ b/mcp-apps/output/01-wire.txt @@ -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: + +## resources/read ui://inventory/board-sdk.html +mimeType=text/html;profile=mcp-app +_meta={"ui":{"prefersBorder":true,"csp":{"resourceDomains":["https://unpkg.com"]}}} +text starts: + +## resources/read ui://probe/dark.html +mimeType=text/html;profile=mcp-app +_meta=(absent) +text starts: dark + +## resources/read ui://probe/explicit.html +mimeType=text/html;profile=mcp-app +_meta=(absent) +text starts: explicit diff --git a/mcp-apps/output/02-capability.txt b/mcp-apps/output/02-capability.txt new file mode 100644 index 0000000..483d09b --- /dev/null +++ b/mcp-apps/output/02-capability.txt @@ -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}]} diff --git a/mcp-apps/output/03-callback.txt b/mcp-apps/output/03-callback.txt new file mode 100644 index 0000000..d39fd24 --- /dev/null +++ b/mcp-apps/output/03-callback.txt @@ -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 diff --git a/mcp-apps/output/04-spring-ai-client.txt b/mcp-apps/output/04-spring-ai-client.txt new file mode 100644 index 0000000..7af8faf --- /dev/null +++ b/mcp-apps/output/04-spring-ai-client.txt @@ -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"}] diff --git a/mcp-apps/output/05-browser-board.txt b/mcp-apps/output/05-browser-board.txt new file mode 100644 index 0000000..274f5fe --- /dev/null +++ b/mcp-apps/output/05-browser-board.txt @@ -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 diff --git a/mcp-apps/output/06-browser-csp.txt b/mcp-apps/output/06-browser-csp.txt new file mode 100644 index 0000000..0d31725 --- /dev/null +++ b/mcp-apps/output/06-browser-csp.txt @@ -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/ext-apps@2.0.4/dist/src/app-with-deps.js' violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline'". diff --git a/mcp-apps/output/07-browser-injection.txt b/mcp-apps/output/07-browser-injection.txt new file mode 100644 index 0000000..da22d90 --- /dev/null +++ b/mcp-apps/output/07-browser-injection.txt @@ -0,0 +1,15 @@ +# A product name carrying , rendered two ways + +## textContent (the shipped view) +CB-99 row text: Cable > 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 metaProvider(); +org.springframework.ai.mcp.annotation.McpIcon[] icons(); +org.springframework.ai.mcp.annotation.McpClientCapability[] requiredCapabilities(); diff --git a/mcp-apps/output/basic-host.png b/mcp-apps/output/basic-host.png new file mode 100644 index 0000000..d78a4e7 Binary files /dev/null and b/mcp-apps/output/basic-host.png differ diff --git a/mcp-apps/output/board-sdk.png b/mcp-apps/output/board-sdk.png new file mode 100644 index 0000000..735d659 Binary files /dev/null and b/mcp-apps/output/board-sdk.png differ diff --git a/mcp-apps/output/board.png b/mcp-apps/output/board.png new file mode 100644 index 0000000..8e21f49 Binary files /dev/null and b/mcp-apps/output/board.png differ diff --git a/mcp-apps/pom.xml b/mcp-apps/pom.xml new file mode 100644 index 0000000..a537705 --- /dev/null +++ b/mcp-apps/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + + com.ankurm.agents + java-ai-agents + 1.0.0 + + + mcp-apps + MCP Apps: interactive HTML UIs from a Spring AI MCP server + + + + 4.2.0 + 2.1.0 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.ai + spring-ai-starter-mcp-server-webmvc + + + org.springframework.ai + spring-ai-starter-mcp-client + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + mcp-apps + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + repackage + + + + + + diff --git a/mcp-apps/scripts/basic-host.sh b/mcp-apps/scripts/basic-host.sh new file mode 100755 index 0000000..26bda21 --- /dev/null +++ b/mcp-apps/scripts/basic-host.sh @@ -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 diff --git a/mcp-apps/scripts/jar-search.sh b/mcp-apps/scripts/jar-search.sh new file mode 100755 index 0000000..67d0a9a --- /dev/null +++ b/mcp-apps/scripts/jar-search.sh @@ -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" diff --git a/mcp-apps/scripts/run-all.sh b/mcp-apps/scripts/run-all.sh new file mode 100755 index 0000000..1b39baa --- /dev/null +++ b/mcp-apps/scripts/run-all.sh @@ -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 diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/CorsConfig.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/CorsConfig.java new file mode 100644 index 0000000..b1a2064 --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/CorsConfig.java @@ -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 origins; + + public CorsConfig(@Value("${app.cors-origins:}") List 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"); + } + } +} diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/Inventory.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/Inventory.java new file mode 100644 index 0000000..8357281 --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/Inventory.java @@ -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 "; + + private final Map 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 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; + } +} diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/InventoryTools.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/InventoryTools.java new file mode 100644 index 0000000..f5ed457 --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/InventoryTools.java @@ -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 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 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 snapshot() { + return Map.of("items", inventory.all()); + } +} diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/McpAppsApplication.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/McpAppsApplication.java new file mode 100644 index 0000000..26c7806 --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/McpAppsApplication.java @@ -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); + } +} diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/UiMeta.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/UiMeta.java new file mode 100644 index 0000000..7518661 --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/UiMeta.java @@ -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 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 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 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 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 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 getMeta() { + return Map.of("ui", Map.of("csp", Map.of("resourceDomains", List.of(CDN)), "prefersBorder", true)); + } + } +} diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/UiResources.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/UiResources.java new file mode 100644 index 0000000..9382bf7 --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/UiResources.java @@ -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); + } +} diff --git a/mcp-apps/src/main/java/com/ankurm/mcpapps/VisibilityFilter.java b/mcp-apps/src/main/java/com/ankurm/mcpapps/VisibilityFilter.java new file mode 100644 index 0000000..0bf443b --- /dev/null +++ b/mcp-apps/src/main/java/com/ankurm/mcpapps/VisibilityFilter.java @@ -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"); + } +} diff --git a/mcp-apps/src/main/resources/application-browserhost.properties b/mcp-apps/src/main/resources/application-browserhost.properties new file mode 100644 index 0000000..8755d9b --- /dev/null +++ b/mcp-apps/src/main/resources/application-browserhost.properties @@ -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 diff --git a/mcp-apps/src/main/resources/application-poisoned.properties b/mcp-apps/src/main/resources/application-poisoned.properties new file mode 100644 index 0000000..9d3525a --- /dev/null +++ b/mcp-apps/src/main/resources/application-poisoned.properties @@ -0,0 +1 @@ +app.poisoned-item=true diff --git a/mcp-apps/src/main/resources/application-unsafe.properties b/mcp-apps/src/main/resources/application-unsafe.properties new file mode 100644 index 0000000..b0f0066 --- /dev/null +++ b/mcp-apps/src/main/resources/application-unsafe.properties @@ -0,0 +1,2 @@ +app.unsafe-render=true +app.poisoned-item=true diff --git a/mcp-apps/src/main/resources/application.properties b/mcp-apps/src/main/resources/application.properties new file mode 100644 index 0000000..1ebf0bc --- /dev/null +++ b/mcp-apps/src/main/resources/application.properties @@ -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 diff --git a/mcp-apps/src/main/resources/ui/board-sdk.html b/mcp-apps/src/main/resources/ui/board-sdk.html new file mode 100644 index 0000000..a5f738c --- /dev/null +++ b/mcp-apps/src/main/resources/ui/board-sdk.html @@ -0,0 +1,51 @@ + + + + +Stock board (SDK) + + + +
  • Waiting for the tool result…
+ + +
+ + + diff --git a/mcp-apps/src/main/resources/ui/board.html b/mcp-apps/src/main/resources/ui/board.html new file mode 100644 index 0000000..8e0a50e --- /dev/null +++ b/mcp-apps/src/main/resources/ui/board.html @@ -0,0 +1,112 @@ + + + + +Stock board + + + + + + +
SKUItemStock
Waiting for the tool result…
+
+ + + diff --git a/mcp-apps/src/test/java/com/ankurm/mcpapps/Clients.java b/mcp-apps/src/test/java/com/ankurm/mcpapps/Clients.java new file mode 100644 index 0000000..e781d8a --- /dev/null +++ b/mcp-apps/src/test/java/com/ankurm/mcpapps/Clients.java @@ -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(); + } +} diff --git a/mcp-apps/src/test/java/com/ankurm/mcpapps/McpAppsServerTest.java b/mcp-apps/src/test/java/com/ankurm/mcpapps/McpAppsServerTest.java new file mode 100644 index 0000000..a3e36f8 --- /dev/null +++ b/mcp-apps/src/test/java/com/ankurm/mcpapps/McpAppsServerTest.java @@ -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 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 names = client.listTools().tools().stream().map(Tool::name).sorted().toList(); + t.line(names.toString()); + for (var args : List.of(Map.of("sku", "KB-01", "quantity", 10), + Map.of("sku", "KB-01", "quantity", 500), + Map.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 names(ToolCallback[] callbacks) { + return java.util.Arrays.stream(callbacks).map(c -> c.getToolDefinition().name()).sorted().toList(); + } +} diff --git a/mcp-apps/src/test/java/com/ankurm/mcpapps/ProbeResources.java b/mcp-apps/src/test/java/com/ankurm/mcpapps/ProbeResources.java new file mode 100644 index 0000000..eeab351 --- /dev/null +++ b/mcp-apps/src/test/java/com/ankurm/mcpapps/ProbeResources.java @@ -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 "" + theme + ""; + } + + /** 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", "explicit") + .mimeType(UiMeta.MIME_TYPE) + .build())).build(); + } +} diff --git a/mcp-apps/src/test/java/com/ankurm/mcpapps/Transcript.java b/mcp-apps/src/test/java/com/ankurm/mcpapps/Transcript.java new file mode 100644 index 0000000..bd12e8c --- /dev/null +++ b/mcp-apps/src/test/java/com/ankurm/mcpapps/Transcript.java @@ -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); + } + } +} diff --git a/pom.xml b/pom.xml index cea85e1..331f5fa 100644 --- a/pom.xml +++ b/pom.xml @@ -27,6 +27,7 @@ log-anomaly classic-ml-vs-llm pr-reviewer + mcp-apps