@ag-ui/mcp-apps-middleware

中文文档
0.1.3发布于 2026/10/31MITTypeScriptESM + CJS构建来源已验证近 30 天下载 142万

MCP Apps middleware for AG-UI that enables UI-enabled tools from MCP (Model Context Protocol) servers.

原始使用文档
文档目录12 节
  1. Installation
  2. Usage
  3. Features
  4. Configuration
  5. Server ID
  6. Activity Snapshot
  7. Proxied MCP Requests
  8. Exported Utilities
  9. Proxy connections
  10. Tool visibility
  11. License
  12. Verification

@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 @ag-ui/mcp-apps-middleware
# or
pnpm add @ag-ui/mcp-apps-middleware

Usage

import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";

const agent = new YourAgent().use(
  new MCPAppsMiddleware({
    mcpServers: [
      {
        type: "http",
        url: "http://localhost:3001/mcp",
        serverId: "weather-server",
      },
    ],
  }),
);

Features

  • Discovers model-visible tools from MCP servers, including prerequisites without UI metadata
  • Injects tools into the agent's tool list
  • Executes tool calls and returns their results; emits activity snapshots only for tools with UI resource URIs
  • Supports proxied MCP requests for frontend resource fetching

Tools are model-visible by default. An explicit _meta.ui.visibility list must include "model" to expose a tool to the agent; app-only tools remain available through the iframe proxy. For example, Excalidraw's read_me returns the format guide as a normal tool result, while create_view also produces a UI activity.

After a tool returns, including a UI tool, the middleware continues the agent with the original call ID and result. The model can finish its turn without a separate user message. It waits for unresolved frontend tool calls and preserves interrupted or cancelled runs. Tool chains are limited to ten rounds; exceeding the limit fails the stream.

Configuration

interface MCPAppsMiddlewareConfig {
  mcpServers?: MCPClientConfig[];
  discoveryFailureMode?: "continue" | "throw"; // Default: "continue"
}

type MCPClientConfig =
  | {
      type: "http";
      url: string;
      headers?: Record<string, string>;
      serverId?: string;
    }
  | {
      type: "sse";
      url: string;
      headers?: Record<string, string>;
      serverId?: string;
    };

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 transport type and url only.

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 transport type and URL only
    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.

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 transport type and URL only
  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 {
  MCPAppsActivityType, // "mcp-apps" constant
  getServerHash, // Hash transport type and URL; excludes headers
} from "@ag-ui/mcp-apps-middleware";

Proxy connections

Requires @modelcontextprotocol/sdk >=1.15.0. Version 1.15.0 is the first release with custom fetch support in both HTTP and SSE client transports, and it includes HTTP terminateSession(). These APIs enforce the origin guard and session cleanup. The lockfile pins this package's SDK to 1.15.0 so CI tests the minimum supported version.

The middleware accepts only tools/call, resources/read, notifications/message, and ping from an iframe proxy request. It rejects other methods before it connects to the MCP server. HTTP discovery, tool calls, and proxy requests delete their MCP sessions before closing the client. Session deletion uses its own three-second abort signal so cleanup can run after a failed handshake aborts the SDK signal. If a server rejects session deletion or does not respond within three seconds, the client still closes and preserves the original operation result.

Server hashes exclude headers so browser-visible references do not contain a checksum of credentials. This changes hashes for servers configured with headers. Recreate activity messages after upgrading; use stable serverId values for references that must survive configuration changes. If multiple configurations share a transport type and URL, each must have a distinct serverId. Hash-only requests for that endpoint are rejected because they cannot identify the intended credential scope.

MCP connections do not follow redirects, and transport requests must stay on the configured origin. URLs must use HTTP(S) and must not contain embedded user credentials.

Discovery continues past unavailable servers by default. Set discoveryFailureMode: "throw" to stop before invoking the agent if any configured server cannot provide its tools. Proxy responses and thrown discovery errors omit raw upstream response bodies. Server-side diagnostics include serverId, the credential-free server hash, and the original error in both discovery modes and on proxy failures. Treat these logs as operator-only data: upstream errors can include private response bodies.

Tool visibility

Discovery reads _meta.ui.resourceUri, with _meta["ui/resourceUri"] as a legacy fallback. When _meta.ui.visibility is omitted, tools remain visible to the model by default. An explicit visibility list must include "model" for model-facing discovery. Tools marked ["app"] stay hidden from the model and remain callable through the iframe proxy.

License

MIT

Verification

Run the opt-in public Excalidraw integration test from the repository root:

MCP_APPS_LIVE_TEST=1 pnpm exec nx run @ag-ui/mcp-apps-middleware:test --skip-nx-cache

This exercises real MCP tool discovery, prerequisite and UI tool execution, and UI resource retrieval. Model choice, browser rendering, and replay behavior require downstream application validation.

Failed middleware results carry metadata["ag-ui:tool-result"].error. The string marker (including an empty string) preserves error status through client history without changing the result payload. Claude SDK recovery reads this marker when no explicit tool-message error is present.

版本与发布记录

@ag-ui/mcp-apps-middleware 共发布 7 个版本,首次发布于 2025/12/05;过去 12 个月发布了 7 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.3latest2026/10/317 天前
0.1.22026/10/0830 天前
0.1.12026/09/121 个月前
0.1.02026/09/111 个月前
0.0.32026/01/159 个月前
0.0.22026/01/139 个月前

关于 @ag-ui/mcp-apps-middleware 的常见问题

@ag-ui/mcp-apps-middleware 是什么?

MCP Apps middleware for AG-UI that enables UI-enabled tools from MCP (Model Context Protocol) servers.

如何安装 @ag-ui/mcp-apps-middleware?

在项目目录运行 npm install @ag-ui/mcp-apps-middleware,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(7.8.1)、@ag-ui/client(>=1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ag-ui/mcp-apps-middleware 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ag-ui/mcp-apps-middleware 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ag-ui/mcp-apps-middleware 可以商用吗?

@ag-ui/mcp-apps-middleware 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ag-ui/mcp-apps-middleware 的下载量有多少?

根据 npm 官方下载统计,@ag-ui/mcp-apps-middleware 在 2026/10/05 – 2026/11/03 这 30 天内被下载 1,419,879 次,日均约 47,329 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ag-ui/mcp-apps-middleware 还在维护吗?

最新版本 0.1.3 发布于 2026/10/31(7 天前);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2025/12/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。