@mayflowergmbh/ag-ui-mcp-apps-middleware
v0.0.8-mayflower.0
Published
AG-UI middleware that exposes UI-enabled tools from MCP (Model Context Protocol) servers. Discovers MCP Apps tools, forwards progress notifications, executes tool calls in parallel, and emits AG-UI activity snapshots for frontend rendering.
Maintainers
Readme
@mayflowergmbh/ag-ui-mcp-apps-middleware
MCP Apps middleware for AG-UI that enables UI-enabled tools from MCP (Model Context Protocol) servers.
Installation
npm install @mayflowergmbh/ag-ui-mcp-apps-middleware
# or
pnpm add @mayflowergmbh/ag-ui-mcp-apps-middlewareIf you want to preserve an existing @ag-ui/mcp-apps-middleware import path in a
consumer app, install it via an npm alias:
pnpm add @ag-ui/mcp-apps-middleware@npm:@mayflowergmbh/ag-ui-mcp-apps-middlewareUsage
import { MCPAppsMiddleware } from "@mayflowergmbh/ag-ui-mcp-apps-middleware";
const agent = new YourAgent().use(
new MCPAppsMiddleware({
mcpServers: [
{
type: "http",
url: "http://localhost:3001/mcp",
serverId: "weather-server",
headers: { Authorization: "Bearer ..." },
},
],
}),
);Features
- Discovers UI-enabled tools from MCP servers
- Supports the preferred nested MCP Apps metadata shape (
_meta.ui.resourceUri) - Keeps deprecated flat metadata (
_meta["ui/resourceUri"]) working for compatibility - Advertises both canonical and legacy MCP Apps HTML MIME types
- Injects tools into the agent's tool list
- Prefers result-scoped
structuredContent.resourceUrivalues when a tool returns one - Executes pending UI tool calls in parallel and reuses one MCP client per server for the batch
- Forwards MCP
notifications/progressto AG-UI as incrementalACTIVITY_SNAPSHOTevents - Supports proxied MCP requests for frontend resource fetching (
tools/call,tools/list,resources/read,resources/list,resources/templates/list,prompts/list,prompts/get,notifications/message,ping) - Pluggable logger so transport / tool-execution failures route through the host's logging stack
- Warns on tool name collisions across configured MCP servers
- Optional per-server passthrough mode (
includeToolsWithoutResource) for treating an MCP server as a general tool catalog source rather than a SEP-1865 UI-only source
Configuration
interface MCPAppsMiddlewareConfig {
mcpServers?: MCPClientConfig[];
/** Optional logger; defaults to a console-based logger. */
logger?: Logger;
}
type MCPClientConfig =
| {
type: "http";
url: string;
headers?: Record<string, string>;
serverId?: string;
/** Skip the final ACTIVITY_SNAPSHOT emit. Default: true. */
emitActivity?: boolean;
/** Inject tools without `_meta.ui.resourceUri`. Default: false. */
includeToolsWithoutResource?: boolean;
}
| {
type: "sse";
url: string;
headers?: Record<string, string>;
serverId?: string;
emitActivity?: boolean;
includeToolsWithoutResource?: boolean;
};
interface Logger {
warn: (message: string, context?: Record<string, unknown>) => void;
error: (
message: string,
error?: unknown,
context?: Record<string, unknown>,
) => void;
info?: (message: string, context?: Record<string, unknown>) => void;
debug?: (message: string, context?: Record<string, unknown>) => void;
}emitActivity
Set emitActivity: false for a server when the frontend renders the widget directly from the tool-call args (e.g. via a dedicated tool-call renderer). The middleware will still execute the tool call and emit TOOL_CALL_RESULT, but skip the final ACTIVITY_SNAPSHOT so the widget is not double-mounted.
includeToolsWithoutResource
By default the middleware acts as a SEP-1865 UI-tool source: it filters the
server's tools/list to only those that carry a _meta.ui.resourceUri (or the
deprecated flat _meta["ui/resourceUri"]). Set
includeToolsWithoutResource: true to instead treat the server as a general
tool catalog source — tools without that metadata are also injected into the
agent's tool list. The middleware still executes those tool calls normally and
emits TOOL_CALL_RESULT; the final ACTIVITY_SNAPSHOT is suppressed for tools
that have no resourceUri at all (neither tool-linked nor result-scoped via
structuredContent.resourceUri), since the snapshot has no URI to advertise.
This is the right setting when the host renders a tool's result via a frontend
tool-call renderer (reading the streamed args) rather than via the MCP Apps
activity surface.
Logger
Pass a logger to route warnings (tool name collisions) and errors (transport / tool-execution failures) through your own logging stack. When omitted, the middleware falls back to console.warn / console.error.
new MCPAppsMiddleware({
mcpServers: [...],
logger: {
warn: (msg, ctx) => log.warn({ msg, ...ctx }),
error: (msg, err, ctx) => log.error({ msg, err, ...ctx }),
},
});Tool name collisions
If two configured servers expose a tool with the same name, the last one loaded wins. The middleware warns through the logger with both server hashes and IDs so the host can disambiguate. To avoid collisions, set distinct serverIds and either expose unique tool names server-side or namespace your tools.
Tool Metadata
MCP Apps tools are discovered through tool metadata that links a tool to a predeclared ui:// resource.
Preferred metadata shape:
_meta: {
ui: {
resourceUri: "ui://weather/forecast";
}
}Deprecated but still supported for compatibility:
_meta: {
"ui/resourceUri": "ui://weather/forecast"
}If both are present, the nested _meta.ui.resourceUri value takes precedence.
MIME Types
The middleware advertises support for both:
- Canonical MCP Apps MIME type:
text/html;profile=mcp-app - Legacy compatibility MIME type:
text/html+mcp
Server ID
The optional serverId field provides a stable identifier for the server. This is useful when:
- Server URLs may change (e.g., different environments)
- You want human-readable server identification
- Frontend code needs to reference servers by name
If serverId is not provided, the server is identified by an MD5 hash of its configuration.
Activity Snapshot
The middleware emits activity snapshots with the following structure:
{
type: "ACTIVITY_SNAPSHOT",
activityType: "mcp-apps",
content: {
result: MCPToolCallResult, // Result from the tool execution
resourceUri: string, // URI of the UI resource to fetch
serverHash: string, // MD5 hash of server config
serverId?: string, // Server ID (if configured)
toolInput: Record<string, unknown> // Arguments passed to the tool
},
replace: true
}The frontend should fetch the resource content via proxied MCP request using resourceUri and either serverHash or serverId.
resourceUri resolution order is:
result.structuredContent.resourceUriwhen the tool returns a validui://URI- the tool-linked metadata resource URI from
_meta.ui.resourceUrior_meta["ui/resourceUri"]
This lets tools point the activity snapshot at a concrete UI instance while preserving the metadata-linked resource as the default fallback.
Streaming Progress
While a UI tool call is executing, the middleware forwards MCP notifications/progress to the frontend using AG-UI's canonical streaming pattern: one ACTIVITY_SNAPSHOT per tool call followed by ACTIVITY_DELTA events carrying RFC 6902 JSON Patches. The snapshot's messageId is stable per tool call (mcp-apps-progress:<toolCallId>), so the AG-UI default apply path produces a single live-updating activity message even with multiple concurrent tool calls.
On the first progress tick:
{
type: "ACTIVITY_SNAPSHOT",
messageId: `mcp-apps-progress:${toolCallId}`,
activityType: "mcp-apps-progress",
content: {
progress: number, // Per MCP spec, monotonically increasing
total?: number, // Only present if the MCP server provided it
message?: string, // Human-readable progress (per MCP spec)
toolCallId: string,
toolName: string,
serverHash: string,
serverId?: string
},
replace: false // Idempotent: re-emits are dropped by the apply path
}On every subsequent tick:
{
type: "ACTIVITY_DELTA",
messageId: `mcp-apps-progress:${toolCallId}`,
activityType: "mcp-apps-progress",
patch: [
{ op: "replace", path: "/progress", value: 0.75 },
{ op: "add", path: "/message", value: "almost done" }, // example
// ...only changed fields are included
]
}The middleware uses add / remove ops when an optional total or message field appears or disappears across ticks, and replace for value changes on existing fields. The stable toolCallId, toolName, serverHash, and serverId are not re-emitted on deltas.
Import the constant on the consumer side to filter for these events:
import { MCPAppsProgressActivityType } from "@mayflowergmbh/ag-ui-mcp-apps-middleware";A final mcp-apps snapshot (with replace: true, on a different messageId) is emitted after the tool call completes, unless the server was configured with emitActivity: false.
mcp-apps-progressis a middleware-private extension. It is not part of SEP-1865 and is not consumed by CopilotKit's stockMCPAppsActivityRenderer. Hosts that want to surface a progress indicator must render themcp-apps-progressactivity type themselves.
Performance and Concurrency
- Pending UI tool calls are executed in parallel via
Promise.all. Independent RPCs no longer block on each other. - A run-scoped MCP client cache reuses a single client per server across all of that run's tool calls — one connect/close per (server, run) instead of one per call.
- Tool discovery (
fetchUITools) queries all configured servers in parallel; a failure on one server is logged through the configured logger but does not block the others.
Proxied MCP Requests
The middleware supports proxied MCP requests from the frontend. Pass a ProxiedMCPRequest in forwardedProps.__proxiedMCPRequest:
interface ProxiedMCPRequest {
serverHash: string; // MD5 hash of server config
serverId?: string; // Optional server ID for lookup
method: string; // MCP method (e.g., "resources/read", "tools/call")
params?: Record<string, unknown>;
}Server lookup prefers serverId if provided, falling back to serverHash.
Exported Utilities
import {
MCPAppsMiddleware, // The middleware class
MCPAppsActivityType, // "mcp-apps" constant for the final widget snapshot
MCPAppsProgressActivityType, // "mcp-apps-progress" constant for streaming progress events
getServerHash, // Generate server hash from config
type MCPAppsMiddlewareConfig,
type MCPClientConfig,
type MCPClientConfigHTTP,
type MCPClientConfigSSE,
type ProxiedMCPRequest,
type Logger,
} from "@mayflowergmbh/ag-ui-mcp-apps-middleware";License
MIT
