ui-mcp

v0.0.1-beta.11
@agentic-ui-experience/ui-mcp Checked 3 days ago Published 1 month ago

MCP server adapter for this project's A2UI integration.

MCP server adapter for this project's A2UI integration. This package does not render or ingest UI. It exposes a send_ui_to_client MCP tool and optional Catalog discovery, depending on the configured Schema delivery mode. The send tool returns validated A2UI messages as a canonical MCP EmbeddedResource. The Host extracts that resource and forwards its messages to @agentic-ui-experience/ui-runtime. MCP is one integration path for producing the project's UI Message Contract.

Summary extracted from the README.

@agentic-ui-experience/ui-mcp

MCP server adapter for this project's A2UI integration.

This package does not render or ingest UI. It exposes a send_ui_to_client MCP tool and optional Catalog discovery, depending on the configured Schema delivery mode. The send tool returns validated A2UI messages as a canonical MCP EmbeddedResource. The Host extracts that resource and forwards its messages to @agentic-ui-experience/ui-runtime.

MCP is one integration path for producing the project's UI Message Contract. The Host app still owns the Transport that forwards the result to the frontend and the Runtime still owns Surface state; this package does not choose or operate that Transport. See the project glossary.

@agentic-ui-experience/ui-mcp is an MCP adapter over @agentic-ui-experience/ui-core/tool-mode. Catalog configuration, catalog resource payloads, catalog filtering, and send_ui_to_client normalization live in ui-core; this package only maps those provider-neutral operations onto MCP resources and tools.

Generated tool and Catalog instructions require A2UI v0.9.1, and incoming messages accept only v0.9.1; legacy v0.9 wire messages are rejected. This wire version negotiates through the official A2UI "v0.9" capability family; the family key is not a second accepted message version. Dynamic A2UI tool results use only the canonical application/a2ui+json media type; the client helper deliberately does not recognize the legacy application/json+a2ui media type.

A server serves exactly one catalog. A2UI fixes a surface's catalog at createSurface time and never composes two catalogs into one component tree, and the upstream agent SDK selects a single catalog before it prompts the model, so the catalog is a server configuration rather than a model choice. To serve more than one vocabulary, merge them when you define the catalog. Omit catalog to serve this repository's Basic Catalog compatibility unit. Its ID, Core schema, and installed Renderer vocabulary move together; this package does not claim that local unit is interchangeable with a newer upstream Catalog that happens to have a different identity.

import { createUIMCPServer } from "@agentic-ui-experience/ui-mcp";

const server = createUIMCPServer({
  catalog: weatherPromptDescriptor
});

await server.connect(transport);

Schema delivery

Choose how the Agent obtains the generation Schema when creating or starting the server, not in individual tool-call arguments:

schemaDelivery Tools registered Where the model gets component definitions
"discovery" (default) get_ui_catalog, send_ui_to_client Structured JSON Schema in selected get_ui_catalog results, loaded on demand.
"inline" send_ui_to_client only The complete Catalog-bound inputSchema returned by tools/list.
const server = createUIMCPServer({
  catalog: weatherPromptDescriptor,
  schemaDelivery: "inline"
});
ax-ui-mcp --transport stdio --catalog ./weather-catalog.js --schema-delivery inline

In inline mode, the Agent Host supplies the send tool definition to the model. The Schema is in tools/list → send_ui_to_client.inputSchema, not copied into the description and not passed as a schema argument. The model generates tools/call.arguments: { messages, surfaceId? } from those definitions. Neither get_ui_catalog nor a resource read is a prerequisite. The a2ui://catalog resource remains available in both modes with complete Host-facing metadata.

The inline Schema contains the configured Basic and Custom components, all Basic catalog functions, and the fixed Catalog ID. The description retains generation rules, style guidance, and examples. Use inline when the Agent Host can supply the complete JSON Schema, including local $ref definitions, to the model; use discovery when definitions should be loaded on demand.

schemaDelivery changes when the Schema is delivered, not its constraints. Basic definitions always use structured JSON Schema; there is no separate instruction-format option. Invalid delivery values are errors. This is a project choice, not a requirement shared by every official sample; see the pinned upstream comparison.

Inline uses Core's createUISendToolSpec(), not a second execution path. Both modes share capability checks, normalization, strict carrier validation, and the EmbeddedResource output described below.

Custom Schema scope: ordinary props schemas with type: "object" and compatible nested objects, arrays, unions, and local references are supported, as are boolean true/false schemas. Source $schema must be omitted or be http://json-schema.org/draft-07/schema#. Protocol-common fields id/component/accessibility/weight must not be declared in props. Complex root constraints or root references, IDs/anchors/external references, references back to the augmented props root, incompatible dialect keywords (such as Draft 7 tuple items or dependencies), validation siblings of $ref, and duplicate component names produce a targeted error recommending discovery. The full Core boundary is intentionally conservative; discovery and normalizer support are unchanged.

