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,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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user