Project A2UI-over-MCP contract

send_ui_to_client transports A2UI messages, while get_ui_catalog is this project's discovery contract; it is not an official A2UI-over-MCP tool.

A successful send_ui_to_client call always returns fallback text followed by one canonical A2UI embedded resource:

{
  content: [
    {
      type: "text",
      text: "Generated an interactive A2UI interface."
    },
    {
      type: "resource",
      resource: {
        uri: "a2ui://surface/main",
        mimeType: "application/a2ui+json",
        text: "[{\"version\":\"v0.9.1\",...}]"
      }
    }
  ]
}

The send tool has no output schema and successful calls do not duplicate the payload in structuredContent. A failed call contains isError: true and text only, never a resource. The emitted a2ui://surface/<encoded-surface-id> URI is a stable provider identifier for the embedded payload; it is not a registered readable resource and clients must not treat that path shape as a protocol requirement.

A custom normalizer must return JSON-semantically equivalent uiJson and uiMessages values. The server verifies this invariant, then strictly validates the parsed carrier against its configured Catalog and the call's optional surfaceId, before it uses the original uiJson as resource text or derives the resource URI. Whitespace and object-key order may differ; malformed, divergent, or protocol-invalid representations become tool errors.

A successful get_ui_catalog call exposes its complete logical result through both MCP result channels. The text content item's text is the JSON serialization of that result, and structuredContent contains the same full logical object. Neither representation is a reduced schema-only projection.

Catalog capability negotiation

Before accepting UI, the server requires the client to advertise the exact configured Catalog ID at:

{
  clientCapabilities: {
    "v0.9": {
      supportedCatalogIds: [catalogId]
    }
  }
}

Use the browser-safe @agentic-ui-experience/ui-mcp/client entry point to build the declaration:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import {
  createA2UIClientCapabilities
} from "@agentic-ui-experience/ui-mcp/client";

const capabilities = createA2UIClientCapabilities([catalogId]);
const client = new Client(
  { name: "my-a2ui-host", version: "1.0.0" },
  { capabilities }
);

The builder includes the official initialize-time capabilities.a2ui shape and an extensions["a2ui/client-capabilities"] mirror for MCP SDK versions that strip unknown top-level Client capabilities. A stateful server prefers the official field when available and then checks this bridge.

A stateless client must repeat the declaration on every UI tool call because no initialize state survives between requests:

await client.callTool({
  name: "send_ui_to_client",
  arguments: { messages },
  _meta: { a2ui: capabilities.a2ui }
});

Request-local _meta.a2ui takes precedence over initialized state. If it is present but malformed or does not list the server's exact Catalog ID, the call fails without running normalization.

Browser-safe result extraction

The same client entry point strictly extracts canonical A2UI resources without importing MCP server or Node-only code:

import {
  extractUIMCPToolResult
} from "@agentic-ui-experience/ui-mcp/client";

const extracted = extractUIMCPToolResult(toolResult);
if (extracted) {
  runtime.ingest(extracted.uiMessages);
}

The extractor accepts any valid absolute provider URI, including a2ui://recipe-card and a2ui://surface/main. It validates the embedded JSON, protocol messages, and Catalog. Tool errors and malformed or ambiguous canonical resources throw; an ordinary non-A2UI result returns undefined. It does not fall back to old structuredContent, legacy MIME, or binary resource blobs.

CLI

@agentic-ui-experience/ui-mcp also ships a small MCP server CLI:

ax-ui-mcp --transport stdio

From this monorepo, build the package once and use the package scripts:

pnpm --filter @agentic-ui-experience/ui-mcp build
pnpm --filter @agentic-ui-experience/ui-mcp start:stdio

For Streamable HTTP MCP:

ax-ui-mcp \
  --transport http \
  --host 127.0.0.1 \
  --port 3001 \
  --endpoint /mcp

The same HTTP defaults are available as:

pnpm --filter @agentic-ui-experience/ui-mcp start:http

To inspect the stdio MCP server with MCP Inspector:

pnpm --filter @agentic-ui-experience/ui-mcp inspector

The HTTP server is stateless: each MCP request gets a fresh MCP server and StreamableHTTPServerTransport. This matches the SDK's stateless Streamable HTTP mode and avoids storing session state inside @agentic-ui-experience/ui-mcp. Consequently every send_ui_to_client request must include _meta.a2ui; an initialize declaration alone cannot authorize a later request on this server.

CORS is closed by default. To expose the HTTP endpoint to browser clients, pass one or more explicit origins:

ax-ui-mcp --transport http --cors-origin http://localhost:5175

For local development only, --cors-origin "*" returns:

Access-Control-Allow-Origin: *

The local-development wildcard CORS shortcut is:

pnpm --filter @agentic-ui-experience/ui-mcp start:http:cors

A custom catalog can be loaded from an ESM module:

ax-ui-mcp \
  --transport http \
  --catalog ./weather-catalog.js

The CLI generates v0.9.1 instructions and accepts only --protocol-version v0.9.1. Passing legacy v0.9 is an error.

With the package scripts, append extra CLI flags after --:

pnpm --filter @agentic-ui-experience/ui-mcp start:http -- \
  --catalog ./weather-catalog.js

The catalog module may export a descriptor directly or as catalog:

export const catalog = {
  id: "example/weather/v1",
  baseComponentNames: ["Card", "Text"],
  customComponents: []
};

Agent workflow

The default discovery flow is:

// Step 1a: discover the catalog. With no componentNames, catalog.kind is
// "directory", componentPurposes is complete, and component definitions
// are absent.
get_ui_catalog();

// Step 1b: request a "selection". Structured JSON Schema is placed under
// catalog.definitions, including its shared $defs reference context.
// Request function definitions only for functions the UI calls.
get_ui_catalog({
  componentNames: ["Card", "Text", "WeatherIcon"],
  functionNames: ["formatDate"]
});

// Step 2: submit messages built from the catalog returned by get_ui_catalog.
send_ui_to_client({
  surfaceId: "main",
  messages: [
    { version: "v0.9.1", createSurface: { surfaceId: "main", catalogId: "com.agentic-ui-experience.examples.weather.v1" } },
    { version: "v0.9.1", updateComponents: { surfaceId: "main", components: [{ id: "root", component: "Text", text: "Current weather" }] } }
  ]
});

The MCP client, not the model-visible arguments above, supplies the negotiated A2UI capability through initialize state or request _meta.

Neither tool takes a catalogId. The server pins the catalog, so there is nothing for the model to choose; createSurface.catalogId is validated against the configured catalog. Once the Host forwards these messages to its Runtime, a surfaceId must be unique among active surfaces: a duplicate active createSurface is an error, while an ID may be reused after deleteSurface.

componentNames selects the result variant. When omitted, catalog.kind is "directory" and the result contains the complete componentPurposes map. It contains no component definitions; if functionNames is explicitly supplied, catalog.definitions contains the requested functions and their shared reference context. Component purposes and lightweight function discovery are retained.

When componentNames is present, catalog.kind is "selection". It omits componentPurposes and does not expose a model-facing descriptor. catalog.definitions contains componentNames, functionNames, $defs, optional basicComponents, and customComponents / functions maps. basicComponents always uses { format: "json-schema", schema: object }.

Generated Basic and function $ref values resolve from the entire catalog.definitions object, not from the internal Basic Schema:

  • Basic component bodies occur only in basicComponents.schema.components.
  • Function bodies occur only in functions; the shared anyFunction selector points to the requested #/functions/<name> entries.
  • $defs.common carries the Common types document, and $defs.catalog.$defs carries Catalog shared definitions. The internal Basic Schema has no duplicate $defs or functions and is not independently self-contained.
  • Custom props schemas remain unchanged, with local references resolved from each Custom schema's own document root. Inline's Custom projection limits do not apply to these raw discovery schemas.

Function definitions remain opt-in through functionNames and are independent of component selection. Omitting functionNames returns no function definitions. Function-only queries, Custom-only selections with functions, and empty function selections use the same shared context.

instructions refers to catalog.definitions and does not contain JSON Schema dumps. MCP text and structuredContent carry the same logical bundle; delivery selection does not change validation constraints.

send_ui_to_client accepts structured messages. Do not pass ui_json, do not serialize the message list into a JSON string, and do not pass static catalog schema such as customComponents in the tool call.

In discovery mode, send_ui_to_client is the final submission tool, not the schema source: call get_ui_catalog first and build components from catalog.definitions. In inline mode, build the same arguments directly from the send tool's inputSchema; no get tool is registered.

The catalog is also exposed as an MCP resource with media type application/json. This remains JSON catalog metadata, not an A2UI message, so the A2UI message media types do not apply. Resources are read by Hosts and clients rather than selected from by a model, so this payload remains complete Host-facing metadata: it carries every component, every function, and the full descriptor, including styleGuide and examples:

a2ui://catalog