🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: render MCP Apps interactive views inside conversations (#21231)
Moraxb2608a34b5ea
diff --git a/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.ts b/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.tsnew file mode 100644index 00000000000..08a5c5f79ff--- /dev/null+++ b/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.ts@@ -0,0 +1,401 @@+import { getMcpServerFingerprint } from '@lobechat/const/mcpApp';+import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';+import { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import McpCtr from './McpCtr';++const { mcpClientMocks } = vi.hoisted(() => ({+ mcpClientMocks: vi.fn(),+}));++vi.mock('../libs/mcp/client', () => ({+ MCPClient: class {+ constructor(+ public params: unknown,+ options?: unknown,+ ) {+ return mcpClientMocks(options);+ }+ },+ MCPConnectionError: class extends Error {+ name = 'MCPConnectionError';+ stderrLogs: string[] = [];+ },+}));++const mockApp = { getService: vi.fn(() => null) } as unknown as App;++const stdioParams = { args: ['--stdio'], command: 'weather-mcp', name: 'weather' };++const makeClient = (overrides: Record<string, unknown> = {}) => ({+ callTool: vi.fn().mockResolvedValue({ content: [{ text: 'sunny', type: 'text' }] }),+ disconnect: vi.fn().mockResolvedValue(undefined),+ getProtocolEra: vi.fn().mockReturnValue('legacy'),+ getToolUiResourceUri: vi.fn().mockResolvedValue('ui://weather/view'),+ initialize: vi.fn().mockResolvedValue(undefined),+ isToolCallableByApp: vi.fn().mockResolvedValue(true),+ isToolHiddenFromModel: vi.fn().mockResolvedValue(false),+ listResources: vi.fn().mockResolvedValue([]),+ readResource: vi.fn().mockResolvedValue({ contents: [{ text: '<html />', uri: 'ui://x' }] }),+ ...overrides,+});++describe('McpCtr MCP Apps', () => {+ let ctr: McpCtr;++ beforeEach(() => {+ vi.resetAllMocks();+ ctr = new McpCtr(mockApp);+ });++ it('marks results of tools that declare a ui:// view while MCP Apps are on', async () => {+ mcpClientMocks.mockReturnValue(makeClient());++ const result = await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ mcpApps: true,+ params: stdioParams,+ toolName: 'show_weather',+ } as any);++ expect(mcpClientMocks).toHaveBeenCalledWith({ mcpApps: true });+ // With the server the view may be read back from+ expect((result.state as any).mcpApp).toEqual({+ resourceUri: 'ui://weather/view',+ server: await getMcpServerFingerprint({ ...stdioParams, type: 'stdio' }),+ });+ });++ it("neither announces MCP Apps nor looks up views while the user's flag is off", async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ params: stdioParams,+ toolName: 'show_weather',+ } as any);++ expect(mcpClientMocks).toHaveBeenCalledWith({ mcpApps: false });+ expect(client.getToolUiResourceUri).not.toHaveBeenCalled();+ expect((result.state as any).mcpApp).toBeUndefined();+ });++ it('pools sessions that announce MCP Apps apart from ones that do not', async () => {+ mcpClientMocks.mockImplementation(() => makeClient());+ const run = (mcpApps: boolean) =>+ ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ mcpApps,+ params: stdioParams,+ toolName: 'show_weather',+ } as any);++ await run(false);+ await run(true);+ await run(true);++ expect(mcpClientMocks.mock.calls).toEqual([[{ mcpApps: false }], [{ mcpApps: true }]]);+ });++ it("returns a view the tool's own media, not the chat's uploaded copies", async () => {+ const image = { data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' };+ const client = makeClient({+ callTool: vi.fn().mockResolvedValue({ content: [image, { text: 'done', type: 'text' }] }),+ });+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ fromApp: true,+ mcpApps: true,+ params: stdioParams,+ toolName: 'snapshot',+ } as any);++ expect(result.success).toBe(true);+ expect((result.state as any).content).toEqual([image, { text: 'done', type: 'text' }]);+ expect(result.content).toBe('done');+ });++ it("refuses a view's call while MCP Apps are off", async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ fromApp: true,+ params: stdioParams,+ toolName: 'refresh',+ } as any);++ expect(client.callTool).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ });++ it('still runs the tool when the view lookup fails', async () => {+ const client = makeClient({+ getToolUiResourceUri: vi.fn().mockRejectedValue(new Error('list failed')),+ });+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ params: stdioParams,+ toolName: 'show_weather',+ } as any);++ expect(client.callTool).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);+ expect((result.state as any).mcpApp).toBeUndefined();+ });++ it("runs a view's call to a tool visible to the app", async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ const result = deserializeMcpIpcPayload<any>(+ await ctr.callTool(+ serializeMcpIpcPayload({+ args: {},+ env: undefined,+ fromApp: true,+ mcpApps: true,+ params: stdioParams,+ toolName: 'refresh',+ }),+ ),+ );++ expect(client.isToolCallableByApp).toHaveBeenCalledWith('refresh');+ expect(client.callTool).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);+ });++ it('refuses a model call to a tool only its views may call, and runs it when visibility is unknown', async () => {+ const hidden = makeClient({ isToolHiddenFromModel: vi.fn().mockResolvedValue(true) });+ mcpClientMocks.mockReturnValue(hidden);+ const call = async () =>+ deserializeMcpIpcPayload<any>(+ await ctr.callTool(+ serializeMcpIpcPayload({+ args: {},+ http: { name: 'local', url: 'http://127.0.0.1:3000/mcp' },+ mcpApps: true,+ toolName: 'load_page',+ }),+ ),+ );++ const refused = await call();+ expect(hidden.callTool).not.toHaveBeenCalled();+ expect(refused.success).toBe(false);++ // A failed listing must not stop the model's calls+ const unknown = makeClient({+ isToolHiddenFromModel: vi.fn().mockRejectedValue(new Error('list failed')),+ });+ mcpClientMocks.mockReturnValue(unknown);+ // A fresh controller, so its session is the new client+ ctr = new McpCtr(mockApp);+ const ran = await call();+ expect(ran.success).toBe(true);+ });++ it.each([+ ['kept from views', vi.fn().mockResolvedValue(false)],+ ['of unknown visibility', vi.fn().mockRejectedValue(new Error('list failed'))],+ ])("refuses a view's call to a tool %s without running it", async (_, isToolCallableByApp) => {+ const client = makeClient({ isToolCallableByApp });+ mcpClientMocks.mockReturnValue(client);++ const result = deserializeMcpIpcPayload<any>(+ await ctr.callTool(+ serializeMcpIpcPayload({+ args: {},+ fromApp: true,+ http: { name: 'local', url: 'http://127.0.0.1:3000/mcp' },+ mcpApps: true,+ toolName: 'delete_all',+ }),+ ),+ );++ expect(client.callTool).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.state.isError).toBe(true);+ });++ it('recovers a view call whose session expired during the visibility check', async () => {+ const stale = Object.assign(new Error('session expired'), { name: 'MCPConnectionError' });+ const expired = makeClient({ isToolCallableByApp: vi.fn().mockRejectedValue(stale) });+ const fresh = makeClient();+ mcpClientMocks.mockReturnValueOnce(expired).mockReturnValueOnce(fresh);++ const result = await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ fromApp: true,+ mcpApps: true,+ params: stdioParams,+ toolName: 'refresh',+ } as any);++ // Not taken for a refusal: the session is replaced and the call runs on it+ expect(expired.disconnect).toHaveBeenCalled();+ expect(fresh.callTool).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);+ });++ it("evicts a view call's dead session instead of reusing it for the next call", async () => {+ const dead = makeClient({+ isToolCallableByApp: vi+ .fn()+ .mockRejectedValue(new SdkError(SdkErrorCode.NotConnected, 'Not connected')),+ });+ const fresh = makeClient();+ mcpClientMocks.mockReturnValueOnce(dead).mockReturnValueOnce(fresh);+ const viewCall = () =>+ ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ fromApp: true,+ mcpApps: true,+ params: stdioParams,+ toolName: 'refresh',+ } as any);++ await viewCall().catch(() => {});+ expect(dead.disconnect).toHaveBeenCalled();++ await viewCall();+ expect(fresh.callTool).toHaveBeenCalledTimes(1);+ });++ it('does not check visibility for conversation calls', async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ await ctr.runStdioMcpTool({+ args: '{}',+ env: undefined,+ params: stdioParams,+ toolName: 'show_weather',+ } as any);++ expect(client.isToolCallableByApp).not.toHaveBeenCalled();+ });++ it("falls back to the resource's listing entry for the view's metadata", async () => {+ const csp = { connectDomains: ['https://api.example.com'] };+ mcpClientMocks.mockReturnValue(+ makeClient({+ listResources: vi.fn().mockResolvedValue([{ _meta: { ui: { csp } }, uri: 'ui://x' }]),+ readResource: vi+ .fn()+ .mockResolvedValue({ contents: [{ text: '<html />', uri: 'ui://x' }] }),+ }),+ );++ const result = deserializeMcpIpcPayload<any>(+ (await ctr.readUiResource(+ serializeMcpIpcPayload({ params: stdioParams, uri: 'ui://x' }) as any,+ )) as any,+ );++ expect(result.contents[0]._meta).toEqual({ ui: { csp } });+ });++ it('reads ui:// resources over IPC and refuses other URIs', async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.readUiResource(+ serializeMcpIpcPayload({ env: undefined, params: stdioParams, uri: 'ui://x' }) as any,+ );+ expect(deserializeMcpIpcPayload(result as any)).toEqual({+ contents: [{ text: '<html />', uri: 'ui://x' }],+ });++ await expect(+ ctr.readUiResource(+ serializeMcpIpcPayload({ env: undefined, params: stdioParams, uri: 'file:///x' }) as any,+ ),+ ).rejects.toThrow('ui://');+ expect(client.readResource).toHaveBeenCalledTimes(1);+ });++ it('reads views of local-network http servers', async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ await ctr.readUiResource(+ serializeMcpIpcPayload({+ http: { name: 'local', url: 'http://127.0.0.1:3000/mcp' },+ uri: 'ui://x',+ }) as any,+ );++ expect(client.readResource).toHaveBeenCalledWith('ui://x');+ });++ it('runs tool calls of local-network http servers over IPC', async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.callTool(+ serializeMcpIpcPayload({+ args: { city: 'Paris' },+ http: { name: 'local', url: 'http://127.0.0.1:3000/mcp' },+ toolName: 'show_weather',+ }) as any,+ );++ expect(client.callTool).toHaveBeenCalledWith('show_weather', { city: 'Paris' });+ expect((deserializeMcpIpcPayload(result as any) as any).success).toBe(true);+ });++ it('evicts a dead pooled session and retries the read on a fresh one', async () => {+ const dead = makeClient({+ readResource: vi+ .fn()+ .mockRejectedValue(new SdkError(SdkErrorCode.NotConnected, 'Not connected')),+ });+ const fresh = makeClient();+ mcpClientMocks.mockReturnValueOnce(dead).mockReturnValueOnce(fresh);++ const result = await ctr.readUiResource(+ serializeMcpIpcPayload({ params: stdioParams, uri: 'ui://x' }) as any,+ );++ expect(deserializeMcpIpcPayload(result as any)).toEqual({+ contents: [{ text: '<html />', uri: 'ui://x' }],+ });+ expect(dead.disconnect).toHaveBeenCalled();++ // the fresh session stays pooled for the next read+ await ctr.readUiResource(serializeMcpIpcPayload({ params: stdioParams, uri: 'ui://x' }) as any);+ expect(fresh.readResource).toHaveBeenCalledTimes(2);+ });++ it('does not retry application errors', async () => {+ const client = makeClient({+ readResource: vi.fn().mockRejectedValue(new Error('Resource not found')),+ });+ mcpClientMocks.mockReturnValue(client);++ await expect(+ ctr.readUiResource(serializeMcpIpcPayload({ params: stdioParams, uri: 'ui://x' }) as any),+ ).rejects.toThrow('Resource not found');+ expect(client.readResource).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.ts b/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.tsnew file mode 100644index 00000000000..ed9292b82cf--- /dev/null+++ b/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.ts@@ -0,0 +1,136 @@+import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import McpCtr from './McpCtr';++const { mcpClientMocks } = vi.hoisted(() => ({ mcpClientMocks: vi.fn() }));++vi.mock('../libs/mcp/client', () => ({+ MCPClient: class {+ constructor(+ public params: unknown,+ options?: unknown,+ ) {+ return mcpClientMocks(options);+ }+ },+ MCPConnectionError: class extends Error {+ name = 'MCPConnectionError';+ stderrLogs: string[] = [];+ },+}));++const mockApp = { getService: vi.fn(() => null) } as unknown as App;++const tools = [+ { description: 'Show it', inputSchema: { type: 'object' }, name: 'show_dashboard' },+ {+ _meta: { ui: { visibility: ['app'] } },+ description: 'Next page',+ inputSchema: { type: 'object' },+ name: 'load_page',+ },+];++// Kept from the model's `api`, still known to the view-call policy+const appOnlyToolNames = ['load_page'];++const makeClient = () => ({+ disconnect: vi.fn().mockResolvedValue(undefined),+ initialize: vi.fn().mockResolvedValue(undefined),+ listManifests: vi.fn().mockResolvedValue({ tools }),+ listTools: vi.fn().mockResolvedValue(tools),+});++const http = { name: 'dash', url: 'http://localhost:4000/mcp' };+const stdio = { args: [], command: 'dash-mcp', name: 'dash' };++describe('McpCtr tool visibility', () => {+ let ctr: McpCtr;++ beforeEach(() => {+ vi.resetAllMocks();+ mcpClientMocks.mockImplementation(makeClient);+ ctr = new McpCtr(mockApp);+ });++ it.each([+ [+ 'stdio manifest',+ (ctr: McpCtr) =>+ ctr.getStdioMcpServerManifest(serializeMcpIpcPayload({ ...stdio, mcpApps: true })),+ ],+ [+ 'HTTP manifest',+ (ctr: McpCtr) =>+ ctr.getStreamableMcpServerManifest(+ serializeMcpIpcPayload({ identifier: 'dash', mcpApps: true, url: http.url }),+ ),+ ],+ [+ 'stdio listing',+ (ctr: McpCtr) => ctr.listTools(serializeMcpIpcPayload({ mcpApps: true, stdio } as any)),+ ],+ [+ 'HTTP listing',+ (ctr: McpCtr) => ctr.listTools(serializeMcpIpcPayload({ http, mcpApps: true } as any)),+ ],+ ])('discovers on a session announcing MCP Apps when on (%s)', async (_, discover) => {+ // A server may list the tools only its views call just to such a client+ await discover(ctr);++ expect(mcpClientMocks).toHaveBeenCalledWith({ mcpApps: true });+ });++ it('keeps view-only tools out of the stdio manifest the model reads', async () => {+ const manifest = deserializeMcpIpcPayload<any>(+ await ctr.getStdioMcpServerManifest(serializeMcpIpcPayload(stdio)),+ );++ expect(manifest.api.map((api: { name: string }) => api.name)).toEqual(['show_dashboard']);+ expect(manifest.meta.description).toBe('dash MCP server has 1 tool');+ expect(manifest.mcpAppOnlyApi.map((api: { name: string }) => api.name)).toEqual(+ appOnlyToolNames,+ );+ });++ it('keeps view-only tools out of the HTTP manifest the model reads', async () => {+ const manifest = deserializeMcpIpcPayload<any>(+ await ctr.getStreamableMcpServerManifest(+ serializeMcpIpcPayload({ identifier: 'dash', url: http.url }),+ ),+ );++ expect(manifest.api.map((api: { name: string }) => api.name)).toEqual(['show_dashboard']);+ expect(manifest.meta.description).toBe('dash MCP server has 1 tool, like "show_dashboard"');+ expect(manifest.mcpAppOnlyApi.map((api: { name: string }) => api.name)).toEqual(+ appOnlyToolNames,+ );+ });++ it.each([+ ['stdio', { stdio }],+ ['HTTP', { http }],+ ])('lists every %s tool with its declared visibility for connector sync', async (_, input) => {+ const listed = deserializeMcpIpcPayload<any>(+ await ctr.listTools(serializeMcpIpcPayload(input as any)),+ );++ expect(listed).toEqual([+ {+ description: 'Show it',+ inputSchema: { type: 'object' },+ name: 'show_dashboard',+ visibility: undefined,+ },+ {+ description: 'Next page',+ inputSchema: { type: 'object' },+ name: 'load_page',+ visibility: ['app'],+ },+ ]);+ });+});diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.tsindex 92b0f28d3c9..f7205fdc276 100644--- a/apps/desktop/src/main/controllers/McpCtr.ts+++ b/apps/desktop/src/main/controllers/McpCtr.ts@@ -1,6 +1,14 @@import { createHash, randomUUID } from 'node:crypto';import path from 'node:path';+import {+ getMcpServerFingerprint,+ getMcpToolVisibility,+ isMcpToolVisibleTo,+ lacksUiResourceMeta,+ partitionMcpToolsForViews,+ withListingUiMeta,+} from '@lobechat/const/mcpApp';import {deserializeMcpIpcPayload,type McpIpcPayload,@@ -21,6 +29,7 @@ import type {AudioContent,ImageContent,MCPClientParams,+ McpTool,ResourceContent,ToolCallContent,ToolCallResult,@@ -85,7 +94,7 @@ interface CustomPluginMetadata {name?: string;}-interface GetStdioMcpServerManifestInput {+interface GetStdioMcpServerManifestInput extends McpSessionOptions {args?: string[];command: string;env?: Record<string, string>;@@ -94,7 +103,7 @@ interface GetStdioMcpServerManifestInput {type?: 'stdio';}-interface GetStreamableMcpServerManifestInput {+interface GetStreamableMcpServerManifestInput extends McpSessionOptions {auth?: {accessToken?: string;token?: string;@@ -106,15 +115,100 @@ interface GetStreamableMcpServerManifestInput {url: string;}-export interface CallToolInput {+export interface StdioCallToolInput extends McpCallOptions {args: any;env: any;+ http?: undefined;params: GetStdioMcpServerManifestInput;toolName: string;}+/** A call to an HTTP endpoint only this machine can reach (localhost / LAN). */+export interface HttpCallToolInput extends McpCallOptions {+ args: any;+ http: {+ auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };+ headers?: Record<string, string>;+ name: string;+ url: string;+ };+ toolName: string;+}++export type CallToolInput = StdioCallToolInput | HttpCallToolInput;++/** List a stdio or local-network HTTP server's tools, as the server declares them. */+export type ListToolsInput = McpSessionOptions &+ (+ | { http: HttpCallToolInput['http']; stdio?: undefined }+ | { http?: undefined; stdio: GetStdioMcpServerManifestInput }+ );++/** A tool as `listTools` reports it, with its MCP Apps `visibility` when declared. */+export interface ListedMcpTool {+ description?: string;+ inputSchema: McpTool['inputSchema'];+ name: string;+ visibility?: string[];+}++export interface ReadUiResourceInput {+ env?: any;+ /** HTTP endpoint only this machine can reach (localhost / LAN). */+ http?: {+ auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };+ headers?: Record<string, string>;+ name: string;+ url: string;+ };+ params?: GetStdioMcpServerManifestInput;+ uri: string;+}+type SuperJSONSerialized<T = unknown> = McpIpcPayload<T>;+interface McpSessionOptions {+ /** Announce MCP Apps on the session: the user has the `mcp_apps` flag. */+ mcpApps?: boolean;+}++/** How a tool call runs: whether a view made it, and whether MCP Apps are on. */+interface McpCallOptions extends McpSessionOptions {+ /** An MCP App view's `tools/call`: only tools visible to the app run. */+ fromApp?: boolean;+}++/**+ * A manifest's api is what the model may call: tools whose MCP Apps visibility+ * leaves out "model" exist only for their view, which reaches them through+ * `callTool`, so they stay out of it.+ */+const toPluginApi = (tools: McpTool[]) =>+ tools.map((item) => ({+ description: item.description,+ name: item.name,+ parameters: item.inputSchema as any,+ }));++const toModelApi = (tools: McpTool[]) =>+ toPluginApi(+ tools.filter((tool) => isMcpToolVisibleTo(getMcpToolVisibility(tool._meta), 'model')),+ );++/**+ * MCP Apps: what a plugin's views may call beyond its model-facing `api`, and+ * which `api` tools they may not, so the view-call policy finds every tool a+ * view may reach without the model seeing the view-only ones.+ */+const toMcpAppsManifestFields = (tools: McpTool[]) => {+ const { appOnlyTools, modelOnlyToolNames } = partitionMcpToolsForViews(tools);++ return {+ ...(appOnlyTools.length > 0 && { mcpAppOnlyApi: toPluginApi(appOnlyTools) }),+ ...(modelOnlyToolNames.length > 0 && { mcpModelOnlyTools: modelOnlyToolNames }),+ };+};+const deserializePayload = deserializeMcpIpcPayload;const serializePayload = serializeMcpIpcPayload;@@ -235,6 +329,8 @@ export default class McpCtr extends ControllerModule {* a call fails.*/private mcpClientPool = new Map<string, MCPClient>();+ /** The pool key each client was created under, so eviction finds its own entry. */+ private mcpClientKeys = new WeakMap<MCPClient, string>();private mcpClientInitialization?: Map<string, Promise<MCPClient>>;/**@@ -315,8 +411,12 @@ export default class McpCtr extends ControllerModule {* one when the pool has no healthy entry. Callers must NOT disconnect the* returned client — pooled sessions outlive a single tool call.*/- private async acquireClient(params: MCPClientParams): Promise<MCPClient> {- const key = serializeMcpClientParams(params);+ private async acquireClient(+ params: MCPClientParams,+ { mcpApps = false }: McpSessionOptions = {},+ ): Promise<MCPClient> {+ // Sessions that announce MCP Apps and ones that don't are pooled apart+ const key = `${serializeMcpClientParams(params)}${mcpApps ? '#mcp-apps' : ''}`;// Every acquire refreshes the session's idle clock (fire-and-forget —// reaping must never delay or fail the tool call it runs alongside).@@ -333,8 +433,9 @@ export default class McpCtr extends ControllerModule {const inFlight = this.mcpClientInitialization?.get(key);if (inFlight) return inFlight;- const creating = this.createClient(params)+ const creating = this.createClient(params, { mcpApps }).then((client) => {+ this.mcpClientKeys.set(client, key);this.mcpClientPool.set(key, client);this.mcpClientLastUsedAt.set(key, Date.now());return client;@@ -397,7 +498,7 @@ export default class McpCtr extends ControllerModule {*/private async evictClient(params: MCPClientParams, client?: MCPClient): Promise<void> {if (!client) return;- const key = serializeMcpClientParams(params);+ const key = this.mcpClientKeys.get(client) ?? serializeMcpClientParams(params);const pooled = this.mcpClientPool.get(key);// Only evict when the failing call ran on the pooled instance —// a concurrent recreate may have already replaced it.@@ -420,9 +521,9 @@ export default class McpCtr extends ControllerModule {}}- private async createClient(params: MCPClientParams) {+ private async createClient(params: MCPClientParams, options: McpSessionOptions = {}) {const { MCPClient } = await loadMcpClient();- const client = new MCPClient(params);+ const client = new MCPClient(params, options);await client.initialize();return client;}@@ -494,27 +595,26 @@ export default class McpCtr extends ControllerModule {let client: MCPClient | undefined;try {- client = await this.acquireClient(params);+ client = await this.acquireClient(params, { mcpApps: input.mcpApps });// Lease for the manifest refresh too: a concurrent stale-session// eviction must not disconnect underneath this pending request.const manifest = await this.withClientLease(client, () => client!.listManifests());const identifier = input.name;- const tools = manifest.tools || [];+ const api = toModelApi(manifest.tools || []);return serializePayload({- api: tools.map((item) => ({- description: item.description,- name: item.name,- parameters: item.inputSchema as any,- })),+ api,identifier,meta: {avatar: input.metadata?.avatar || 'MCP_AVATAR',- description: input.metadata?.description || getMcpServerDescription(identifier, manifest),+ description:+ input.metadata?.description ||+ getMcpServerDescription(identifier, { ...manifest, tools: api }),title: input.metadata?.name || identifier,},...manifest,+ ...toMcpAppsManifestFields(manifest.tools || []),mcpParams: params,type: 'mcp' as any,});@@ -557,24 +657,22 @@ export default class McpCtr extends ControllerModule {url: input.url,};- const client = await this.createClient(params);+ const client = await this.createClient(params, { mcpApps: input.mcpApps });try {const tools = await client.listTools();+ const api = toModelApi(tools);const identifier = input.identifier;return serializePayload({- api: tools.map((item) => ({- description: item.description,- name: item.name,- parameters: item.inputSchema as any,- })),+ api,identifier,+ ...toMcpAppsManifestFields(tools),mcpParams: params,meta: {avatar: input.metadata?.avatar || 'MCP_AVATAR',description:input.metadata?.description ||- getMcpServerDescription(identifier, { tools }, { includeToolExample: true }),+ getMcpServerDescription(identifier, { tools: api }, { includeToolExample: true }),title: identifier,},type: 'mcp' as any,@@ -584,10 +682,172 @@ export default class McpCtr extends ControllerModule {}}+ /**+ * Every tool a stdio or local-network HTTP server lists, including the ones+ * only its views may call. A connector syncs this full list, since a view's+ * call must find its tool synced; the model's manifest filters it later.+ */+ @IpcMethod()+ async listTools(payload: SuperJSONSerialized<ListToolsInput>) {+ const input = deserializePayload<ListToolsInput>(payload);+ const toListed = (tools: McpTool[]): ListedMcpTool[] =>+ tools.map((tool) => ({+ description: tool.description,+ inputSchema: tool.inputSchema,+ name: tool.name,+ visibility: getMcpToolVisibility(tool._meta),+ }));++ if (input.http) {+ const client = await this.createClient(+ { ...input.http, type: 'http' },+ { mcpApps: input.mcpApps },+ );+ try {+ return serializePayload(toListed(await client.listTools()));+ } finally {+ await client.disconnect();+ }+ }++ const params: MCPClientParams = {+ args: input.stdio.args || [],+ command: input.stdio.command,+ env: input.stdio.env,+ name: input.stdio.name,+ type: 'stdio',+ };+ let client: MCPClient | undefined;+ try {+ client = await this.acquireClient(params, { mcpApps: input.mcpApps });+ const tools = await this.withClientLease(client, () => client!.listTools());+ return serializePayload(toListed(tools));+ } catch (error) {+ // Same as the manifest refresh: drop a broken pooled session.+ await this.evictClient(params, client);+ throw error;+ }+ }+@IpcMethod()async callTool(payload: SuperJSONSerialized<CallToolInput>) {const input = deserializePayload<CallToolInput>(payload);- return serializePayload(await this.runStdioMcpTool(input));+ if ('http' in input && input.http) {+ return serializePayload(+ await this.runHttpMcpTool(input.http, input.toolName, input.args, {+ fromApp: input.fromApp,+ mcpApps: input.mcpApps,+ }),+ );+ }+ return serializePayload(await this.runStdioMcpTool(input as StdioCallToolInput));+ }++ /**+ * Read an MCP Apps `ui://` resource from a stdio or local-network HTTP+ * server, so the chat can render a tool result's interactive view.+ *+ * Unlike the web routes, not gated by the `mcp_apps` flag: the main process+ * has no per-user flags, and the renderer only asks while the flag is on.+ */+ @IpcMethod()+ async readUiResource(payload: SuperJSONSerialized<ReadUiResourceInput>) {+ const input = deserializePayload<ReadUiResourceInput>(payload);+ if (!input.uri?.startsWith('ui://')) throw new Error('Only ui:// resources can be read');++ let params: MCPClientParams;+ if (input.http) {+ params = { ...input.http, type: 'http' };+ } else if (input.params) {+ params = {+ args: input.params.args || [],+ command: input.params.command,+ env: input.env,+ name: input.params.name,+ type: 'stdio',+ };+ } else {+ throw new Error('Missing MCP server params');+ }++ const read = (client: MCPClient) =>+ this.withClientLease(client, async () => {+ const result = await client.readResource(input.uri);+ // A view's _meta.ui may be declared once, on its resources/list entry+ if (!lacksUiResourceMeta(result)) return result;++ const listed = await client.listResources().catch((error) => {+ logger.warn('Failed to list resources for MCP App metadata:', { error });+ return [];+ });+ return withListingUiMeta(result, input.uri, listed);+ });+ // Reading is idempotent, so unlike tool calls a dead transport is retried+ // too: the stale session is evicted and the read runs once on a fresh one.+ const isSessionFailure = (error: unknown) =>+ isStaleSessionError(error) || isDeadTransportError(error);++ // Views are read only while MCP Apps are on, on a session that announces them+ const client = await this.acquireClient(params, { mcpApps: true });+ try {+ return serializePayload(await read(client));+ } catch (error) {+ if (!isSessionFailure(error)) throw error;++ logger.warn('MCP App resource read failed on pooled session, retrying with a fresh one:', {+ message: (error as Error).message,+ });+ await this.evictClient(params, client);+ const retryClient = await this.acquireClient(params, { mcpApps: true });+ try {+ return serializePayload(await read(retryClient));+ } catch (retryError) {+ if (isSessionFailure(retryError)) await this.evictClient(params, retryClient);+ throw retryError;+ }+ }+ }++ /** Fails closed: a view's call is refused while the tool's visibility can't be learned. */+ private async isToolCallableByApp(client: MCPClient, toolName: string) {+ try {+ return await client.isToolCallableByApp(toolName);+ } catch (error) {+ // A broken session is the call's own failure: let runMcpTool evict and+ // recover it, or every later view call would reuse the dead session+ if (isStaleSessionError(error, client.getProtocolEra()) || isDeadTransportError(error)) {+ throw error;+ }+ logger.warn('Failed to resolve MCP App visibility for tool:', { error, toolName });+ return false;+ }+ }++ /**+ * Fails open: while the tool's visibility can't be learned, the model's call+ * runs as it did before MCP Apps.+ */+ private async isToolHiddenFromModel(client: MCPClient, toolName: string) {+ try {+ return await client.isToolHiddenFromModel(toolName);+ } catch (error) {+ // A broken session is the call's own failure, recovered by runMcpTool+ if (isStaleSessionError(error, client.getProtocolEra()) || isDeadTransportError(error)) {+ throw error;+ }+ logger.warn('Failed to resolve MCP App visibility for tool:', { error, toolName });+ return false;+ }+ }++ /** Never fails the tool call: an unknown UI resource only means no interactive view. */+ private async getToolUiResourceUri(client: MCPClient, toolName: string) {+ try {+ return await client.getToolUiResourceUri(toolName);+ } catch (error) {+ logger.warn('Failed to resolve MCP App resource for tool:', { error, toolName });+ return undefined;+ }}/**@@ -598,7 +858,7 @@ export default class McpCtr extends ControllerModule {* caller can shape its own error response.*/async runStdioMcpTool(- input: CallToolInput,+ input: StdioCallToolInput,): Promise<{ content: string; state: unknown; success: boolean }> {return this.runMcpTool({@@ -610,6 +870,7 @@ export default class McpCtr extends ControllerModule {},input.toolName,input.args,+ { fromApp: input.fromApp, mcpApps: input.mcpApps },);}@@ -627,6 +888,7 @@ export default class McpCtr extends ControllerModule {},toolName: string,rawArgs: unknown,+ options: McpCallOptions = {},): Promise<{ content: string; state: unknown; success: boolean }> {return this.runMcpTool({@@ -638,6 +900,7 @@ export default class McpCtr extends ControllerModule {},toolName,rawArgs,+ options,);}@@ -645,6 +908,7 @@ export default class McpCtr extends ControllerModule {params: MCPClientParams,toolName: string,rawArgs: unknown,+ { fromApp = false, mcpApps = false }: McpCallOptions = {},): Promise<{ content: string; state: unknown; success: boolean }> {try {const args = safeParseToRecord(rawArgs);@@ -660,17 +924,56 @@ export default class McpCtr extends ControllerModule {const runOn = (client: MCPClient) =>this.withClientLease(client, async () => {try {+ // A view may only call tools whose visibility includes the app,+ // and only while MCP Apps are on+ if (fromApp && !(mcpApps && (await this.isToolCallableByApp(client, toolName)))) {+ const message = `The tool "${toolName}" can't be called from an interactive view.`;+ return {+ content: message,+ error: { message, name: 'MCPToolError' },+ state: { content: [{ text: message, type: 'text' }], isError: true },+ success: false,+ };+ }+ // A tool the server keeps from the model is its views' alone, even+ // when the model names it (e.g. from an earlier turn)+ if (!fromApp && mcpApps && (await this.isToolHiddenFromModel(client, toolName))) {+ const message = `The tool "${toolName}" can only be called from its interactive view.`;+ return {+ content: message,+ error: { message, name: 'MCPToolError' },+ state: { content: [{ text: message, type: 'text' }], isError: true },+ success: false,+ };+ }+ const uiResourceUri = mcpApps+ ? await this.getToolUiResourceUri(client, toolName)+ : undefined;const raw = (await client.callTool(toolName, args)) as ToolCallResult;- const processed = raw.isError- ? raw.content- : await this.processContentBlocks(raw.content);- const content = await toMarkdown(processed, (key) =>- this.fileService.getFileHTTPURL(key),- );+ // A view gets the tool's own MCP result: its media stays base64+ // `data`, not the uploaded keys the chat stores and renders+ const processed =+ raw.isError || fromApp ? raw.content : await this.processContentBlocks(raw.content);+ const content = fromApp+ ? processed.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('\n')+ : await toMarkdown(processed, (key) => this.fileService.getFileHTTPURL(key));+ const state = {+ ...raw,+ content: processed,+ // MCP Apps: the `ui://` resource the chat renders this result with,+ // and the server it may be read back from+ ...(uiResourceUri &&+ !raw.isError && {+ mcpApp: {+ resourceUri: uiResourceUri,+ server: await getMcpServerFingerprint(params),+ },+ }),+ };return {content,...(raw.isError ? { error: { message: content, name: 'MCPToolError' } } : {}),- state: { ...raw, content: processed },+ state,success: raw.isError !== true,};} catch (error) {@@ -681,7 +984,7 @@ export default class McpCtr extends ControllerModule {});try {- return await runOn(await this.acquireClient(params));+ return await runOn(await this.acquireClient(params, { mcpApps }));} catch (firstError) {const failedClient = (firstError as { ranOnClient?: MCPClient })?.ranOnClient;if (!isStaleSessionError(firstError, failedClient?.getProtocolEra())) {@@ -714,7 +1017,7 @@ export default class McpCtr extends ControllerModule {// per key, so two concurrent calls that shared the same stale client// and both failed build ONE replacement process — not two racing// create/set writes that strand the loser (and its established state).- const retryClient = await this.acquireClient(params);+ const retryClient = await this.acquireClient(params, { mcpApps });try {return await runOn(retryClient);} catch (retryError) {diff --git a/apps/desktop/src/main/libs/mcp/client.mcpApp.test.ts b/apps/desktop/src/main/libs/mcp/client.mcpApp.test.tsnew file mode 100644index 00000000000..f98691bbea0--- /dev/null+++ b/apps/desktop/src/main/libs/mcp/client.mcpApp.test.ts@@ -0,0 +1,125 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { MCPClient } from './client';++const { clientOptions, listTools, notificationHandlers } = vi.hoisted(() => ({+ clientOptions: [] as unknown[],+ listTools: vi.fn(),+ // The handlers each client registered, by notification method+ notificationHandlers: new Map<string, () => void>(),+}));++vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ Client: class {+ getProtocolEra = () => 'legacy';+ listTools = listTools;+ setNotificationHandler = (method: string, handler: () => void) =>+ notificationHandlers.set(method, handler);+ constructor(_info: unknown, options?: unknown) {+ clientOptions.push(options);+ }+ },+}));++const params = { name: 'local', type: 'http' as const, url: 'http://127.0.0.1:3000/mcp' };++beforeEach(() => {+ clientOptions.length = 0;+ listTools.mockReset();+});++describe('desktop MCPClient MCP Apps capability', () => {+ it('announces MCP Apps only when asked to', () => {+ new MCPClient(params);+ new MCPClient(params, { mcpApps: true });++ expect(+ clientOptions.map((options) => (options as { capabilities?: unknown }).capabilities),+ ).toEqual([+ undefined,+ {+ extensions: { 'io.modelcontextprotocol/ui': { mimeTypes: ['text/html;profile=mcp-app'] } },+ },+ ]);+ });+});++describe('desktop MCPClient.isToolCallableByApp', () => {+ it('refuses tools whose visibility leaves out the app, and allows the default', async () => {+ listTools.mockResolvedValue({+ tools: [+ { _meta: { ui: { visibility: ['model'] } }, name: 'delete_all' },+ { _meta: { ui: { visibility: ['app'] } }, name: 'refresh' },+ { name: 'search' },+ ],+ });+ const client = new MCPClient(params);++ await expect(client.isToolCallableByApp('delete_all')).resolves.toBe(false);+ await expect(client.isToolCallableByApp('refresh')).resolves.toBe(true);+ await expect(client.isToolCallableByApp('search')).resolves.toBe(true);+ expect(listTools).toHaveBeenCalledTimes(1);+ });++ it('surfaces a failed listing, which the controller treats as refused', async () => {+ listTools.mockRejectedValue(new Error('offline'));+ const client = new MCPClient(params);++ await expect(client.isToolCallableByApp('search')).rejects.toThrow('offline');+ });+});++describe('desktop MCPClient after the server changes its tools', () => {+ it('lists them again for visibility and views once it says they changed', async () => {+ listTools.mockResolvedValueOnce({+ tools: [{ _meta: { ui: { resourceUri: 'ui://old', visibility: ['app'] } }, name: 'page' }],+ });+ const client = new MCPClient(params, { mcpApps: true });+ await expect(client.isToolCallableByApp('page')).resolves.toBe(true);++ // The server takes the tool from views and moves its view+ listTools.mockResolvedValueOnce({+ tools: [{ _meta: { ui: { resourceUri: 'ui://new', visibility: ['model'] } }, name: 'page' }],+ });+ notificationHandlers.get('notifications/tools/list_changed')?.();++ await expect(client.isToolCallableByApp('page')).resolves.toBe(false);+ await expect(client.getToolUiResourceUri('page')).resolves.toBe('ui://new');+ await expect(client.isToolHiddenFromModel('page')).resolves.toBe(false);+ expect(listTools).toHaveBeenCalledTimes(2);+ });+});++describe('desktop MCPClient when the server cannot list its tools', () => {+ it('gives up at once for a while instead of listing again before every lookup', async () => {+ vi.useFakeTimers();+ try {+ listTools.mockRejectedValue(new Error('slow server'));+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolHiddenFromModel('page')).rejects.toThrow('slow server');+ await expect(client.getToolUiResourceUri('page')).rejects.toThrow();+ await expect(client.isToolCallableByApp('page')).rejects.toThrow();+ expect(listTools).toHaveBeenCalledTimes(1);++ // Tried again once the cooldown has passed+ listTools.mockResolvedValue({ tools: [{ name: 'page' }] });+ vi.advanceTimersByTime(60_000);+ await expect(client.isToolCallableByApp('page')).resolves.toBe(true);+ expect(listTools).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('desktop MCPClient.isToolCallableByApp for names the listing did not name', () => {+ it('refuses them: only tools the server offered to views run', async () => {+ listTools.mockResolvedValueOnce({ tools: [{ name: 'search' }] });+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolCallableByApp('search')).resolves.toBe(true);+ await expect(client.isToolCallableByApp('not_listed')).resolves.toBe(false);+ });+});diff --git a/apps/desktop/src/main/libs/mcp/client.ts b/apps/desktop/src/main/libs/mcp/client.tsindex fa1abb6716f..d14ba6a1fec 100644--- a/apps/desktop/src/main/libs/mcp/client.ts+++ b/apps/desktop/src/main/libs/mcp/client.ts@@ -1,6 +1,7 @@import { spawn } from 'node:child_process';import type { Readable } from 'node:stream';+import { getMcpToolVisibility, isMcpToolVisibleTo } from '@lobechat/const/mcpApp';import { toRecord } from '@lobechat/utils/object';import type { Progress, Transport } from '@modelcontextprotocol/client';import {@@ -87,6 +88,9 @@ export interface StdioSpawnFailureInput {* Electron main process heap while the 5s pre-check window runs. */const PRECHECK_OUTPUT_CAP_BYTES = 64 * 1024;+/** After a failed tool listing, MCP App lookups give up at once for this long. */+const TOOL_LISTING_RETRY_MS = 60_000;+/** Grace window between `exit` and `close` before the pre-check classifies* on the data captured so far — a grandchild holding the stdio pipes can* keep `close` pending indefinitely (see the `close`/`exit` handlers in@@ -359,16 +363,54 @@ export class MCPClient {* "Connection closed" is the only way to surface an actionable error.*/private stdioParams?: { args?: string[]; command: string; env?: Record<string, string> };-- constructor(params: MCPClientParams) {+ /** tool name → `ui://` resource URI, filled from the last `listTools` */+ private uiResourceUris?: Map<string, string>;+ /**+ * The tools a view may call (`_meta.ui.visibility` with "app", or unset), from+ * the same listing. An allow-list: a name the listing didn't name is refused.+ */+ private appVisibleTools?: Set<string>;+ /** Tools only views may call (`_meta.ui.visibility` without "model"), from the same listing */+ private modelHiddenTools?: Set<string>;+ /** When the last listing for these lookups failed, while none has succeeded */+ private toolListingFailedAt?: number;++ constructor(+ params: MCPClientParams,+ {+ mcpApps = false,+ }: {+ /**+ * Announce MCP Apps (SEP-1865), so servers expose their interactive views.+ * Only for users with the `mcp_apps` flag: a server may answer an+ * announcing client with app-specific results instead of its text fallback.+ */+ mcpApps?: boolean;+ } = {},+ ) {this.mcp = new Client({ name: 'lobehub-desktop-mcp-client', version: '1.0.0' },{+ ...(mcpApps && {+ capabilities: {+ extensions: {+ 'io.modelcontextprotocol/ui': { mimeTypes: ['text/html;profile=mcp-app'] },+ },+ },+ }),// Do not add a probe subprocess/timeout to stdio installations or calls.versionNegotiation: { mode: params.type === 'http' ? 'auto' : 'legacy' },inputRequired: { autoFulfill: false },},);+ // A server whose tools changed (a view's visibility, its `ui://` resource)+ // voids what its last listing taught; the next lookup lists them again+ this.mcp.setNotificationHandler('notifications/tools/list_changed', () => {+ this.uiResourceUris = undefined;+ this.appVisibleTools = undefined;+ this.modelHiddenTools = undefined;+ this.toolListingFailedAt = undefined;+ });switch (params.type) {case 'http': {@@ -725,9 +767,84 @@ export class MCPClient {async listTools() {const { tools } = await this.mcp.listTools();+ this.uiResourceUris = new Map(+ (tools || []).flatMap((tool) => {+ const meta = tool._meta as Record<string, any> | undefined;+ const uri = meta?.ui?.resourceUri ?? meta?.['ui/resourceUri'];+ return typeof uri === 'string' && uri.startsWith('ui://')+ ? [[tool.name, uri] as const]+ : [];+ }),+ );+ this.appVisibleTools = new Set(+ (tools || [])+ .filter((tool) => isMcpToolVisibleTo(getMcpToolVisibility(tool._meta), 'app'))+ .map((tool) => tool.name),+ );+ this.modelHiddenTools = new Set(+ (tools || [])+ .filter((tool) => !isMcpToolVisibleTo(getMcpToolVisibility(tool._meta), 'model'))+ .map((tool) => tool.name),+ );return (tools || []) as McpTool[];}+ /**+ * List the tools once for the MCP App lookups below. A failed listing is not+ * retried for {@link TOOL_LISTING_RETRY_MS}: each lookup fails at once+ * meanwhile, so a server that can't list them doesn't add a listing wait+ * (or two) before every tool call.+ */+ private async ensureToolsListed() {+ if (this.appVisibleTools) return;+ const failedAt = this.toolListingFailedAt;+ if (failedAt !== undefined && Date.now() - failedAt < TOOL_LISTING_RETRY_MS) {+ throw new Error('The MCP server could not list its tools recently');+ }+ try {+ await this.listTools();+ this.toolListingFailedAt = undefined;+ } catch (error) {+ this.toolListingFailedAt = Date.now();+ throw error;+ }+ }++ /**+ * Whether the server keeps `toolName` from the model: its+ * `_meta.ui.visibility` lacks "model", so only its views may call it.+ */+ async isToolHiddenFromModel(toolName: string): Promise<boolean> {+ await this.ensureToolsListed();++ return !!this.modelHiddenTools?.has(toolName);+ }++ /**+ * Whether an MCP App view may call `toolName`: the listing named it, with a+ * `_meta.ui.visibility` that includes "app" or is unset. Lists tools once per+ * client to learn it.+ */+ async isToolCallableByApp(toolName: string): Promise<boolean> {+ await this.ensureToolsListed();++ return !!this.appVisibleTools?.has(toolName);+ }++ /**+ * The MCP Apps `ui://` resource a tool renders its result with, if any.+ * Lists tools once per client to learn it.+ */+ async getToolUiResourceUri(toolName: string): Promise<string | undefined> {+ await this.ensureToolsListed();++ return this.uiResourceUris?.get(toolName);+ }++ async readResource(uri: string) {+ return this.mcp.readResource({ uri });+ }+async listResources() {const { resources } = await this.mcp.listResources();return (resources || []) as McpResource[];diff --git a/apps/desktop/src/main/libs/mcp/types.ts b/apps/desktop/src/main/libs/mcp/types.tsindex 6dd0caf07c6..5939c75d8b0 100644--- a/apps/desktop/src/main/libs/mcp/types.ts+++ b/apps/desktop/src/main/libs/mcp/types.ts@@ -1,4 +1,6 @@export interface McpTool {+ /** Server metadata, e.g. MCP Apps `ui.resourceUri` / `ui.visibility` */+ _meta?: Record<string, unknown>;description: string;inputSchema: {[k: string]: unknown;@@ -80,11 +82,7 @@ export interface ResourceLinkContent {}export type ToolCallContent =- | TextContent- | ImageContent- | AudioContent- | ResourceContent- | ResourceLinkContent;+ TextContent | ImageContent | AudioContent | ResourceContent | ResourceLinkContent;export interface ToolCallResult {content: ToolCallContent[];diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.tsindex 27f93733202..563be319cb5 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts@@ -97,6 +97,18 @@ describe('connectorRouter.syncToolsFromClientById', () => {);});+ it('keeps the MCP Apps visibility the desktop reported for each tool', async () => {+ await caller().syncToolsFromClientById({+ id: CONNECTOR_ID,+ tools: [{ toolName: 'show_dashboard' }, { toolName: 'load_page', visibility: ['app'] }],+ });++ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [+ expect.objectContaining({ metadata: null, toolName: 'show_dashboard' }),+ expect.objectContaining({ metadata: { visibility: ['app'] }, toolName: 'load_page' }),+ ]);+ });+it('rejects an unknown connector id', async () => {connectorModelMock.findById.mockResolvedValue(undefined);diff --git a/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.tsnew file mode 100644index 00000000000..143b6d8898e--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts@@ -0,0 +1,82 @@+import { TRPCError } from '@trpc/server';++import type { ConnectorModel } from '@/database/models/connector';+import type { ConnectorMetadata } from '@/database/schemas';+import { ConnectorStatus } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';++import { isWorkspaceNonOwner } from './assertWorkspaceRowManageable';++/**+ * Create connector entry if not exists (or update metadata), return connectorId.+ *+ * These bootstrap syncs run whenever any member opens a shared skill's detail+ * panel, so an existing row created by someone else must not be rewritten by a+ * non-owner caller — the row is returned read-only (`writable: false`) and the+ * caller skips the tool upsert instead of throwing, keeping browsing intact.+ */+export async function upsertConnectorEntry(+ ctx: {+ connectorModel: ConnectorModel;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+ workspaceRole?: string;+ },+ params: {+ avatar?: string;+ composio?: ConnectorMetadata['composio'];+ description?: string;+ identifier: string;+ name: string;+ sourceType: string;+ },+): Promise<{ connectorId: string; writable: boolean }> {+ const metadata: ConnectorMetadata = {};+ if (params.description) metadata.description = params.description;+ if (params.avatar) metadata.avatar = params.avatar;+ if (params.composio) metadata.composio = params.composio;++ // Viewers keep browse access: they resolve existing rows read-only below,+ // but must never create or rewrite connector state. These bootstrap+ // endpoints run without the RBAC middleware, so ctx.workspaceRole may be+ // absent — a missing role must NOT be treated as writable; fall back to an+ // explicit member-level permission check (viewers lack agent:update).+ const canWrite = !ctx.workspaceId+ ? true+ : ctx.workspaceRole+ ? ctx.workspaceRole !== 'viewer'+ : await hasWorkspaceScopedPermission({+ action: 'AGENT_UPDATE',+ db: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ const existing = await ctx.connectorModel.queryByIdentifiers([params.identifier]);+ if (existing.length > 0) {+ const row = existing[0];+ const writable = canWrite && (!isWorkspaceNonOwner(ctx) || row.userId === ctx.userId);+ if (writable) {+ // Preserve runtime-owned metadata (especially Composio account identity)+ // while refreshing display fields from the latest plugin manifest.+ await ctx.connectorModel.update(row.id, { metadata: { ...row.metadata, ...metadata } });+ }+ return { connectorId: row.id, writable };+ }++ if (!canWrite) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Viewers cannot install connectors' });+ }++ const created = await ctx.connectorModel.create({+ identifier: params.identifier,+ isEnabled: true,+ metadata,+ name: params.name,+ sourceType: params.sourceType as any,+ status: ConnectorStatus.connected,+ });+ return { connectorId: created.id, writable: true };+}diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 09f0c48780a..fab06cd4573 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -1,5 +1,6 @@import { getComposioAppByIdentifier } from '@lobechat/const';import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';+import { buildMcpToolMetadata } from '@lobechat/const/mcpApp';import { upsertPluginMode } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -14,20 +15,23 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';import { WorkspaceModel } from '@/database/models/workspace';import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';-import type { ConnectorMetadata, OIDCConfig } from '@/database/schemas';+import type { OIDCConfig } from '@/database/schemas';import {ConnectorMcpConnectionType,ConnectorSourceType,ConnectorStatus,ConnectorToolPermission,} from '@/database/schemas';-import type { LobeChatDatabase } from '@/database/type';import { getComposioClient } from '@/libs/composio';import { getMCPConnectionErrorType, inferCrudType } from '@/libs/mcp/utils';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { callConnectorToolById, ConnectorToolCallError } from '@/server/services/connector/exec';+import {+ callConnectorToolById,+ ConnectorToolCallError,+ readConnectorUiResourceById,+} from '@/server/services/connector/exec';import {buildAuthorizationUrl,discoverConnectorOAuth,@@ -41,17 +45,13 @@ import {saveConnectorOAuthState,} from '@/server/services/connector/stateStore';import { syncConnectorToolsById } from '@/server/services/connector/sync';-import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';import {resolveConnectorAuthorizerId,resolveUserDisplayMap,withTrustedLinkedByUserId,} from '@/server/utils/connectorAttribution';-import {- assertWorkspaceRowManageable,- isWorkspaceNonOwner,-} from './_helpers/assertWorkspaceRowManageable';+import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';import {assertConnectorCredentialsManageable,assertConnectorMaintainable,@@ -59,6 +59,7 @@ import {getConnectorMemberManage,isWorkspaceConnectorAdmin,} from './_helpers/connectorManagePolicy';+import { upsertConnectorEntry } from './_helpers/upsertConnectorEntry';const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -67,6 +68,7 @@ const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(async (optsconst wsId = ctx.workspaceId ?? undefined;return opts.next({ctx: {+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId, wsId, gateKeeper),connectorToolModel: new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId),pluginModel: new PluginModel(ctx.serverDB, ctx.userId, wsId),@@ -828,8 +830,14 @@ export const connectorRouter = router({callTool: connectorWriteProcedure.input(z.object({+ /** Resolve the identifier for this agent (agent-owned connector first). */+ agentId: z.string().optional(),args: z.string().optional(),+ /** An MCP App view's `tools/call`: only tools visible to the app run. */+ fromApp: z.boolean().optional(),identifier: z.string().min(1),+ /** With `fromApp`: the server the view came from (`getMcpServerFingerprint`). */+ server: z.string().optional(),toolName: z.string().min(1),}),)@@ -849,6 +857,30 @@ export const connectorRouter = router({}}),+ /**+ * Read the MCP Apps `ui://` resource a connector tool result renders with.+ */+ readUiResource: connectorProcedure+ .input(+ z.object({+ agentId: z.string().optional(),+ identifier: z.string().min(1),+ /** The server the result came from (`getMcpServerFingerprint`). */+ server: z.string().min(1),+ uri: z.string().startsWith('ui://'),+ }),+ )+ .query(async ({ input, ctx }) => {+ try {+ return await readConnectorUiResourceById(input, ctx);+ } catch (err: any) {+ if (err instanceof ConnectorToolCallError) {+ throw new TRPCError({ cause: err, code: err.code, message: err.message });+ }+ throw err;+ }+ }),+/*** Reset all tool permissions for a connector back to 'auto' (fully open).*/@@ -957,6 +989,8 @@ export const connectorRouter = router({description: z.string().optional(),inputSchema: z.record(z.string(), z.unknown()).optional(),toolName: z.string(),+ /** The MCP tool's `_meta.ui.visibility`, when it declares one. */+ visibility: z.array(z.string()).optional(),}),),}),@@ -971,6 +1005,7 @@ export const connectorRouter = router({crudType: inferCrudType(t.toolName),description: t.description,inputSchema: t.inputSchema,+ metadata: buildMcpToolMetadata(t.visibility),toolName: t.toolName,}));@@ -1096,79 +1131,6 @@ export const connectorRouter = router({// ── Private helpers ───────────────────────────────────────────────────────────-/**- * Create connector entry if not exists (or update metadata), return connectorId.- *- * These bootstrap syncs run whenever any member opens a shared skill's detail- * panel, so an existing row created by someone else must not be rewritten by a- * non-owner caller — the row is returned read-only (`writable: false`) and the- * caller skips the tool upsert instead of throwing, keeping browsing intact.- */-async function upsertConnectorEntry(- ctx: {- connectorModel: ConnectorModel;- serverDB: LobeChatDatabase;- userId: string;- workspaceId?: string | null;- workspaceRole?: string;- },- params: {- avatar?: string;- composio?: ConnectorMetadata['composio'];- description?: string;- identifier: string;- name: string;- sourceType: string;- },-): Promise<{ connectorId: string; writable: boolean }> {- const metadata: ConnectorMetadata = {};- if (params.description) metadata.description = params.description;- if (params.avatar) metadata.avatar = params.avatar;- if (params.composio) metadata.composio = params.composio;-- // Viewers keep browse access: they resolve existing rows read-only below,- // but must never create or rewrite connector state. These bootstrap- // endpoints run without the RBAC middleware, so ctx.workspaceRole may be- // absent — a missing role must NOT be treated as writable; fall back to an- // explicit member-level permission check (viewers lack agent:update).- const canWrite = !ctx.workspaceId- ? true- : ctx.workspaceRole- ? ctx.workspaceRole !== 'viewer'- : await hasWorkspaceScopedPermission({- action: 'AGENT_UPDATE',- db: ctx.serverDB,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });-- const existing = await ctx.connectorModel.queryByIdentifiers([params.identifier]);- if (existing.length > 0) {- const row = existing[0];- const writable = canWrite && (!isWorkspaceNonOwner(ctx) || row.userId === ctx.userId);- if (writable) {- // Preserve runtime-owned metadata (especially Composio account identity)- // while refreshing display fields from the latest plugin manifest.- await ctx.connectorModel.update(row.id, { metadata: { ...row.metadata, ...metadata } });- }- return { connectorId: row.id, writable };- }-- if (!canWrite) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'Viewers cannot install connectors' });- }-- const created = await ctx.connectorModel.create({- identifier: params.identifier,- isEnabled: true,- metadata,- name: params.name,- sourceType: params.sourceType as any,- status: ConnectorStatus.connected,- });- return { connectorId: created.id, writable: true };-}-/** Map builtin manifest humanIntervention → default ConnectorToolPermission */function resolveDefaultPermission(humanIntervention: unknown): ConnectorToolPermission {if (humanIntervention === 'required' || humanIntervention === 'always') {diff --git a/apps/server/src/routers/tools/mcp.test.ts b/apps/server/src/routers/tools/mcp.test.tsnew file mode 100644index 00000000000..ec047df46a6--- /dev/null+++ b/apps/server/src/routers/tools/mcp.test.ts@@ -0,0 +1,151 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mcpRouter } from './mcp';++const { mockCallTool, mockGetStreamableManifest, mockMcpAppsEnabled, mockReadUiResource } =+ vi.hoisted(() => ({+ mockCallTool: vi.fn(),+ mockGetStreamableManifest: vi.fn(),+ mockMcpAppsEnabled: vi.fn(),+ mockReadUiResource: vi.fn(),+ }));++vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mockMcpAppsEnabled }));++vi.mock('./_helpers', () => ({ scheduleToolCallReport: vi.fn() }));++// Not a connector: the call skips the connector permission gate+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn(function () {+ return { queryByIdentifiers: vi.fn().mockResolvedValue([]) };+ }),+}));++vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: vi.fn(function (opts: any) {+ return opts.next({ ctx: opts.ctx });+ }),+ telemetry: vi.fn(function (opts: any) {+ return opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/server/services/mcp', () => ({+ mcpService: {+ callTool: mockCallTool,+ getStreamableMcpServerManifest: mockGetStreamableManifest,+ readUiResource: mockReadUiResource,+ },+}));++describe('tools mcpRouter.callTool', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it.each([true, false])(+ 'passes the caller mcp_apps flag (%s) to the MCP call',+ async (enabled) => {+ mockMcpAppsEnabled.mockResolvedValue(enabled);+ mockCallTool.mockResolvedValue({ content: 'ok', state: { content: [] }, success: true });+ const caller = mcpRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++ await caller.callTool({+ args: '{}',+ params: { name: 'weather', type: 'http', url: 'https://mcp.example.com/mcp' },+ toolName: 'forecast',+ });++ expect(mockMcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(mockCallTool).toHaveBeenCalledWith(expect.objectContaining({ mcpApps: enabled }));+ },+ );++ it.each([true, undefined])(+ 'passes whether a view made the call (%s) to the MCP call',+ async (fromApp) => {+ mockMcpAppsEnabled.mockResolvedValue(true);+ mockCallTool.mockResolvedValue({ content: 'ok', state: { content: [] }, success: true });+ const caller = mcpRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++ await caller.callTool({+ args: '{}',+ fromApp,+ params: { name: 'weather', type: 'http', url: 'https://mcp.example.com/mcp' },+ toolName: 'forecast',+ });++ expect(mockCallTool).toHaveBeenCalledWith(expect.objectContaining({ fromApp }));+ },+ );+});++describe('tools mcpRouter.getStreamableMcpServerManifest', () => {+ it.each([true, false])("discovers under the caller's mcp_apps flag (%s)", async (enabled) => {+ mockMcpAppsEnabled.mockResolvedValue(enabled);+ mockGetStreamableManifest.mockResolvedValue({ api: [] });+ const caller = mcpRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++ await caller.getStreamableMcpServerManifest({+ identifier: 'srv',+ url: 'https://mcp.example.com/mcp',+ });++ expect(mockMcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(mockGetStreamableManifest).toHaveBeenCalledWith(+ 'srv',+ 'https://mcp.example.com/mcp',+ undefined,+ undefined,+ undefined,+ { mcpApps: enabled },+ );+ });+});++describe('tools mcpRouter.readUiResource', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockMcpAppsEnabled.mockResolvedValue(true);+ });++ it('refuses to read a view while the mcp_apps flag is off', async () => {+ mockMcpAppsEnabled.mockResolvedValue(false);+ const caller = mcpRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++ await expect(+ caller.readUiResource({+ params: { name: 'weather', type: 'http', url: 'https://mcp.example.com/mcp' },+ uri: 'ui://weather/view.html',+ }),+ ).rejects.toHaveProperty('code', 'FORBIDDEN');++ expect(mockMcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(mockReadUiResource).not.toHaveBeenCalled();+ });++ it('reads the view through the MCP service, credentials in the mutation input', async () => {+ const caller = mcpRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);+ const view = { contents: [{ text: '<html />', uri: 'ui://weather/view.html' }] };+ mockReadUiResource.mockResolvedValue(view);+ const params = {+ auth: { token: 'secret', type: 'bearer' as const },+ name: 'weather-demo',+ type: 'http' as const,+ url: 'https://mcp.example.com/mcp',+ };++ await expect(caller.readUiResource({ params, uri: 'ui://weather/view.html' })).resolves.toEqual(+ view,+ );++ expect(mockReadUiResource).toHaveBeenCalledWith(params, 'ui://weather/view.html');+ });+});diff --git a/apps/server/src/routers/tools/mcp.ts b/apps/server/src/routers/tools/mcp.tsindex d42fd507180..9471de6be69 100644--- a/apps/server/src/routers/tools/mcp.ts+++ b/apps/server/src/routers/tools/mcp.ts@@ -2,6 +2,7 @@ import {GetStreamableMcpServerManifestInputSchema,StreamableHTTPAuthSchema,} from '@lobechat/types';+import { TRPCError } from '@trpc/server';import { z } from 'zod';import {@@ -17,6 +18,7 @@ import { serverDatabase, telemetry } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';import { mcpService } from '@/server/services/mcp';import { processContentBlocks } from '@/server/services/mcp/contentProcessor';+import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { scheduleToolCallReport } from './_helpers';@@ -73,13 +75,15 @@ const mcpProcedure = wsCompatProcedureexport const mcpRouter = router({getStreamableMcpServerManifest: mcpProcedure.input(GetStreamableMcpServerManifestInputSchema)- .query(async ({ input }) => {+ .query(async ({ ctx, input }) => {return await mcpService.getStreamableMcpServerManifest(input.identifier,input.url,input.metadata,input.auth,input.headers,+ // With MCP Apps on, the tools only views call are listed and kept too+ { mcpApps: await isMcpAppsEnabled(ctx.userId) },);}),// --- MCP Interaction ---@@ -107,6 +111,23 @@ export const mcpRouter = router({return await mcpService.listPrompts(input);}),+ /**+ * Read an MCP Apps `ui://` resource so the chat can render a tool result's+ * interactive view. A mutation, though it only reads: the params carry the+ * plugin's auth and headers, which must travel in a POST body, not a GET URL.+ * Refused while the `mcp_apps` flag is off, since the read opens a session+ * that advertises MCP Apps.+ */+ readUiResource: mcpProcedure+ .input(z.object({ params: mcpClientParamsSchema, uri: z.string().startsWith('ui://') }))+ .mutation(async ({ ctx, input }) => {+ if (!(await isMcpAppsEnabled(ctx.userId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Interactive views are turned off' });+ }++ return await mcpService.readUiResource(input.params, input.uri);+ }),+// callTool now accepts MCPClientParams, toolName, and argscallTool: mcpProcedure// Executes tools with side effects — workspace viewers are read-only.@@ -114,6 +135,8 @@ export const mcpRouter = router({.input(z.object({args: z.any(), // Arguments for the tool call+ /** An MCP App view's `tools/call`: only tools visible to the app run. */+ fromApp: z.boolean().optional(),meta: metaSchema, // Optional metadata for reportingparams: mcpClientParamsSchema, // Use the unified schema for client paramstoolName: z.string(),@@ -175,6 +198,8 @@ export const mcpRouter = router({result = await mcpService.callTool({argsStr: input.args,clientParams: input.params,+ fromApp: input.fromApp,+ mcpApps: await isMcpAppsEnabled(ctx.userId),processContentBlocks: boundProcessContentBlocks,toolName: input.toolName,});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.tsindex bc7502b4cc8..e515ab32ff3 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts@@ -314,6 +314,7 @@ describe('AiAgentService.execAgent - hetero runs keep the composer-authored usertoolCallId: 'call-1',},],+ mcpAppSource: { identifier: 'weather-demo' },pageSelections: [{content: 'Selected page paragraph',diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.tsindex 57653d5f228..d5b80514a90 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts@@ -280,8 +280,10 @@ describe('discoverTools — unpinned custom MCP connectors', () => {// An activatable connector whose upstream tools changed must not keep// offering the old list until someone re-syncs it by hand.expect(scheduleStaleConnectorToolsRefresh).toHaveBeenCalledTimes(1);- const [connectors] = vi.mocked(scheduleStaleConnectorToolsRefresh).mock.calls[0];+ const [connectors, , ctx] = vi.mocked(scheduleStaleConnectorToolsRefresh).mock.calls[0];expect(connectors.map((c) => c.identifier)).toContain(YINGMI);+ // The refresh lists under the run's user, whose mcp_apps flag finds view-only tools+ expect(ctx).toMatchObject({ userId: 'user-1' });});describe('share visitor run', () => {diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.tsindex d3d6996b6b0..97abbddba22 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts@@ -91,7 +91,12 @@ export const scheduleConnectorRefresh = (scheduleStaleConnectorToolsRefresh([...params.connectorsMcp, ...params.discoverableConnectorsMcp],buildLastSyncedAtMap([...params.connectorTools, ...params.discoverableConnectorTools]),- { connectorModel: refreshConnectorModel, connectorToolModel: deps.connectorToolModel },+ {+ connectorModel: refreshConnectorModel,+ connectorToolModel: deps.connectorToolModel,+ // Lists under this user's mcp_apps flag, so view-only tools are found too+ userId: deps.userId,+ },);} catch (err) {log('execAgent: failed to schedule connector tool refresh (ignored): %O', err);diff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.tsindex ed4cbb21739..18a3c78c5fd 100644--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts@@ -104,6 +104,21 @@ describe('mergeQueuedFollowUps', () => {).toEqual({ editorData: doc('only') });});+ it('names the MCP App view only when every merged follow-up came from it', () => {+ const fromView = (id: string, createdAt: number, identifier: string) =>+ followUp(id, createdAt, { userMessage: { metadata: { mcpAppSource: { identifier } } } });++ expect(+ mergeQueuedFollowUps([fromView('a', 1, 'weather'), fromView('b', 2, 'weather')]).userMessage,+ ).toEqual({ metadata: { mcpAppSource: { identifier: 'weather' } } });+ expect(+ mergeQueuedFollowUps([fromView('a', 1, 'weather'), followUp('b', 2, {})]).userMessage,+ ).toBeUndefined();+ expect(+ mergeQueuedFollowUps([fromView('a', 1, 'weather'), fromView('b', 2, 'maps')]).userMessage,+ ).toBeUndefined();+ });+it('runs with the newest settings and drops per-send client ids once merged', () => {const merged = mergeQueuedFollowUps([followUp('a', 1, { clientIds: { userMessageId: 'u-a' } as any, deviceId: 'old' }),diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.tsindex b107531bb39..1b581e2920a 100644--- a/apps/server/src/services/aiAgent/steerQueue/index.ts+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts@@ -1,7 +1,11 @@import { createHash, randomUUID } from 'node:crypto';import type { AgentSenderMetadata, ComposerUserMessage, MessageMetadata } from '@lobechat/types';-import { COMPOSER_USER_MESSAGE_METADATA_KEYS, toComposerUserMessage } from '@lobechat/types';+import {+ COMPOSER_USER_MESSAGE_METADATA_KEYS,+ mergeMcpAppSource,+ toComposerUserMessage,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -71,11 +75,16 @@ const uniq = <T>(items: T[]) => [...new Set(items)];const mergeComposerUserMessages = (messages: (ComposerUserMessage | undefined)[],): ComposerUserMessage | undefined => {- const metadata: Record<string, unknown[]> = {};+ const metadata: Record<string, unknown> = {};for (const key of COMPOSER_USER_MESSAGE_METADATA_KEYS) {+ if (key === 'mcpAppSource') continue;const values = messages.flatMap((message): unknown[] => message?.metadata?.[key] ?? []);if (values.length) metadata[key] = values;}+ const mcpAppSource = mergeMcpAppSource(+ messages.map((message) => message?.metadata?.mcpAppSource),+ );+ if (mcpAppSource) metadata.mcpAppSource = mcpAppSource;const editorData = messages.length === 1 ? messages[0]?.editorData : undefined;return toComposerUserMessage({ editorData, metadata: metadata as MessageMetadata });diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.tsindex 2b170263ca1..4cdbb45c093 100644--- a/apps/server/src/services/connector/exec.test.ts+++ b/apps/server/src/services/connector/exec.test.ts@@ -1,15 +1,20 @@+import { getMcpServerFingerprint } from '@lobechat/const/mcpApp';import { beforeEach, describe, expect, it, vi } from 'vitest';import { ConnectorToolPermission } from '@/database/schemas';import { deviceGateway } from '@/server/services/deviceGateway';import { mcpService } from '@/server/services/mcp';-import { callConnectorToolById } from './exec';+import { callConnectorToolById, readConnectorUiResourceById } from './exec';import { scheduleStaleConnectorToolsRefresh } from './refresh';import { ensureFreshConnectorToken } from './tokens';-vi.mock('@/server/services/mcp', () => ({ mcpService: { callTool: vi.fn() } }));+vi.mock('@/server/services/mcp', () => ({+ mcpService: { callTool: vi.fn(), readUiResource: vi.fn() },+}));vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { isConfigured: false } }));+const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));+vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));// The background tool-list refresh is exercised in refresh.test.ts. Here we only// verify the call site wires it up and stays isolated from it.@@ -36,14 +41,19 @@ const tool = (over: Record<string, unknown> = {}) => ({...over,});-const makeCtx = (connectors: any[], tools: any[]) =>+const makeCtx = (connectors: any[], tools: any[], { agentVisible = true } = {}) =>({- connectorModel: { queryByIdentifiers: vi.fn().mockResolvedValue(connectors) },+ agentModel: { existsById: vi.fn().mockResolvedValue(agentVisible) },+ connectorModel: {+ queryByIdentifiers: vi.fn().mockResolvedValue(connectors),+ resolveByIdentifiers: vi.fn().mockResolvedValue(connectors),+ },connectorToolModel: { queryByConnector: vi.fn().mockResolvedValue(tools) },}) as any;beforeEach(() => {vi.clearAllMocks();+ mcpAppsEnabled.mockResolvedValue(false);vi.mocked(ensureFreshConnectorToken).mockImplementation(async (c: any) => c);(deviceGateway as any).isConfigured = false;});@@ -79,6 +89,23 @@ describe('callConnectorToolById', () => {expect(mcpService.callTool).not.toHaveBeenCalled();});+ it('refuses a model call to a tool only its view may call, and runs the view call', async () => {+ const ctx = makeCtx([connector], [tool({ metadata: { visibility: ['app'] } })]);+ vi.mocked(mcpService.callTool).mockResolvedValue({ content: 'ok' } as any);++ await expect(+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),+ ).rejects.toHaveProperty('code', 'FORBIDDEN');+ expect(mcpService.callTool).not.toHaveBeenCalled();++ const server = await getMcpServerFingerprint({ type: 'http', url: connector.mcpServerUrl! });+ await callConnectorToolById(+ { fromApp: true, identifier: 'my-conn', server, toolName: 'do_thing' },+ ctx,+ );+ expect(mcpService.callTool).toHaveBeenCalledWith(expect.objectContaining({ fromApp: true }));+ });+it('calls the remote MCP with the connector auth for an allowed tool', async () => {vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });const ctx = makeCtx([connector], [tool()]);@@ -102,6 +129,61 @@ describe('callConnectorToolById', () => {);});+ it.each([true, false])('passes the caller mcp_apps flag (%s) through', async (enabled) => {+ mcpAppsEnabled.mockResolvedValueOnce(enabled);+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });+ const ctx = { ...makeCtx([connector], [tool()]), userId: 'user-1' };++ await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);++ expect(mcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(mcpService.callTool).toHaveBeenCalledWith(expect.objectContaining({ mcpApps: enabled }));+ });++ it.each([true, undefined])(+ 'passes whether a view made the call (%s) through',+ async (fromApp) => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });+ const ctx = makeCtx([connector], [tool()]);++ const server = await getMcpServerFingerprint({ type: 'http', url: connector.mcpServerUrl! });+ await callConnectorToolById(+ { fromApp, identifier: 'my-conn', server, toolName: 'do_thing' },+ ctx,+ );++ expect(mcpService.callTool).toHaveBeenCalledWith(expect.objectContaining({ fromApp }));+ },+ );++ it("refuses a view's call once only the connector's routing headers changed", async () => {+ const server = await getMcpServerFingerprint({ type: 'http', url: connector.mcpServerUrl! });+ const retargeted = { ...connector, metadata: { customHeaders: { 'X-Tenant': 'b' } } };++ await expect(+ callConnectorToolById(+ { fromApp: true, identifier: 'my-conn', server, toolName: 'do_thing' },+ makeCtx([retargeted], [tool()]),+ ),+ ).rejects.toHaveProperty('code', 'FORBIDDEN');+ expect(mcpService.callTool).not.toHaveBeenCalled();+ });++ it("refuses a view's call once the connector reaches another server than the view's", async () => {+ const ctx = makeCtx([connector], [tool()]);+ const other = await getMcpServerFingerprint({ type: 'http', url: 'https://old.example.com' });++ for (const server of [other, undefined]) {+ await expect(+ callConnectorToolById(+ { fromApp: true, identifier: 'my-conn', server, toolName: 'do_thing' },+ ctx,+ ),+ ).rejects.toHaveProperty('code', 'FORBIDDEN');+ }+ expect(mcpService.callTool).not.toHaveBeenCalled();+ });+it('uses the refreshed token when the connector token was refreshed', async () => {vi.mocked(ensureFreshConnectorToken).mockResolvedValueOnce({...connector,@@ -210,3 +292,153 @@ describe('callConnectorToolById', () => {expect(mcpService.callTool).toHaveBeenCalledTimes(1);});});++describe('readConnectorUiResourceById', () => {+ // The server the connector reaches, which the results in these cases came from+ let SERVER: string;++ beforeEach(async () => {+ mcpAppsEnabled.mockResolvedValue(true);+ SERVER = await getMcpServerFingerprint({ type: 'http', url: connector.mcpServerUrl! });+ });++ it('refuses a view whose result came from another server than the connector reaches', async () => {+ const other = await getMcpServerFingerprint({ type: 'http', url: 'https://old.example.com' });++ await expect(+ readConnectorUiResourceById(+ { identifier: 'my-conn', server: other, uri: 'ui://app' },+ makeCtx([connector], []),+ ),+ ).rejects.toHaveProperty('code', 'NOT_FOUND');+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ expect(mcpService.readUiResource).not.toHaveBeenCalled();+ });++ it('refuses to read a view while the mcp_apps flag is off', async () => {+ mcpAppsEnabled.mockResolvedValue(false);+ const ctx = { ...makeCtx([connector], []), userId: 'user-1' };++ await expect(+ readConnectorUiResourceById({ identifier: 'my-conn', server: SERVER, uri: 'ui://app' }, ctx),+ ).rejects.toHaveProperty('code', 'FORBIDDEN');++ expect(mcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ expect(mcpService.readUiResource).not.toHaveBeenCalled();+ });++ it('reads the resource with the connector credentials', async () => {+ vi.mocked(mcpService.readUiResource).mockResolvedValue({ contents: [] } as any);+ const ctx = makeCtx([connector], []);++ await readConnectorUiResourceById(+ { identifier: 'my-conn', server: SERVER, uri: 'ui://app' },+ ctx,+ );++ expect(ensureFreshConnectorToken).toHaveBeenCalledWith(connector, ctx.connectorModel);+ expect(mcpService.readUiResource).toHaveBeenCalledWith(+ expect.objectContaining({ url: 'https://mcp.example.com' }),+ 'ui://app',+ );+ });++ it('rejects missing, disabled and stdio connectors', async () => {+ await expect(+ readConnectorUiResourceById(+ { identifier: 'x', server: SERVER, uri: 'ui://app' },+ makeCtx([], []),+ ),+ ).rejects.toHaveProperty('code', 'NOT_FOUND');+ await expect(+ readConnectorUiResourceById(+ { identifier: 'my-conn', server: SERVER, uri: 'ui://app' },+ makeCtx([{ ...connector, isEnabled: false }], []),+ ),+ ).rejects.toHaveProperty('code', 'FORBIDDEN');+ await expect(+ readConnectorUiResourceById(+ { identifier: 'my-conn', server: SERVER, uri: 'ui://app' },+ makeCtx([{ ...connector, mcpConnectionType: 'stdio' }], []),+ ),+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');+ expect(mcpService.readUiResource).not.toHaveBeenCalled();+ });++ it('resolves the connector for the agent when one is given', async () => {+ vi.mocked(mcpService.readUiResource).mockResolvedValue({ contents: [] } as any);+ const ctx = makeCtx([connector], []);++ await readConnectorUiResourceById(+ { agentId: 'agt_1', identifier: 'my-conn', server: SERVER, uri: 'ui://app' },+ ctx,+ );++ expect(ctx.connectorModel.resolveByIdentifiers).toHaveBeenCalledWith(['my-conn'], 'agt_1');+ expect(ctx.connectorModel.queryByIdentifiers).not.toHaveBeenCalled();+ });++ it('does not fetch a local-network connector from a cloud deployment', async () => {+ (deviceGateway as any).isConfigured = true;++ await expect(+ readConnectorUiResourceById(+ { identifier: 'my-conn', server: SERVER, uri: 'ui://app' },+ makeCtx([{ ...connector, mcpServerUrl: 'http://192.168.1.20:8080/mcp' }], []),+ ),+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');+ expect(mcpService.readUiResource).not.toHaveBeenCalled();+ });+});++describe('callConnectorToolById agent resolution', () => {+ it('resolves the connector for the agent when one is given', async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true } as any);+ const ctx = makeCtx([connector], [tool()]);++ await callConnectorToolById(+ { agentId: 'agt_1', identifier: 'my-conn', toolName: 'do_thing' },+ ctx,+ );++ expect(ctx.agentModel.existsById).toHaveBeenCalledWith('agt_1');+ expect(ctx.connectorModel.resolveByIdentifiers).toHaveBeenCalledWith(['my-conn'], 'agt_1');+ expect(ctx.connectorModel.queryByIdentifiers).not.toHaveBeenCalled();+ });+});++// Connector rows are scoped by workspace only: another member's private agent+// must not lend its connectors (and their credentials) to the caller.+describe('agent-scoped connectors of an agent the caller cannot see', () => {+ it('does not run a tool on them', async () => {+ const ctx = makeCtx([connector], [tool()], { agentVisible: false });++ await expect(+ callConnectorToolById(+ { agentId: 'agt_private', identifier: 'my-conn', toolName: 'do_thing' },+ ctx,+ ),+ ).rejects.toHaveProperty('code', 'NOT_FOUND');++ expect(ctx.agentModel.existsById).toHaveBeenCalledWith('agt_private');+ expect(ctx.connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ expect(mcpService.callTool).not.toHaveBeenCalled();+ });++ it('does not read their views', async () => {+ mcpAppsEnabled.mockResolvedValue(true);+ const ctx = makeCtx([connector], [], { agentVisible: false });++ await expect(+ readConnectorUiResourceById(+ { agentId: 'agt_private', identifier: 'my-conn', server: 'any', uri: 'ui://app' },+ ctx,+ ),+ ).rejects.toHaveProperty('code', 'NOT_FOUND');++ expect(ctx.connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();+ expect(mcpService.readUiResource).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex 25357eb01f6..22429e6ac96 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -1,8 +1,12 @@+import { getMcpServerFingerprint, isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';import { isLocalOrPrivateUrl } from '@lobechat/utils';+import type { AgentModel } from '@/database/models/agent';+import type { DecryptedConnector } from '@/database/models/connector';import { ConnectorMcpConnectionType, ConnectorToolPermission } from '@/database/schemas';import { deviceGateway } from '@/server/services/deviceGateway';import { mcpService } from '@/server/services/mcp';+import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';import { buildConnectorMcpParams, type ConnectorToolSyncContext } from './sync';@@ -21,6 +25,33 @@ export class ConnectorToolCallError extends Error {}}+export interface ConnectorExecContext extends ConnectorToolSyncContext {+ /** Visibility-aware: decides whether the caller may act as the given agent. */+ agentModel: Pick<AgentModel, 'existsById'>;+ /** `userId` decides the caller's `mcp_apps` flag. */+ userId?: string | null;+}++/**+ * The connector an identifier names. With an agent, resolve the way that agent's+ * runs do (agent-owned > mounted > free base row); without one, keep the base+ * lookup the classic chat path has always used.+ *+ * Connector rows are scoped by workspace only, so in a workspace another+ * member's private agent would resolve to its connectors and their+ * credentials. Only an agent the caller can see may be resolved; any other id+ * reads as not found.+ */+const findConnector = async (+ params: { agentId?: string; identifier: string },+ ctx: ConnectorExecContext,+) => {+ if (!params.agentId) return ctx.connectorModel.queryByIdentifiers([params.identifier]);+ if (!(await ctx.agentModel.existsById(params.agentId))) return [];++ return ctx.connectorModel.resolveByIdentifiers([params.identifier], params.agentId);+};+/*** Execute a single connector tool, enforcing the full permission model:* - the connector must exist and be enabled,@@ -31,17 +62,51 @@ export class ConnectorToolCallError extends Error {* Refreshes the OAuth token first, then calls the remote MCP with the decrypted* credentials. Shared by the `connector.callTool` tRPC procedure.*/+/**+ * Whether an HTTP connector reaches `server` (`getMcpServerFingerprint`): its+ * URL and headers as its calls send them.+ */+const reachesServer = async (+ connector: DecryptedConnector,+ server: string | undefined,+): Promise<boolean> => {+ if (!server || !connector.mcpServerUrl) return false;+ const params = buildConnectorMcpParams(connector);+ if (params.type !== 'http') return false;++ return (+ (await getMcpServerFingerprint({ headers: params.headers, type: 'http', url: params.url })) ===+ server+ );+};+export const callConnectorToolById = async (- params: { args?: string; identifier: string; toolName: string },- ctx: ConnectorToolSyncContext,+ params: {+ agentId?: string;+ args?: string;+ /** An MCP App view's `tools/call`: only tools visible to the app run. */+ fromApp?: boolean;+ identifier: string;+ /** With `fromApp`: the server the view came from; its calls reach no other. */+ server?: string;+ toolName: string;+ },+ ctx: ConnectorExecContext,): Promise<unknown> => {- const [connector] = await ctx.connectorModel.queryByIdentifiers([params.identifier]);+ const [connector] = await findConnector(params, ctx);if (!connector) {throw new ConnectorToolCallError('NOT_FOUND', 'Connector not found');}if (!connector.isEnabled) {throw new ConnectorToolCallError('FORBIDDEN', 'Connector is disabled');}+ // A view open since the connector was pointed elsewhere must not drive the new server+ if (params.fromApp && !(await reachesServer(connector, params.server))) {+ throw new ConnectorToolCallError(+ 'FORBIDDEN',+ 'This view came from another server than the connector reaches now',+ );+ }// The tool MUST be present in the synced list — this is the single source of// truth for what is callable. Unknown names (unsynced or hand-crafted) are@@ -60,6 +125,14 @@ export const callConnectorToolById = async (`Tool '${params.toolName}' is disabled for this connector`,);}+ // A view-only tool never enters the model's tool list; refuse a model call+ // that names it anyway.+ if (!params.fromApp && !isSyncedMcpToolVisibleTo(tool, 'model')) {+ throw new ConnectorToolCallError(+ 'FORBIDDEN',+ `Tool '${params.toolName}' can only be called from its interactive view`,+ );+ }// Keep the tool list fresh through normal use: if it hasn't been synced in a// while, refresh it from the upstream MCP server in the background so the user@@ -104,6 +177,63 @@ export const callConnectorToolById = async (return mcpService.callTool({argsStr: params.args ?? '{}',clientParams: buildConnectorMcpParams(fresh),+ fromApp: params.fromApp,+ mcpApps: await isMcpAppsEnabled(ctx.userId),toolName: params.toolName,});};++/**+ * Read an MCP Apps `ui://` resource from a connector's server, so the chat can+ * render a connector tool result's interactive view. Same connector checks as+ * {@link callConnectorToolById}, minus the per-tool ones. Refused while the+ * `mcp_apps` flag is off, since the read opens a session that advertises MCP Apps.+ */+export const readConnectorUiResourceById = async (+ /** `server`: the server the result came from; the view is read from no other. */+ params: { agentId?: string; identifier: string; server: string; uri: string },+ ctx: ConnectorExecContext,+) => {+ if (!(await isMcpAppsEnabled(ctx.userId))) {+ throw new ConnectorToolCallError('FORBIDDEN', 'Interactive views are turned off');+ }++ const [connector] = await findConnector(params, ctx);+ if (!connector) {+ throw new ConnectorToolCallError('NOT_FOUND', 'Connector not found');+ }+ if (!connector.isEnabled) {+ throw new ConnectorToolCallError('FORBIDDEN', 'Connector is disabled');+ }+ if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) {+ throw new ConnectorToolCallError(+ 'BAD_REQUEST',+ 'Interactive views are not supported for stdio connectors yet',+ );+ }+ // A cloud server can't reach a localhost / LAN endpoint, and resource reads+ // aren't tunneled to the device yet; the chat falls back to the plain result.+ if (+ deviceGateway.isConfigured &&+ !!connector.mcpServerUrl &&+ isLocalOrPrivateUrl(connector.mcpServerUrl)+ ) {+ throw new ConnectorToolCallError(+ 'BAD_REQUEST',+ 'Interactive views are not supported for local-network connectors yet',+ );+ }++ // The identifier may name another server now (the connector was edited, or+ // the agent's copy replaced): its HTML must not get this result's data+ if (!(await reachesServer(connector, params.server))) {+ throw new ConnectorToolCallError(+ 'NOT_FOUND',+ 'This view came from another server than the connector reaches now',+ );+ }++ const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);++ return mcpService.readUiResource(buildConnectorMcpParams(fresh), params.uri);+};diff --git a/apps/server/src/services/connector/refresh.ts b/apps/server/src/services/connector/refresh.tsindex 321a8361b97..ca1f285e291 100644--- a/apps/server/src/services/connector/refresh.ts+++ b/apps/server/src/services/connector/refresh.ts@@ -89,7 +89,8 @@ export const buildLastSyncedAtMap = (export const scheduleStaleConnectorToolsRefresh = (connectors: StaleRefreshConnector[],lastSyncedAtById: Map<string, number>,- ctx: ConnectorToolSyncContext,+ /** `userId` decides the `mcp_apps` flag the refresh lists tools under. */+ ctx: ConnectorToolSyncContext & { userId?: string | null },now: number = Date.now(),): void => {// This runs inline on the request/agent-run hot path. It is a best-effortdiff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.tsindex 30e515c3236..cafdfeb5c63 100644--- a/apps/server/src/services/connector/sync.test.ts+++ b/apps/server/src/services/connector/sync.test.ts@@ -1,9 +1,20 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import type { DecryptedConnector } from '@/database/models/connector';import type { ConnectorCredentials } from '@/database/schemas';+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';+import { mcpService } from '@/server/services/mcp';-import { buildConnectorMcpParams, buildHttpAuthFromCredentials } from './sync';+import {+ buildConnectorMcpParams,+ buildHttpAuthFromCredentials,+ syncConnectorToolsById,+} from './sync';++vi.mock('@/server/services/mcp', () => ({ mcpService: { listRawTools: vi.fn() } }));+const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));+vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));+vi.mock('./tokens', () => ({ ensureFreshConnectorToken: async (connector: unknown) => connector }));const httpConnector = (credentials: ConnectorCredentials | null,@@ -27,7 +38,7 @@ describe('buildHttpAuthFromCredentials', () => {expect(buildHttpAuthFromCredentials(null)).toEqual({});});- it('maps oauth2 to bearer auth with refresh metadata', () => {+ it('maps oauth2 to the access token alone, already refreshed by the caller', () => {const result = buildHttpAuthFromCredentials({accessToken: 'access',clientSecret: 'secret',@@ -36,16 +47,7 @@ describe('buildHttpAuthFromCredentials', () => {type: 'oauth2',});- expect(result).toEqual({- auth: {- accessToken: 'access',- clientId: undefined,- clientSecret: 'secret',- refreshToken: 'refresh',- tokenExpiresAt: 123,- type: 'oauth2',- },- });+ expect(result).toEqual({ auth: { accessToken: 'access', type: 'oauth2' } });expect(result.headers).toBeUndefined();});@@ -73,11 +75,41 @@ describe('buildHttpAuthFromCredentials', () => {});describe('buildConnectorMcpParams', () => {+ it('matches the params agent runs use for an OAuth connector too', () => {+ const connector = httpConnector({+ accessToken: 'access',+ clientSecret: 'secret',+ expiresAt: 123,+ refreshToken: 'refresh',+ type: 'oauth2',+ });+ const [manifest] = buildConnectorManifests(+ [connector],+ [{ toolName: 'do_thing', userConnectorId: 'c1' } as any],+ );++ expect(buildConnectorMcpParams(connector)).toEqual((manifest as any).mcpParams);+ });++ it('matches the params agent runs use, so a view reaches the same MCP session', () => {+ // Display name differs from the identifier: the session key must not depend on it+ const connector = httpConnector(+ { token: 'tok', type: 'bearer' },+ { customHeaders: { x: '1' } },+ );+ const [manifest] = buildConnectorManifests(+ [connector],+ [{ toolName: 'do_thing', userConnectorId: 'c1' } as any],+ );++ expect(buildConnectorMcpParams(connector)).toEqual((manifest as any).mcpParams);+ });+it('builds http params with bearer auth', () => {expect(buildConnectorMcpParams(httpConnector({ token: 'tok', type: 'bearer' }))).toEqual({auth: { token: 'tok', type: 'bearer' },headers: undefined,- name: 'My Connector',+ name: 'my-conn',type: 'http',url: 'https://mcp.example.com',});@@ -91,7 +123,7 @@ describe('buildConnectorMcpParams', () => {).toEqual({auth: undefined,headers: { Authorization: 'Token x' },- name: 'My Connector',+ name: 'my-conn',type: 'http',url: 'https://mcp.example.com',});@@ -100,15 +132,12 @@ describe('buildConnectorMcpParams', () => {it('merges metadata.customHeaders alongside bearer auth', () => {expect(buildConnectorMcpParams(- httpConnector(- { token: 'tok', type: 'bearer' },- { customHeaders: { 'X-Tenant': 't1' } },- ),+ httpConnector({ token: 'tok', type: 'bearer' }, { customHeaders: { 'X-Tenant': 't1' } }),),).toEqual({auth: { token: 'tok', type: 'bearer' },headers: { 'X-Tenant': 't1' },- name: 'My Connector',+ name: 'my-conn',type: 'http',url: 'https://mcp.example.com',});@@ -116,13 +145,11 @@ describe('buildConnectorMcpParams', () => {it('applies metadata.customHeaders with no auth credential', () => {expect(- buildConnectorMcpParams(- httpConnector(null, { customHeaders: { 'X-Api-Key': 'abc' } }),- ),+ buildConnectorMcpParams(httpConnector(null, { customHeaders: { 'X-Api-Key': 'abc' } })),).toEqual({auth: undefined,headers: { 'X-Api-Key': 'abc' },- name: 'My Connector',+ name: 'my-conn',type: 'http',url: 'https://mcp.example.com',});@@ -139,7 +166,7 @@ describe('buildConnectorMcpParams', () => {).toEqual({auth: undefined,headers: { Authorization: 'Token new' },- name: 'My Connector',+ name: 'my-conn',type: 'http',url: 'https://mcp.example.com',});@@ -149,7 +176,7 @@ describe('buildConnectorMcpParams', () => {expect(buildConnectorMcpParams(httpConnector(null))).toEqual({auth: undefined,headers: undefined,- name: 'My Connector',+ name: 'my-conn',type: 'http',url: 'https://mcp.example.com',});@@ -169,8 +196,55 @@ describe('buildConnectorMcpParams', () => {args: ['serve'],command: 'my-mcp',env: { FOO: 'bar' },- name: 'Local Connector',+ name: 'local-conn',type: 'stdio',});});});++describe('syncConnectorToolsById', () => {+ it("syncs view-only tools too, recording each tool's MCP Apps visibility", async () => {+ vi.mocked(mcpService.listRawTools).mockResolvedValue([+ { description: 'Show', inputSchema: { type: 'object' }, name: 'show_dashboard' },+ {+ _meta: { ui: { visibility: ['app'] } },+ description: 'Page',+ inputSchema: { type: 'object' },+ name: 'load_page',+ },+ ]);+ const upsertMany = vi.fn();+ const updateStatus = vi.fn();++ const result = await syncConnectorToolsById('c1', {+ connectorModel: { findById: async () => httpConnector(null), updateStatus } as any,+ connectorToolModel: { upsertMany } as any,+ });++ expect(result).toEqual({ toolCount: 2 });+ expect(upsertMany).toHaveBeenCalledWith('c1', [+ expect.objectContaining({ metadata: null, toolName: 'show_dashboard' }),+ expect.objectContaining({ metadata: { visibility: ['app'] }, toolName: 'load_page' }),+ ]);+ });++ it.each([true, false])(+ "lists on a session announcing MCP Apps under the user's flag (%s)",+ async (enabled) => {+ // A server may list the tools only its views call just to such a client+ mcpAppsEnabled.mockResolvedValueOnce(enabled);+ vi.mocked(mcpService.listRawTools).mockResolvedValue([]);++ await syncConnectorToolsById('c1', {+ connectorModel: { findById: async () => httpConnector(null), updateStatus: vi.fn() } as any,+ connectorToolModel: { upsertMany: vi.fn() } as any,+ userId: 'user-1',+ });++ expect(mcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(mcpService.listRawTools).toHaveBeenCalledWith(expect.anything(), {+ mcpApps: enabled,+ });+ },+ );+});diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.tsindex d3bb9770eed..418d962033f 100644--- a/apps/server/src/services/connector/sync.ts+++ b/apps/server/src/services/connector/sync.ts@@ -1,3 +1,5 @@+import { buildMcpToolMetadata, getMcpToolVisibility } from '@lobechat/const/mcpApp';+import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';import type { ConnectorToolModel } from '@/database/models/connectorTool';import type { ConnectorCredentials } from '@/database/schemas';@@ -5,6 +7,7 @@ import { ConnectorMcpConnectionType, ConnectorStatus } from '@/database/schemas'import type { AuthConfig } from '@/libs/mcp';import { inferCrudType } from '@/libs/mcp/utils';import { mcpService } from '@/server/services/mcp';+import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { ensureFreshConnectorToken } from './tokens';@@ -13,7 +16,14 @@ export interface ConnectorToolSyncContext {connectorToolModel: ConnectorToolModel;}-/** Build the MCP client connection params (with auth) from a connector row. */+/**+ * Build the MCP client connection params (with auth) from a connector row.+ *+ * Must match the params agent runs use (`buildConnectorManifests`): the MCP+ * client session is cached by these params, so a view's resource read and+ * tool calls only reach the session its tool ran on when they are equal.+ * `name` is therefore the stable identifier, not the editable display name.+ */export const buildConnectorMcpParams = (connector: DecryptedConnector,): Parameters<typeof mcpService.listRawTools>[0] => {@@ -23,7 +33,7 @@ export const buildConnectorMcpParams = (args: connector.mcpStdioConfig.args ?? [],command: connector.mcpStdioConfig.command,env: connector.mcpStdioConfig.env,- name: connector.name,+ name: connector.identifier,type: 'stdio',};}@@ -34,12 +44,11 @@ export const buildConnectorMcpParams = (// type. Merge them on top of any header-type credential headers (older rows// stored custom headers as a 'header' credential before this split).const customHeaders = connector.metadata?.customHeaders as Record<string, string> | undefined;- const mergedHeaders =- headers || customHeaders ? { ...headers, ...customHeaders } : undefined;+ const mergedHeaders = headers || customHeaders ? { ...headers, ...customHeaders } : undefined;return {auth,headers: mergedHeaders,- name: connector.name,+ name: connector.identifier,type: 'http',url: connector.mcpServerUrl,};@@ -60,16 +69,11 @@ export const buildHttpAuthFromCredentials = (switch (credentials.type) {case 'oauth2': {- return {- auth: {- accessToken: credentials.accessToken,- clientId: undefined,- clientSecret: credentials.clientSecret,- refreshToken: credentials.refreshToken,- tokenExpiresAt: credentials.expiresAt,- type: 'oauth2',- },- };+ // Only the access token: callers refresh it first (ensureFreshConnectorToken),+ // and the MCP client sends nothing else. Refresh metadata here would also+ // make these params, and so the cached MCP session, differ from the agent+ // runtime's for the same connector.+ return { auth: { accessToken: credentials.accessToken, type: 'oauth2' } };}case 'bearer': {return { auth: { token: credentials.token, type: 'bearer' } };@@ -96,7 +100,8 @@ export const buildHttpAuthFromCredentials = (*/export const syncConnectorToolsById = async (connectorId: string,- ctx: ConnectorToolSyncContext,+ /** `userId` decides the `mcp_apps` flag: with it on, view-only tools are listed too. */+ ctx: ConnectorToolSyncContext & { userId?: string | null },): Promise<{ toolCount: number }> => {let connector = await ctx.connectorModel.findById(connectorId);if (!connector) throw new Error('Connector not found');@@ -112,7 +117,11 @@ export const syncConnectorToolsById = async (let rawTools: Awaited<ReturnType<typeof mcpService.listRawTools>>;try {- rawTools = await mcpService.listRawTools(mcpParams);+ // A server may list the tools only its views call just to a client+ // announcing MCP Apps; they are synced, and kept from the model, all the same+ rawTools = await mcpService.listRawTools(mcpParams, {+ mcpApps: await isMcpAppsEnabled(ctx.userId),+ });} catch (err) {await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);throw err;@@ -122,6 +131,9 @@ export const syncConnectorToolsById = async (crudType: inferCrudType(t.name),description: t.description,inputSchema: t.inputSchema as Record<string, unknown>,+ // Kept even for view-only tools: a view's call must find the tool synced,+ // while the manifest build leaves it out of the model's tool list.+ metadata: buildMcpToolMetadata(getMcpToolVisibility(t._meta)),toolName: t.name,}));diff --git a/apps/server/src/services/mcp/featureGate.test.ts b/apps/server/src/services/mcp/featureGate.test.tsnew file mode 100644index 00000000000..33f2e27103f--- /dev/null+++ b/apps/server/src/services/mcp/featureGate.test.ts@@ -0,0 +1,31 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { isMcpAppsEnabled } from './featureGate';++const getFlags = vi.hoisted(() => vi.fn());+vi.mock('@/server/featureFlags', () => ({ getServerFeatureFlagsStateFromRuntimeConfig: getFlags }));++describe('isMcpAppsEnabled', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('follows the mcp_apps flag for the user', async () => {+ getFlags.mockResolvedValue({ enableMcpApps: true });+ await expect(isMcpAppsEnabled('user-1')).resolves.toBe(true);+ expect(getFlags).toHaveBeenCalledWith('user-1');++ getFlags.mockResolvedValue({ enableMcpApps: false });+ await expect(isMcpAppsEnabled('user-1')).resolves.toBe(false);+ });++ it('treats an unreadable flag as off instead of failing the tool call', async () => {+ getFlags.mockRejectedValue(new Error('redis down'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(isMcpAppsEnabled('user-1')).resolves.toBe(false);+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });+});diff --git a/apps/server/src/services/mcp/featureGate.ts b/apps/server/src/services/mcp/featureGate.tsnew file mode 100644index 00000000000..4be11ea4252--- /dev/null+++ b/apps/server/src/services/mcp/featureGate.ts@@ -0,0 +1,20 @@+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';++/**+ * Whether MCP Apps are on for this user (runtime flag `mcp_apps`, off by+ * default). Off: MCP sessions don't advertise the extension and tool calls+ * don't look up a `ui://` view, so servers answer exactly as they did before.+ *+ * Never fails the tool call it gates: a flag that can't be read counts as off.+ */+export const isMcpAppsEnabled = async (userId?: string | null): Promise<boolean> => {+ try {+ return (+ (await getServerFeatureFlagsStateFromRuntimeConfig(userId ?? undefined)).enableMcpApps ===+ true+ );+ } catch (error) {+ console.error('[MCPApp] Failed to read the mcp_apps feature flag:', error);+ return false;+ }+};diff --git a/apps/server/src/services/mcp/index.manifestDescriptions.test.ts b/apps/server/src/services/mcp/index.manifestDescriptions.test.tsindex 2697ae1f04d..af838835831 100644--- a/apps/server/src/services/mcp/index.manifestDescriptions.test.ts+++ b/apps/server/src/services/mcp/index.manifestDescriptions.test.ts@@ -112,3 +112,40 @@ describe('MCP automatic descriptions and installed tool prompts', () => {},);});++describe('MCP manifests leave out tools only views may call', () => {+ const mixed = [+ { inputSchema: { type: 'object' as const }, name: 'hello' },+ {+ _meta: { ui: { visibility: ['app'] } },+ inputSchema: { type: 'object' as const },+ name: 'load_page',+ },+ ];++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(MCPClient.prototype.listTools).mockResolvedValue(mixed);+ vi.mocked(MCPClient.prototype.listManifests).mockResolvedValue({+ prompts: undefined,+ resources: undefined,+ title: undefined,+ tools: mixed,+ version: undefined,+ });+ });++ it.each(['stdio', 'http'] as const)('%s manifest lists only model-visible tools', async (t) => {+ const service = new MCPService();+ const manifest =+ t === 'stdio'+ ? await service.getStdioMcpServerManifest({ command: 'mcp', name: 'test-mcp' })+ : await service.getStreamableMcpServerManifest('test-mcp', 'https://mcp.example.com');++ expect(manifest.api.map((api) => api.name)).toEqual(['hello']);+ expect(manifest.meta.description).toMatch(/^test-mcp MCP server has 1 tool/);+ // Still known to the view-call policy, outside the model's `api`+ expect(manifest.mcpAppOnlyApi?.map((api) => api.name)).toEqual(['load_page']);+ expect(manifest.mcpModelOnlyTools).toBeUndefined();+ });+});diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.tsindex 8b8dbf08f19..f9de5d76ea4 100644--- a/apps/server/src/services/mcp/index.test.ts+++ b/apps/server/src/services/mcp/index.test.ts@@ -1,6 +1,7 @@import { inspect } from 'node:util';import type * as LobeConst from '@lobechat/const';+import { getMcpServerFingerprint } from '@lobechat/const/mcpApp';import {ProtocolError,ProtocolErrorCode,@@ -139,6 +140,37 @@ describe('MCPService stdio authorization', () => {});});+describe('MCPService MCP Apps sessions', () => {+ const httpParams = { name: 'weather', type: 'http' as const, url: 'https://mcp.example.com' };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(MCPClient.prototype.callTool).mockResolvedValue({ content: [] });+ vi.mocked(MCPClient.prototype.getToolUiResourceUri).mockResolvedValue(undefined);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('advertises MCP Apps only on sessions for users with the flag, cached apart', async () => {+ const service = new MCPService();+ const call = (mcpApps: boolean) =>+ service.callTool({ argsStr: '{}', clientParams: httpParams, mcpApps, toolName: 'forecast' });++ await call(false);+ await call(true);+ await call(false);+ await call(true);++ // One session per capability set, each reused+ expect(MCPClient).toHaveBeenCalledTimes(2);+ expect(MCPClient).toHaveBeenNthCalledWith(1, httpParams, { mcpApps: false });+ expect(MCPClient).toHaveBeenNthCalledWith(2, httpParams, { mcpApps: true });+ expect(MCPClient.prototype.getToolUiResourceUri).toHaveBeenCalledTimes(2);+ });+});+describe('MCPService log redaction', () => {beforeEach(() => {vi.clearAllMocks();@@ -248,6 +280,7 @@ describe('MCPService log redaction', () => {callTool: vi.fn().mockResolvedValue({content: [{ text: 'tool-result-secret', type: 'text' }],}),+ getToolUiResourceUri: vi.fn().mockResolvedValue(undefined),};vi.spyOn(service as any, 'getClient').mockResolvedValue(mockClient);@@ -279,6 +312,9 @@ describe('MCPService', () => {// 创建 mock 客户端mockClient = {callTool: vi.fn(),+ getToolUiResourceUri: vi.fn().mockResolvedValue(undefined),+ isToolCallableByApp: vi.fn().mockResolvedValue(true),+ isToolHiddenFromModel: vi.fn().mockResolvedValue(false),listManifests: vi.fn(),listPrompts: vi.fn(),listResources: vi.fn(),@@ -289,6 +325,28 @@ describe('MCPService', () => {getClientSpy = vi.spyOn(mcpService as any, 'getClient').mockResolvedValue(mockClient);});+ describe('manifest discovery with MCP Apps', () => {+ it('discovers on a session announcing MCP Apps when asked, so view-only tools are found', async () => {+ mockClient.listTools.mockResolvedValue([]);+ mockClient.listManifests.mockResolvedValue({ tools: [] });++ await mcpService.getStreamableMcpServerManifest(+ 'srv',+ 'https://mcp.example.com',+ undefined,+ undefined,+ undefined,+ { mcpApps: true },+ );+ await mcpService.getStdioMcpServerManifest({ command: 'srv', name: 'srv' }, undefined, {+ mcpApps: true,+ });++ expect(getClientSpy).toHaveBeenNthCalledWith(1, expect.anything(), false, { mcpApps: true });+ expect(getClientSpy).toHaveBeenNthCalledWith(2, expect.anything(), false, { mcpApps: true });+ });+ });+describe('manifest descriptions', () => {it.each(['My server description'])('keeps stdio descriptions as metadata (%s)',@@ -485,6 +543,148 @@ describe('MCPService', () => {expect(result.state).toEqual(errorResult);});+ it('should attach the MCP App resource for tools that declare a ui:// resource', async () => {+ mockClient.getToolUiResourceUri.mockResolvedValue('ui://weather/view.html');+ mockClient.callTool.mockResolvedValue({+ content: [{ type: 'text', text: 'sunny' }],+ isError: false,+ });++ const result = await mcpService.callTool({+ clientParams: mockParams,+ mcpApps: true,+ toolName: 'weather',+ argsStr: '{}',+ });++ expect(getClientSpy).toHaveBeenCalledWith(mockParams, false, { mcpApps: true });+ expect(mockClient.getToolUiResourceUri).toHaveBeenCalledWith('weather');+ // With the server it may be read back from+ expect(result.state.mcpApp).toEqual({+ resourceUri: 'ui://weather/view.html',+ server: await getMcpServerFingerprint(mockParams),+ });+ });++ it("runs a view's call to a tool whose visibility includes the app", async () => {+ mockClient.callTool.mockResolvedValue({+ content: [{ type: 'text', text: 'sunny' }],+ isError: false,+ });++ const result = await mcpService.callTool({+ argsStr: '{}',+ clientParams: mockParams,+ fromApp: true,+ mcpApps: true,+ toolName: 'weather',+ });++ expect(mockClient.isToolCallableByApp).toHaveBeenCalledWith('weather');+ expect(mockClient.callTool).toHaveBeenCalledWith('weather', {});+ expect(result.success).toBe(true);+ });++ it("refuses a view's call to a tool kept from views, without running it", async () => {+ mockClient.isToolCallableByApp.mockResolvedValue(false);++ const result = await mcpService.callTool({+ argsStr: '{}',+ clientParams: mockParams,+ fromApp: true,+ mcpApps: true,+ toolName: 'delete_all',+ });++ expect(mockClient.callTool).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.state.isError).toBe(true);+ });++ it('refuses a model call to a tool only its views may call, without running it', async () => {+ mockClient.isToolHiddenFromModel.mockResolvedValue(true);++ const result = await mcpService.callTool({+ argsStr: '{}',+ clientParams: mockParams,+ mcpApps: true,+ toolName: 'load_page',+ });++ expect(mockClient.isToolHiddenFromModel).toHaveBeenCalledWith('load_page');+ expect(mockClient.callTool).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ });++ it("returns a view the tool's own media, not the chat's uploaded copies", async () => {+ const image = { data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' };+ mockClient.callTool.mockResolvedValue({ content: [image], isError: false });+ const processContentBlocks = vi.fn(async (blocks: any[]) =>+ blocks.map((block) => ({ ...block, data: 'https://files.example.com/a.png' })),+ );++ const result = await mcpService.callTool({+ argsStr: '{}',+ clientParams: mockParams,+ fromApp: true,+ mcpApps: true,+ processContentBlocks,+ toolName: 'snapshot',+ });++ expect(processContentBlocks).not.toHaveBeenCalled();+ expect(result.state.content).toEqual([image]);+ });++ it("refuses a view's call while the mcp_apps flag is off", async () => {+ const result = await mcpService.callTool({+ argsStr: '{}',+ clientParams: mockParams,+ fromApp: true,+ toolName: 'weather',+ });++ expect(mockClient.isToolCallableByApp).not.toHaveBeenCalled();+ expect(mockClient.callTool).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ });++ it('should neither look up nor attach a view while the mcp_apps flag is off', async () => {+ mockClient.getToolUiResourceUri.mockResolvedValue('ui://weather/view.html');+ mockClient.callTool.mockResolvedValue({+ content: [{ type: 'text', text: 'sunny' }],+ isError: false,+ });++ const result = await mcpService.callTool({+ clientParams: mockParams,+ toolName: 'weather',+ argsStr: '{}',+ });++ // A session without the MCP Apps capability, and no listTools round trip+ expect(getClientSpy).toHaveBeenCalledWith(mockParams, false, { mcpApps: false });+ expect(mockClient.getToolUiResourceUri).not.toHaveBeenCalled();+ expect(result.state.mcpApp).toBeUndefined();+ });++ it('should not attach the MCP App resource to error results', async () => {+ mockClient.getToolUiResourceUri.mockResolvedValue('ui://weather/view.html');+ mockClient.callTool.mockResolvedValue({+ content: [{ type: 'text', text: 'boom' }],+ isError: true,+ });++ const result = await mcpService.callTool({+ clientParams: mockParams,+ mcpApps: true,+ toolName: 'weather',+ argsStr: '{}',+ });++ expect(result.state.mcpApp).toBeUndefined();+ });+it('should throw TRPCError when client throws error', async () => {const error = new Error('MCP client error');mockClient.callTool.mockRejectedValue(error);@@ -535,8 +735,8 @@ describe('MCPService', () => {expect(result.success).toBe(true);expect(mockClient.callTool).toHaveBeenCalledTimes(2);// Retry must drop the cached client: first attempt skipCache=false, retry skipCache=true- expect(getClientSpy).toHaveBeenNthCalledWith(1, mockParams, false);- expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true);+ expect(getClientSpy).toHaveBeenNthCalledWith(1, mockParams, false, { mcpApps: false });+ expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true, { mcpApps: false });});it('should retry up to 3 times for NoValidSessionId error', async () => {@@ -603,6 +803,55 @@ describe('MCPService', () => {});});+ describe('readUiResource', () => {+ const mockParams = { name: 'test-mcp', type: 'http' as const, url: 'https://example.com/mcp' };++ it('reads ui:// resources through the client', async () => {+ const resource = { contents: [{ text: '<html></html>', uri: 'ui://app' }] };+ mockClient.readResource = vi.fn().mockResolvedValue(resource);++ await expect(mcpService.readUiResource(mockParams, 'ui://app')).resolves.toEqual(resource);+ expect(mockClient.readResource).toHaveBeenCalledWith('ui://app');+ // The session that advertised MCP Apps, like the call that stored the view+ expect(getClientSpy).toHaveBeenCalledWith(mockParams, false, { mcpApps: true });+ });++ it("falls back to the resource's listing entry for the view's metadata", async () => {+ const csp = { connectDomains: ['https://api.example.com'] };+ mockClient.readResource = vi+ .fn()+ .mockResolvedValue({ contents: [{ text: '<html />', uri: 'ui://app' }] });+ mockClient.listResources = vi+ .fn()+ .mockResolvedValue([{ _meta: { ui: { csp } }, name: 'app', uri: 'ui://app' }]);++ const result = await mcpService.readUiResource(mockParams, 'ui://app');++ // Without it the CSP would block every domain the app declared+ expect(result.contents[0]._meta).toEqual({ ui: { csp } });+ });++ it("doesn't list resources when the read declares the view's metadata", async () => {+ const own = { _meta: { ui: { prefersBorder: false } }, text: '<html />', uri: 'ui://app' };+ mockClient.readResource = vi.fn().mockResolvedValue({ contents: [own] });+ mockClient.listResources = vi.fn();++ await expect(mcpService.readUiResource(mockParams, 'ui://app')).resolves.toEqual({+ contents: [own],+ });+ expect(mockClient.listResources).not.toHaveBeenCalled();+ });++ it('rejects non-ui:// URIs without touching the server', async () => {+ mockClient.readResource = vi.fn();++ await expect(mcpService.readUiResource(mockParams, 'file:///etc/passwd')).rejects.toThrow(+ TRPCError,+ );+ expect(mockClient.readResource).not.toHaveBeenCalled();+ });+ });+describe('listTools', () => {const mockParams = {name: 'test-mcp',@@ -757,7 +1006,7 @@ describe('MCPService', () => {expect(result).toEqual(resources);expect(mockClient.listResources).toHaveBeenCalledTimes(2);- expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true);+ expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true, { mcpApps: false });});it('should throw TRPCError on other errors without retry', async () => {@@ -785,7 +1034,7 @@ describe('MCPService', () => {expect(result).toEqual(prompts);expect(mockClient.listPrompts).toHaveBeenCalledTimes(2);- expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true);+ expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true, { mcpApps: false });});it('should throw TRPCError on other errors without retry', async () => {diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.tsindex acc8afd5f1d..7861512d72c 100644--- a/apps/server/src/services/mcp/index.ts+++ b/apps/server/src/services/mcp/index.ts@@ -1,4 +1,10 @@import { isDesktop } from '@lobechat/const';+import {+ getMcpServerFingerprint,+ lacksUiResourceMeta,+ partitionMcpToolsForViews,+ withListingUiMeta,+} from '@lobechat/const/mcpApp';import {type CheckMcpInstallResult,ConnectorErrorCode,@@ -16,6 +22,7 @@ import retry from 'async-retry';import debug from 'debug';import {+ type McpAppToolState,type MCPClientParams,type McpPrompt,type McpResource,@@ -23,6 +30,7 @@ import {type StdioMCPParams,} from '@/libs/mcp';import { MCPClient } from '@/libs/mcp';+import { isToolVisibleToModel } from '@/libs/mcp/mcpApp';import {getMCPConnectionErrorType,getMCPErrorLogMetadata,@@ -57,6 +65,7 @@ export interface MCPToolCallProcessedResult {state: {content: any[];isError?: boolean;+ mcpApp?: McpAppToolState;};success: boolean;}@@ -125,6 +134,7 @@ export class MCPService {params: MCPClientParams,operationName: string,operation: (client: MCPClient) => Promise<T>,+ { mcpApps = false }: { mcpApps?: boolean } = {},): Promise<T> {const connection = this.getConnectionLogMetadata(params);@@ -140,7 +150,7 @@ export class MCPService {// failure (bad URL/token, stdio spawn error) is NOT a stale-session// error, so it must bail immediately instead of retrying — otherwise// we'd repeat auth attempts / respawn stdio commands needlessly.- const client = await this.getClient(params, skipCache);+ const client = await this.getClient(params, skipCache, { mcpApps });return await operation(client);} catch (error) {// Only retry for NoValidSessionId errors@@ -176,22 +186,29 @@ export class MCPService {return this.withSessionRetry(params, 'listing tools', async (client) => {const result = await client.listTools();log(`Tools listed successfully, result count: %d`, result.length);- return result.map<LobeChatPluginApi>((item) => ({- // Assuming identifier is the unique name/id- description: item.description,- name: item.name,- parameters: item.inputSchema as ToolManifestSettings,- }));+ return this.transformMCPToolToLobeAPI(result);});}// listTools now accepts MCPClientParams- async listRawTools(params: MCPClientParams): Promise<McpTool[]> {- return this.withSessionRetry(params, 'listing tools', async (client) => {- const result = await client.listTools();- log(`Tools listed successfully, result count: %d`, result.length);- return result;- });+ async listRawTools(+ params: MCPClientParams,+ /**+ * List on a session that announces MCP Apps (the user's `mcp_apps` flag):+ * a server may list the tools only its views call just to such a client.+ */+ { mcpApps = false }: { mcpApps?: boolean } = {},+ ): Promise<McpTool[]> {+ return this.withSessionRetry(+ params,+ 'listing tools',+ async (client) => {+ const result = await client.listTools();+ log(`Tools listed successfully, result count: %d`, result.length);+ return result;+ },+ { mcpApps },+ );}// listResources now accepts MCPClientParams@@ -212,15 +229,54 @@ export class MCPService {});}+ /**+ * Read an MCP Apps `ui://` resource (the HTML a tool result renders with).+ * Only `ui://` URIs are allowed so this can't be used as a generic resource reader.+ * Uses the session that advertised MCP Apps, as the tool call that stored+ * the view did.+ */+ async readUiResource(params: MCPClientParams, uri: string) {+ if (!uri.startsWith('ui://')) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Only ui:// resources can be read' });+ }++ return this.withSessionRetry(+ params,+ `reading resource "${uri}"`,+ async (client) => {+ const result = await client.readResource(uri);+ // A view's _meta.ui may be declared once, on its resources/list entry+ if (!lacksUiResourceMeta(result)) return result;++ return withListingUiMeta(result, uri, await client.listResources());+ },+ { mcpApps: true },+ );+ }+// callTool now accepts an object with clientParams, toolName, argsStr, and processContentBlocksasync callTool(options: {argsStr: any;clientParams: MCPClientParams;+ /**+ * The call comes from an MCP App view (`tools/call`), not the model. Only+ * tools whose `_meta.ui.visibility` includes "app" run; others, and any+ * call while `mcpApps` is off, return a failed result without reaching the tool.+ */+ fromApp?: boolean;+ /**+ * Runtime flag `mcp_apps` for the calling user. On: the session advertises+ * MCP Apps and the result carries the tool's `ui://` view. Off: the call+ * runs as it did before MCP Apps, with no capability and no tool lookup.+ */+ mcpApps?: boolean;processContentBlocks?: ProcessContentBlocksFn;toolName: string;}): Promise<any> {const {clientParams,+ fromApp = false,+ mcpApps = false,toolName,argsStr,processContentBlocks: processContentBlocksFn,@@ -228,19 +284,52 @@ export class MCPService {const args = safeParseJSON(argsStr);- return this.withSessionRetry(clientParams, `calling tool "${toolName}"`, async (client) => {+ const run = async (client: MCPClient) => {log('Calling MCP tool: %s', toolName);+ // Resolved before the call: a stale-session error here is retried by+ // withSessionRetry, which must never re-run a tool that already executed.+ if (fromApp && !(mcpApps && (await client.isToolCallableByApp(toolName)))) {+ const message = `The tool "${toolName}" can't be called from an interactive view.`;+ return {+ content: message,+ state: { content: [{ text: message, type: 'text' }], isError: true },+ success: false,+ };+ }+ // A tool the server keeps from the model is its views' alone, even when+ // the model names it (e.g. from an earlier turn)+ if (!fromApp && mcpApps && (await client.isToolHiddenFromModel(toolName))) {+ const message = `The tool "${toolName}" can only be called from its interactive view.`;+ return {+ content: message,+ state: { content: [{ text: message, type: 'text' }], isError: true },+ success: false,+ };+ }+ const uiResourceUri = mcpApps ? await client.getToolUiResourceUri(toolName) : undefined;+try {// Delegate the call to the MCPClient instanceconst result = await client.callTool(toolName, args); // Pass args directly// Use the common processing method+ // A view gets the tool's own MCP result: its media stays base64 `data`,+ // not the uploaded URLs the chat storesconst processedResult = await MCPService.processToolCallResult(result,- processContentBlocksFn,+ fromApp ? undefined : processContentBlocksFn,);+ // MCP Apps: let the chat UI know which `ui://` resource renders this+ // result, and from which server it may be read back+ if (uiResourceUri && !result.isError) {+ processedResult.state.mcpApp = {+ resourceUri: uiResourceUri,+ server: await getMcpServerFingerprint(clientParams),+ };+ }+log('MCP tool call completed: %O', {contentBlockCount: Array.isArray(processedResult.state.content)? processedResult.state.content.length@@ -270,11 +359,17 @@ export class MCPService {// Other errors propagate; withSessionRetry wraps them as a TRPCErrorthrow error;}- });+ };++ return this.withSessionRetry(clientParams, `calling tool "${toolName}"`, run, { mcpApps });}// Private method to get or initialize a client based on parameters- private async getClient(params: MCPClientParams, skipCache = false): Promise<MCPClient> {+ private async getClient(+ params: MCPClientParams,+ skipCache = false,+ { mcpApps = false }: { mcpApps?: boolean } = {},+ ): Promise<MCPClient> {// Every server caller (including connector sync and agent tool execution)// must enforce the same Desktop-only stdio boundary, even for cached clients.if (params.type === 'stdio' && !isDesktop) {@@ -285,7 +380,9 @@ export class MCPService {});}- const key = this.serializeParams(params); // Use custom serialization+ // A session announces its capabilities once, at initialize, so sessions+ // with and without MCP Apps are cached apart.+ const key = `${this.serializeParams(params)}${mcpApps ? '#mcp-apps' : ''}`;if (!skipCache && this.clients.has(key)) {return this.clients.get(key)!;@@ -294,7 +391,7 @@ export class MCPService {const connection = this.getConnectionLogMetadata(params);log(`No cached client found, Initializing new client.`);try {- const client = new MCPClient(params);+ const client = new MCPClient(params, { mcpApps });await client.initialize({onProgress: (progress) => {log(`New client initializing... ${progress.progress}/${progress.total}`);@@ -368,6 +465,8 @@ export class MCPService {type: 'none' | 'bearer' | 'oauth2';},headers?: Record<string, string>,+ /** Discover on a session that announces MCP Apps, so view-only tools are found too. */+ { mcpApps = false }: { mcpApps?: boolean } = {},): Promise<ToolManifest> {const mcpParams = { name: identifier, type: 'http' as const, url };@@ -381,11 +480,13 @@ export class MCPService {(mcpParams as any).headers = headers;}- const tools = await this.listTools(mcpParams);+ const rawTools = await this.listRawTools(mcpParams, { mcpApps });+ const tools = this.transformMCPToolToLobeAPI(rawTools);return {api: tools,identifier,+ ...this.toMcpAppsManifestFields(rawTools),// @ts-ignoremcpParams,meta: {@@ -403,6 +504,8 @@ export class MCPService {async getStdioMcpServerManifest(params: Omit<StdioMCPParams, 'type'>,metadata?: CustomPluginMetadata,+ /** Discover on a session that announces MCP Apps, so view-only tools are found too. */+ { mcpApps = false }: { mcpApps?: boolean } = {},): Promise<ToolManifest> {const mcpParams = {args: params.args,@@ -412,21 +515,24 @@ export class MCPService {type: 'stdio' as const,};- const client = await this.getClient(mcpParams); // Get client using params+ const client = await this.getClient(mcpParams, false, { mcpApps });const manifest = await client.listManifests();const identifier = params.name;+ const api = manifest.tools ? this.transformMCPToolToLobeAPI(manifest.tools) : [];return {- api: manifest.tools ? this.transformMCPToolToLobeAPI(manifest.tools) : [],+ api,identifier,meta: {avatar: metadata?.avatar || 'MCP_AVATAR',- description: metadata?.description || getMcpServerDescription(identifier, manifest),+ description:+ metadata?.description || getMcpServerDescription(identifier, { ...manifest, tools: api }),title: metadata?.name || identifier,},...manifest,+ ...this.toMcpAppsManifestFields(manifest.tools ?? []),// @ts-ignoremcpParams,// TODO: temporary@@ -497,14 +603,37 @@ export class MCPService {}}- private transformMCPToolToLobeAPI = (data: McpTool[]) => {- return data.map<LobeChatPluginApi>((item) => ({+ /**+ * The model-facing api of a plugin manifest. Tools whose MCP Apps visibility+ * leaves out "model" exist only for their view, which calls them through the+ * MCP session, so they never enter the manifest.+ */+ private transformMCPToolToLobeAPI = (data: McpTool[]) =>+ this.toLobeApi(data.filter(isToolVisibleToModel));++ /**+ * MCP Apps: what a plugin's views may call beyond its model-facing `api`,+ * and which `api` tools they may not, so the view-call policy finds every+ * tool a view may reach without the model seeing the view-only ones.+ */+ private toMcpAppsManifestFields = (+ data: McpTool[],+ ): Pick<ToolManifest, 'mcpAppOnlyApi' | 'mcpModelOnlyTools'> => {+ const { appOnlyTools, modelOnlyToolNames } = partitionMcpToolsForViews(data);++ return {+ ...(appOnlyTools.length > 0 && { mcpAppOnlyApi: this.toLobeApi(appOnlyTools) }),+ ...(modelOnlyToolNames.length > 0 && { mcpModelOnlyTools: modelOnlyToolNames }),+ };+ };++ private toLobeApi = (data: McpTool[]) =>+ data.map<LobeChatPluginApi>((item) => ({// Assuming identifier is the unique name/iddescription: item.description,name: item.name,parameters: item.inputSchema as ToolManifestSettings,}));- };}// Export a singleton instancediff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex ab1c43768de..39a58fdebf4 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -20,6 +20,8 @@ vi.mock('@/server/services/deviceGateway', () => ({queryDeviceList: vi.fn().mockResolvedValue([]),},}));+const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));+vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),}));@@ -529,6 +531,24 @@ describe('ToolExecutionService', () => {);});+ it('drops the MCP App view a device marked on its result', async () => {+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValueOnce({+ content: 'ok',+ state: { content: [], mcpApp: { resourceUri: 'ui://dash/view' } },+ success: true,+ } as any);+ const result = await makeService().executeTool(+ mcpPayload,+ contextWith(+ { args: [], command: 'dash-mcp', name: 'my-mcp', type: 'stdio' },+ { activeDeviceId: 'device-1' },+ ),+ );++ // Another client opening the conversation would serve it from its own machine+ expect(result.state).toEqual({ content: [] });+ });+it('tunnels a local-network HTTP MCP call and narrows the auth payload', async () => {const service = makeService();await service.executeTool(@@ -738,6 +758,83 @@ describe('ToolExecutionService', () => {expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();});+ it.each([true, false])(+ "passes the run owner's mcp_apps flag (%s) to the server MCP call",+ async (enabled) => {+ mcpAppsEnabled.mockResolvedValueOnce(enabled);+ const callTool = vi.fn().mockResolvedValue({ ok: true });+ const service = makeService({ callTool });++ await service.executeTool(+ mcpPayload,+ contextWith({ name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' }),+ );++ expect(mcpAppsEnabled).toHaveBeenCalledWith('user-1');+ expect(callTool).toHaveBeenCalledWith(expect.objectContaining({ mcpApps: enabled }));+ },+ );++ it("gives the model only the text of an HTTP MCP result with a view, keeping the view's data in its state", async () => {+ const raw = {+ _meta: { view: { rows: ['secret'] } },+ content: [{ text: 'Found 1 row', type: 'text' }],+ structuredContent: { rows: ['secret'] },+ };+ const callTool = vi.fn().mockResolvedValue({+ content: 'Found 1 row',+ state: { ...raw, mcpApp: { resourceUri: 'ui://rows' } },+ success: true,+ });+ const service = makeService({ callTool });++ const result = await service.executeTool(+ mcpPayload,+ contextWith({ name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' }),+ );++ expect(result.content).toBe('Found 1 row');+ expect(result.state).toMatchObject({+ state: { _meta: raw._meta, mcpApp: { resourceUri: 'ui://rows' } },+ });+ });++ it("keeps an HTTP MCP result's structured output for the model when it has no view", async () => {+ const callTool = vi.fn().mockResolvedValue({+ content: '',+ state: { content: [], structuredContent: { temperature: 20 } },+ success: true,+ });+ const service = makeService({ callTool });++ const result = await service.executeTool(+ mcpPayload,+ contextWith({ name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' }),+ );++ expect(JSON.parse(result.content).state.structuredContent).toEqual({ temperature: 20 });+ });++ it("keeps an HTTP MCP result's _meta from the model when it has no view, in its state", async () => {+ // An error from an Apps-aware server: no view, but view-only metadata+ const state = {+ _meta: { view: { token: 'view-only' } },+ content: [{ text: 'failed', type: 'text' }],+ isError: true,+ };+ const callTool = vi.fn().mockResolvedValue({ content: 'failed', state, success: false });+ const service = makeService({ callTool });++ const result = await service.executeTool(+ mcpPayload,+ contextWith({ name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' }),+ );++ expect(result.content).not.toContain('view-only');+ expect(JSON.parse(result.content).state.content).toEqual(state.content);+ expect(result.state).toMatchObject({ state });+ });+it.each([{ name: 'my-mcp', type: 'http', url: 'http://localhost:8080/mcp' },{ args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 03544db1d7c..d8f2f4d4153 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -21,6 +21,7 @@ import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceCimport { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';+import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { DiscoverService } from '../discover';import { type MCPService } from '../mcp';@@ -126,6 +127,22 @@ const getThrownErrorText = (error: unknown): string => {}};+/**+ * What the model reads of a server MCP call. A result with an MCP App view+ * gives its text only: MCP Apps keeps `structuredContent` and `_meta` for the+ * view, out of model context. Any other result (no view, an error, a failed+ * view lookup) keeps its serialized form, `structuredContent` included, but+ * never `_meta`: protocol metadata, where an Apps-aware server keeps what only+ * its views may see.+ */+const toModelContent = (result: any): string => {+ if (result?.state?.mcpApp) return result.content;+ if (!result?.state || typeof result.state !== 'object') return JSON.stringify(result);++ const { _meta, ...state } = result.state;+ return JSON.stringify({ ...result, state });+};+export class ToolExecutionService {private builtinToolsExecutor: BuiltinToolsExecutor;private mcpService: MCPService;@@ -342,13 +359,14 @@ export class ToolExecutionService {const result = await this.mcpService.callTool({argsStr: args,clientParams: mcpParams,+ mcpApps: await isMcpAppsEnabled(context.userId),toolName: apiName,});log('MCP tool execution completed for: %s:%s', identifier, apiName);return {- content: typeof result === 'string' ? result : JSON.stringify(result),+ content: typeof result === 'string' ? result : toModelContent(result),...(result?.success === false? { error: { code: 'MCP_TOOL_ERROR', message: result.error?.message ?? result.content } }: {}),@@ -538,9 +556,14 @@ export class ToolExecutionService {});}+ // An MCP App view is read and driven from the client that opens the+ // conversation, not from the device that ran the tool, so a result from a+ // device offers none.+ const { mcpApp: _deviceView, ...state } = (result.state as Record<string, any>) ?? {};+return {content: result.content,- state: (result.state as Record<string, any>) ?? undefined,+ state: result.state ? state : undefined,success: true,};}diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdxindex 824ec9a3a17..b29b581d2d6 100644--- a/docs/self-hosting/advanced/feature-flags.mdx+++ b/docs/self-hosting/advanced/feature-flags.mdx@@ -45,6 +45,7 @@ You can achieve various feature combinations using the above configuration synta| `agent_gateway_mux_mobile` | LobeHub Mobile rollout switch for the multiplexed gateway socket and protocol-v2 payloads; Web needs no flag and follows `AGENT_GATEWAY_PROTOCOL`. Requires a gateway that serves `/v2/ws`. | Disabled || `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled || `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `builtin-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |+| `mcp_apps` | MCP Apps: a tool result whose MCP server declares an interactive `ui://` view renders that view (the server's HTML, in a sandboxed iframe) in the conversation. When off, such results render as plain tool results and the server does not announce MCP Apps support to MCP servers. | Disabled || `edit_agent` | Allows users to edit assistants. | Enabled || `ai_image` | Controls AI image generation feature and page (/image). | Enabled || `speech_to_text` | Enables speech-to-text functionality. | Enabled |diff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdxindex 2e5dfb5f413..92d27a99524 100644--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx@@ -32,29 +32,30 @@ tags:关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。</Callout>-| 配置项 | 解释 | 默认值 |-| -------------------------- | ----------------------------------------------------------------------------------------------------------------- | --- |-| `check_updates` | 允许检查更新。 | 开启 |-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |-| `agent_gateway_mux_mobile` | LobeHub Mobile 使用多路复用网关连接与 v2 协议载荷的灰度开关;Web 无需开关,跟随 `AGENT_GATEWAY_PROTOCOL`;需要网关提供 `/v2/ws`。 | 关闭 |-| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |-| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |-| `edit_agent` | 允许用户编辑助手。 | 开启 |-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |-| `speech_to_text` | 启用语音转文本功能。 | 开启 |-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |-| `welcome_suggest` | 显示欢迎建议。 | 开启 |-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |-| `market` | 启用助手市场功能。 | 开启 |-| `knowledge_base` | 启用知识库功能。 | 开启 |-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |+| 配置项 | 解释 | 默认值 |+| -------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --- |+| `check_updates` | 允许检查更新。 | 开启 |+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |+| `agent_gateway_mux_mobile` | LobeHub Mobile 使用多路复用网关连接与 v2 协议载荷的灰度开关;Web 无需开关,跟随 `AGENT_GATEWAY_PROTOCOL`;需要网关提供 `/v2/ws`。 | 关闭 |+| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |+| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |+| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 |+| `edit_agent` | 允许用户编辑助手。 | 开启 |+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |+| `speech_to_text` | 启用语音转文本功能。 | 开启 |+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |+| `welcome_suggest` | 显示欢迎建议。 | 开启 |+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |+| `market` | 启用助手市场功能。 | 开启 |+| `knowledge_base` | 启用知识库功能。 | 开启 |+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |## 交互式助理分享:部署与灰度边界diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 5a1084fc719..d7b0d27fdf5 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -882,6 +882,22 @@"list.item.local.title": "Custom","loading.content": "Calling Skill…","loading.plugin": "Skill running…",+ "mcpApp.message.confirm.cancel": "Cancel",+ "mcpApp.message.confirm.content": "The {{app}} view wants to send this message to the conversation. Sending it starts a new reply.",+ "mcpApp.message.confirm.ok": "Send",+ "mcpApp.message.confirm.title": "Send this message from the view?",+ "mcpApp.message.source": "Follow-up from the {{app}} view",+ "mcpApp.openLink.confirm.cancel": "Cancel",+ "mcpApp.openLink.confirm.content": "The {{app}} view wants to open this link.",+ "mcpApp.openLink.confirm.ok": "Open",+ "mcpApp.openLink.confirm.title": "Open this link from the view?",+ "mcpApp.toolCall.busy": "The tool \"{{tool}}\" was not run: too many of this view's tool calls are waiting for approval. Try again once they are answered.",+ "mcpApp.toolCall.confirm.cancel": "Deny",+ "mcpApp.toolCall.confirm.content": "The {{app}} view wants to run the tool \"{{tool}}\" with these arguments. Your approval settings ask before it runs.",+ "mcpApp.toolCall.confirm.ok": "Allow",+ "mcpApp.toolCall.confirm.title": "Allow this tool to run?",+ "mcpApp.toolCall.rejected": "The tool \"{{tool}}\" was not run: it is not available to this view or was not approved.",+ "mcpApp.waitingApproval": "Waiting for your approval…","mcpEmpty.deployment": "No deployment options","mcpEmpty.prompts": "No prompts","mcpEmpty.resources": "No resources",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 60ff2381ac9..d1fc44fc89b 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -882,6 +882,22 @@"list.item.local.title": "自定义","loading.content": "调用技能中…","loading.plugin": "技能运行中…",+ "mcpApp.message.confirm.cancel": "取消",+ "mcpApp.message.confirm.content": "{{app}} 的页面想把下面这条消息发到对话里,发送后助理会开始新的回复。",+ "mcpApp.message.confirm.ok": "发送",+ "mcpApp.message.confirm.title": "要发送这条来自页面的消息吗?",+ "mcpApp.message.source": "来自 {{app}} 页面的追问",+ "mcpApp.openLink.confirm.cancel": "取消",+ "mcpApp.openLink.confirm.content": "{{app}} 的页面想打开下面这个链接。",+ "mcpApp.openLink.confirm.ok": "打开",+ "mcpApp.openLink.confirm.title": "要打开这个来自页面的链接吗?",+ "mcpApp.toolCall.busy": "工具「{{tool}}」没有运行:这个页面还有太多工具调用在等你审批,处理完之后再试。",+ "mcpApp.toolCall.confirm.cancel": "拒绝",+ "mcpApp.toolCall.confirm.content": "{{app}} 的页面想用下面的参数运行工具「{{tool}}」。按你的审批设置,运行前需要你确认。",+ "mcpApp.toolCall.confirm.ok": "允许",+ "mcpApp.toolCall.confirm.title": "允许运行这个工具吗?",+ "mcpApp.toolCall.rejected": "工具「{{tool}}」没有运行:这个页面不能调用它,或者你没有允许。",+ "mcpApp.waitingApproval": "正在等待你的审批…","mcpEmpty.deployment": "暂无部署选项","mcpEmpty.prompts": "该技能暂无提示词","mcpEmpty.resources": "该技能暂无资源",diff --git a/package.json b/package.jsonindex 7ec0fe82af0..c4dc9fc1821 100644--- a/package.json+++ b/package.json@@ -333,6 +333,7 @@"@lobehub/market-sdk": "0.46.0","@lobehub/ui": "^6.12.0","@modelcontextprotocol/client": "~2.4.0",+ "@modelcontextprotocol/ext-apps": "^2.0.3","@neondatabase/serverless": "^1.1.0","@next/third-parties": "^16.3.0","@opentelemetry/auto-instrumentations-node": "^0.76.0",diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex ef54d0674e4..6ca61ec287a 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -309,6 +309,17 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config).enableDashboard).toBe(false);});+ it('should keep MCP Apps views off by default and enable them per user or globally', () => {+ expect(DEFAULT_FEATURE_FLAGS.mcp_apps).toBe(false);+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableMcpApps).toBe(false);++ expect(mapFeatureFlagsEnvToState({ mcp_apps: true }).enableMcpApps).toBe(true);++ const config = { mcp_apps: ['user-123'] };+ expect(mapFeatureFlagsEnvToState(config, 'user-123').enableMcpApps).toBe(true);+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableMcpApps).toBe(false);+ });+it('should keep the rail layout off by default and enable it per user or globally', () => {expect(DEFAULT_FEATURE_FLAGS.im_layout).toBe(false);expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableImLayout).toBe(false);diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 89ed77bd34a..48b76cc2c89 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -64,6 +64,14 @@ export const FeatureFlagsSchema = z.object({*/dashboard: FeatureFlagValue.optional(),+ /**+ * MCP Apps: a tool result that declares an interactive `ui://` view renders+ * that view (third-party HTML in a sandboxed iframe) in the conversation and+ * stays on screen when the turn folds. Off: such results render as plain+ * tool results. Array values are user ids.+ */+ mcp_apps: FeatureFlagValue.optional(),+/*** Trial gate for the rail layout: icon rail + one wrapped list column and* content, the IM-style Messages list (Lobe AI opens by default), Contacts,@@ -196,6 +204,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {// Off: a personal-trial layout, enabled per user id.im_layout: false,+ // Off until an admin publishes a user allowlist or flips it to true.+ mcp_apps: false,+// Off until an admin publishes a user allowlist or flips it to true.channel: false,@@ -246,6 +257,7 @@ export const mapFeatureFlagsEnvToState = (),enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId, 'agent_llm_relay'),enableDashboard: evaluateFeatureFlag(config.dashboard, userId, 'dashboard'),+ enableMcpApps: evaluateFeatureFlag(config.mcp_apps, userId, 'mcp_apps'),enableImLayout: evaluateFeatureFlag(config.im_layout, userId, 'im_layout'),enableChannels: evaluateFeatureFlag(config.channel, userId, 'channel'),enableManagedCloudDevice: evaluateFeatureFlag(diff --git a/packages/const/package.json b/packages/const/package.jsonindex 961cee0d1a4..b815c1744af 100644--- a/packages/const/package.json+++ b/packages/const/package.json@@ -10,6 +10,7 @@"./desktopGlobalShortcuts": "./src/desktopGlobalShortcuts.ts","./goal": "./src/goal.ts","./hotkeys": "./src/hotkeys.ts",+ "./mcpApp": "./src/mcpApp.ts","./mediaRef": "./src/mediaRef.ts","./plugin": "./src/plugin.ts","./rbac": "./src/rbac.ts",diff --git a/packages/const/src/mcpApp.test.ts b/packages/const/src/mcpApp.test.tsnew file mode 100644index 00000000000..4001c059b99--- /dev/null+++ b/packages/const/src/mcpApp.test.ts@@ -0,0 +1,172 @@+import { describe, expect, it } from 'vitest';++import {+ buildMcpToolMetadata,+ getMcpServerFingerprint,+ getMcpToolVisibility,+ isMcpToolVisibleTo,+ isSyncedMcpToolVisibleTo,+ lacksUiResourceMeta,+ partitionMcpToolsForViews,+ withListingUiMeta,+} from './mcpApp';++describe('getMcpToolVisibility', () => {+ it('reads `_meta.ui.visibility`, keeping only strings', () => {+ expect(getMcpToolVisibility({ ui: { visibility: ['app', 1, 'model'] } })).toEqual([+ 'app',+ 'model',+ ]);+ });++ it('returns undefined when the tool declares none', () => {+ expect(getMcpToolVisibility(undefined)).toBeUndefined();+ expect(getMcpToolVisibility({ ui: { resourceUri: 'ui://x' } })).toBeUndefined();+ expect(getMcpToolVisibility({ ui: { visibility: 'app' } })).toBeUndefined();+ });+});++describe('isMcpToolVisibleTo', () => {+ it('treats an unset visibility as visible to both', () => {+ expect(isMcpToolVisibleTo(undefined, 'model')).toBe(true);+ expect(isMcpToolVisibleTo(undefined, 'app')).toBe(true);+ });++ it('allows only the listed audiences', () => {+ expect(isMcpToolVisibleTo(['app'], 'model')).toBe(false);+ expect(isMcpToolVisibleTo(['app'], 'app')).toBe(true);+ expect(isMcpToolVisibleTo(['model'], 'app')).toBe(false);+ expect(isMcpToolVisibleTo([], 'model')).toBe(false);+ });+});++describe('synced tool metadata', () => {+ it('round-trips the declared visibility through the row metadata', () => {+ const row = { metadata: buildMcpToolMetadata(['app']) };++ expect(row.metadata).toEqual({ visibility: ['app'] });+ expect(isSyncedMcpToolVisibleTo(row, 'model')).toBe(false);+ expect(isSyncedMcpToolVisibleTo(row, 'app')).toBe(true);+ });++ it('stores nothing for an undeclared visibility, which stays visible to the model', () => {+ expect(buildMcpToolMetadata(undefined)).toBeNull();+ expect(isSyncedMcpToolVisibleTo({ metadata: null }, 'model')).toBe(true);+ expect(isSyncedMcpToolVisibleTo({}, 'model')).toBe(true);+ });+});++describe('partitionMcpToolsForViews', () => {+ const tool = (name: string, visibility?: string[]) => ({+ _meta: visibility ? { ui: { visibility } } : undefined,+ name,+ });++ it("keeps what views may call beyond the model's list, and what they may not", () => {+ const { appOnlyTools, modelOnlyToolNames } = partitionMcpToolsForViews([+ tool('both'),+ tool('model', ['model']),+ tool('app', ['app']),+ tool('none', []),+ ]);++ expect(appOnlyTools.map((t) => t.name)).toEqual(['app']);+ expect(modelOnlyToolNames).toEqual(['model']);+ });+});++describe('withListingUiMeta', () => {+ const csp = { connectDomains: ['https://api.example.com'] };++ it("fills a view's metadata from its resources/list entry when the read declares none", () => {+ const result = { contents: [{ text: '<html />', uri: 'ui://app' }] };++ expect(lacksUiResourceMeta(result)).toBe(true);+ expect(+ withListingUiMeta(result, 'ui://app', [+ { _meta: { ui: { csp: { connectDomains: [] } } }, uri: 'ui://other' },+ { _meta: { ui: { csp } }, uri: 'ui://app' },+ ]).contents,+ ).toEqual([{ _meta: { ui: { csp } }, text: '<html />', uri: 'ui://app' }]);+ });++ it("keeps the read's own metadata, which the listing only backs up", () => {+ const own = { _meta: { ui: { csp: { connectDomains: [] } } }, text: '', uri: 'ui://app' };++ expect(lacksUiResourceMeta({ contents: [own] })).toBe(false);+ expect(+ withListingUiMeta({ contents: [own] }, 'ui://app', [+ { _meta: { ui: { csp } }, uri: 'ui://app' },+ ]).contents,+ ).toEqual([own]);+ });+});++describe('getMcpServerFingerprint', () => {+ it('names a server the same however it is reached, and keeps its address out', async () => {+ const url = 'https://mcp.example.com/mcp?token=secret';+ const http = await getMcpServerFingerprint({ type: 'http', url });++ expect(http).toMatch(/^[\da-f]{64}$/);+ expect(http).not.toContain('secret');+ expect(await getMcpServerFingerprint({ type: 'http', url })).toBe(http);+ expect(+ await getMcpServerFingerprint({ args: ['mcp.js'], command: 'node', type: 'stdio' }),+ ).toBe(await getMcpServerFingerprint({ args: ['mcp.js'], command: 'node', type: 'stdio' }));+ });++ it('tells different servers apart', async () => {+ const fingerprints = await Promise.all([+ getMcpServerFingerprint({ type: 'http', url: 'https://a.example.com/mcp' }),+ getMcpServerFingerprint({ type: 'http', url: 'https://b.example.com/mcp' }),+ getMcpServerFingerprint({ args: ['a.js'], command: 'node', type: 'stdio' }),+ getMcpServerFingerprint({ args: ['b.js'], command: 'node', type: 'stdio' }),+ // Not the same as one argument holding both+ getMcpServerFingerprint({ args: ['a.js b.js'], command: 'node', type: 'stdio' }),+ getMcpServerFingerprint({ args: ['a.js', 'b.js'], command: 'node', type: 'stdio' }),+ // So are the headers a gateway may route by+ getMcpServerFingerprint({+ headers: { 'x-tenant': 'a' },+ type: 'http',+ url: 'https://a.example.com/mcp',+ }),+ // The environment, which may pick the endpoint, is part of it+ getMcpServerFingerprint({+ args: ['a.js'],+ command: 'node',+ env: { URL: 'b' },+ type: 'stdio',+ }),+ ]);++ // In any order, and an empty one is none+ expect(+ await getMcpServerFingerprint({+ command: 'node',+ env: { A: '1', B: '2' },+ type: 'stdio',+ }),+ ).toBe(+ await getMcpServerFingerprint({ command: 'node', env: { B: '2', A: '1' }, type: 'stdio' }),+ );+ expect(await getMcpServerFingerprint({ command: 'node', env: {}, type: 'stdio' })).toBe(+ await getMcpServerFingerprint({ command: 'node', type: 'stdio' }),+ );++ expect(new Set(fingerprints).size).toBe(fingerprints.length);+ });+});++describe('getMcpServerFingerprint outside a secure context', () => {+ it('names the server the same without crypto.subtle', async () => {+ const address = { type: 'http' as const, url: 'http://10.0.0.5:3000/mcp' };+ const fingerprint = await getMcpServerFingerprint(address);+ const subtle = Object.getOwnPropertyDescriptor(globalThis.crypto, 'subtle');+ Object.defineProperty(globalThis.crypto, 'subtle', { configurable: true, value: undefined });+ try {+ await expect(getMcpServerFingerprint(address)).resolves.toBe(fingerprint);+ } finally {+ if (subtle) Object.defineProperty(globalThis.crypto, 'subtle', subtle);+ }+ });+});diff --git a/packages/const/src/mcpApp.ts b/packages/const/src/mcpApp.tsnew file mode 100644index 00000000000..564b949f468--- /dev/null+++ b/packages/const/src/mcpApp.ts@@ -0,0 +1,154 @@+import { sha256Hex } from './sha256';++/**+ * Who may call an MCP tool, per MCP Apps (SEP-1865) `_meta.ui.visibility`:+ * `"model"` is the agent's tool list, `"app"` is an interactive view's+ * `tools/call`.+ */+export type McpToolAudience = 'app' | 'model';++/** The `_meta.ui.visibility` a tool declares, or `undefined` when it declares none. */+export const getMcpToolVisibility = (meta: unknown): string[] | undefined => {+ const visibility = (meta as { ui?: { visibility?: unknown } } | undefined)?.ui?.visibility;+ if (!Array.isArray(visibility)) return;++ return visibility.filter((item): item is string => typeof item === 'string');+};++/**+ * Whether `audience` may call a tool with this declared visibility. Unset means+ * `["model", "app"]`, so tools that predate MCP Apps stay visible to both.+ */+export const isMcpToolVisibleTo = (+ visibility: readonly string[] | null | undefined,+ audience: McpToolAudience,+): boolean => !visibility || visibility.includes(audience);++/**+ * The `metadata` a synced tool row (`user_connector_tools.metadata`) keeps for+ * the visibility its MCP server declared; `null` when it declared none.+ */+export const buildMcpToolMetadata = (+ visibility: readonly string[] | undefined,+): { visibility: string[] } | null => (visibility ? { visibility: [...visibility] } : null);++/**+ * Whether `audience` may call a synced tool, read from the row `metadata`+ * {@link buildMcpToolMetadata} wrote. A row synced before visibility was+ * stored counts as unset.+ */+export const isSyncedMcpToolVisibleTo = (+ tool: { metadata?: Record<string, unknown> | null },+ audience: McpToolAudience,+): boolean => {+ const visibility = tool.metadata?.visibility;++ return isMcpToolVisibleTo(+ Array.isArray(visibility)+ ? visibility.filter((item): item is string => typeof item === 'string')+ : undefined,+ audience,+ );+};++/**+ * What a plugin manifest keeps beside its model-facing `api` for MCP Apps+ * views: the tools only views may call (visibility with "app" but not+ * "model"), and the `api` tools views may not call (no "app").+ */+export const partitionMcpToolsForViews = <T extends { _meta?: unknown; name: string }>(+ tools: readonly T[],+) => {+ const audiences = tools.map((tool) => {+ const visibility = getMcpToolVisibility(tool._meta);+ return {+ app: isMcpToolVisibleTo(visibility, 'app'),+ model: isMcpToolVisibleTo(visibility, 'model'),+ tool,+ };+ });++ return {+ appOnlyTools: audiences.filter(({ app, model }) => app && !model).map(({ tool }) => tool),+ modelOnlyToolNames: audiences+ .filter(({ app, model }) => model && !app)+ .map(({ tool }) => tool.name),+ };+};++interface UiResourceItem {+ _meta?: unknown;+ uri?: string;+}++const uiMetaOf = (item: UiResourceItem | undefined) =>+ (item?._meta as { ui?: unknown } | undefined)?.ui;++/** Whether some `resources/read` content item declares no `_meta.ui` of its own. */+export const lacksUiResourceMeta = (result: { contents?: readonly UiResourceItem[] }): boolean =>+ (result.contents ?? []).some((item) => !uiMetaOf(item));++/**+ * MCP Apps reads a view's `_meta.ui` (CSP, permissions, border) from its+ * `resources/read` content item, with its `resources/list` entry as the+ * fallback: a server may declare it once where it registers the resource.+ * Fill content items that declare none from the listing entry for `uri`.+ */+export const withListingUiMeta = <R extends { contents?: UiResourceItem[] }>(+ result: R,+ uri: string,+ listed: readonly UiResourceItem[] | undefined,+): R => {+ const listingUi = uiMetaOf(listed?.find((entry) => entry.uri === uri));+ if (!listingUi || !result.contents) return result;++ return {+ ...result,+ contents: result.contents.map((item) =>+ uiMetaOf(item)+ ? item+ : { ...item, _meta: { ...(item._meta as object | undefined), ui: listingUi } },+ ),+ };+};++/** The part of an MCP connection that says which server it reaches. */+export type McpServerAddress =+ | {+ /** Part of which server it is: a gateway may route by header (tenant, backend). */+ headers?: Record<string, string> | null;+ type: 'http';+ url: string;+ }+ | {+ args?: readonly string[];+ command: string;+ /** Part of which server it is: a stdio server may pick its endpoint by env. */+ env?: Record<string, string> | null;+ type: 'stdio';+ };++// Sorted, so the same entries name the same server in any order; none and `{}` alike+const withEntries = (base: string, entries: Record<string, string> | null | undefined) => {+ const sorted = Object.entries(entries ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ return sorted.length > 0 ? `${base} ${JSON.stringify(sorted)}` : base;+};++const serverIdentity = (address: McpServerAddress): string =>+ address.type === 'http'+ ? withEntries(`http ${address.url}`, address.headers)+ : withEntries(+ `stdio ${JSON.stringify([address.command, ...(address.args ?? [])])}`,+ address.env,+ );++/**+ * Names the MCP server a tool result came from without storing its address+ * (a URL or header may carry a token): a SHA-256 of the URL and headers, or of+ * the command, its arguments and environment. Auth (`params.auth`) is not part+ * of it: a refreshed token reaches the same server. A result's view is only read back from the server it names.+ */+export const getMcpServerFingerprint = async (address: McpServerAddress): Promise<string> => {+ // Not `crypto.subtle`: browsers leave it out of pages that aren't a secure context+ return sha256Hex(serverIdentity(address));+};diff --git a/packages/const/src/sha256.test.ts b/packages/const/src/sha256.test.tsnew file mode 100644index 00000000000..af7a270d031--- /dev/null+++ b/packages/const/src/sha256.test.ts@@ -0,0 +1,37 @@+import { createHash } from 'node:crypto';++import { describe, expect, it } from 'vitest';++import { sha256Hex } from './sha256';++const nodeSha256 = (input: string) => createHash('sha256').update(input, 'utf8').digest('hex');++describe('sha256Hex', () => {+ it('matches the standard digest across padding boundaries and UTF-8 input', () => {+ const inputs = [+ '',+ 'abc',+ 'http https://mcp.example.com/mcp?token=secret',+ 'stdio ["node","mcp.js"]',+ 'a'.repeat(55),+ 'a'.repeat(56),+ 'a'.repeat(63),+ 'a'.repeat(64),+ 'a'.repeat(65),+ 'b'.repeat(1000),+ '多语言 ✓ émoji 🚀',+ ];++ for (const input of inputs) expect(sha256Hex(input)).toBe(nodeSha256(input));+ });++ it('works without crypto.subtle, as in a page that is not a secure context', () => {+ const subtle = Object.getOwnPropertyDescriptor(globalThis.crypto, 'subtle');+ Object.defineProperty(globalThis.crypto, 'subtle', { configurable: true, value: undefined });+ try {+ expect(sha256Hex('abc')).toBe(nodeSha256('abc'));+ } finally {+ if (subtle) Object.defineProperty(globalThis.crypto, 'subtle', subtle);+ }+ });+});diff --git a/packages/const/src/sha256.ts b/packages/const/src/sha256.tsnew file mode 100644index 00000000000..c7f8d1cc1da--- /dev/null+++ b/packages/const/src/sha256.ts@@ -0,0 +1,80 @@+/**+ * SHA-256 (FIPS 180-4) of a UTF-8 string, as lowercase hex. Synchronous and+ * dependency-free so it runs everywhere a fingerprint must match: the server,+ * the desktop main process, and browsers without `crypto.subtle` (a page+ * served over plain HTTP from a non-localhost address is not a secure context).+ * Not for secrets or large inputs.+ */++const K = new Uint32Array([+ 0x42_8a_2f_98, 0x71_37_44_91, 0xb5_c0_fb_cf, 0xe9_b5_db_a5, 0x39_56_c2_5b, 0x59_f1_11_f1,+ 0x92_3f_82_a4, 0xab_1c_5e_d5, 0xd8_07_aa_98, 0x12_83_5b_01, 0x24_31_85_be, 0x55_0c_7d_c3,+ 0x72_be_5d_74, 0x80_de_b1_fe, 0x9b_dc_06_a7, 0xc1_9b_f1_74, 0xe4_9b_69_c1, 0xef_be_47_86,+ 0x0f_c1_9d_c6, 0x24_0c_a1_cc, 0x2d_e9_2c_6f, 0x4a_74_84_aa, 0x5c_b0_a9_dc, 0x76_f9_88_da,+ 0x98_3e_51_52, 0xa8_31_c6_6d, 0xb0_03_27_c8, 0xbf_59_7f_c7, 0xc6_e0_0b_f3, 0xd5_a7_91_47,+ 0x06_ca_63_51, 0x14_29_29_67, 0x27_b7_0a_85, 0x2e_1b_21_38, 0x4d_2c_6d_fc, 0x53_38_0d_13,+ 0x65_0a_73_54, 0x76_6a_0a_bb, 0x81_c2_c9_2e, 0x92_72_2c_85, 0xa2_bf_e8_a1, 0xa8_1a_66_4b,+ 0xc2_4b_8b_70, 0xc7_6c_51_a3, 0xd1_92_e8_19, 0xd6_99_06_24, 0xf4_0e_35_85, 0x10_6a_a0_70,+ 0x19_a4_c1_16, 0x1e_37_6c_08, 0x27_48_77_4c, 0x34_b0_bc_b5, 0x39_1c_0c_b3, 0x4e_d8_aa_4a,+ 0x5b_9c_ca_4f, 0x68_2e_6f_f3, 0x74_8f_82_ee, 0x78_a5_63_6f, 0x84_c8_78_14, 0x8c_c7_02_08,+ 0x90_be_ff_fa, 0xa4_50_6c_eb, 0xbe_f9_a3_f7, 0xc6_71_78_f2,+]);++const rotr = (value: number, bits: number) => (value >>> bits) | (value << (32 - bits));++export const sha256Hex = (input: string): string => {+ const bytes = new TextEncoder().encode(input);+ // Message, a 1 bit, zero padding, then the 64-bit bit length: a multiple of 64 bytes+ const length = Math.ceil((bytes.length + 9) / 64) * 64;+ const padded = new Uint8Array(length);+ padded.set(bytes);+ padded[bytes.length] = 0x80;+ const view = new DataView(padded.buffer);+ const bitLength = bytes.length * 8;+ view.setUint32(length - 8, Math.floor(bitLength / 2 ** 32));+ view.setUint32(length - 4, bitLength >>> 0);++ const hash = new Uint32Array([+ 0x6a_09_e6_67, 0xbb_67_ae_85, 0x3c_6e_f3_72, 0xa5_4f_f5_3a, 0x51_0e_52_7f, 0x9b_05_68_8c,+ 0x1f_83_d9_ab, 0x5b_e0_cd_19,+ ]);+ const w = new Uint32Array(64);++ for (let offset = 0; offset < length; offset += 64) {+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);+ for (let i = 16; i < 64; i++) {+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;+ }++ let [a, b, c, d, e, f, g, h] = hash;+ for (let i = 0; i < 64; i++) {+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);+ const choice = (e & f) ^ (~e & g);+ const t1 = (h + s1 + choice + K[i] + w[i]) >>> 0;+ const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);+ const majority = (a & b) ^ (a & c) ^ (b & c);+ const t2 = (s0 + majority) >>> 0;+ h = g;+ g = f;+ f = e;+ e = (d + t1) >>> 0;+ d = c;+ c = b;+ b = a;+ a = (t1 + t2) >>> 0;+ }++ hash[0] += a;+ hash[1] += b;+ hash[2] += c;+ hash[3] += d;+ hash[4] += e;+ hash[5] += f;+ hash[6] += g;+ hash[7] += h;+ }++ return Array.from(hash, (word) => word.toString(16).padStart(8, '0')).join('');+};diff --git a/packages/database/src/models/__tests__/connectorTool.test.ts b/packages/database/src/models/__tests__/connectorTool.test.tsindex a75a93a61b9..25006033b7a 100644--- a/packages/database/src/models/__tests__/connectorTool.test.ts+++ b/packages/database/src/models/__tests__/connectorTool.test.ts@@ -177,6 +177,21 @@ describe('ConnectorToolModel', () => {expect(row.isWorkArtifact).toBe(true);});+ it('stores the synced metadata and replaces it on every re-sync', async () => {+ const model = new ConnectorToolModel(serverDB, userId);++ await model.upsertMany(connectorId, [+ tool({ metadata: { visibility: ['app'] }, toolName: 'load_page' }),+ ]);+ expect((await model.queryByConnector(connectorId))[0].metadata).toEqual({+ visibility: ['app'],+ });++ // The server dropped its visibility: the tool is visible to the model again+ await model.upsertMany(connectorId, [tool({ toolName: 'load_page' })]);+ expect((await model.queryByConnector(connectorId))[0].metadata).toBeNull();+ });+it('writes workspaceId when the model is workspace-scoped', async () => {const model = new ConnectorToolModel(serverDB, userId, workspaceId);diff --git a/packages/database/src/models/connectorTool.ts b/packages/database/src/models/connectorTool.tsindex 7ad30b893d7..3e60b8ed0d8 100644--- a/packages/database/src/models/connectorTool.ts+++ b/packages/database/src/models/connectorTool.ts@@ -17,6 +17,8 @@ export interface SyncToolInput {description?: string;displayName?: string;inputSchema?: Record<string, unknown>;+ /** Manifest-derived metadata, e.g. the MCP Apps `visibility` of the tool. */+ metadata?: Record<string, unknown> | null;outputSchema?: Record<string, unknown>;renderConfig?: Record<string, unknown>;toolName: string;@@ -49,7 +51,7 @@ export class ConnectorToolModel {* Batch-upsert tools from a manifest sync.** Manifest-derived fields are always overwritten (toolName, displayName,- * description, inputSchema, outputSchema, crudType, renderConfig).+ * description, inputSchema, outputSchema, crudType, renderConfig, metadata).* User-controlled fields (permission, isWorkArtifact, workArtifactConfig,* limitConfig) are preserved on conflict.*/@@ -65,6 +67,7 @@ export class ConnectorToolModel {displayName: t.displayName ?? null,inputSchema: t.inputSchema ?? null,isWorkArtifact: false,+ metadata: t.metadata ?? null,outputSchema: t.outputSchema ?? null,permission: t.defaultPermission ?? Permission.auto,renderConfig: t.renderConfig ?? null,@@ -87,6 +90,7 @@ export class ConnectorToolModel {description: sql`excluded.description`,displayName: sql`excluded.display_name`,inputSchema: sql`excluded.input_schema`,+ metadata: sql`excluded.metadata`,outputSchema: sql`excluded.output_schema`,renderConfig: sql`excluded.render_config`,updatedAt: new Date(),diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex 03c4f37d184..78157c3a418 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -278,7 +278,7 @@ export type ConnectorToolPermission =** Rows are batch-upserted when a connector is connected or its manifest is* refreshed. On upsert, only manifest-derived fields (displayName, description,- * inputSchema, outputSchema, crudType, renderConfig) are overwritten;+ * inputSchema, outputSchema, crudType, renderConfig, metadata) are overwritten;* user-controlled fields (permission, isWorkArtifact, workArtifactConfig,* limitConfig) are never overwritten so that user preferences survive* manifest refreshes.@@ -352,7 +352,12 @@ export const userConnectorTools = pgTable(*/limitConfig: jsonb('limit_config').$type<Record<string, unknown>>(),- /** Safe non-sensitive metadata for display and future extensibility */+ /**+ * Safe non-sensitive metadata synced from the manifest, rewritten on every+ * sync. `visibility` holds an MCP tool's `_meta.ui.visibility` (MCP Apps):+ * a tool without "model" stays callable by its view but is left out of+ * the model's tool list.+ */metadata: jsonb('metadata').$type<Record<string, unknown>>(),...timestamps,diff --git a/packages/locales/src/default/plugin.test.ts b/packages/locales/src/default/plugin.test.tsnew file mode 100644index 00000000000..c83d501f043--- /dev/null+++ b/packages/locales/src/default/plugin.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import enUS from '../../../../locales/en-US/plugin.json';+import plugin from './plugin';++describe('MCP App copy', () => {+ // en-US is mirrored by hand from the default source, so drift shows up as broken copy+ const keys = Object.keys(plugin).filter((key) => key.startsWith('mcpApp.'));++ it('covers the MCP App keys', () => {+ expect(keys.length).toBeGreaterThan(0);+ });++ it.each(keys)('mirrors %s in en-US', (key) => {+ expect(enUS[key as keyof typeof enUS]).toBe(plugin[key as keyof typeof plugin]);+ });+});diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex f7a497c054d..35c16adfbe1 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -903,6 +903,26 @@ export default {'list.item.local.title': 'Custom','loading.content': 'Calling Skill…','loading.plugin': 'Skill running…',+ 'mcpApp.message.confirm.cancel': 'Cancel',+ 'mcpApp.message.confirm.content':+ 'The {{app}} view wants to send this message to the conversation. Sending it starts a new reply.',+ 'mcpApp.message.confirm.ok': 'Send',+ 'mcpApp.message.confirm.title': 'Send this message from the view?',+ 'mcpApp.message.source': 'Follow-up from the {{app}} view',+ 'mcpApp.openLink.confirm.cancel': 'Cancel',+ 'mcpApp.openLink.confirm.content': 'The {{app}} view wants to open this link.',+ 'mcpApp.openLink.confirm.ok': 'Open',+ 'mcpApp.openLink.confirm.title': 'Open this link from the view?',+ 'mcpApp.toolCall.busy':+ 'The tool "{{tool}}" was not run: too many of this view\'s tool calls are waiting for approval. Try again once they are answered.',+ 'mcpApp.toolCall.confirm.cancel': 'Deny',+ 'mcpApp.toolCall.confirm.content':+ 'The {{app}} view wants to run the tool "{{tool}}" with these arguments. Your approval settings ask before it runs.',+ 'mcpApp.toolCall.confirm.ok': 'Allow',+ 'mcpApp.toolCall.confirm.title': 'Allow this tool to run?',+ 'mcpApp.toolCall.rejected':+ 'The tool "{{tool}}" was not run: it is not available to this view or was not approved.',+ 'mcpApp.waitingApproval': 'Waiting for your approval…','mcpEmpty.deployment': 'No deployment options','mcpEmpty.prompts': 'No prompts','mcpEmpty.resources': 'No resources',diff --git a/packages/mecha/src/toolSet/manifestPool.test.ts b/packages/mecha/src/toolSet/manifestPool.test.tsindex 483b2558b0e..a36bd07ea58 100644--- a/packages/mecha/src/toolSet/manifestPool.test.ts+++ b/packages/mecha/src/toolSet/manifestPool.test.ts@@ -44,6 +44,34 @@ describe('buildConnectorManifest', () => {buildConnectorManifest({ identifier: 'x', isEnabled: true, name: 'x', tools: [] }),).toBeUndefined();});++ it('leaves out tools whose MCP Apps visibility excludes the model', () => {+ const built = buildConnectorManifest({+ identifier: 'dashboard',+ isEnabled: true,+ name: 'Dashboard',+ tools: [+ { metadata: { visibility: ['model', 'app'] }, permission: 'auto', toolName: 'show' },+ { metadata: { visibility: ['app'] }, permission: 'auto', toolName: 'load_page' },+ { metadata: { visibility: ['model'] }, permission: 'auto', toolName: 'export' },+ { metadata: null, permission: 'auto', toolName: 'legacy' },+ ],+ })!;++ expect(built.api.map((a) => a.name)).toEqual(['show', 'export', 'legacy']);+ expect(built.meta.description).toBe('Dashboard connector with 3 tools');+ });++ it('builds nothing when every tool is for views only', () => {+ expect(+ buildConnectorManifest({+ identifier: 'dashboard',+ isEnabled: true,+ name: 'Dashboard',+ tools: [{ metadata: { visibility: ['app'] }, permission: 'auto', toolName: 'load_page' }],+ }),+ ).toBeUndefined();+ });});describe('patchManifestWithPermissions', () => {diff --git a/packages/mecha/src/toolSet/manifestPool.ts b/packages/mecha/src/toolSet/manifestPool.tsindex 1351f58c76d..cf97100b053 100644--- a/packages/mecha/src/toolSet/manifestPool.ts+++ b/packages/mecha/src/toolSet/manifestPool.ts@@ -1,3 +1,4 @@+import { isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';import type { LobeToolManifest } from '@lobechat/context-engine';import type { BuiltinToolResolveContext, LobeBuiltinTool } from '@lobechat/types';import debug from 'debug';@@ -13,6 +14,8 @@ export type ConnectorToolPermissions = Map<string, ConnectorToolPermissionValueexport interface ConnectorToolFacts {description?: string | null;inputSchema?: unknown;+ /** Synced tool metadata; `visibility` is the MCP tool's `_meta.ui.visibility`. */+ metadata?: Record<string, unknown> | null;permission?: ConnectorToolPermissionValue | string | null;toolName: string;}@@ -63,17 +66,20 @@ export function patchManifestWithPermissions<M extends { api: readonly { name: s}/**- * A connector's tools as one MCP manifest: every synced tool is listed- * (disabled ones with the blocking description), permissions become- * `humanIntervention`. Returns nothing for a disabled connector or one with no- * synced tools — such a connector must not replace a same-named plugin while- * contributing nothing to call.+ * A connector's tools as one MCP manifest: every synced tool the model may+ * see is listed (disabled ones with the blocking description), permissions+ * become `humanIntervention`. Tools only views may call are left out. Returns+ * nothing for a disabled connector or one with no tools for the model — such a+ * connector must not replace a same-named plugin while contributing nothing+ * to call.*/export const buildConnectorManifest = (connector: ConnectorFacts): LobeToolManifest | undefined => {if (!connector.isEnabled) return undefined;- if (connector.tools.length === 0) return undefined;- const api = connector.tools.map((tool) => {+ const modelTools = connector.tools.filter((tool) => isSyncedMcpToolVisibleTo(tool, 'model'));+ if (modelTools.length === 0) return undefined;++ const api = modelTools.map((tool) => {const parameters = (tool.inputSchema ?? { properties: {}, type: 'object' }) as Record<string,unknowndiff --git a/packages/openapi/src/services/mcp-server.service.ts b/packages/openapi/src/services/mcp-server.service.tsindex f1e596c5432..9f050103829 100644--- a/packages/openapi/src/services/mcp-server.service.ts+++ b/packages/openapi/src/services/mcp-server.service.ts@@ -167,6 +167,7 @@ export class McpServerService extends BaseService {const { toolCount } = await syncConnectorToolsById(id, {connectorModel: model,connectorToolModel: this.connectorToolModel,+ userId: this.userId,});return { id, status: ConnectorStatus.connected, toolCount };}diff --git a/packages/types/src/message/common/composerUserMessage.ts b/packages/types/src/message/common/composerUserMessage.tsindex 4fbaebabe88..39d95b29eb7 100644--- a/packages/types/src/message/common/composerUserMessage.ts+++ b/packages/types/src/message/common/composerUserMessage.ts@@ -1,11 +1,12 @@import { z } from 'zod';-import type { MessageMetadata } from './metadata';+import type { MessageMcpAppSource, MessageMetadata } from './metadata';import { MessageMetadataSchema } from './metadata';/*** Metadata the composer authors for the user message it sends: content attached- * from the conversation, a page or code, and local file snapshots.+ * from the conversation, a page or code, local file snapshots, and the MCP App+ * view that posted it.** Both send transports persist the user message from this one shape —* `aiChat.sendMessageInServer` (client / in-process hetero runtimes) and@@ -20,6 +21,7 @@ import { MessageMetadataSchema } from './metadata';export const ComposerUserMessageMetadataSchema = MessageMetadataSchema.pick({contextSelections: true,localSystemToolSnapshots: true,+ mcpAppSource: true,pageSelections: true,});@@ -33,6 +35,21 @@ export const ComposerUserMessageSchema = z.object({export type ComposerUserMessage = z.infer<typeof ComposerUserMessageSchema>;+/**+ * The MCP App view a merged send came from: only when every merged message was+ * posted by that same view. One typed message among them means the user wrote+ * part of the text, so the bubble must not name the view.+ */+export const mergeMcpAppSource = (+ sources: (MessageMcpAppSource | undefined)[],+): MessageMcpAppSource | undefined => {+ const [first] = sources;++ return first && sources.every((source) => source?.identifier === first.identifier)+ ? first+ : undefined;+};+/** The keys of {@link ComposerUserMessageMetadataSchema}, for code that walks every field. */export const COMPOSER_USER_MESSAGE_METADATA_KEYS = Object.keys(ComposerUserMessageMetadataSchema.shape,diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex fb86f22caa2..5df2de96239 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -240,6 +240,10 @@ export const MessageSignalSchema = z.object({type: z.enum(['tool-stdout', 'tool-callback', 'task-completion']),});+export const MessageMcpAppSourceSchema = z.object({+ identifier: z.string(),+});+export const MessageSubAgentCallbackSchema = z.object({agentId: z.string().optional(),name: z.string(),@@ -463,6 +467,8 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceScheisMultimodal: z.boolean().optional(),isSupervisor: z.boolean().optional(),localSystemToolSnapshots: z.array(LocalSystemToolSnapshotSchema).optional(),+ // User message an MCP App view posted; its bubble names that view.+ mcpAppSource: MessageMcpAppSourceSchema.optional(),// Creation provenance (agent operation that produced this message). Listed// here so zod does NOT strip the runtime's stamp from writes going through// CreateMessageParamsSchema / UpdateMessageParamsSchema.@@ -695,6 +701,12 @@ export interface MessageMetadata {* Local-system tool snapshots materialized when the user sent @file mentions.*/localSystemToolSnapshots?: LocalSystemToolSnapshot[];+ /**+ * Present on a user message an MCP App view posted into the conversation+ * (`ui/message`). The bubble names the view, so the message reads as a+ * follow-up from it rather than something the user typed.+ */+ mcpAppSource?: MessageMcpAppSource;/*** Orchestration role of the message author within a group conversation.* `'supervisor'` = the group's coordinating agent, `'member'` = a delegated@@ -850,6 +862,12 @@ export interface MessageWorkMetadata {}/** Who sent a background sub-agent's answer — see `MessageMetadata.subAgentCallback`. */+/** The MCP App view a user message came from — see `MessageMetadata.mcpAppSource`. */+export interface MessageMcpAppSource {+ /** The MCP server (plugin or connector identifier) whose view posted the message. */+ identifier: string;+}+export interface MessageSubAgentCallback {/*** The agent that answered: a `callAgent` target, or the parent agent itselfdiff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex ed34084f3f7..5c3fbc7a8d5 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -67,6 +67,11 @@ export type IFeatureFlagsState = {* working.*/enableManagedCloudDevice: boolean | undefined;+ /**+ * MCP Apps views in the conversation (`mcp_apps`). Off by default: tool results+ * that declare a `ui://` view render as plain results.+ */+ enableMcpApps: boolean | undefined;enableOnboardingV2: boolean | undefined;enableRAGEval: boolean | undefined;enableSTT: boolean | undefined;diff --git a/packages/types/src/tool/manifest.ts b/packages/types/src/tool/manifest.tsindex 35797db0e0f..8e955f66e7b 100644--- a/packages/types/src/tool/manifest.ts+++ b/packages/types/src/tool/manifest.ts@@ -24,6 +24,13 @@ export interface ToolManifest {gateway?: string;homepage?: string;identifier: string;+ /**+ * MCP Apps: tools the server keeps from the model (`_meta.ui.visibility`+ * without "model"). Only its views may call them; never part of `api`.+ */+ mcpAppOnlyApi?: LobeChatPluginApi[];+ /** MCP Apps: tools in `api` the server's views may not call (no "app"). */+ mcpModelOnlyTools?: string[];meta: Meta;openapi?: string;settings?: ToolManifestSettings;@@ -41,6 +48,8 @@ export const ToolManifestSchema = z.object({gateway: z.string().optional(),homepage: z.string().optional(),identifier: z.string(),+ mcpAppOnlyApi: z.array(LobeChatPluginApiSchema).optional(),+ mcpModelOnlyTools: z.array(z.string()).optional(),meta: MetaSchema,openapi: z.string().optional(),settings: ToolManifestSettingsSchema.optional(),diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.tsindex 4ac0905fa07..40ba2e3d8ea 100644--- a/src/app/(backend)/oauth/connector/callback/route.ts+++ b/src/app/(backend)/oauth/connector/callback/route.ts@@ -174,6 +174,7 @@ export const GET = async (req: NextRequest) => {const { toolCount } = await syncConnectorToolsById(payload.connectorId, {connectorModel,connectorToolModel,+ userId: payload.lobeUserId,});synced = true;log('connector %s authorized + synced %d tools', payload.connectorId, toolCount);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsxindex f2d6aea6841..738650d5231 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx@@ -1,14 +1,22 @@import { getBuiltinRender } from '@lobechat/builtin-tools/renders';+import { isDesktop } from '@lobechat/const';import { type ChatPluginPayload } from '@lobechat/types';import { Flexbox, Skeleton } from '@lobehub/ui';import { memo } from 'react';import { useToolResultPayload } from '@/hooks/useToolResultPayload';+import { canServeMcpAppHere, getMcpAppFromState, unwrapMcpToolState } from '@/libs/mcp/mcpApp';+import dynamic from '@/libs/next/dynamic';+import { useElectronStore } from '@/store/electron';+import { electronGatewaySelectors } from '@/store/electron/selectors/gateway';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { dataSelectors, useConversationStore } from '../../../../../store';import CustomRender from './CustomRender';import { FallbackArgumentRender } from './FallbacktArgumentRender';+const McpAppView = dynamic(() => import('@/features/MCPApp/McpAppView'), { ssr: false });+interface ToolRenderProps {content: string;messageId?: string;@@ -21,6 +29,11 @@ interface ToolRenderProps {const ToolRender = memo<ToolRenderProps>(({ showCustomToolRender, content, messageId, plugin, pluginState, toolCallId }) => {const hasCustomRender = !!getBuiltinRender(plugin?.identifier, plugin?.apiName);+ const enableMcpApps = useServerConfigStore(serverConfigSelectors.enableMcpApps);+ const [currentDeviceId, useFetchGatewayStableDeviceId] = useElectronStore((s) => [+ electronGatewaySelectors.gatewayStableDeviceId(s),+ s.useFetchGatewayStableDeviceId,+ ]);// Tools whose card renders the stored body — the read path projected it away// and this component is where it comes back. Safe to fetch on mount: the@@ -35,7 +48,13 @@ const ToolRender = memo<ToolRenderProps>(const resolvedContent = payload?.content ?? content;const resolvedState = payload?.pluginState ?? pluginState;- if (needsStoredPayload && isLoading && !payload) {+ // MCP Apps: the tool declared an interactive `ui://` view for its result+ const mcpApp = enableMcpApps ? getMcpAppFromState(resolvedState) : undefined;+ // A view from a desktop's local MCP process: learn whether this is that desktop+ useFetchGatewayStableDeviceId(isDesktop && !!mcpApp?.deviceId);++ const resolvingDevice = isDesktop && !!mcpApp?.deviceId && currentDeviceId === undefined;+ if ((needsStoredPayload && isLoading && !payload) || resolvingDevice) {return (<Flexbox paddingBlock={8} width={'100%'}><Skeleton height={96} width={'100%'} />@@ -55,13 +74,33 @@ const ToolRender = memo<ToolRenderProps>();}- return (+ const fallback = (<FallbackArgumentRendercontent={resolvedContent}requestArgs={plugin?.arguments}toolCallId={toolCallId}/>);++ // A view from another desktop's local MCP process would run here instead+ if (mcpApp && canServeMcpAppHere(mcpApp, currentDeviceId) && showCustomToolRender && plugin) {+ return (+ <McpAppView+ apiName={plugin.apiName}+ arguments={plugin.arguments}+ fallback={fallback}+ identifier={plugin.identifier}+ messageId={messageId}+ resourceUri={mcpApp.resourceUri}+ result={{ content: resolvedContent, state: unwrapMcpToolState(resolvedState) }}+ server={mcpApp.server}+ toolCallId={toolCallId}+ onThisDevice={!!mcpApp.deviceId}+ />+ );+ }++ return fallback;},);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsxindex c0e690d3828..876ef4ff425 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx@@ -5,9 +5,11 @@ import isEqual from 'fast-deep-equal';import { memo, useState } from 'react';import SafeBoundary from '@/components/ErrorBoundary';+import { getMcpAppFromState } from '@/libs/mcp/mcpApp';import dynamic from '@/libs/next/dynamic';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';@@ -50,10 +52,14 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =const renderDisplayControl = useToolStore(toolSelectors.getRenderDisplayControl(identifier, apiName, result?.state),);+ // MCP Apps results open by default so their interactive view is visible+ const isMcpApp = useServerConfigStore(+ (s) => serverConfigSelectors.enableMcpApps(s) && !!getMcpAppFromState(result?.state),+ );const isPending = intervention?.status === 'pending';const isReject = intervention?.status === 'rejected';const isAbort = intervention?.status === 'aborted';- const needExpand = renderDisplayControl !== 'collapsed' || isPending;+ const needExpand = renderDisplayControl !== 'collapsed' || isPending || isMcpApp;const isAlwaysExpand = renderDisplayControl === 'alwaysExpand';const { handleExpand, setShowDebug, showDebug, showToolRender } = useToolExpandState({diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.tsindex bf3f4b12379..7ee49045652 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.test.ts@@ -21,6 +21,20 @@ describe('hasToolResultBody', () => {expect(hasToolResultBody(undefined)).toBe(false);});+ it('counts an MCP App result whose data is all for its view, with no text', () => {+ const state = {+ content: [],+ mcpApp: { resourceUri: 'ui://dash/view' },+ structuredContent: { rows: [1, 2] },+ };++ expect(hasToolResultBody({ content: '', state })).toBe(true);+ // Nor once the host envelope wraps it+ expect(hasToolResultBody({ content: '', state: { content: '', state, success: true } })).toBe(+ true,+ );+ });+it('does not count the streaming placeholder', () => {expect(hasToolResultBody({ content: LOADING_FLAT })).toBe(false);expect(hasToolResultBody({ content: LOADING_FLAT, contentLength: 12 })).toBe(false);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.tsindex 84adb47ca01..b3519ff7507 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/toolResultBody.ts@@ -1,6 +1,8 @@import { LOADING_FLAT } from '@lobechat/const';import type { ChatToolResult } from '@lobechat/types';+import { getMcpAppFromState } from '@/libs/mcp/mcpApp';+/*** Did this tool actually produce a result body?*@@ -10,8 +12,12 @@ import type { ChatToolResult } from '@lobechat/types';* in `contentLength`. Reading the body alone flips a finished tool back into* its loading placeholder for as long as the assistant message is busy.*/-export const hasToolResultBody = (result?: Pick<ChatToolResult, 'content' | 'contentLength'>) => {+export const hasToolResultBody = (+ result?: Pick<ChatToolResult, 'content' | 'contentLength'> & { state?: unknown },+) => {if (!result || result.content === LOADING_FLAT) return false;- return !!result.content || (result.contentLength ?? 0) > 0;+ // An MCP App result is its view: it may carry no text for the model at all,+ // its data in `structuredContent` for the view+ return !!result.content || (result.contentLength ?? 0) > 0 || !!getMcpAppFromState(result.state);};diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsxindex ac3794b5755..f281610ab38 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx@@ -30,6 +30,12 @@ vi.mock('@/store/chat/slices/operation/selectors', () => ({},}));+// The `mcp_apps` flag's default: these cases cover the layout without MCP App views.+vi.mock('@/store/serverConfig', () => ({+ serverConfigSelectors: { enableMcpApps: () => false },+ useServerConfigStore: (selector: (s: unknown) => unknown) => selector({}),+}));+// Mock the council list so importing Group doesn't pull in the AgentCouncil// render chain (→ shared-tool-ui inspectors → `@lobehub/ui` `keyframes`), which is// out of scope for this unit test.diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsxindex 89cb36d802f..ec42a51e5da 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx@@ -1,4 +1,3 @@-import { splitAssistantGroupFinalAnswer } from '@lobechat/conversation-flow';import { Flexbox } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';@@ -8,6 +7,7 @@ import ContentLoading from '@/features/Conversation/Messages/components/ContentLimport { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import type { OperationStatus } from '@/store/chat/slices/operation/types';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import type { AssistantContentBlock } from '@/types/index';import { messageStateSelectors, useConversationStore } from '../../../store';@@ -17,9 +17,14 @@ import { CollapsedMessage } from './CollapsedMessage';import type { GroupChainInput, GroupChainView } from './groupChain';import { buildChainView, getChainDurationsMs, getLastBlockCreatedAt } from './groupChain';import ProcessFold from './ProcessFold';-import { renderChainSegment } from './renderChainSegment';+import { getChainSegmentKey, renderChainSegment } from './renderChainSegment';import type { GroupRenderSegment } from './segments';-import { countAssistantLlmCalls, hasRenderableFinalAnswer, shouldFoldProcess } from './segments';+import {+ countAssistantLlmCalls,+ hasRenderableFinalAnswer,+ shouldFoldProcess,+ splitProcessForFold,+} from './segments';import SteerMessage from './SteerMessage';import type { WorkflowExpandLevelDefault } from './WorkflowCollapse';@@ -129,16 +134,20 @@ const Group = memo<GroupChildrenProps>(() => chains.map((chain) => ({ assistantGroupId: chain.id })),[chains],);+ // Off: no view is lifted or broken out, and the turn renders as it did+ // before MCP Apps.+ const enableMcpApps = useServerConfigStore(serverConfigSelectors.enableMcpApps);const views = useMemo(() =>chainsWithFinishTypes.map((chain, index) =>buildChainView(chain, {+ enableMcpApps,hasActiveOperation: !!activeFlags[index],isGenerating: !!generatingFlags[index],}),),- [activeFlags, chainsWithFinishTypes, generatingFlags],+ [activeFlags, chainsWithFinishTypes, enableMcpApps, generatingFlags],);const lastView = views.at(-1)!;const isGenerating = lastView.isGenerating;@@ -163,13 +172,22 @@ const Group = memo<GroupChildrenProps>(const renderChain = (view: GroupChainView,segments: GroupRenderSegment[],- variant: 'process' | 'final',+ variant: 'process' | 'folded' | 'final',) => (<MessageAggregationContextkey={`${view.id}.${variant}`}value={contextValues[views.indexOf(view)]!}>- {segments.map((segment) => renderChainSegment(view, segment, renderOptions))}+ {/* Keyed by the segment's place in the whole turn, not in this slice:+ folding changes the slice, and a positional key would remount a+ lifted view that stays on screen. The key does not depend on the+ mcp_apps flag, so flags arriving after the first paint don't remount+ every segment. */}+ {segments.map((segment) => (+ <Fragment key={getChainSegmentKey(view, segment)}>+ {renderChainSegment(view, segment, renderOptions)}+ </Fragment>+ ))}</MessageAggregationContext>);@@ -184,8 +202,11 @@ const Group = memo<GroupChildrenProps>(// final answer: a queued follow-up is only sent once the turn before it has// finished, so that turn's answer is a real reply, not process. Each steer// bubble sits after the answer of the turn it followed. A turn that stopped- // on a tool call has no final answer and folds whole.- const splits = views.map((view) => splitAssistantGroupFinalAnswer(view.segments));+ // on a tool call has no final answer and folds whole. MCP App views are+ // lifted out of the fold and sit between it and the answer. They stay in+ // the `process` chain in both states, so folding does not remount (and+ // reload) a view the user may already be using.+ const splits = views.map((view) => splitProcessForFold(view.segments, { enableMcpApps }));const finalSegments = splits.at(-1)!.finalSegments;const foldProcess = shouldFoldProcess({enabled: enableProcessFold,@@ -193,12 +214,22 @@ const Group = memo<GroupChildrenProps>(isGenerating,isLatestItem,operationEnded: !views.some((view) => view.hasActiveOperation),- processSegments: splits.flatMap((split) => split.processSegments),+ processSegments: splits.flatMap((split) => [+ ...split.processSegments,+ ...split.liftedSegments,+ ]),});const renderFold = (view: GroupChainView, index: number) => {const segments = splits[index]!.processSegments;if (segments.length === 0) return null;+ // Only intermediate prose is left once the views are lifted: nothing to fold.+ if (+ splits[index]!.liftedSegments.length > 0 &&+ !segments.some((segment) => segment.kind === 'workflow')+ ) {+ return renderChain(view, segments, 'folded');+ }const durationMs = chainDurations[index] ?? 0;return (<ProcessFold@@ -206,7 +237,7 @@ const Group = memo<GroupChildrenProps>(key={view.id}stepCount={countAssistantLlmCalls(view.segments)}>- <Flexbox gap={8}>{renderChain(view, segments, 'process')}</Flexbox>+ <Flexbox gap={8}>{renderChain(view, segments, 'folded')}</Flexbox></ProcessFold>);};@@ -216,14 +247,13 @@ const Group = memo<GroupChildrenProps>({views.map((view, index) => (<Fragment key={view.id}>{view.steerUserId && <SteerMessage id={view.steerUserId} />}- {foldProcess ? (- <>- {renderFold(view, index)}- {renderChain(view, splits[index]!.finalSegments, 'final')}- </>- ) : (- renderChain(view, view.segments, 'process')+ {foldProcess && renderFold(view, index)}+ {renderChain(+ view,+ foldProcess ? splits[index]!.liftedSegments : view.segments,+ 'process',)}+ {foldProcess && renderChain(view, splits[index]!.finalSegments, 'final')}</Fragment>))}{!foldProcess && lastView.showTailRunningIndicator && (diff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.tsindex 7b28cdfe921..7e8b2c9cd66 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.test.ts@@ -94,3 +94,29 @@ describe('buildChainView task-completion notices', () => {expect(rendered.find((block) => block.id === 'wake')?.showTaskCompletionNotice).toBe(true);});});++describe('buildChainView MCP App views', () => {+ const appTool = {+ apiName: 'show_dashboard',+ arguments: '{}',+ id: 't1',+ identifier: 'dash',+ result: { content: 'ok', id: 'r1', state: { mcpApp: { resourceUri: 'ui://dash/view' } } },+ type: 'mcp' as const,+ };+ const nextTool = { ...appTool, apiName: 'search', id: 't2', result: undefined };+ // The segment key the group renders the view under (`getChainSegmentKey`)+ const viewKey = (tools: unknown[]) =>+ buildChainView(+ { blocks: [{ content: '', id: 'step1', tools }] as AssistantContentBlock[], id: 'group' },+ { enableMcpApps: true, hasActiveOperation: true, isGenerating: true },+ ).segments.flatMap((segment) => (segment.kind === 'workflow' ? segment.blocks : []))[0]+ ?.renderKey;++ it('keeps the key of a lone view once the model calls another tool in its step', () => {+ const alone = viewKey([appTool]);++ expect(alone).toBeDefined();+ expect(viewKey([appTool, nextTool])).toBe(alone);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.tsindex 5a177792ee2..e1354909876 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupChain.ts@@ -5,10 +5,14 @@ import type {import { partitionAssistantGroupBlocks } from '@lobechat/conversation-flow';import { LOADING_FLAT } from '@/const/message';-import type { AssistantContentBlock, MessageSignal } from '@/types/index';+import type {+ AssistantContentBlock,+ ChatToolPayloadWithResult,+ MessageSignal,+} from '@/types/index';import { areWorkflowToolsComplete } from '../toolDisplayNames';-import { isImageBearingTool } from '../toolRenderRules';+import { isBreakoutTool, isImageBearingTool } from '../toolRenderRules';import type { GroupRenderSegment } from './segments';import type { RenderableAssistantContentBlock } from './types';@@ -178,8 +182,19 @@ export const isEmptyBlock = (block: RenderableAssistantContentBlock) =>!block.reasoning &&!block.metadata?.finishType;-const toRenderableBlock = (block: AssistantGroupSemanticBlock): RenderableAssistantContentBlock => {- if (!block.projection) return block;+const toRenderableBlock = (+ block: AssistantGroupSemanticBlock,+ isBreakout: (tool: ChatToolPayloadWithResult) => boolean,+): RenderableAssistantContentBlock => {+ if (!block.projection) {+ // A lone tool that breaks out (an MCP App view, a produced image) renders+ // inline under the key it will keep once a later tool splits the step into+ // runs (`${block.id}__${tool.id}`), so its view isn't remounted then+ const [tool, ...rest] = block.tools ?? [];+ return tool && rest.length === 0 && isBreakout(tool)+ ? { ...block, renderKey: `${block.id}__${tool.id}${WORKFLOW_DOM_ID_SUFFIX}` }+ : block;+ }const suffix = block.projection === 'answer' ? ANSWER_DOM_ID_SUFFIX : WORKFLOW_DOM_ID_SUFFIX;const key = `${block.projectionKey ?? block.id}${suffix}`;@@ -215,12 +230,18 @@ const markTaskCompletionNotices = (segments: GroupRenderSegment[]): GroupRenderS);};-const toRenderSegments = (segments: AssistantGroupSegment[]): GroupRenderSegment[] =>+const toRenderSegments = (+ segments: AssistantGroupSegment[],+ isBreakout: (tool: ChatToolPayloadWithResult) => boolean,+): GroupRenderSegment[] =>markTaskCompletionNotices(segments.map((segment) =>segment.kind === 'answer'- ? { block: toRenderableBlock(segment.block), kind: 'answer' }- : { ...segment, blocks: segment.blocks.map(toRenderableBlock) },+ ? { block: toRenderableBlock(segment.block, () => false), kind: 'answer' }+ : {+ ...segment,+ blocks: segment.blocks.map((block) => toRenderableBlock(block, isBreakout)),+ },),);@@ -268,17 +289,23 @@ export const hasPendingIntervention = (blocks: RenderableAssistantContentBlock[]export const buildChainView = (chain: GroupChainInput,- state: { hasActiveOperation: boolean; isGenerating: boolean },+ state: {+ /** Runtime flag `mcp_apps`: MCP App views break out of collapsed runs too. */+ enableMcpApps?: boolean;+ hasActiveOperation: boolean;+ isGenerating: boolean;+ },): GroupChainView => {const { isGenerating } = state;+ const isBreakout = state.enableMcpApps ? isBreakoutTool : isImageBearingTool;const partitioned = partitionAssistantGroupBlocks(chain.blocks, {- isBreakoutTool: isImageBearingTool,+ isBreakoutTool: isBreakout,isGenerating,toolsPhaseComplete: isGenerating? areWorkflowToolsComplete(chain.blocks.flatMap((block) => block.tools ?? [])): undefined,});- const segments = toRenderSegments(partitioned.segments);+ const segments = toRenderSegments(partitioned.segments, isBreakout);// When the turn ends on an inline single-tool segment whose tool already// settled but the run is still generating (waiting on the next step), thediff --git a/src/features/Conversation/Messages/AssistantGroup/components/groupFold.mcpApp.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/groupFold.mcpApp.test.tsnew file mode 100644index 00000000000..96e18020b31--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/components/groupFold.mcpApp.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest';++import type { AssistantContentBlock } from '@/types/index';++import { buildChainView } from './groupChain';+import { getChainSegmentKey } from './renderChainSegment';+import type { GroupRenderSegment } from './segments';+import { splitProcessForFold } from './segments';++const tool = (id: string, apiName: string, state?: Record<string, unknown>) =>+ ({+ apiName,+ id,+ identifier: 'weather-demo',+ result: { content: 'ok', id: `${id}-r`, state },+ }) as any;++const blocks = [+ { content: '', id: 'step-1', tools: [tool('t1', 'search_city')] },+ { content: '', id: 'step-2', tools: [tool('t2', 'get_air_quality')] },+ {+ content: '',+ id: 'step-3',+ tools: [+ tool('t3', 'get_weather', { content: [], mcpApp: { resourceUri: 'ui://weather/view' } }),+ ],+ },+ { content: 'Paris looks good for a day out.', id: 'step-4' },+] as AssistantContentBlock[];++const view = (chainBlocks: AssistantContentBlock[], enableMcpApps: boolean) =>+ buildChainView(+ { blocks: chainBlocks, id: 'assistant-1' },+ { enableMcpApps, hasActiveOperation: false, isGenerating: false },+ );++const blockIds = (segments: GroupRenderSegment[]) =>+ segments.flatMap((segment) =>+ segment.kind === 'workflow' ? segment.blocks.map((block) => block.id) : [segment.block.id],+ );++// The group's layout once a turn's process may fold (Group.tsx renders these slices)+describe('folding a turn with an MCP App view', () => {+ it('keeps the view out of the fold, between the folded steps and the answer', () => {+ const chain = view(blocks, true);+ const { finalSegments, liftedSegments, processSegments } = splitProcessForFold(chain.segments, {+ enableMcpApps: true,+ });++ expect(blockIds(processSegments)).toEqual(['step-1', 'step-2']);+ expect(blockIds(liftedSegments)).toEqual(['step-3']);+ expect(blockIds(finalSegments)).toEqual(['step-4']);+ });++ it('keys the view by its place in the whole turn, so folding does not remount it', () => {+ const chain = view(blocks, true);+ const viewSegment = splitProcessForFold(chain.segments, { enableMcpApps: true })+ .liftedSegments[0]!;++ // The same key the unfolded turn renders the segment under+ expect(getChainSegmentKey(chain, viewSegment)).toBe(+ getChainSegmentKey(+ chain,+ chain.segments.find((s) => blockIds([s]).includes('step-3'))!,+ ),+ );+ });++ it('keeps every key when the mcp_apps flag arrives after the first paint', () => {+ const plain = [+ { content: '', id: 'step-1', tools: [tool('t1', 'search_city')] },+ { content: 'Paris looks good for a day out.', id: 'step-2' },+ ] as AssistantContentBlock[];+ const keys = (enableMcpApps: boolean) => {+ const chain = view(plain, enableMcpApps);+ return chain.segments.map((segment) => getChainSegmentKey(chain, segment));+ };++ expect(keys(true)).toEqual(keys(false));+ });++ it('folds the view with the rest of the process while the mcp_apps flag is off', () => {+ const chain = view(blocks, false);+ const { finalSegments, liftedSegments, processSegments } = splitProcessForFold(chain.segments, {+ enableMcpApps: false,+ });++ expect(liftedSegments).toEqual([]);+ expect(blockIds(processSegments)).toContain('step-3');+ expect(blockIds(finalSegments)).toEqual(['step-4']);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsx b/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsxindex fda20b12e9b..991d543e86c 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/renderChainSegment.tsx@@ -20,6 +20,23 @@ export interface ChainSegmentRenderOptions {messageIndex: number;}+/**+ * A segment's key within its whole turn, not within the slice being rendered:+ * folding moves a segment between slices (fold, lifted, final), and a key tied+ * to its place in the slice would remount it. Built like the keys+ * {@link renderChainSegment} gives the segment's own elements, so it does not+ * depend on how the turn is sliced or on any runtime flag.+ */+export const getChainSegmentKey = (view: GroupChainView, segment: GroupRenderSegment): string => {+ const index = view.segments.indexOf(segment);++ if (segment.kind === 'workflow') {+ return segment.blocks[0]?.renderKey ?? `${view.id}.workflow.${index}`;+ }++ return segment.block.renderKey ?? `${view.id}.${segment.block.id}.${index}`;+};+export const renderChainSegment = (view: GroupChainView,segment: GroupRenderSegment,diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.tsindex 90e53651758..41aadd0bd11 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts@@ -5,6 +5,7 @@ import { LOADING_FLAT } from '@/const/message';import {countAssistantLlmCalls,hasRenderableFinalAnswer,+ liftMcpAppSegments,resolveWorkflowExpandLevel,shouldFoldProcess,} from './segments';@@ -185,6 +186,29 @@ describe('shouldFoldProcess', () => {).toBe(false);});+ it('folds a finished turn whose process carries an MCP App view', () => {+ const appTool = {+ apiName: 'get_weather',+ id: 'app',+ identifier: 'weather-demo',+ result: {+ content: 'ok',+ id: 'r',+ state: { content: [], mcpApp: { resourceUri: 'ui://weather/view' } },+ },+ };+ expect(+ shouldFoldProcess({+ enabled: true,+ hasFinalAnswer: true,+ isGenerating: false,+ isLatestItem: true,+ operationEnded: true,+ processSegments: [{ blocks: [{ id: 'app', tools: [appTool] } as any], kind: 'workflow' }],+ }),+ ).toBe(true);+ });+it('does not fold when the process has no workflow (e.g. pure prose)', () => {expect(shouldFoldProcess({@@ -222,3 +246,72 @@ describe('resolveWorkflowExpandLevel', () => {});});});++describe('liftMcpAppSegments', () => {+ const mcpView = (id: string) => ({+ apiName: 'get_weather',+ id,+ identifier: 'weather-demo',+ result: {+ content: 'ok',+ id: `${id}-r`,+ state: { content: [], mcpApp: { resourceUri: 'ui://weather/view' } },+ },+ });+ const plain = (id: string) => ({+ apiName: 'search_city',+ id,+ identifier: 'weather-demo',+ result: { content: 'ok', id: `${id}-r` },+ });++ it('keeps the MCP App view out of a multi-step fold and leaves the other steps folded', () => {+ const steps = {+ blocks: [{ id: 's1', tools: [plain('a'), plain('b')] } as any],+ kind: 'workflow' as const,+ };+ const view = {+ blocks: [{ id: 's2', tools: [mcpView('c')] } as any],+ kind: 'workflow' as const,+ standalone: true,+ };+ const prose = {+ block: { content: 'Checking.', id: 's1-prose' } as any,+ kind: 'answer' as const,+ };++ const { folded, lifted } = liftMcpAppSegments([steps, prose, view]);++ expect(folded).toEqual([steps, prose]);+ expect(lifted).toEqual([view]);+ });++ it("lifts a lone view out of the segment it shares with the answer's reasoning", () => {+ const view = { id: 's1', tools: [mcpView('a')] } as any;+ const reasoning = { content: '', id: 's2', reasoning: { content: 'Thinking.' } } as any;+ const shared = { blocks: [view, reasoning], kind: 'workflow' as const };++ expect(liftMcpAppSegments([shared])).toEqual({+ folded: [{ blocks: [reasoning], kind: 'workflow' }],+ lifted: [{ blocks: [view], kind: 'workflow' }],+ });+ });++ it('does not lift a segment that mixes a view with ordinary tools', () => {+ const mixed = {+ blocks: [{ id: 's1', tools: [plain('a'), mcpView('b')] } as any],+ kind: 'workflow' as const,+ };++ expect(liftMcpAppSegments([mixed])).toEqual({ folded: [mixed], lifted: [] });+ });++ it('does not lift a tool from an MCP server without a view', () => {+ const noView = {+ blocks: [{ id: 's1', tools: [plain('a')] } as any],+ kind: 'workflow' as const,+ };++ expect(liftMcpAppSegments([noView])).toEqual({ folded: [noView], lifted: [] });+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.tsindex bd7c5c68e14..e8098ad5665 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts@@ -1,8 +1,9 @@import type { AssistantGroupSegment } from '@lobechat/conversation-flow';+import { splitAssistantGroupFinalAnswer } from '@lobechat/conversation-flow';import { LOADING_FLAT } from '@/const/message';-import { isImageOutputTool } from '../toolRenderRules';+import { isImageOutputTool, isMcpAppTool } from '../toolRenderRules';import type { RenderableAssistantContentBlock } from './types';import type { WorkflowExpandLevel, WorkflowExpandLevelDefault } from './WorkflowCollapse';@@ -47,10 +48,12 @@ export const hasRenderableFinalAnswer = (segments: GroupRenderSegment[]): boolea* answer is visible, so a tool-only latest turn does not collapse into a lone* header.*- * A turn whose process carries a PRODUCED image never folds — that image is the- * deliverable. A tool that merely READ an image no longer blocks folding: the- * read is one ordinary step, and it surfaces (with its preview) once the fold is- * expanded instead of holding the whole process open.+ * A turn whose process carries a PRODUCED image never folds — that image is+ * the deliverable. An MCP App view is lifted out of the fold instead (see+ * {@link liftMcpAppSegments}), so the rest of the process still folds. A tool+ * that merely READ an image no longer blocks folding: the read is one ordinary+ * step, and it surfaces (with its preview) once the fold is expanded instead of+ * holding the whole process open.*/export const shouldFoldProcess = ({enabled,@@ -78,6 +81,52 @@ export const shouldFoldProcess = ({),);+const isMcpAppBlock = (block: RenderableAssistantContentBlock): boolean =>+ !!block.tools?.length && block.tools.every(isMcpAppTool);++/**+ * Take the MCP App views out of a turn's folded process. Like an image the turn+ * produced, the view is what the user came for, so it stays on screen between+ * the fold and the answer while the other steps fold as usual. A block of MCP+ * App tools alone is lifted: the workflow partition already breaks each view+ * out of a multi-tool run (`isBreakoutTool`). A lone view may share its segment+ * with tool-less neighbours (the answer's reasoning after it), which stay in+ * the fold, in their order.+ */+export const liftMcpAppSegments = (+ processSegments: GroupRenderSegment[],+): { folded: GroupRenderSegment[]; lifted: GroupRenderSegment[] } => {+ const folded: GroupRenderSegment[] = [];+ const lifted: GroupRenderSegment[] = [];+ for (const segment of processSegments) {+ if (segment.kind !== 'workflow' || !segment.blocks.some(isMcpAppBlock)) {+ folded.push(segment);+ continue;+ }+ if (segment.blocks.every(isMcpAppBlock)) {+ lifted.push(segment);+ continue;+ }++ // Each run of views is lifted, each run of other blocks folds+ let run: RenderableAssistantContentBlock[] = [];+ let runIsView = false;+ const flush = () => {+ if (run.length > 0) (runIsView ? lifted : folded).push({ ...segment, blocks: run });+ run = [];+ };+ for (const block of segment.blocks) {+ const isView = isMcpAppBlock(block);+ if (isView !== runIsView) flush();+ runIsView = isView;+ run.push(block);+ }+ flush();+ }++ return { folded, lifted };+};+/*** Merge the per-surface expand override with the user's streaming preference.* An explicit override always wins; the setting only fills a streaming phase@@ -92,3 +141,21 @@ export const resolveWorkflowExpandLevel = (return { ...explicit, streaming: explicit?.streaming ?? streamingSetting };};++/**+ * One turn's segments as the group lays them out once its process may fold:+ * the final answer, the process steps that fold, and the MCP App views lifted+ * out between the fold and the answer. With the `mcp_apps` flag off, nothing+ * is lifted and a view folds with the rest of the process.+ */+export const splitProcessForFold = (+ segments: GroupRenderSegment[],+ { enableMcpApps }: { enableMcpApps: boolean },+) => {+ const split = splitAssistantGroupFinalAnswer(segments);+ const { folded, lifted } = enableMcpApps+ ? liftMcpAppSegments(split.processSegments)+ : { folded: split.processSegments, lifted: [] };++ return { ...split, liftedSegments: lifted, processSegments: folded };+};diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.tsindex 1999834d6d4..ca296f4bcb1 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts@@ -4,7 +4,13 @@ import {} from '@lobechat/builtin-tool-web-onboarding';import { describe, expect, it } from 'vitest';-import { isImageBearingTool, isImageOutputTool, shouldRenderToolCall } from './toolRenderRules';+import {+ isBreakoutTool,+ isImageBearingTool,+ isImageOutputTool,+ isMcpAppTool,+ shouldRenderToolCall,+} from './toolRenderRules';describe('shouldRenderToolCall', () => {it('hides the onboarding completion tool call', () => {@@ -117,3 +123,30 @@ describe('isImageOutputTool', () => {).toBe(false);});});++describe('isMcpAppTool', () => {+ const mcp = (state?: unknown) =>+ ({+ apiName: 'get_weather',+ id: 't',+ identifier: 'weather-demo',+ result: { content: 'x', id: 'r', state },+ }) as any;+ const view = { mcpApp: { resourceUri: 'ui://weather/view' }, content: [] };++ it('is true once the result carries an MCP App view, on client and server-runtime shapes', () => {+ expect(isMcpAppTool(mcp(view))).toBe(true);+ expect(isMcpAppTool(mcp({ content: 'x', state: view, success: true }))).toBe(true);+ });++ it('is false while the result is missing or declares no ui:// view', () => {+ expect(isMcpAppTool(mcp())).toBe(false);+ expect(isMcpAppTool(mcp({ content: [] }))).toBe(false);+ expect(isMcpAppTool(mcp({ content: [], mcpApp: { resourceUri: 'https://x' } }))).toBe(false);+ });++ it('breaks out of collapsed workflow runs', () => {+ expect(isBreakoutTool(mcp(view))).toBe(true);+ expect(isBreakoutTool(mcp({ content: [] }))).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.tsindex b1c3656a7ce..875bbe489f7 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts@@ -8,6 +8,8 @@ import {} from '@lobechat/builtin-tool-web-onboarding';import type { ChatToolPayloadWithResult } from '@lobechat/types';+import { getMcpAppFromState } from '@/libs/mcp/mcpApp';+interface ToolRenderRuleTarget {apiName: string;identifier: string;@@ -60,3 +62,15 @@ export const isImageOutputTool = (tool: ChatToolPayloadWithResult): boolean => {*/export const isImageBearingTool = (tool: ChatToolPayloadWithResult): boolean =>isImageOutputTool(tool) || hasUploadedImages(tool.result?.state);++/**+ * Tools whose result renders an interactive MCP App view. Like a produced image,+ * the view is what the turn delivers, so it stays on screen after the turn+ * while the rest of the process folds.+ */+export const isMcpAppTool = (tool: ChatToolPayloadWithResult): boolean =>+ !!getMcpAppFromState(tool.result?.state);++/** Tools that surface on their own between collapsed workflow runs. */+export const isBreakoutTool = (tool: ChatToolPayloadWithResult): boolean =>+ isImageBearingTool(tool) || isMcpAppTool(tool);diff --git a/src/features/Conversation/Messages/User/McpAppSourceFooter.tsx b/src/features/Conversation/Messages/User/McpAppSourceFooter.tsxnew file mode 100644index 00000000000..9e6d26a6eea--- /dev/null+++ b/src/features/Conversation/Messages/User/McpAppSourceFooter.tsx@@ -0,0 +1,28 @@+'use client';++import type { MessageMcpAppSource } from '@lobechat/types';+import { cssVar, Flexbox, Icon, Text } from '@lobehub/ui';+import { AppWindowIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { mcpAppNameSelector } from '@/features/MCPApp/appName';+import { useToolStore } from '@/store/tool';++/**+ * Quiet line under a user bubble an MCP App view posted. It marks the message+ * as a follow-up sent from that view inside this conversation, not a fresh+ * question the user typed.+ */+export const McpAppSourceFooter = ({ source }: { source: MessageMcpAppSource }) => {+ const { t } = useTranslation('plugin');+ const appName = useToolStore(mcpAppNameSelector(source.identifier));++ return (+ <Flexbox horizontal align={'center'} gap={4} justify={'flex-end'} paddingBlock={4}>+ <Icon icon={AppWindowIcon} size={14} style={{ color: cssVar.colorTextQuaternary }} />+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('mcpApp.message.source', { app: appName })}+ </Text>+ </Flexbox>+ );+};diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex c55be3fd8cc..306b2f1673b 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -27,6 +27,7 @@ import AgentSenderSourceLink from './components/AgentSenderSourceLink';import UserMessageContent from './components/MessageContent';import { ScmEventAvatar, ScmEventSenderTitle } from './components/ScmEventSender';import { UserMessageExtra } from './Extra';+import { McpAppSourceFooter } from './McpAppSourceFooter';import { getAgentSender, getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';import ScheduledRunFooter from './ScheduledRunFooter';import {@@ -146,6 +147,7 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {belowMessage={<>{subAgentCallback && <SubAgentThreadLink callback={subAgentCallback} />}+ {metadata?.mcpAppSource && <McpAppSourceFooter source={metadata.mcpAppSource} />}<ScheduledRunFooter id={id} /></>}diff --git a/src/features/MCPApp/McpAppView.tsx b/src/features/MCPApp/McpAppView.tsxnew file mode 100644index 00000000000..84ef3362f12--- /dev/null+++ b/src/features/MCPApp/McpAppView.tsx@@ -0,0 +1,215 @@+'use client';++import { Flexbox, Skeleton, Spin, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { type AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';+import * as stylex from '@stylexjs/stylex';+import { useLatest } from 'ahooks';+import { memo, type ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useConversationStore } from '@/features/Conversation/store';+import { useIsDark } from '@/hooks/useIsDark';+import { useToolStore } from '@/store/tool';++import { type AppViewSession, connectAppView, getAppViewPhase } from './appHost';+import { buildHostContext } from './bridge';+import { buildAppFrameDocument, VIEW_FRAME_SANDBOX } from './frameDocument';+import { retireAppFrame } from './frameRetire';+import { APP_IFRAME_ALLOW, buildAppCsp, pickAppResource } from './utils';+import { mcpAppAgentIdSelector } from './viewAgent';++const DEFAULT_HEIGHT = 320;++const styles = stylex.create({+ bordered: {+ overflow: 'hidden',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorBgContainer,+ backgroundImage: 'none',+ },+ iframe: {+ display: 'block',+ width: '100%',+ borderWidth: '0',+ borderStyle: 'none',+ backgroundColor: 'transparent',+ backgroundImage: 'none',+ },+ iframeHeight: (height: string) => ({ height }),+});++export interface McpAppViewProps {+ apiName: string;+ /** Raw JSON arguments of the tool call. */+ arguments?: string;+ /** Rendered instead when the view can't be loaded. */+ fallback: ReactNode;+ identifier: string;+ /** The message carrying the result; its agent is the one the view acts as. */+ messageId?: string;+ /** This desktop's own MCP process produced the result: the view is read, and calls, there. */+ onThisDevice?: boolean;+ resourceUri: string;+ /** Tool call result envelope (`{ content, state, success }`). */+ result: { content: string; state?: any };+ /** The MCP server the result came from; the view is read from no other. */+ server?: string;+ toolCallId: string;+}++/**+ * Renders an MCP Apps (SEP-1865) view: the `ui://` HTML a tool declares, in a+ * sandboxed iframe that talks to LobeHub over the MCP Apps postMessage protocol.+ */+const McpAppView = memo<McpAppViewProps>(+ ({+ apiName,+ arguments: args,+ fallback,+ identifier,+ messageId,+ onThisDevice = false,+ resourceUri,+ result,+ server,+ toolCallId,+ }) => {+ const iframeRef = useRef<HTMLIFrameElement>(null);+ const [height, setHeight] = useState(DEFAULT_HEIGHT);+ // This view's requests still waiting for the user's answer+ const [waitingApprovals, setWaitingApprovals] = useState(0);+ const isDark = useIsDark();+ const sendMessage = useConversationStore((s) => s.sendMessage);+ const canSendMessage = useConversationStore((s) => s.composerTarget.writable);+ // The agent that produced the result: in a group, the member, not the supervisor+ const agentId = useConversationStore(mcpAppAgentIdSelector(messageId));+ const { t } = useTranslation('plugin');++ const useFetchMcpAppResource = useToolStore((s) => s.useFetchMcpAppResource);+ const { data, error, isLoading } = useFetchMcpAppResource(identifier, resourceUri, {+ agentId,+ onThisDevice,+ server,+ });++ const resource = pickAppResource(data, resourceUri);+ // A string: the effects below compare it by value, so no memo is needed+ const srcDoc =+ resource && buildAppFrameDocument(resource.html, buildAppCsp(resource.meta?.csp));+ // The document whose view tried to leave it, so the wrapper dropped the view+ const [droppedDoc, setDroppedDoc] = useState<string>();+ const navigated = !!srcDoc && droppedDoc === srcDoc;++ // Everything the bridge reads after mount goes through a ref, so the+ // iframe session is created once per document instead of per render.+ const latest = useLatest({+ agentId,+ args,+ canSendMessage,+ identifier,+ isDark,+ onThisDevice,+ result,+ sendMessage,+ server,+ t,+ });+ const bridgeRef = useRef<AppBridge>(undefined);+ // The session of the view now in the frame+ const sessionRef = useRef<AppViewSession>(undefined);++ useEffect(() => {+ const target = iframeRef.current?.contentWindow;+ if (!srcDoc || navigated || !target) return;++ const session = connectAppView({+ getContext: () => latest.current,+ onHeight: setHeight,+ onNavigated: () => setDroppedDoc(srcDoc),+ onWaitingApprovalsChange: (delta) => setWaitingApprovals((count) => count + delta),+ resourceUri,+ target,+ toolCallId,+ });+ sessionRef.current = session;+ bridgeRef.current = session.bridge;++ return () => {+ // A frame being removed was handed to `retireAppFrame`, which ends it+ if (sessionRef.current !== session) return;+ sessionRef.current = undefined;+ bridgeRef.current = undefined;+ session.dispose();+ };+ }, [latest, navigated, resourceUri, srcDoc, toolCallId]);++ // While the frame is about to be removed it still runs here (a layout+ // cleanup), so its view is told and given time to finish first+ const hasFrame = !!srcDoc && !navigated;+ useLayoutEffect(() => {+ if (!hasFrame) return;+ const frame = iframeRef.current;++ return () => {+ const session = sessionRef.current;+ if (!frame || !session) return;+ const retired = retireAppFrame(frame, {+ // Not removed after all: a session started since replaces this one+ keep: () => {+ if (sessionRef.current !== session) session.dispose();+ },+ teardown: session.teardown,+ });+ if (!retired) return;+ sessionRef.current = undefined;+ bridgeRef.current = undefined;+ };+ }, [hasFrame]);++ useEffect(() => {+ bridgeRef.current?.setHostContext(buildHostContext(isDark));+ }, [isDark]);++ useEffect(() => {+ if (error) console.warn(`[MCPApp] failed to load ${resourceUri}:`, error);+ }, [error, resourceUri]);++ const phase = getAppViewPhase({ isLoading, navigated, srcDoc });+ if (phase === 'loading') return <Skeleton height={DEFAULT_HEIGHT} width={'100%'} />;+ if (phase === 'fallback') return fallback;++ return (+ <Flexbox gap={8}>+ <div {...stylex.props(resource?.meta?.prefersBorder !== false && styles.bordered)}>+ <iframe+ allow={APP_IFRAME_ALLOW}+ ref={iframeRef}+ // No `allow-same-origin`: the view runs on an opaque origin and can+ // reach LobeHub only through the postMessage bridge. The frame loads+ // the wrapper, which holds the view to its declared frame domains.+ sandbox={VIEW_FRAME_SANDBOX}+ srcDoc={srcDoc}+ title={`${identifier} / ${apiName}`}+ {...stylex.props(styles.iframe, styles.iframeHeight(`${height}px`))}+ />+ </div>+ {waitingApprovals > 0 && (+ <Flexbox horizontal align={'center'} gap={8} role={'status'}>+ <Spin size={'small'} />+ <Text fontSize={12} type={'secondary'}>+ {t('mcpApp.waitingApproval')}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);++McpAppView.displayName = 'McpAppView';++export default McpAppView;diff --git a/src/features/MCPApp/abortSignal.test.ts b/src/features/MCPApp/abortSignal.test.tsnew file mode 100644index 00000000000..5f4fe8ef8c1--- /dev/null+++ b/src/features/MCPApp/abortSignal.test.ts@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { anySignal } from './abortSignal';++describe('anySignal', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('aborts once any source aborts, without AbortSignal.any', () => {+ // Older browsers have no AbortSignal.any+ vi.spyOn(AbortSignal, 'any').mockImplementation(() => {+ throw new TypeError('AbortSignal.any is not a function');+ });+ const view = new AbortController();+ const request = new AbortController();++ const { signal } = anySignal([view.signal, request.signal]);+ expect(signal.aborted).toBe(false);++ request.abort();+ expect(signal.aborted).toBe(true);+ });++ it('starts aborted when a source already is', () => {+ const request = new AbortController();+ request.abort();++ expect(anySignal([new AbortController().signal, request.signal]).signal.aborted).toBe(true);+ });++ it('leaves no listener on its sources once disposed', () => {+ const view = new AbortController();+ const added = vi.spyOn(view.signal, 'addEventListener');+ const removed = vi.spyOn(view.signal, 'removeEventListener');++ const { dispose, signal } = anySignal([view.signal, new AbortController().signal]);+ dispose();++ expect(removed.mock.calls.map(([, listener]) => listener)).toEqual(+ added.mock.calls.map(([, listener]) => listener),+ );+ view.abort();+ expect(signal.aborted).toBe(false);+ });+});diff --git a/src/features/MCPApp/abortSignal.ts b/src/features/MCPApp/abortSignal.tsnew file mode 100644index 00000000000..1767281a189--- /dev/null+++ b/src/features/MCPApp/abortSignal.ts@@ -0,0 +1,20 @@+/**+ * A signal that aborts once any of `signals` does, like `AbortSignal.any`,+ * which Safari < 17.4, Chrome < 116 and Firefox < 124 lack. Call `dispose`+ * when done, so a long-lived source doesn't keep a listener per use.+ */+export const anySignal = (signals: AbortSignal[]) => {+ const controller = new AbortController();+ const dispose = () => {+ for (const signal of signals) signal.removeEventListener('abort', onAbort);+ };+ const onAbort = () => {+ dispose();+ controller.abort();+ };++ if (signals.some((signal) => signal.aborted)) controller.abort();+ else for (const signal of signals) signal.addEventListener('abort', onAbort, { once: true });++ return { dispose, signal: controller.signal };+};diff --git a/src/features/MCPApp/appHost.test.ts b/src/features/MCPApp/appHost.test.tsnew file mode 100644index 00000000000..45849ef64d1--- /dev/null+++ b/src/features/MCPApp/appHost.test.ts@@ -0,0 +1,581 @@+/**+ * @vitest-environment happy-dom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { connectAppView, getAppViewPhase, MAX_APP_VIEW_HEIGHT } from './appHost';+import { buildAppFrameDocument, VIEW_FRAME_SANDBOX } from './frameDocument';+import { APP_IFRAME_ALLOW, buildAppCsp } from './utils';++const {+ confirmAppMessage,+ confirmAppOpenLink,+ confirmAppToolCall,+ getAppToolCallPolicy,+ invokeMcpToolCall,+ sendMessage,+} = vi.hoisted(() => ({+ confirmAppMessage: vi.fn(),+ confirmAppOpenLink: vi.fn(),+ confirmAppToolCall: vi.fn(),+ getAppToolCallPolicy: vi.fn(),+ invokeMcpToolCall: vi.fn(),+ sendMessage: vi.fn(),+}));++vi.mock('@/services/mcp', () => ({ mcpService: { invokeMcpToolCall } }));++vi.mock('@/store/tool', () => ({ getToolStoreState: () => ({}) }));++vi.mock('./appName', () => ({ mcpAppNameSelector: () => () => 'Weather Demo' }));++vi.mock('./confirm', () => ({ confirmAppMessage, confirmAppOpenLink, confirmAppToolCall }));++vi.mock('./toolCallPolicy', () => ({ getAppToolCallPolicy }));++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++const disposers: (() => void)[] = [];++/** Connect a view in a fresh frame, as McpAppView does once the frame has loaded. */+const setup = ({ canSendMessage = true }: { canSendMessage?: boolean } = {}) => {+ const iframe = document.createElement('iframe');+ document.body.append(iframe);+ const target = iframe.contentWindow!;+ const posted = vi.spyOn(target, 'postMessage');+ const onHeight = vi.fn();+ const onNavigated = vi.fn();+ let waiting = 0;+ const onWaitingApprovalsChange = vi.fn((delta: 1 | -1) => (waiting += delta));++ const { dispose, teardown } = connectAppView({+ getContext: () => ({+ agentId: 'agt_1',+ args: '{"city":"Paris"}',+ canSendMessage,+ identifier: 'weather-demo',+ isDark: false,+ onThisDevice: true,+ result: { content: 'sunny' },+ sendMessage,+ server: 'weather-server',+ t: (key: string) => key,+ }),+ onHeight,+ onNavigated,+ onWaitingApprovalsChange,+ resourceUri: 'ui://weather/view',+ target,+ toolCallId: 'call_1',+ });+ let disposed = false;+ const goAway = () => {+ if (disposed) return;+ disposed = true;+ dispose();+ };+ disposers.push(goAway);++ /** Deliver a JSON-RPC message as if the view posted it. */+ const fromView = async (data: Record<string, unknown>) => {+ window.dispatchEvent(+ new MessageEvent('message', { data: { jsonrpc: '2.0', ...data }, source: target }),+ );+ await flush();+ };+ const sent = () => posted.mock.calls.map(([message]) => message as any);+ const response = (id: number) => sent().find((message) => message.id === id);+ const message = (id: number, text: string) =>+ fromView({+ id,+ method: 'ui/message',+ params: { content: [{ text, type: 'text' }], role: 'user' },+ });+ const call = (id: number, city: string) =>+ fromView({ id, method: 'tools/call', params: { arguments: { city }, name: 'get_forecast' } });++ return {+ call,+ dispose: goAway,+ fromView,+ iframe,+ message,+ onHeight,+ onNavigated,+ onWaitingApprovalsChange,+ response,+ sent,+ target,+ teardown: () => {+ disposed = true;+ return teardown();+ },+ waiting: () => waiting,+ };+};++describe('the frame an MCP App view runs in', () => {+ it('keeps powerful features off whatever permissions the view declares', () => {+ for (const feature of ['camera', 'microphone', 'geolocation', 'clipboard-write']) {+ expect(APP_IFRAME_ALLOW).toContain(`${feature} 'none'`);+ }+ expect(VIEW_FRAME_SANDBOX).toBe('allow-scripts allow-forms');+ });++ it('loads the view behind the wrapper that holds it to its declared frame domains', () => {+ const doc = buildAppFrameDocument('<p>weather</p>', buildAppCsp(undefined));++ expect(doc.indexOf('Content-Security-Policy')).toBeLessThan(doc.indexOf('<script>'));+ expect(doc).toContain(`frame-src 'none'`);+ expect(doc).toContain('frame.srcdoc = ');+ expect(doc).toContain('\\u003cp>weather\\u003c/p>');+ });+});++describe('getAppViewPhase', () => {+ it('shows the skeleton while the document loads', () => {+ expect(getAppViewPhase({ isLoading: true, navigated: false })).toBe('loading');+ });++ it('falls back without a document, or once the view left its document', () => {+ expect(getAppViewPhase({ isLoading: false, navigated: false })).toBe('fallback');+ expect(getAppViewPhase({ isLoading: false, navigated: true, srcDoc: '<p />' })).toBe(+ 'fallback',+ );+ });++ it('keeps a loaded view when a revalidation of its HTML fails', () => {+ // A failed SWR revalidation keeps `data`: the document, not the error, decides+ expect(getAppViewPhase({ isLoading: false, navigated: false, srcDoc: '<p />' })).toBe('view');+ });+});++describe('connectAppView', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getAppToolCallPolicy.mockResolvedValue('confirm');+ sendMessage.mockImplementation(async ({ onMessageAccepted }) => onMessageAccepted?.());+ });++ afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+ document.body.innerHTML = '';+ vi.restoreAllMocks();+ });++ it('caps the height a view asks for', async () => {+ const { fromView, onHeight } = setup();++ await fromView({ method: 'ui/notifications/size-changed', params: { height: 99_999 } });++ expect(onHeight).toHaveBeenCalledWith(MAX_APP_VIEW_HEIGHT);+ });++ it('reports a view that left its document, only from its own frame', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const { onNavigated, target } = setup();+ const notice = { source: 'lobe-mcp-app-frame', type: 'navigated' };++ window.dispatchEvent(new MessageEvent('message', { data: notice, source: window }));+ await flush();+ expect(onNavigated).not.toHaveBeenCalled();++ window.dispatchEvent(new MessageEvent('message', { data: notice, source: target }));+ expect(onNavigated).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('left its document'));+ });++ it('drops the approvals of a view once it goes away, as after leaving its document', async () => {+ confirmAppToolCall.mockImplementation(() => new Promise(() => {}));+ const { call, dispose } = setup();++ await call(1, 'Rome');+ const { signal } = confirmAppToolCall.mock.calls[0][0] as { signal: AbortSignal };+ expect(signal.aborted).toBe(false);++ // McpAppView disposes the session when the wrapper reports the view left+ dispose();+ expect(signal.aborted).toBe(true);+ });++ it('requires consent for a message from any of several views, whichever has focus', async () => {+ const clock = vi.spyOn(performance, 'now').mockReturnValue(0);+ Object.defineProperty(navigator, 'userActivation', {+ configurable: true,+ value: { isActive: true },+ });+ confirmAppMessage.mockResolvedValue(false);+ const first = setup();+ const second = setup();+ clock.mockReturnValue(5000);+ first.iframe.focus();+ // Focus can be stolen by a view that did not receive the user's click.+ second.iframe.focus();++ await second.message(1, 'What should I wear?');++ expect(confirmAppMessage).toHaveBeenCalledWith(+ expect.objectContaining({ text: 'What should I wear?' }),+ );+ expect(sendMessage).not.toHaveBeenCalled();+ expect(second.response(1)?.result).toEqual({ isError: true });+ Reflect.deleteProperty(navigator, 'userActivation');+ });++ it('asks before sending a message posted without a gesture, and drops it when declined', async () => {+ confirmAppMessage.mockResolvedValue(false);+ const { message, response } = setup();++ await message(1, 'Posted on load');++ expect(confirmAppMessage).toHaveBeenCalledWith({+ appName: 'Weather Demo',+ signal: expect.any(AbortSignal),+ text: 'Posted on load',+ });+ expect(sendMessage).not.toHaveBeenCalled();+ expect(response(1)?.result).toEqual({ isError: true });+ });++ it('refuses a message in a conversation that takes none, without asking', async () => {+ const { message, response } = setup({ canSendMessage: false });++ await message(1, 'Reply in this thread');++ expect(confirmAppMessage).not.toHaveBeenCalled();+ expect(sendMessage).not.toHaveBeenCalled();+ expect(response(1)?.result).toEqual({ isError: true });+ });++ it('refuses a second message while one is still pending', async () => {+ let confirmMessage!: (allowed: boolean) => void;+ confirmAppMessage.mockReturnValue(new Promise((resolve) => (confirmMessage = resolve)));+ const { message, response } = setup();++ await message(1, 'first');+ await message(2, 'second');+ expect(response(2)?.result).toEqual({ isError: true });+ expect(confirmAppMessage).toHaveBeenCalledTimes(1);++ confirmMessage(true);+ await flush();+ expect(sendMessage).toHaveBeenCalledTimes(1);+ expect(response(1)?.result).toEqual({});+ });++ it('shows the app by name and the arguments before a tool call that needs approval', async () => {+ confirmAppToolCall.mockResolvedValue(false);+ const { call, response } = setup();++ await call(1, 'Rome');++ expect(confirmAppToolCall).toHaveBeenCalledWith({+ appName: 'Weather Demo',+ args: { city: 'Rome' },+ signal: expect.any(AbortSignal),+ tool: 'get_forecast',+ });+ expect(invokeMcpToolCall).not.toHaveBeenCalled();+ expect(response(1)?.result.isError).toBe(true);+ });++ it('asks about parallel tool calls in turn instead of refusing the later ones', async () => {+ const answers: ((allowed: boolean) => void)[] = [];+ confirmAppToolCall.mockImplementation(() => new Promise((resolve) => answers.push(resolve)));+ invokeMcpToolCall.mockResolvedValue({ content: 'rainy', success: true });+ const { call, response } = setup();++ await call(1, 'Rome');+ await call(2, 'Oslo');+ // Both wait for an answer; the confirm queue shows their modals one at a time+ expect(confirmAppToolCall).toHaveBeenCalledTimes(2);+ expect(response(2)).toBeUndefined();++ answers[0](true);+ answers[1](false);+ await flush();+ expect(invokeMcpToolCall).toHaveBeenCalledTimes(1);+ expect(response(1)?.result.isError).toBeFalsy();+ expect(response(2)?.result).toMatchObject({+ content: [{ text: 'mcpApp.toolCall.rejected' }],+ isError: true,+ });+ });++ it('refuses tool calls as busy, not denied, once too many wait for approval', async () => {+ const answers: ((allowed: boolean) => void)[] = [];+ confirmAppToolCall.mockImplementation(() => new Promise((resolve) => answers.push(resolve)));+ const { call, response } = setup();++ for (const id of [1, 2, 3, 4]) await call(id, 'Rome');++ expect(confirmAppToolCall).toHaveBeenCalledTimes(3);+ expect(response(4)?.result).toMatchObject({+ content: [{ text: 'mcpApp.toolCall.busy' }],+ isError: true,+ });++ // Answering one frees a slot+ answers[0](false);+ await flush();+ await call(5, 'Rome');+ expect(confirmAppToolCall).toHaveBeenCalledTimes(4);+ });++ it('withdraws its pending approvals when the view goes away', async () => {+ confirmAppToolCall.mockReturnValue(new Promise(() => {}));+ const { call, dispose } = setup();++ await call(1, 'Rome');+ const { signal } = confirmAppToolCall.mock.calls[0][0] as { signal: AbortSignal };+ expect(signal.aborted).toBe(false);++ dispose();+ expect(signal.aborted).toBe(true);+ });++ it('drops an approval once the view stops waiting for that request', async () => {+ // Like the real confirm: an aborted approval resolves `false`, whatever the user clicks later+ const settle = ({ signal }: { signal: AbortSignal }) =>+ new Promise<boolean>((resolve) =>+ signal.addEventListener('abort', () => resolve(false), { once: true }),+ );+ confirmAppToolCall.mockImplementation(settle);+ confirmAppMessage.mockImplementation(settle);+ const { call, fromView, message } = setup();+ const cancel = (requestId: number) =>+ fromView({ method: 'notifications/cancelled', params: { reason: 'timeout', requestId } });++ await call(1, 'Rome');+ await call(2, 'Oslo');+ await message(3, 'Posted on load');+ const [first, second] = confirmAppToolCall.mock.calls.map(+ ([options]) => (options as { signal: AbortSignal }).signal,+ );+ const { signal: messageSignal } = confirmAppMessage.mock.calls[0][0] as {+ signal: AbortSignal;+ };++ // The view timed out on its first call and on the message+ await cancel(1);+ await cancel(3);++ expect(first.aborted).toBe(true);+ expect(second.aborted).toBe(false);+ expect(messageSignal.aborted).toBe(true);+ expect(invokeMcpToolCall).not.toHaveBeenCalled();+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it('asks for approval, and drops it on cancel, in browsers without AbortSignal.any', async () => {+ vi.spyOn(AbortSignal, 'any').mockImplementation(() => {+ throw new TypeError('AbortSignal.any is not a function');+ });+ confirmAppToolCall.mockReturnValue(new Promise(() => {}));+ const { call, fromView } = setup();++ await call(1, 'Rome');+ expect(confirmAppToolCall).toHaveBeenCalledTimes(1);+ const { signal } = confirmAppToolCall.mock.calls[0][0] as { signal: AbortSignal };+ expect(signal.aborted).toBe(false);++ await fromView({ method: 'notifications/cancelled', params: { requestId: 1 } });+ expect(signal.aborted).toBe(true);+ });++ it('counts its requests waiting for an answer, for the status under the view', async () => {+ const answers: ((allowed: boolean) => void)[] = [];+ confirmAppToolCall.mockImplementation(() => new Promise((resolve) => answers.push(resolve)));+ const { call, waiting } = setup();+ expect(waiting()).toBe(0);++ await call(1, 'Rome');+ await call(2, 'Oslo');+ expect(waiting()).toBe(2);++ // Still waiting while the second one is unanswered+ answers[0](false);+ await flush();+ expect(waiting()).toBe(1);++ answers[1](false);+ await flush();+ expect(waiting()).toBe(0);+ });++ it('runs an approved view tool call on this machine for local servers', async () => {+ confirmAppToolCall.mockResolvedValue(true);+ invokeMcpToolCall.mockResolvedValue({ content: 'rainy', success: true });+ const { call } = setup();++ await call(1, 'Rome');++ expect(invokeMcpToolCall).toHaveBeenCalledWith(+ expect.objectContaining({ apiName: 'get_forecast', identifier: 'weather-demo' }),+ // On the server, and where, the view came from+ {+ agentId: 'agt_1',+ fromMcpApp: true,+ onThisDevice: true,+ server: 'weather-server',+ signal: expect.any(AbortSignal),+ },+ );+ });++ it('cancels an approved message the view gives up on before it is accepted', async () => {+ confirmAppMessage.mockResolvedValue(true);+ sendMessage.mockImplementation(() => new Promise(() => {}));+ const { fromView, message } = setup();++ await message(1, 'Follow up');+ const { signal } = sendMessage.mock.calls[0][0] as { signal: AbortSignal };+ expect(signal.aborted).toBe(false);++ await fromView({ method: 'notifications/cancelled', params: { requestId: 1 } });+ expect(signal.aborted).toBe(true);+ });++ it('still runs calls that need no approval while a removed view finishes, then ends them', async () => {+ getAppToolCallPolicy.mockResolvedValue('allow');+ invokeMcpToolCall.mockResolvedValue({ content: 'saved', success: true });+ const { call, fromView, response, sent, teardown } = setup();+ await fromView({ method: 'ui/notifications/initialized' });++ const finished = teardown();+ await flush();+ const request = sent().find((m) => m.method === 'ui/resource-teardown');+ expect(request).toBeDefined();++ // The view saves its pending edits before it answers+ await call(7, 'Paris');+ expect(invokeMcpToolCall).toHaveBeenCalledTimes(1);+ const { signal } = invokeMcpToolCall.mock.calls[0][1] as { signal: AbortSignal };+ expect(signal.aborted).toBe(false);+ expect(response(7)?.result.isError).toBeFalsy();++ await fromView({ id: request.id, result: {} });+ await finished;++ // Once it finished, nothing it asks for runs any more+ await call(9, 'Rome');+ expect(invokeMcpToolCall).toHaveBeenCalledTimes(1);+ });++ it('cancels an approved message not yet accepted the moment its view starts to go away', async () => {+ confirmAppMessage.mockResolvedValue(true);+ sendMessage.mockImplementation(() => new Promise(() => {}));+ const { fromView, message, teardown } = setup();+ await fromView({ method: 'ui/notifications/initialized' });++ await message(1, 'Follow up');+ const { signal } = sendMessage.mock.calls[0][0] as { signal: AbortSignal };+ void teardown();++ expect(signal.aborted).toBe(true);+ });++ it('drops a prompt the moment its view starts to go away', async () => {+ getAppToolCallPolicy.mockResolvedValue('confirm');+ confirmAppToolCall.mockImplementation(+ ({ signal }: { signal: AbortSignal }) =>+ new Promise((resolve) => signal.addEventListener('abort', () => resolve(false))),+ );+ const { call, fromView, response, teardown } = setup();+ await fromView({ method: 'ui/notifications/initialized' });++ await call(8, 'Rome');+ void teardown();+ await flush();++ expect(invokeMcpToolCall).not.toHaveBeenCalled();+ expect(response(8)?.result.isError).toBe(true);+ });++ it('cancels an approved message before acceptance once the view goes away', async () => {+ confirmAppMessage.mockResolvedValue(true);+ sendMessage.mockImplementation(() => new Promise(() => {}));+ const { dispose, message } = setup();++ await message(1, 'Follow up');+ const { signal } = sendMessage.mock.calls[0][0] as { signal: AbortSignal };++ dispose();+ expect(signal.aborted).toBe(true);+ });++ it('opens a link the view asks for only after the user allows it', async () => {+ const open = vi.spyOn(window, 'open').mockReturnValue(null);+ const { fromView, response } = setup();+ const link = (id: number) =>+ fromView({ id, method: 'ui/open-link', params: { url: 'https://example.com/?d=sunny' } });++ confirmAppOpenLink.mockResolvedValueOnce(false);+ await link(1);+ expect(confirmAppOpenLink).toHaveBeenCalledWith(+ expect.objectContaining({ appName: 'Weather Demo', url: 'https://example.com/?d=sunny' }),+ );+ expect(open).not.toHaveBeenCalled();+ expect(response(1)?.result.isError).toBe(true);++ confirmAppOpenLink.mockResolvedValueOnce(true);+ await link(2);+ expect(open).toHaveBeenCalledWith(+ 'https://example.com/?d=sunny',+ '_blank',+ 'noopener,noreferrer',+ );+ expect(response(2)?.result.isError).toBeUndefined();+ });++ it('asks about one link at a time', async () => {+ vi.spyOn(window, 'open').mockReturnValue(null);+ confirmAppOpenLink.mockImplementation(() => new Promise(() => {}));+ const { fromView, response } = setup();++ await fromView({ id: 1, method: 'ui/open-link', params: { url: 'https://a.example' } });+ await fromView({ id: 2, method: 'ui/open-link', params: { url: 'https://b.example' } });++ expect(confirmAppOpenLink).toHaveBeenCalledTimes(1);+ expect(response(2)?.result.isError).toBe(true);+ });++ it('does not run an allowed call once the view went away while its policy loaded', async () => {+ let decide!: (policy: string) => void;+ getAppToolCallPolicy.mockReturnValue(new Promise((resolve) => (decide = resolve)));+ const { call, dispose } = setup();++ await call(1, 'Rome');+ dispose();+ decide('allow');+ await flush();++ expect(invokeMcpToolCall).not.toHaveBeenCalled();+ });++ it('does not run an allowed call the view cancelled while its policy loaded', async () => {+ let decide!: (policy: string) => void;+ getAppToolCallPolicy.mockReturnValue(new Promise((resolve) => (decide = resolve)));+ const { call, fromView } = setup();++ await call(1, 'Rome');+ await fromView({ method: 'notifications/cancelled', params: { requestId: 1 } });+ decide('allow');+ await flush();++ expect(invokeMcpToolCall).not.toHaveBeenCalled();+ });++ it('cancels a running call once the view goes away', async () => {+ getAppToolCallPolicy.mockResolvedValue('allow');+ invokeMcpToolCall.mockReturnValue(new Promise(() => {}));+ const { call, dispose } = setup();++ await call(1, 'Rome');+ const { signal } = invokeMcpToolCall.mock.calls[0][1] as { signal: AbortSignal };+ expect(signal.aborted).toBe(false);++ dispose();+ expect(signal.aborted).toBe(true);+ });+});diff --git a/src/features/MCPApp/appHost.ts b/src/features/MCPApp/appHost.tsnew file mode 100644index 00000000000..0e518f06ec0--- /dev/null+++ b/src/features/MCPApp/appHost.ts@@ -0,0 +1,288 @@+import type { SendMessageParams } from '@lobechat/types';+import { safeParseJSON } from '@lobechat/utils';+import type { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { TFunction } from 'i18next';++import { mcpService } from '@/services/mcp';+import { getToolStoreState } from '@/store/tool';++import { anySignal } from './abortSignal';+import { mcpAppNameSelector } from './appName';+import { buildHostContext, connectMcpAppBridge } from './bridge';+import { confirmAppMessage, confirmAppOpenLink, confirmAppToolCall } from './confirm';+import { isAppFrameNavigatedNotice } from './frameDocument';+import { sendAppMessage } from './sendAppMessage';+import { getAppToolCallPolicy } from './toolCallPolicy';+import { toCallToolResult } from './utils';+import { withoutStoredMedia } from './viewToolResult';++export const MAX_APP_VIEW_HEIGHT = 2000;+// Tool calls from one view that may wait for approval at once; more are refused as busy+export const MAX_PENDING_TOOL_APPROVALS = 3;++/** What the view's session reads when a request arrives: the latest render's values. */+export interface AppViewContext {+ agentId?: string;+ /** Raw JSON arguments of the tool call. */+ args?: string;+ /**+ * The conversation surface takes new messages: its composer is writable. A+ * read-only one (a thread a tool started) keeps the view from posting too.+ */+ canSendMessage: boolean;+ identifier: string;+ isDark: boolean;+ /** This desktop's own MCP process produced the result; the view's calls run there. */+ onThisDevice: boolean;+ /** Tool call result envelope (`{ content, state, success }`). */+ result: { content: string; state?: any };+ sendMessage: (params: SendMessageParams) => Promise<void>;+ /** The MCP server the view came from; its tool calls reach no other. */+ server?: string;+ t: TFunction<'plugin'> | ((key: string, options?: Record<string, unknown>) => string);+}++export interface ConnectAppViewOptions {+ getContext: () => AppViewContext;+ onHeight: (height: number) => void;+ /** The view left its document and the wrapper dropped it. */+ onNavigated: () => void;+ /** `+1` when one of this view's requests starts waiting for the user, `-1` when it stops. */+ onWaitingApprovalsChange: (delta: 1 | -1) => void;+ resourceUri: string;+ /** The view's frame window: the wrapper document's. */+ target: Window;+ toolCallId: string;+}++const getAppName = (identifier: string, agentId?: string) =>+ mcpAppNameSelector(identifier, agentId)(getToolStoreState());++/**+ * Connect LobeHub to one MCP App view: the bridge session plus what LobeHub+ * does for the view's requests (tool calls, messages, links), under the same+ * approval rules as the conversation. Once the view goes away call `dispose`,+ * or `teardown` while its frame still runs: both end the session and drop the+ * view's approvals, waiting or shown.+ */+/** How long a view removed from the page may take to finish (save pending edits). */+export const APP_VIEW_TEARDOWN_TIMEOUT_MS = 3000;++export interface AppViewSession {+ bridge: AppBridge;+ /** End the session at once: the view is already gone. */+ dispose: () => void;+ /** Let the view finish, within {@link APP_VIEW_TEARDOWN_TIMEOUT_MS}, then end the session. */+ teardown: () => Promise<void>;+}++export const connectAppView = ({+ getContext,+ onHeight,+ onNavigated,+ onWaitingApprovalsChange,+ resourceUri,+ target,+ toolCallId,+}: ConnectAppViewOptions): AppViewSession => {+ const handleFrameNotice = (event: MessageEvent) => {+ if (event.source === target && isAppFrameNavigatedNotice(event.data)) {+ console.warn(`[MCPApp] ${resourceUri} left its document and was removed`);+ onNavigated();+ }+ };+ window.addEventListener('message', handleFrameNotice);++ // One message at a time, so a view can't line up runs behind a pending one+ let sending = false;+ // One link prompt at a time, so a view can't stack them up+ let linking = false;+ // Approvals queue up and open one at a time; a few per view, so a view+ // can't bury the user under modals+ let pendingToolApprovals = 0;+ // Drops this view's approvals, waiting or shown, once it goes away (or+ // starts to): nobody can see a prompt for a view being removed+ const approvals = new AbortController();+ // Ends what the view started, once it is gone. Later than `approvals` during+ // a teardown: the view may still save its edits through a tool call then.+ const session = new AbortController();+ // The view can't see the modal its request waits for, possibly behind+ // another view's, so say under it that it's waiting rather than hung+ const awaitApproval = async (+ request: AbortSignal,+ ask: (signal: AbortSignal) => Promise<boolean>,+ ) => {+ // An approval also lapses once the view stops waiting for its request (it+ // timed out behind other modals): answering it would run work nobody reads+ const { dispose, signal } = anySignal([approvals.signal, request]);+ onWaitingApprovalsChange(1);+ try {+ return await ask(signal);+ } finally {+ dispose();+ onWaitingApprovalsChange(-1);+ }+ };++ const { bridge, dispose, teardown } = connectMcpAppBridge(target, {+ // Views may only call tools on the server that rendered them, and+ // under the same approval rules as the conversation.+ callTool: async (name, toolArgs, request) => {+ const { agentId, identifier, onThisDevice, server, t } = getContext();+ const policy = await getAppToolCallPolicy(identifier, name, { agentId, toolArgs });+ let allowed = policy === 'allow';+ if (policy === 'confirm') {+ if (pendingToolApprovals >= MAX_PENDING_TOOL_APPROVALS) {+ return {+ content: [{ text: t('mcpApp.toolCall.busy', { tool: name }), type: 'text' }],+ isError: true,+ };+ }++ pendingToolApprovals += 1;+ try {+ allowed = await awaitApproval(request, (signal) =>+ confirmAppToolCall({+ appName: getAppName(identifier, agentId),+ args: toolArgs,+ signal,+ tool: name,+ }),+ );+ } finally {+ pendingToolApprovals -= 1;+ }+ }++ if (!allowed) {+ return {+ content: [{ text: t('mcpApp.toolCall.rejected', { tool: name }), type: 'text' }],+ isError: true,+ };+ }++ // The view may have gone, or stopped waiting, while the policy loaded+ // or an approval was open: nobody would read the result, so don't run it.+ const { dispose: disposeCall, signal } = anySignal([session.signal, request]);+ try {+ if (signal.aborted) throw new DOMException('The view stopped waiting', 'AbortError');++ return toCallToolResult(+ await mcpService.invokeMcpToolCall(+ {+ apiName: name,+ arguments: JSON.stringify(toolArgs),+ id: `${toolCallId}:${name}`,+ identifier,+ type: 'mcp',+ },+ // The view's HTML came from this machine for a local server, so its calls do too+ { agentId, fromMcpApp: true, onThisDevice, server, signal },+ ),+ );+ } finally {+ disposeCall();+ }+ },+ hostContext: buildHostContext(getContext().isDark),+ onSizeChange: (nextHeight) => onHeight(Math.min(nextHeight, MAX_APP_VIEW_HEIGHT)),+ // A view can ask without a gesture and carry data in the URL, so the+ // user sees the link before it opens+ openLink: async (url, request) => {+ if (linking) return false;+ linking = true;+ try {+ const { agentId, identifier } = getContext();+ const allowed = await awaitApproval(request, (signal) =>+ confirmAppOpenLink({ appName: getAppName(identifier, agentId), signal, url }),+ );+ if (allowed) window.open(url, '_blank', 'noopener,noreferrer');++ return allowed;+ } finally {+ linking = false;+ }+ },+ // A message starts a billed run. Parent activation and iframe focus+ // cannot prove which opaque-origin view the user acted in, so every+ // message needs consent in the host.+ sendMessage: async (text, request) => {+ if (sending || !getContext().canSendMessage) return false;+ sending = true;+ try {+ const { agentId, identifier } = getContext();+ if (+ !(await awaitApproval(request, (signal) =>+ confirmAppMessage({ appName: getAppName(identifier, agentId), signal, text }),+ ))+ ) {+ return false;+ }++ // Until the conversation accepts it, the view going away or giving up+ // on the request cancels the send rather than starting a reply+ // Its lifetime is the prompts', not the session's: a view being removed+ // may still save its edits, but never starts a reply+ const { dispose: disposeSend, signal } = anySignal([approvals.signal, request]);+ try {+ return await sendAppMessage(getContext().sendMessage, text, identifier, signal);+ } finally {+ disposeSend();+ }+ } finally {+ sending = false;+ }+ },+ toolInput: () => safeParseJSON(getContext().args || '{}') ?? {},+ // The chat stored this result's media as uploads; the view reads base64+ toolResult: () => {+ const { result } = getContext();+ return withoutStoredMedia(toCallToolResult({ ...result, success: !result.state?.isError }));+ },+ });++ const end = () => {+ window.removeEventListener('message', handleFrameNotice);+ approvals.abort();+ session.abort();+ };++ return {+ bridge,+ dispose: () => {+ end();+ dispose();+ },+ // Prompts go at once; calls that need none still run while the view+ // finishes (saves its edits), and end with it+ teardown: async () => {+ approvals.abort();+ try {+ await teardown(APP_VIEW_TEARDOWN_TIMEOUT_MS);+ } finally {+ end();+ }+ },+ };+};++export type AppViewPhase = 'fallback' | 'loading' | 'view';++/**+ * What a view's slot shows. A failed revalidation keeps a view that already+ * loaded: whether the iframe (and the bridge bound to it) exists depends on the+ * document alone, never on a later fetch error.+ */+export const getAppViewPhase = ({+ isLoading,+ navigated,+ srcDoc,+}: {+ isLoading: boolean;+ navigated: boolean;+ srcDoc?: string;+}): AppViewPhase => {+ if (isLoading) return 'loading';+ if (!srcDoc || navigated) return 'fallback';+ return 'view';+};diff --git a/src/features/MCPApp/appName.test.ts b/src/features/MCPApp/appName.test.tsnew file mode 100644index 00000000000..7d89c31f535--- /dev/null+++ b/src/features/MCPApp/appName.test.ts@@ -0,0 +1,38 @@+import { afterEach, describe, expect, it } from 'vitest';++import { getToolStoreState, useToolStore } from '@/store/tool';++import { mcpAppNameSelector } from './appName';++const initialState = useToolStore.getState();++afterEach(() => {+ useToolStore.setState(initialState, true);+});++// The name a view's follow-up message and its confirm modals show+describe('mcpAppNameSelector', () => {+ it("names a plugin's view by the plugin's display name", () => {+ useToolStore.setState({+ installedPlugins: [+ {+ identifier: 'weather-demo',+ manifest: { api: [], identifier: 'weather-demo', meta: { title: 'Weather Demo' } },+ type: 'customPlugin',+ },+ ] as any,+ });++ expect(mcpAppNameSelector('weather-demo')(getToolStoreState())).toBe('Weather Demo');+ });++ it("names a connector's view by the connector name", () => {+ useToolStore.setState({ connectors: [{ identifier: 'linear-abc', name: 'Linear' }] as any });++ expect(mcpAppNameSelector('linear-abc')(getToolStoreState())).toBe('Linear');+ });++ it('falls back to the identifier once the app is gone', () => {+ expect(mcpAppNameSelector('removed-app')(getToolStoreState())).toBe('removed-app');+ });+});diff --git a/src/features/MCPApp/appName.ts b/src/features/MCPApp/appName.tsnew file mode 100644index 00000000000..bc5b966f9cf--- /dev/null+++ b/src/features/MCPApp/appName.ts@@ -0,0 +1,15 @@+import { toolSelectors } from '@/store/tool/selectors';+import { connectorSelectors } from '@/store/tool/slices/connector';+import type { ToolStore } from '@/store/tool/store';++/**+ * The name an MCP App goes by in the conversation: its plugin's title, else the+ * connector's name (the agent's own connector first), else the identifier once+ * the plugin or connector is gone.+ */+export const mcpAppNameSelector =+ (identifier: string, agentId?: string) =>+ (s: ToolStore): string =>+ toolSelectors.getMetaById(identifier)(s)?.title ||+ connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s)?.name ||+ identifier;diff --git a/src/features/MCPApp/bridge.test.ts b/src/features/MCPApp/bridge.test.tsnew file mode 100644index 00000000000..5ea6c10bf27--- /dev/null+++ b/src/features/MCPApp/bridge.test.ts@@ -0,0 +1,201 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { buildHostContext, connectMcpAppBridge, type McpAppBridgeHost } from './bridge';++const setup = (overrides: Partial<McpAppBridgeHost> = {}) => {+ const iframe = document.createElement('iframe');+ document.body.append(iframe);+ const target = iframe.contentWindow!;+ const posted = vi.spyOn(target, 'postMessage');++ const host: McpAppBridgeHost = {+ callTool: vi.fn().mockResolvedValue({ content: [{ text: 'rainy', type: 'text' }] }),+ hostContext: buildHostContext(false),+ onSizeChange: vi.fn(),+ openLink: vi.fn().mockResolvedValue(true),+ sendMessage: vi.fn(),+ toolInput: () => ({ city: 'Paris' }),+ toolResult: () => ({ content: [{ text: 'sunny', type: 'text' }] }),+ ...overrides,+ };+ const connection = connectMcpAppBridge(target, host);++ /** Deliver a JSON-RPC message as if the view posted it. */+ const fromView = async (data: Record<string, unknown>) => {+ window.dispatchEvent(+ new MessageEvent('message', { data: { jsonrpc: '2.0', ...data }, source: target }),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ };+ const sent = () => posted.mock.calls.map(([message]) => message as any);+ const response = (id: number) => sent().find((message) => message.id === id);++ return { connection, fromView, host, response, sent };+};++describe('connectMcpAppBridge', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ vi.restoreAllMocks();+ });++ it('leaves ui/open-link to the host, which may decline it', async () => {+ const open = vi.spyOn(window, 'open').mockReturnValue(null);+ const { fromView, host, response } = setup();++ await fromView({ id: 1, method: 'ui/open-link', params: { url: 'https://example.com/?q=1' } });+ expect(host.openLink).toHaveBeenCalledWith('https://example.com/?q=1', expect.any(AbortSignal));+ expect(response(1)?.result.isError).toBeUndefined();++ vi.mocked(host.openLink).mockResolvedValueOnce(false);+ await fromView({ id: 2, method: 'ui/open-link', params: { url: 'https://example.com/' } });+ expect(response(2)?.result.isError).toBe(true);++ // Only web links reach the host+ await fromView({ id: 3, method: 'ui/open-link', params: { url: 'javascript:alert(1)' } });+ expect(host.openLink).toHaveBeenCalledTimes(2);+ expect(response(3)?.result.isError).toBe(true);+ // The bridge never opens anything itself+ expect(open).not.toHaveBeenCalled();+ });++ it('answers ui/initialize, then sends the tool input and result', async () => {+ const { fromView, response, sent } = setup();++ await fromView({+ id: 1,+ method: 'ui/initialize',+ params: {+ appCapabilities: {},+ appInfo: { name: 'weather', version: '1.0.0' },+ protocolVersion: '2026-01-26',+ },+ });+ expect(response(1)?.result.hostInfo.name).toBe('LobeHub');+ expect(response(1)?.result.hostContext.theme).toBe('light');++ await fromView({ method: 'ui/notifications/initialized' });++ const input = sent().find((m) => m.method === 'ui/notifications/tool-input');+ const result = sent().find((m) => m.method === 'ui/notifications/tool-result');+ expect(input.params).toEqual({ arguments: { city: 'Paris' } });+ expect(result.params).toEqual({ content: [{ text: 'sunny', type: 'text' }] });+ });++ it('routes tool calls and user messages to the host', async () => {+ const { fromView, host, response } = setup();+ await fromView({ method: 'ui/notifications/initialized' });++ await fromView({+ id: 2,+ method: 'tools/call',+ params: { arguments: { city: 'Rome' }, name: 'get_forecast' },+ });+ expect(host.callTool).toHaveBeenCalledWith(+ 'get_forecast',+ { city: 'Rome' },+ expect.any(AbortSignal),+ );+ expect(response(2)?.result).toEqual({ content: [{ text: 'rainy', type: 'text' }] });++ await fromView({+ id: 3,+ method: 'ui/message',+ params: { content: [{ text: 'Plan a trip to Rome', type: 'text' }], role: 'user' },+ });+ expect(host.sendMessage).toHaveBeenCalledWith('Plan a trip to Rome', expect.any(AbortSignal));+ expect(response(3)?.result).toEqual({});+ });++ it('aborts a request signal once the view cancels that request', async () => {+ const { fromView, host } = setup({ callTool: vi.fn(() => new Promise<never>(() => {})) });+ await fromView({ method: 'ui/notifications/initialized' });++ await fromView({+ id: 7,+ method: 'tools/call',+ params: { arguments: {}, name: 'get_forecast' },+ });+ const signal = vi.mocked(host.callTool).mock.calls[0][2];+ expect(signal.aborted).toBe(false);++ // What the view sends when its request times out+ await fromView({+ method: 'notifications/cancelled',+ params: { reason: 'timeout', requestId: 7 },+ });+ expect(signal.aborted).toBe(true);+ });++ it('answers a message the host declined with an error', async () => {+ const { fromView, response } = setup({ sendMessage: vi.fn().mockResolvedValue(false) });+ await fromView({ method: 'ui/notifications/initialized' });++ await fromView({+ id: 6,+ method: 'ui/message',+ params: { content: [{ text: 'Plan a trip to Rome', type: 'text' }], role: 'user' },+ });+ expect(response(6)?.result).toEqual({ isError: true });+ });++ it('reports size changes and ignores messages from other windows', async () => {+ const { connection, fromView, host } = setup();++ await fromView({ method: 'ui/notifications/size-changed', params: { height: 480.2 } });+ expect(host.onSizeChange).toHaveBeenCalledWith(481);++ window.dispatchEvent(+ new MessageEvent('message', {+ data: { jsonrpc: '2.0', method: 'ui/notifications/size-changed', params: { height: 9 } },+ source: window,+ }),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(host.onSizeChange).toHaveBeenCalledTimes(1);++ connection.dispose();+ await fromView({ method: 'ui/notifications/size-changed', params: { height: 100 } });+ expect(host.onSizeChange).toHaveBeenCalledTimes(1);+ });+ it('tells an initialized view it is going away and waits for its answer before closing', async () => {+ const { connection, fromView, sent } = setup();+ await fromView({ method: 'ui/notifications/initialized' });+ const close = vi.spyOn(connection.bridge, 'close');++ let done = false;+ const teardown = connection.teardown(3000).then(() => (done = true));+ await new Promise((resolve) => setTimeout(resolve, 0));+ const request = sent().find((m) => m.method === 'ui/resource-teardown');+ expect(request).toBeDefined();+ expect(done).toBe(false);+ expect(close).not.toHaveBeenCalled();++ // The view saved its edits and answers+ await fromView({ id: request.id, result: {} });+ await teardown;+ expect(close).toHaveBeenCalled();+ });++ it('closes a view that never answers once the wait is over, and one never initialized at once', async () => {+ vi.useFakeTimers();+ try {+ const silent = setup();+ silent.fromView({ method: 'ui/notifications/initialized' });+ await vi.advanceTimersByTimeAsync(0);+ const closeSilent = vi.spyOn(silent.connection.bridge, 'close');+ const teardown = silent.connection.teardown(3000);+ await vi.advanceTimersByTimeAsync(3000);+ await teardown;+ expect(closeSilent).toHaveBeenCalled();++ const fresh = setup();+ const closeFresh = vi.spyOn(fresh.connection.bridge, 'close');+ await fresh.connection.teardown(3000);+ expect(fresh.sent().some((m) => m.method === 'ui/resource-teardown')).toBe(false);+ expect(closeFresh).toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/src/features/MCPApp/bridge.ts b/src/features/MCPApp/bridge.tsnew file mode 100644index 00000000000..31cb70975f2--- /dev/null+++ b/src/features/MCPApp/bridge.ts@@ -0,0 +1,120 @@+import { CURRENT_VERSION } from '@lobechat/const';+import type { CallToolResult } from '@modelcontextprotocol/client';+import {+ AppBridge,+ type McpUiHostContext,+ type McpUiSizeChangedNotification,+ PostMessageTransport,+} from '@modelcontextprotocol/ext-apps/app-bridge';++export const buildHostContext = (isDark: boolean): McpUiHostContext => ({+ availableDisplayModes: ['inline'],+ displayMode: 'inline',+ locale: navigator.language,+ platform: 'web',+ theme: isDark ? 'dark' : 'light',+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+});++export interface McpAppBridgeHost {+ /**+ * Call a tool on the server that rendered the view. `signal` aborts when the+ * view stops waiting for the answer (it timed out or cancelled the request).+ */+ callTool: (+ name: string,+ args: Record<string, unknown>,+ signal: AbortSignal,+ ) => Promise<CallToolResult>;+ hostContext: McpUiHostContext;+ onSizeChange: (height: number) => void;+ /**+ * Open an http(s) link the view asked for; resolves `false` when the host+ * declined it. `signal` aborts when the view stops waiting for the answer.+ */+ openLink: (url: string, signal: AbortSignal) => Promise<boolean>;+ /**+ * Post a user message into the conversation; resolves `false` when the host+ * declined it. `signal` aborts when the view stops waiting for the answer.+ */+ sendMessage: (text: string, signal: AbortSignal) => Promise<boolean | void> | boolean | void;+ toolInput: () => Record<string, unknown>;+ /** The result the view renders; may resolve later (stored media is read back first). */+ toolResult: () => CallToolResult | Promise<CallToolResult>;+}++/**+ * Connect LobeHub to an MCP Apps view living in `target` (the sandboxed+ * iframe's window). `dispose` closes the session at once; `teardown` first+ * lets the view finish, as MCP Apps asks before a view is removed.+ */+export const connectMcpAppBridge = (target: Window, host: McpAppBridgeHost) => {+ const bridge = new AppBridge(+ null,+ { name: 'LobeHub', version: CURRENT_VERSION },+ { message: { text: {} }, openLinks: {}, serverTools: {} },+ { hostContext: host.hostContext },+ );++ bridge.oncalltool = ({ arguments: args, name }, { mcpReq }) =>+ host.callTool(name, args ?? {}, mcpReq.signal);++ bridge.onmessage = async ({ content }, { mcpReq }) => {+ const text = content+ .flatMap((block) => (block.type === 'text' ? [block.text] : []))+ .join('\n')+ .trim();+ if (!text) return { isError: true };++ const sent = await host.sendMessage(text, mcpReq.signal);+ return sent === false ? { isError: true } : {};+ };++ bridge.onopenlink = async ({ url }, { mcpReq }) => {+ if (!/^https?:\/\//i.test(url)) return { isError: true };++ return (await host.openLink(url, mcpReq.signal)) ? {} : { isError: true };+ };++ const handleSizeChange = ({ height }: McpUiSizeChangedNotification['params']) => {+ if (typeof height === 'number' && height > 0) host.onSizeChange(Math.ceil(height));+ };++ let initialized = false;+ const handleInitialized = () => {+ initialized = true;+ void bridge.sendToolInput({ arguments: host.toolInput() });+ void Promise.resolve(host.toolResult()).then((result) => bridge.sendToolResult(result));+ };++ bridge.addEventListener('sizechange', handleSizeChange);+ bridge.addEventListener('initialized', handleInitialized);+ void bridge.connect(new PostMessageTransport(target, target));++ const dispose = () => {+ bridge.removeEventListener('sizechange', handleSizeChange);+ bridge.removeEventListener('initialized', handleInitialized);+ void bridge.close();+ };++ return {+ bridge,+ dispose,+ /**+ * Tell the view it is going away (`ui/resource-teardown`) and give it up to+ * `timeoutMs` to finish (save pending edits) before the session closes. A+ * view that never initialized has nothing to finish.+ */+ teardown: async (timeoutMs: number) => {+ if (initialized) {+ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ bridge.teardownResource({}).catch(() => {}),+ new Promise<void>((resolve) => (timer = setTimeout(resolve, timeoutMs))),+ ]);+ clearTimeout(timer);+ }+ dispose();+ },+ };+};diff --git a/src/features/MCPApp/confirm.test.ts b/src/features/MCPApp/confirm.test.tsnew file mode 100644index 00000000000..b646dbed7c8--- /dev/null+++ b/src/features/MCPApp/confirm.test.ts@@ -0,0 +1,133 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { confirmAppMessage, confirmAppOpenLink, confirmAppToolCall } from './confirm';++interface OpenedModal {+ close: ReturnType<typeof vi.fn>;+ onOpenChange: (open: boolean) => void;+}++const { createModal, opened } = vi.hoisted(() => {+ const opened: OpenedModal[] = [];+ const createModal = vi.fn((options: { onOpenChange: (open: boolean) => void }) => {+ const modal = { close: vi.fn(), onOpenChange: options.onOpenChange };+ opened.push(modal);+ return modal;+ });+ return { createModal, opened };+});++vi.mock('@lobehub/ui', () => ({+ Button: () => null,+ createModal,+ Flexbox: () => null,+ Highlighter: () => null,+ Text: () => null,+}));++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));+const toolCall = (signal?: AbortSignal) =>+ confirmAppToolCall({ appName: 'Weather Demo', args: {}, signal, tool: 'get_forecast' });++describe('MCP App confirm queue', () => {+ beforeEach(() => {+ opened.length = 0;+ createModal.mockClear();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('opens one modal at a time across views', async () => {+ const first = toolCall();+ const second = confirmAppMessage({ appName: 'Other View', text: 'hi' });+ await flush();+ expect(opened).toHaveLength(1);++ opened[0].onOpenChange(false);+ await expect(first).resolves.toBe(false);+ await flush();+ expect(opened).toHaveLength(2);++ opened[1].onOpenChange(false);+ await expect(second).resolves.toBe(false);+ });++ it('queues link prompts with the other requests and resolves false when dismissed', async () => {+ const first = toolCall();+ const link = confirmAppOpenLink({ appName: 'Weather Demo', url: 'https://example.com' });+ await flush();+ expect(opened).toHaveLength(1);++ opened[0].onOpenChange(false);+ await first;+ await flush();+ expect(opened).toHaveLength(2);++ opened[1].onOpenChange(false);+ await expect(link).resolves.toBe(false);+ });++ it('drops a waiting request at once when its view goes away, without opening it', async () => {+ const first = toolCall();+ const view = new AbortController();+ const second = toolCall(view.signal);+ await flush();++ view.abort();+ await expect(second).resolves.toBe(false);++ opened[0].onOpenChange(false);+ await first;+ await flush();+ expect(opened).toHaveLength(1);+ });++ it('closes a shown modal when its view goes away', async () => {+ const view = new AbortController();+ const pending = toolCall(view.signal);+ await flush();+ expect(opened).toHaveLength(1);++ view.abort();+ await expect(pending).resolves.toBe(false);+ expect(opened[0].close).toHaveBeenCalled();++ // The queue moves on to the next request+ const next = toolCall();+ await flush();+ expect(opened).toHaveLength(2);+ opened[1].onOpenChange(false);+ await next;+ });++ it('asks with a signal in browsers without Promise.withResolvers', async () => {+ vi.spyOn(Promise, 'withResolvers').mockImplementation(() => {+ throw new TypeError('Promise.withResolvers is not a function');+ });+ const view = new AbortController();++ const pending = toolCall(view.signal);+ await flush();+ expect(opened).toHaveLength(1);++ opened[0].onOpenChange(false);+ await expect(pending).resolves.toBe(false);+ });++ it('leaves no abort listener on the signal once a request is answered', async () => {+ const view = new AbortController();+ const added = vi.spyOn(view.signal, 'addEventListener');+ const removed = vi.spyOn(view.signal, 'removeEventListener');++ const pending = toolCall(view.signal);+ await flush();+ opened[0].onOpenChange(false);+ await expect(pending).resolves.toBe(false);++ const listeners = (spy: typeof added) => spy.mock.calls.map(([, listener]) => listener);+ expect(listeners(added).length).toBeGreaterThan(0);+ expect(listeners(removed)).toEqual(expect.arrayContaining(listeners(added)));+ });+});diff --git a/src/features/MCPApp/confirm.tsx b/src/features/MCPApp/confirm.tsxnew file mode 100644index 00000000000..849324ec023--- /dev/null+++ b/src/features/MCPApp/confirm.tsx@@ -0,0 +1,152 @@+'use client';++import { Button, createModal, Flexbox, Highlighter, Text } from '@lobehub/ui';+import { t } from 'i18next';+import type { ReactNode } from 'react';++interface ConfirmOptions {+ cancelText: string;+ content: ReactNode;+ okText: string;+ /** Aborted when the view goes away: drops the request, or closes its modal if shown */+ signal?: AbortSignal;+ title: string;+}++// Requests from every view on the page share one queue, so modals open one at a time+let queue: Promise<unknown> = Promise.resolve();++const openModal = ({ cancelText, content, okText, signal, title }: ConfirmOptions) =>+ new Promise<boolean>((resolve) => {+ if (signal?.aborted) return resolve(false);++ let settled = false;+ const settle = (allowed: boolean) => {+ if (settled) return;+ settled = true;+ signal?.removeEventListener('abort', onAbort);+ resolve(allowed);+ modal.close();+ };+ const onAbort = () => settle(false);+ signal?.addEventListener('abort', onAbort, { once: true });+ const modal = createModal({+ content,+ footer: (+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button onClick={() => settle(false)}>{cancelText}</Button>+ <Button type={'primary'} onClick={() => settle(true)}>+ {okText}+ </Button>+ </Flexbox>+ ),+ onOpenChange: (open) => {+ if (!open) settle(false);+ },+ title,+ });+ });++/**+ * Resolves false on Cancel and on any other dismissal (Esc, mask, close), and+ * at once when `signal` aborts, even while waiting behind another modal.+ */+const confirm = (options: ConfirmOptions) => {+ const turn = queue.then(() => openModal(options));+ // A modal that failed to open must not block the ones after it+ queue = turn.catch(() => {});++ const { signal } = options;+ if (!signal) return turn;+ if (signal.aborted) return Promise.resolve(false);++ // Not `Promise.withResolvers`, which Safari < 17.4 and Chrome < 119 lack+ let onAbort = () => {};+ const dropped = new Promise<boolean>((resolve) => {+ onAbort = () => resolve(false);+ signal.addEventListener('abort', onAbort, { once: true });+ });+ // The signal can outlive many requests, so don't leave a listener per answer+ return Promise.race([turn, dropped]).finally(() => signal.removeEventListener('abort', onAbort));+};++/** Ask before a view runs a tool, showing the app by name and the arguments it passes. */+export const confirmAppToolCall = ({+ appName,+ args,+ signal,+ tool,+}: {+ appName: string;+ args: Record<string, unknown>;+ signal?: AbortSignal;+ tool: string;+}) =>+ confirm({+ cancelText: t('mcpApp.toolCall.confirm.cancel', { ns: 'plugin' }),+ content: (+ <Flexbox gap={12}>+ <Text>{t('mcpApp.toolCall.confirm.content', { app: appName, ns: 'plugin', tool })}</Text>+ <Highlighter actionIconSize={'small'} language={'json'} wrap={true}>+ {JSON.stringify(args, null, 2)}+ </Highlighter>+ </Flexbox>+ ),+ okText: t('mcpApp.toolCall.confirm.ok', { ns: 'plugin' }),+ signal,+ title: t('mcpApp.toolCall.confirm.title', { ns: 'plugin' }),+ });++/** Ask before a view posts a message the user did not just send from it. */+export const confirmAppMessage = ({+ appName,+ signal,+ text,+}: {+ appName: string;+ signal?: AbortSignal;+ text: string;+}) =>+ confirm({+ cancelText: t('mcpApp.message.confirm.cancel', { ns: 'plugin' }),+ content: (+ <Flexbox gap={12}>+ <Text>{t('mcpApp.message.confirm.content', { app: appName, ns: 'plugin' })}</Text>+ <Highlighter actionIconSize={'small'} language={'markdown'} wrap={true}>+ {text}+ </Highlighter>+ </Flexbox>+ ),+ okText: t('mcpApp.message.confirm.ok', { ns: 'plugin' }),+ signal,+ title: t('mcpApp.message.confirm.title', { ns: 'plugin' }),+ });++/**+ * Ask before opening a link a view asked for. A view can request one without+ * any gesture and put data in the URL, which would leave past its network+ * policy (on desktop straight to the system browser), so the user sees it first.+ */+export const confirmAppOpenLink = ({+ appName,+ signal,+ url,+}: {+ appName: string;+ signal?: AbortSignal;+ url: string;+}) =>+ confirm({+ cancelText: t('mcpApp.openLink.confirm.cancel', { ns: 'plugin' }),+ content: (+ <Flexbox gap={12}>+ <Text>{t('mcpApp.openLink.confirm.content', { app: appName, ns: 'plugin' })}</Text>+ <Highlighter actionIconSize={'small'} language={'txt'} wrap={true}>+ {url}+ </Highlighter>+ </Flexbox>+ ),+ okText: t('mcpApp.openLink.confirm.ok', { ns: 'plugin' }),+ signal,+ title: t('mcpApp.openLink.confirm.title', { ns: 'plugin' }),+ });diff --git a/src/features/MCPApp/frameDocument.test.ts b/src/features/MCPApp/frameDocument.test.tsnew file mode 100644index 00000000000..83ca085fdea--- /dev/null+++ b/src/features/MCPApp/frameDocument.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';++import {+ buildAppFrameDocument,+ isAppFrameNavigatedNotice,+ MCP_APP_FRAME_SOURCE,+ VIEW_FRAME_SANDBOX,+} from './frameDocument';+import { APP_IFRAME_ALLOW, buildAppCsp, injectCsp } from './utils';++/** The view document the wrapper script assigns to its frame's `srcdoc`. */+const readViewDocument = (wrapper: string) => {+ const literal = /frame\.srcdoc = ("(?:[^"\\]|\\.)*");/.exec(wrapper)?.[1];+ return literal === undefined ? undefined : (JSON.parse(literal) as string);+};++describe('buildAppFrameDocument', () => {+ const csp = buildAppCsp({ frameDomains: ['https://maps.example.com'] });++ it('puts the view policy ahead of the wrapper markup, so it governs the view frame navigation', () => {+ const wrapper = buildAppFrameDocument('<p>weather</p>', csp);++ // The view frame inherits this policy: the same one keeps what the resource declared+ expect(wrapper.startsWith(injectCsp('', csp))).toBe(true);+ expect(csp).toContain('frame-src https://maps.example.com');+ });++ it('keeps an undeclared view frame from navigating anywhere', () => {+ const wrapper = buildAppFrameDocument('<p>weather</p>', buildAppCsp(undefined));++ expect(wrapper).toContain(`frame-src 'none'`);+ });++ it('runs the app HTML behind the same policy in a frame without more sandbox powers', () => {+ const wrapper = buildAppFrameDocument('<p>weather</p>', csp);++ expect(readViewDocument(wrapper)).toBe(injectCsp('<p>weather</p>', csp));+ expect(wrapper).toContain(+ `frame.setAttribute('sandbox', ${JSON.stringify(VIEW_FRAME_SANDBOX)})`,+ );+ expect(wrapper).toContain(`frame.setAttribute('allow', ${JSON.stringify(APP_IFRAME_ALLOW)})`);+ expect(VIEW_FRAME_SANDBOX).not.toContain('allow-same-origin');+ expect(VIEW_FRAME_SANDBOX).not.toContain('allow-top-navigation');+ expect(VIEW_FRAME_SANDBOX).not.toContain('allow-popups');+ });++ it('keeps app markup that closes a script from escaping into the wrapper', () => {+ const app = '</script><script>parent.location="https://evil.example"</script><!--';+ const wrapper = buildAppFrameDocument(app, csp);++ expect(wrapper.match(/<\/script>/g)).toHaveLength(1);+ expect(wrapper).not.toContain('<!--');+ expect(readViewDocument(wrapper)).toBe(injectCsp(app, csp));+ });++ it('drops the view and tells the host once its frame loads a second document', () => {+ const wrapper = buildAppFrameDocument('<p>weather</p>', csp);++ expect(wrapper).toContain('if (loads < 2 || dropped) return;');+ expect(wrapper).toContain('frame.remove();');+ expect(wrapper).toContain(`source: ${JSON.stringify(MCP_APP_FRAME_SOURCE)}, type: 'navigated'`);+ });+});++describe('isAppFrameNavigatedNotice', () => {+ it('only accepts the wrapper notice', () => {+ expect(isAppFrameNavigatedNotice({ source: MCP_APP_FRAME_SOURCE, type: 'navigated' })).toBe(+ true,+ );+ expect(isAppFrameNavigatedNotice({ source: MCP_APP_FRAME_SOURCE, type: 'ready' })).toBe(false);+ expect(isAppFrameNavigatedNotice({ jsonrpc: '2.0', method: 'ui/message' })).toBe(false);+ expect(isAppFrameNavigatedNotice(null)).toBe(false);+ });+});diff --git a/src/features/MCPApp/frameDocument.ts b/src/features/MCPApp/frameDocument.tsnew file mode 100644index 00000000000..bb6cfed770e--- /dev/null+++ b/src/features/MCPApp/frameDocument.ts@@ -0,0 +1,84 @@+import { APP_IFRAME_ALLOW, injectCsp } from './utils';++/**+ * The documents an MCP App view runs in. Two nested frames, both sandboxed+ * without `allow-same-origin` (opaque origin: no cookies, storage or app API):+ *+ * - the **wrapper** is ours. A document's CSP restricts what it fetches and+ * which child frames it may navigate (`frame-src`), not navigations of its+ * own frame, so a view loaded directly could leave with data in its URL+ * (`location.href = …`). The wrapper's `frame-src` holds the view frame to+ * the frame domains the resource declared: the boundary is those domains,+ * which the view may embed and message anyway. It relays the view's+ * postMessage traffic both ways unchanged. When the view frame loads a+ * second document it removes it and stops relaying, so a view that left its+ * document doesn't linger in the chat; a page the view frame reaches first+ * (before its own document finished loading) stays, within those domains.+ * - the **view** frame runs the app's HTML behind the same CSP (`injectCsp`).+ *+ * A srcdoc frame inherits its parent's CSP on top of its own, so the wrapper+ * carries exactly the view's policy: anything stricter would take away what+ * the resource declared.+ */++export const MCP_APP_FRAME_SOURCE = 'lobe-mcp-app-frame';++/** The view frame tried to leave its document; the wrapper dropped it. */+export interface McpAppFrameNavigatedNotice {+ source: typeof MCP_APP_FRAME_SOURCE;+ type: 'navigated';+}++export const VIEW_FRAME_SANDBOX = 'allow-scripts allow-forms';++// Inside an inline script: `<` can't open `</script>` or `<!--` once escaped+const toScriptString = (value: string) => JSON.stringify(value).replaceAll('<', '\\u003c');++const WRAPPER_STYLE =+ 'html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent}' ++ 'iframe{display:block;width:100%;height:100%;border:0;background:transparent;color-scheme:normal}';++const wrapperScript = (viewDocument: string) => `(() => {+ const frame = document.createElement('iframe');+ frame.setAttribute('sandbox', ${toScriptString(VIEW_FRAME_SANDBOX)});+ frame.setAttribute('allow', ${toScriptString(APP_IFRAME_ALLOW)});+ frame.setAttribute('title', 'MCP App');+ let loads = 0;+ let dropped = false;+ // Only the srcdoc ever loads; a second load means the frame left it.+ frame.addEventListener('load', () => {+ loads += 1;+ if (loads < 2 || dropped) return;+ dropped = true;+ frame.remove();+ parent.postMessage({ source: ${toScriptString(MCP_APP_FRAME_SOURCE)}, type: 'navigated' }, '*');+ });+ addEventListener('message', (event) => {+ if (dropped) return;+ if (event.source === parent) frame.contentWindow?.postMessage(event.data, '*');+ else if (event.source === frame.contentWindow) parent.postMessage(event.data, '*');+ });+ frame.srcdoc = ${toScriptString(viewDocument)};+ document.body.append(frame);+})();`;++/**+ * The document the host iframe loads: the wrapper, with the app's HTML (behind+ * `csp`) inside it.+ */+export const buildAppFrameDocument = (html: string, csp: string): string =>+ injectCsp(+ [+ '<meta charset="utf-8">',+ `<style>${WRAPPER_STYLE}</style>`,+ '<body>',+ `<script>${wrapperScript(injectCsp(html, csp))}</script>`,+ ].join('\n'),+ csp,+ );++export const isAppFrameNavigatedNotice = (data: unknown): data is McpAppFrameNavigatedNotice =>+ !!data &&+ typeof data === 'object' &&+ (data as { source?: unknown }).source === MCP_APP_FRAME_SOURCE &&+ (data as { type?: unknown }).type === 'navigated';diff --git a/src/features/MCPApp/frameRetire.test.ts b/src/features/MCPApp/frameRetire.test.tsnew file mode 100644index 00000000000..0778111e165--- /dev/null+++ b/src/features/MCPApp/frameRetire.test.ts@@ -0,0 +1,75 @@+/**+ * @vitest-environment happy-dom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { retireAppFrame } from './frameRetire';++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++// happy-dom has no `moveBefore`; this stand-in moves like it (browsers keep the+// iframe's document; here only where the node ends up matters)+const moveBefore = function (this: HTMLElement, node: Node, child: Node | null) {+ this.insertBefore(node, child);+};++const mountFrame = () => {+ const slot = document.createElement('div');+ const frame = document.createElement('iframe');+ slot.append(frame);+ document.body.append(slot);+ return { frame, slot };+};++describe('retireAppFrame', () => {+ beforeEach(() => {+ (HTMLElement.prototype as any).moveBefore = moveBefore;+ });++ afterEach(() => {+ delete (HTMLElement.prototype as any).moveBefore;+ document.body.innerHTML = '';+ });++ it('keeps an unmounted view running aside until it finished, then removes it', async () => {+ const { frame, slot } = mountFrame();+ let finish!: () => void;+ const teardown = vi.fn(() => new Promise<void>((resolve) => (finish = resolve)));+ const keep = vi.fn();++ expect(retireAppFrame(frame, { keep, teardown })).toBe(true);+ // React then removes the view's slot+ slot.remove();+ await flush();++ expect(teardown).toHaveBeenCalledTimes(1);+ expect(frame.isConnected).toBe(true);+ expect(frame.parentElement).not.toBe(slot);++ finish();+ await flush();+ expect(frame.isConnected).toBe(false);+ expect(keep).not.toHaveBeenCalled();+ });++ it('puts the frame back when its slot stays, as when StrictMode re-runs the effect', async () => {+ const { frame, slot } = mountFrame();+ const teardown = vi.fn(async () => {});+ const keep = vi.fn();++ retireAppFrame(frame, { keep, teardown });+ await flush();++ expect(frame.parentElement).toBe(slot);+ expect(keep).toHaveBeenCalledTimes(1);+ expect(teardown).not.toHaveBeenCalled();+ });++ it('leaves the frame alone where it cannot be moved without reloading', () => {+ delete (HTMLElement.prototype as any).moveBefore;+ const { frame, slot } = mountFrame();++ expect(retireAppFrame(frame, { keep: vi.fn(), teardown: vi.fn() })).toBe(false);+ expect(frame.parentElement).toBe(slot);+ });+});diff --git a/src/features/MCPApp/frameRetire.ts b/src/features/MCPApp/frameRetire.tsnew file mode 100644index 00000000000..f40dcfbcdcb--- /dev/null+++ b/src/features/MCPApp/frameRetire.ts@@ -0,0 +1,67 @@+/**+ * Keep a removed MCP App view running long enough to finish. MCP Apps asks the+ * host to send `ui/resource-teardown` before it removes a view and to wait for+ * the answer (the view may save pending edits), but React drops the iframe's+ * browsing context as soon as it unmounts it, and an ordinary DOM move reloads+ * an iframe. `moveBefore` moves it without reloading, so the frame waits in an+ * off-screen holder while its view finishes.+ */++type MovableParent = HTMLElement & { moveBefore: (node: Node, child: Node | null) => void };++const canMove = (element: HTMLElement): element is MovableParent =>+ typeof (element as Partial<MovableParent>).moveBefore === 'function';++let holder: HTMLElement | undefined;++const getHolder = (): HTMLElement => {+ if (holder?.isConnected) return holder;++ holder = document.createElement('div');+ holder.setAttribute('aria-hidden', 'true');+ holder.dataset.mcpAppRetired = '';+ Object.assign(holder.style, {+ height: '1px',+ left: '-10000px',+ overflow: 'hidden',+ pointerEvents: 'none',+ position: 'fixed',+ top: '0',+ width: '1px',+ });+ document.body.append(holder);++ return holder;+};++/**+ * Call from a layout-effect cleanup, while `frame` is still in the document.+ * Moves the frame aside, then, once the commit is done:+ * - its slot is gone (the view really unmounted): `teardown`, then removes it;+ * - its slot is still there (StrictMode re-ran the effect): moves it back and+ * calls `keep`.+ * Returns false, leaving the frame alone, where it can't be moved intact; the+ * caller then ends the session as before.+ */+export const retireAppFrame = (+ frame: HTMLIFrameElement,+ { keep, teardown }: { keep: () => void; teardown: () => Promise<void> },+): boolean => {+ const slot = frame.parentElement;+ if (!slot || !frame.isConnected || !canMove(slot)) return false;++ const aside = getHolder();+ if (!canMove(aside)) return false;+ aside.moveBefore(frame, null);++ queueMicrotask(() => {+ if (slot.isConnected) {+ slot.moveBefore(frame, null);+ keep();+ return;+ }+ void teardown().finally(() => frame.remove());+ });++ return true;+};diff --git a/src/features/MCPApp/sendAppMessage.test.ts b/src/features/MCPApp/sendAppMessage.test.tsnew file mode 100644index 00000000000..ecbb2913085--- /dev/null+++ b/src/features/MCPApp/sendAppMessage.test.ts@@ -0,0 +1,80 @@+import type { SendMessageParams } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { sendAppMessage } from './sendAppMessage';++describe('sendAppMessage', () => {+ it('does not acknowledge a send that finishes without accepting the message', async () => {+ // Gateway task creation can fail internally without rejecting the outer send.+ const send = vi.fn().mockResolvedValue(undefined);++ await expect(sendAppMessage(send, 'Follow up', 'weather')).resolves.toBe(false);+ });++ it('acknowledges acceptance without waiting for the agent run to finish', async () => {+ let params!: SendMessageParams;+ const send = vi.fn((value: SendMessageParams) => {+ params = value;+ return new Promise<void>(() => {});+ });+ const result = sendAppMessage(send, 'Follow up', 'weather');++ expect(params.message).toBe('Follow up');+ expect(params.metadata?.mcpAppSource).toEqual({ identifier: 'weather' });+ expect(params.onMessageAccepted).toBeTypeOf('function');+ params.onMessageAccepted?.();++ await expect(result).resolves.toBe(true);+ });++ it('sends as a separate turn that leaves the composer draft alone', async () => {+ const send = vi.fn().mockResolvedValue(undefined);++ await sendAppMessage(send, 'Follow up', 'weather');++ expect(send).toHaveBeenCalledWith(expect.objectContaining({ preserveComposer: true }));+ });++ it('lets the caller cancel the send until it is accepted', async () => {+ const send = vi.fn().mockResolvedValue(undefined);+ const view = new AbortController();++ await sendAppMessage(send, 'Follow up', 'weather', view.signal);++ expect(send).toHaveBeenCalledWith(expect.objectContaining({ signal: view.signal }));+ });++ it('does not acknowledge before the acceptance callback fires', async () => {+ let params!: SendMessageParams;+ const send = vi.fn((value: SendMessageParams) => {+ params = value;+ return new Promise<void>(() => {});+ });+ const settled = vi.fn();+ const result = sendAppMessage(send, 'Follow up', 'weather').then(settled);+ await Promise.resolve();+ expect(settled).not.toHaveBeenCalled();++ expect(params.onMessageAccepted).toBeTypeOf('function');+ params.onMessageAccepted?.();+ await result;+ expect(settled).toHaveBeenCalledWith(true);+ });++ it('reports a rejection before acceptance', async () => {+ const send = vi.fn().mockRejectedValue(new Error('Could not create task'));++ await expect(sendAppMessage(send, 'Follow up', 'weather')).rejects.toThrow(+ 'Could not create task',+ );+ });++ it('keeps an accepted message successful if the subsequent run fails', async () => {+ const send = vi.fn(async (params: SendMessageParams) => {+ params.onMessageAccepted?.();+ throw new Error('Agent run failed after storing the message');+ });++ await expect(sendAppMessage(send, 'Follow up', 'weather')).resolves.toBe(true);+ });+});diff --git a/src/features/MCPApp/sendAppMessage.ts b/src/features/MCPApp/sendAppMessage.tsnew file mode 100644index 00000000000..1cc4fe7c810--- /dev/null+++ b/src/features/MCPApp/sendAppMessage.ts@@ -0,0 +1,31 @@+import type { SendMessageParams } from '@lobechat/types';++import { toAppMessage } from './utils';++type SendMessage = (params: SendMessageParams) => Promise<void>;++/**+ * Post a view's message as its own turn. A completed send is not acceptance:+ * preflight or task creation can return without storing it.+ *+ * The composer is left alone: it may hold an unrelated draft, which a normal+ * send marks empty, and a failed send would refill it with the view's text.+ */+export const sendAppMessage = (+ sendMessage: SendMessage,+ text: string,+ identifier: string,+ /**+ * Cancels the send until the conversation accepts the message; once it has,+ * the run belongs to the conversation and is stopped from there.+ */+ signal?: AbortSignal,+): Promise<boolean> =>+ new Promise((resolve, reject) => {+ void sendMessage({+ ...toAppMessage(text, identifier),+ onMessageAccepted: () => resolve(true),+ preserveComposer: true,+ ...(signal && { signal }),+ }).then(() => resolve(false), reject);+ });diff --git a/src/features/MCPApp/toolCallPolicy.test.ts b/src/features/MCPApp/toolCallPolicy.test.tsnew file mode 100644index 00000000000..af54a25870c--- /dev/null+++ b/src/features/MCPApp/toolCallPolicy.test.ts@@ -0,0 +1,379 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getAppToolCallPolicy } from './toolCallPolicy';++const { agentTools, connectors, plugins, toolStore, userIntervention } = vi.hoisted(() => {+ // The agent's own connectors on the server, and which lists the server confirmed+ const agentTools = new Map<string, Map<string, unknown>>();+ const loaded = new Set<string>();++ return {+ agentTools,+ connectors: new Map<string, unknown>(),+ plugins: new Map<string, unknown>(),+ toolStore: {+ ensureConfirmedConnectors: vi.fn(async (agentId?: string) => {+ loaded.add('#base');+ if (agentId) loaded.add(agentId);+ }),+ isConnectorListConfirmed: (agentId?: string) =>+ loaded.has('#base') && (!agentId || loaded.has(agentId)),+ loaded,+ syncConnectorTools: vi.fn(async (_id: string) => {}),+ },+ userIntervention: { allowList: [] as string[], approvalMode: 'manual' },+ };+});++vi.mock('@/store/tool', () => ({ getToolStoreState: () => toolStore }));++vi.mock('@/store/tool/selectors', () => ({+ pluginSelectors: {+ getCustomPluginById: () => () => undefined,+ getInstalledPluginById: (id: string) => () => plugins.get(id),+ },+}));++vi.mock('@/store/tool/slices/connector', () => ({+ connectorSelectors: {+ connectorByIdentifierForAgent: (id: string, agentId?: string) => () =>+ (agentId && toolStore.loaded.has(agentId) ? agentTools.get(agentId)?.get(id) : undefined) ??+ connectors.get(id),+ },+}));++vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));++vi.mock('@/store/user/selectors', () => ({+ toolInterventionSelectors: {+ allowList: () => userIntervention.allowList,+ approvalMode: () => userIntervention.approvalMode,+ },+}));++const connector = (permission: string) => ({+ isEnabled: true,+ mcpServerUrl: 'https://mcp.example.com/mcp',+ tools: [{ permission, toolName: 'send' }],+});++const plugin = (humanIntervention?: unknown) => ({+ manifest: { api: [{ humanIntervention, name: 'send' }] },+});++describe('getAppToolCallPolicy', () => {+ beforeEach(() => {+ agentTools.clear();+ connectors.clear();+ plugins.clear();+ toolStore.loaded.clear();+ toolStore.ensureConfirmedConnectors.mockClear();+ toolStore.syncConnectorTools.mockClear();+ userIntervention.allowList = [];+ userIntervention.approvalMode = 'manual';+ });++ describe('manual mode follows the tool setting', () => {+ it('asks before running a connector tool that needs approval', async () => {+ connectors.set('mail', connector('needs_approval'));+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('confirm');+ });++ it('runs auto connector tools and refuses disabled or unknown ones', async () => {+ connectors.set('mail', { ...connector('auto'), id: 'conn_mail_unknown' });+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('allow');+ expect(await getAppToolCallPolicy('mail', 'delete')).toBe('deny');++ connectors.set('mail', connector('disabled'));+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('deny');+ });++ it('follows the plugin manifest humanIntervention', async () => {+ plugins.set('weather', plugin('required'));+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');++ plugins.set('weather', plugin('never'));+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('allow');++ plugins.set('weather', plugin());+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('allow');+ });++ it('runs an allow-listed tool without asking', async () => {+ connectors.set('mail', connector('needs_approval'));+ userIntervention.allowList = ['mail/send'];++ expect(await getAppToolCallPolicy('mail', 'send')).toBe('allow');+ });++ it('asks for an agent tool the client has not loaded, refuses anything else unknown', async () => {+ expect(await getAppToolCallPolicy('agent-app', 'send', { agentId: 'agt_1' })).toBe('confirm');+ expect(await getAppToolCallPolicy('agent-app', 'send')).toBe('deny');+ });+ });++ describe('MCP Apps tool visibility', () => {+ it('lets a view call a plugin tool kept from the model, under its own setting', async () => {+ plugins.set('weather', {+ manifest: {+ api: [{ name: 'forecast' }],+ mcpAppOnlyApi: [+ { humanIntervention: 'required', name: 'load_page' },+ { name: 'refresh' },+ ],+ },+ });++ expect(await getAppToolCallPolicy('weather', 'load_page')).toBe('confirm');+ expect(await getAppToolCallPolicy('weather', 'refresh')).toBe('allow');+ });++ it('asks about a plugin tool its stored manifest lacks, as one stored before MCP Apps would', async () => {+ plugins.set('weather', plugin());+ expect(await getAppToolCallPolicy('weather', 'load_page')).toBe('confirm');++ // Still refused once its connector disabled it+ connectors.set('weather', { tools: [{ permission: 'disabled', toolName: 'load_page' }] });+ expect(await getAppToolCallPolicy('weather', 'load_page')).toBe('deny');+ });++ it('refuses a view a plugin tool only the model may call', async () => {+ plugins.set('weather', {+ manifest: { api: [{ name: 'delete_all' }], mcpModelOnlyTools: ['delete_all'] },+ });++ expect(await getAppToolCallPolicy('weather', 'delete_all')).toBe('deny');+ });++ it("syncs a connector's tools again, once, for a tool its list synced before MCP Apps lacks", async () => {+ connectors.set('stdio-app', { ...connector('auto'), id: 'conn_stdio' });+ toolStore.syncConnectorTools.mockImplementationOnce(async () => {+ connectors.set('stdio-app', {+ ...connector('auto'),+ id: 'conn_stdio',+ tools: [+ { permission: 'auto', toolName: 'send' },+ { metadata: { visibility: ['app'] }, permission: 'auto', toolName: 'load_page' },+ ],+ });+ });++ expect(await getAppToolCallPolicy('stdio-app', 'load_page')).toBe('allow');+ expect(toolStore.syncConnectorTools).toHaveBeenCalledWith('conn_stdio');++ // A tool the server doesn't offer at all is refused, without syncing again+ expect(await getAppToolCallPolicy('stdio-app', 'missing')).toBe('deny');+ expect(toolStore.syncConnectorTools).toHaveBeenCalledTimes(1);+ });++ it('lets parallel view calls wait for the same resync instead of refusing the later ones', async () => {+ connectors.set('parallel-app', { ...connector('auto'), id: 'conn_parallel' });+ let finish!: () => void;+ toolStore.syncConnectorTools.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = () => {+ connectors.set('parallel-app', {+ ...connector('auto'),+ id: 'conn_parallel',+ tools: ['load_page', 'load_more'].map((toolName) => ({+ metadata: { visibility: ['app'] },+ permission: 'auto',+ toolName,+ })),+ });+ resolve();+ };+ }),+ );++ const first = getAppToolCallPolicy('parallel-app', 'load_page');+ const second = getAppToolCallPolicy('parallel-app', 'load_more');+ await vi.waitFor(() => expect(toolStore.syncConnectorTools).toHaveBeenCalledTimes(1));+ finish();++ expect(await first).toBe('allow');+ expect(await second).toBe('allow');+ expect(toolStore.syncConnectorTools).toHaveBeenCalledTimes(1);+ });++ it('tries a failed resync again on the next call', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ connectors.set('flaky-app', { ...connector('auto'), id: 'conn_flaky' });+ toolStore.syncConnectorTools.mockRejectedValueOnce(new Error('offline'));+ expect(await getAppToolCallPolicy('flaky-app', 'load_page')).toBe('deny');++ toolStore.syncConnectorTools.mockImplementationOnce(async () => {+ connectors.set('flaky-app', {+ ...connector('auto'),+ id: 'conn_flaky',+ tools: [{ metadata: { visibility: ['app'] }, permission: 'auto', toolName: 'load_page' }],+ });+ });+ expect(await getAppToolCallPolicy('flaky-app', 'load_page')).toBe('allow');+ expect(toolStore.syncConnectorTools).toHaveBeenCalledTimes(2);+ });++ it('refuses a view a connector tool only the model may call', async () => {+ connectors.set('mail', {+ ...connector('auto'),+ tools: [{ metadata: { visibility: ['model'] }, permission: 'auto', toolName: 'send' }],+ });++ expect(await getAppToolCallPolicy('mail', 'send')).toBe('deny');+ });++ it('lets a view call a connector tool kept from the model', async () => {+ connectors.set('mail', {+ ...connector('auto'),+ tools: [{ metadata: { visibility: ['app'] }, permission: 'auto', toolName: 'send' }],+ });++ expect(await getAppToolCallPolicy('mail', 'send')).toBe('allow');+ });+ });++ describe("a plugin's connector permissions", () => {+ // syncPluginTools keeps a marketplace plugin's permissions on a connector with no endpoint+ const permissionsOnly = (permission: string) => ({+ isEnabled: true,+ tools: [{ permission, toolName: 'send' }],+ });++ it('asks before a plugin tool its connector marks as needing approval', async () => {+ plugins.set('weather', plugin());+ connectors.set('weather', permissionsOnly('needs_approval'));++ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');+ });++ it('refuses a plugin tool its connector disabled', async () => {+ plugins.set('weather', plugin());+ connectors.set('weather', permissionsOnly('disabled'));++ expect(await getAppToolCallPolicy('weather', 'send')).toBe('deny');+ });++ it("asks about a plugin tool while the connector permissions aren't confirmed", async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ plugins.set('weather', plugin());+ toolStore.ensureConfirmedConnectors.mockRejectedValueOnce(new Error('offline'));++ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');+ });+ });++ describe('agent-owned connectors', () => {+ it("loads the agent's tools before judging, so its stricter copy decides", async () => {+ connectors.set('mail', connector('auto'));+ agentTools.set('agt_1', new Map([['mail', connector('needs_approval')]]));++ expect(await getAppToolCallPolicy('mail', 'send', { agentId: 'agt_1' })).toBe('confirm');+ expect(toolStore.ensureConfirmedConnectors).toHaveBeenCalledWith('agt_1', {+ revalidate: true,+ });+ });++ it('uses the base connector once the agent turns out to have no copy of it', async () => {+ connectors.set('mail', connector('auto'));++ expect(await getAppToolCallPolicy('mail', 'send', { agentId: 'agt_1' })).toBe('allow');+ });++ it("asks when the agent's tools can't be loaded rather than trust the base connector", async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ connectors.set('mail', connector('auto'));+ toolStore.ensureConfirmedConnectors.mockRejectedValueOnce(new Error('offline'));++ expect(await getAppToolCallPolicy('mail', 'send', { agentId: 'agt_1' })).toBe('confirm');+ });++ it('reloads the permissions for every call, asking when they changed since the view opened', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ connectors.set('mail', connector('auto'));+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('allow');++ // Tightened elsewhere (another tab, another workspace member)+ toolStore.ensureConfirmedConnectors.mockImplementationOnce(async () => {+ connectors.set('mail', connector('needs_approval'));+ });+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('confirm');++ // Confirmed earlier, but unreachable now: the earlier answer can't waive approval+ connectors.set('mail', connector('auto'));+ toolStore.ensureConfirmedConnectors.mockRejectedValueOnce(new Error('offline'));+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('confirm');+ expect(toolStore.ensureConfirmedConnectors).toHaveBeenCalledTimes(3);+ });++ it('asks while the only permissions it has were painted from storage', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ // The stored list says auto; the server, which can't be reached, may say otherwise+ connectors.set('mail', connector('auto'));+ toolStore.ensureConfirmedConnectors.mockRejectedValueOnce(new Error('offline'));++ expect(await getAppToolCallPolicy('mail', 'send')).toBe('confirm');+ });+ });++ describe('allow-list mode', () => {+ beforeEach(() => {+ userIntervention.approvalMode = 'allow-list';+ });++ it('asks before a tool that is not on the allow-list, even one set to run automatically', async () => {+ connectors.set('mail', connector('auto'));+ plugins.set('weather', plugin());++ expect(await getAppToolCallPolicy('mail', 'send')).toBe('confirm');+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');+ });++ it('runs a tool on the allow-list', async () => {+ connectors.set('mail', connector('needs_approval'));+ userIntervention.allowList = ['mail/send'];++ expect(await getAppToolCallPolicy('mail', 'send')).toBe('allow');+ });++ it('still refuses a tool the server does not offer', async () => {+ connectors.set('mail', connector('auto'));+ userIntervention.allowList = ['mail/delete'];++ expect(await getAppToolCallPolicy('mail', 'delete')).toBe('deny');+ });+ });++ describe('auto-run mode', () => {+ beforeEach(() => {+ userIntervention.approvalMode = 'auto-run';+ });++ it('runs tools that would ask in manual mode', async () => {+ connectors.set('mail', connector('needs_approval'));+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('allow');+ });++ it('still asks for a tool whose policy is always', async () => {+ plugins.set('weather', plugin('always'));+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');+ });+ });++ it('asks for arguments the security blacklist matches, in every mode', async () => {+ connectors.set('shell', {+ ...connector('auto'),+ tools: [{ permission: 'auto', toolName: 'run' }],+ });+ userIntervention.allowList = ['shell/run'];+ const toolArgs = { command: 'rm -rf ~/' };++ for (const mode of ['manual', 'allow-list', 'auto-run']) {+ userIntervention.approvalMode = mode;+ expect(await getAppToolCallPolicy('shell', 'run', { toolArgs })).toBe('confirm');+ }+ expect(await getAppToolCallPolicy('shell', 'run', { toolArgs: { command: 'ls' } })).toBe(+ 'allow',+ );+ });+});diff --git a/src/features/MCPApp/toolCallPolicy.ts b/src/features/MCPApp/toolCallPolicy.tsnew file mode 100644index 00000000000..d648ec150ae--- /dev/null+++ b/src/features/MCPApp/toolCallPolicy.ts@@ -0,0 +1,224 @@+import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '@lobechat/agent-runtime';+import { isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';+import type {+ HumanInterventionConfig,+ HumanInterventionPolicy,+ ToolManifest,+} from '@lobechat/types';++import { getToolStoreState } from '@/store/tool';+import { pluginSelectors } from '@/store/tool/selectors';+import { connectorSelectors } from '@/store/tool/slices/connector';+import { getUserStoreState } from '@/store/user';+import { toolInterventionSelectors } from '@/store/user/selectors';++/**+ * What LobeHub does with a `tools/call` a view sends. A view can call tools on+ * load without any user gesture, so a call the conversation would stop for+ * approval must ask here too, and a tool known not to be offered to views is+ * refused before it reaches the server.+ */+export type AppToolCallPolicy = 'allow' | 'confirm' | 'deny';++const matchesSecurityBlacklist = (policy: HumanInterventionPolicy, toolArgs: object) =>+ InterventionChecker.checkSecurityBlacklist(+ DEFAULT_SECURITY_BLACKLIST.filter((rule) => (rule.policy ?? 'always') === policy),+ toolArgs,+ ).blocked;++const isDynamicConfig = (config: unknown) =>+ !!config && typeof config === 'object' && !Array.isArray(config) && 'dynamic' in config;++/**+ * Whether a view's call runs at once or asks first: the same decision, in the+ * same order, as the conversation's approval gate+ * (`GeneralChatAgent.checkInterventionNeeded`), under the user's approval mode+ * and allow-list.+ */+export const resolveAppToolCallPolicy = ({+ allowList,+ approvalMode,+ intervention,+ toolArgs,+ toolKey,+}: {+ allowList: string[];+ approvalMode: string;+ /** The tool's own `humanIntervention`; undefined when it sets none. */+ intervention: unknown;+ toolArgs: Record<string, unknown>;+ /** `identifier/apiName`, the allow-list entry. */+ toolKey: string;+}): Exclude<AppToolCallPolicy, 'deny'> => {+ if (matchesSecurityBlacklist('always', toolArgs)) return 'confirm';++ // A dynamic policy needs a resolver the client doesn't have: MCP tools never+ // declare one, so treat it as asking unless the user waived approval.+ const policy = isDynamicConfig(intervention)+ ? 'required'+ : InterventionChecker.shouldIntervene({+ config: intervention as HumanInterventionConfig | undefined,+ // The security pass already ran above, split by policy like the runtime's audits+ securityBlacklist: [],+ toolArgs,+ });+ if (policy === 'always') return 'confirm';++ if (approvalMode === 'auto-run' || approvalMode === 'headless') return 'allow';+ if (matchesSecurityBlacklist('required', toolArgs)) return 'confirm';+ if (allowList.includes(toolKey)) return 'allow';+ if (approvalMode === 'allow-list') return 'confirm';++ return policy === 'never' ? 'allow' : 'confirm';+};++/**+ * What the conversation's lists say about a tool: its own approval setting,+ * null when the server doesn't offer it to views, or `missingFrom` when its+ * connector's synced tools lack it.+ */+type ToolLookup = { intervention?: unknown } | { missingFrom: string } | null;++/**+ * The tool's own approval setting as the conversation's manifest carries it,+ * or null when the server doesn't offer the tool.+ */+const findToolIntervention = (+ identifier: string,+ toolName: string,+ agentId: string | undefined,+ /** The lists were just loaded from the server; if not, nothing here can waive approval. */+ revalidated: boolean,+): ToolLookup => {+ const s = getToolStoreState();+ const confirmed = revalidated && s.isConnectorListConfirmed(agentId);++ const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ // Same routing as `mcpService.invokeMcpToolCall`+ if (+ connector?.isEnabled &&+ (!!connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')+ ) {+ // Until the server confirms the lists, this row may be the base connector+ // standing in for the agent's stricter copy, or a stale copy painted from+ // storage: neither can waive approval, so ask.+ if (!confirmed) return { intervention: 'required' };+ const tool = connector.tools.find((t) => t.toolName === toolName);+ // Synced before MCP Apps was on, the list may lack the tools the server+ // offers only to views+ if (!tool) return { missingFrom: connector.id };+ // A tool only the model may call is refused before anyone is asked about it+ if (tool.permission === 'disabled' || !isSyncedMcpToolVisibleTo(tool, 'app')) return null;+ // Same mapping as the connector manifest (`patchManifestWithPermissions`)+ return { intervention: tool.permission === 'needs_approval' ? 'required' : undefined };+ }++ const plugin =+ pluginSelectors.getInstalledPluginById(identifier)(s) ||+ pluginSelectors.getCustomPluginById(identifier)(s);+ // An agent's own connector the client hasn't loaded: its permission is+ // unknown here, so treat it as needing approval.+ if (!plugin) return agentId ? { intervention: 'required' } : null;++ const manifest = plugin.manifest as+ | (Pick<ToolManifest, 'mcpAppOnlyApi' | 'mcpModelOnlyTools'> & {+ api?: { humanIntervention?: unknown; name: string }[];+ humanIntervention?: unknown;+ })+ | undefined;+ // MCP Apps visibility: a tool only the model may call is refused to views, and+ // one kept from the model is still the view's to call+ if (manifest?.mcpModelOnlyTools?.includes(toolName)) return null;+ const api = [...(manifest?.api ?? []), ...(manifest?.mcpAppOnlyApi ?? [])].find(+ (item) => item.name === toolName,+ );++ // A plugin's tool permissions live on a connector of the same identifier+ // (syncPluginTools), applied as the conversation applies them+ // (patchManifestWithPermissions). Until the server confirms the lists they+ // may be stale or missing, so ask.+ if (!confirmed) return { intervention: 'required' };+ const permission = connector?.tools.find((t) => t.toolName === toolName)?.permission;+ if (permission === 'disabled') return null;+ if (permission === 'needs_approval') return { intervention: 'required' };++ // A manifest stored before MCP Apps was on lacks the tools its server offers+ // only to views. Ask rather than refuse: the session the call runs on still+ // refuses any tool the server doesn't offer to views.+ if (!api) return { intervention: 'required' };++ return { intervention: api.humanIntervention ?? manifest?.humanIntervention };+};++/**+ * Load the connector lists from the server before every call (the agent's own+ * tools too), so the policy and the call that follows resolve the connector+ * the server will run, under its current permissions: one may have changed+ * since the view opened. If they can't be loaded, the policy asks.+ */+const revalidateConnectors = async (agentId: string | undefined): Promise<boolean> => {+ try {+ await getToolStoreState().ensureConfirmedConnectors(agentId, { revalidate: true });+ return true;+ } catch (error) {+ console.warn('[MCPApp] failed to load the connectors for a view tool call:', error);+ return false;+ }+};++// The resync a view's call started for each connector on this page: pending, or done+const connectorResyncs = new Map<string, Promise<boolean>>();++/**+ * Sync a connector's tools again, once per page, so a list synced before MCP+ * Apps was on picks up the tools its server offers only to views (stdio ones+ * too, which only this desktop can list). Calls made meanwhile wait for the+ * same sync; one that failed is tried again by the next call. Whether it+ * succeeded.+ */+const resyncConnectorTools = (connectorId: string): Promise<boolean> => {+ let resync = connectorResyncs.get(connectorId);+ if (!resync) {+ resync = getToolStoreState()+ .syncConnectorTools(connectorId)+ .then(+ () => true,+ (error) => {+ console.warn(+ '[MCPApp] failed to sync the tools of a connector for a view tool call:',+ error,+ );+ // A failed sync may succeed later: the next call tries again+ connectorResyncs.delete(connectorId);+ return false;+ },+ );+ connectorResyncs.set(connectorId, resync);+ }+ return resync;+};++export const getAppToolCallPolicy = async (+ identifier: string,+ toolName: string,+ { agentId, toolArgs = {} }: { agentId?: string; toolArgs?: Record<string, unknown> } = {},+): Promise<AppToolCallPolicy> => {+ const revalidated = await revalidateConnectors(agentId);+ let tool = findToolIntervention(identifier, toolName, agentId, revalidated);+ if (tool && 'missingFrom' in tool) {+ tool = (await resyncConnectorTools(tool.missingFrom))+ ? findToolIntervention(identifier, toolName, agentId, revalidated)+ : null;+ }+ if (!tool || 'missingFrom' in tool) return 'deny';++ const userState = getUserStoreState();++ return resolveAppToolCallPolicy({+ allowList: toolInterventionSelectors.allowList(userState),+ approvalMode: toolInterventionSelectors.approvalMode(userState),+ intervention: tool.intervention,+ toolArgs,+ toolKey: `${identifier}/${toolName}`,+ });+};diff --git a/src/features/MCPApp/utils.test.ts b/src/features/MCPApp/utils.test.tsnew file mode 100644index 00000000000..2419d9ce271--- /dev/null+++ b/src/features/MCPApp/utils.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest';++import { buildAppCsp, injectCsp, pickAppResource, toAppMessage, toCallToolResult } from './utils';++describe('pickAppResource', () => {+ it('picks the matching text entry with its ui meta', () => {+ const resource = pickAppResource(+ {+ contents: [+ { text: 'other', uri: 'ui://other' },+ { _meta: { ui: { prefersBorder: false } }, text: '<p>hi</p>', uri: 'ui://app' },+ ],+ },+ 'ui://app',+ );++ expect(resource).toEqual({ html: '<p>hi</p>', meta: { prefersBorder: false } });+ });++ it('decodes base64 blobs as UTF-8', () => {+ const blob = btoa(String.fromCharCode(...new TextEncoder().encode('<p>你好</p>')));++ expect(pickAppResource({ contents: [{ blob, uri: 'ui://app' }] }, 'ui://app')?.html).toBe(+ '<p>你好</p>',+ );+ });++ it('returns undefined for empty results', () => {+ expect(pickAppResource(undefined, 'ui://app')).toBeUndefined();+ expect(pickAppResource({ contents: [] }, 'ui://app')).toBeUndefined();+ });+});++describe('buildAppCsp', () => {+ it('blocks the network by default', () => {+ const csp = buildAppCsp(undefined);++ expect(csp).toContain(`default-src 'none'`);+ expect(csp).toContain(`connect-src 'none'`);+ expect(csp).toContain(`frame-src 'none'`);+ });++ it('allows declared domains and drops ones that could break out of the policy', () => {+ const csp = buildAppCsp({+ connectDomains: ['https://api.example.com', "https://x.com; script-src 'unsafe-eval'"],+ resourceDomains: ['https://*.cdn.example.com'],+ });++ expect(csp).toContain('connect-src https://api.example.com');+ expect(csp).toContain(`script-src 'unsafe-inline' https://*.cdn.example.com`);+ expect(csp).not.toContain('unsafe-eval');+ });+});++describe('injectCsp', () => {+ const policy = `<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'">`;++ it('puts the policy ahead of the whole document, which stays as written', () => {+ const app = '<!doctype html><html lang="en"><head><script>1</script></head></html>';++ expect(injectCsp(app, "default-src 'none'")).toBe(policy + app);+ });++ it('is not fooled by a <head> inside a comment', () => {+ const app = '<!-- <head> --><script>fetch("https://x")</script><head></head>';++ expect(injectCsp(app, "default-src 'none'")).toBe(policy + app);+ });++ it('covers a script placed before the real <head>', () => {+ const app = '<script>fetch("https://x")</script><html><head></head></html>';++ expect(injectCsp(app, "default-src 'none'")).toBe(policy + app);+ });++ it('escapes the policy into its attribute', () => {+ expect(injectCsp('<div></div>', `a"&`)).toBe(+ '<!doctype html><meta http-equiv="Content-Security-Policy" content="a"&"><div></div>',+ );+ });+});++describe('toAppMessage', () => {+ it('tags the posted message with the view it came from', () => {+ expect(toAppMessage('What should I wear in Paris?', 'weather-demo')).toEqual({+ message: 'What should I wear in Paris?',+ metadata: { mcpAppSource: { identifier: 'weather-demo' } },+ });+ });+});++describe('toCallToolResult', () => {+ it('returns the raw MCP result without the LobeHub mcpApp marker', () => {+ const result = toCallToolResult({+ content: 'sunny',+ state: {+ content: [{ text: 'sunny', type: 'text' }],+ mcpApp: { resourceUri: 'ui://app' },+ structuredContent: { temp: 20 },+ } as any,+ success: true,+ });++ expect(result).toEqual({+ content: [{ text: 'sunny', type: 'text' }],+ structuredContent: { temp: 20 },+ });+ });++ it('wraps plain text results and missing results', () => {+ expect(toCallToolResult({ content: 'ok', state: undefined as any, success: true })).toEqual({+ content: [{ text: 'ok', type: 'text' }],+ isError: false,+ });+ expect(toCallToolResult(undefined).isError).toBe(true);+ });+});diff --git a/src/features/MCPApp/utils.ts b/src/features/MCPApp/utils.tsnew file mode 100644index 00000000000..67d2449a084--- /dev/null+++ b/src/features/MCPApp/utils.ts@@ -0,0 +1,131 @@+import type { MessageMetadata } from '@lobechat/types';+import type { CallToolResult, ReadResourceResult } from '@modelcontextprotocol/client';+import type {+ McpUiResourceCsp,+ McpUiResourceMeta,+} from '@modelcontextprotocol/ext-apps/app-bridge';++import type { MCPToolCallResult } from '@/libs/mcp/types';++export interface McpAppResource {+ html: string;+ meta?: McpUiResourceMeta;+}++const decodeBase64 = (value: string) => {+ const bytes = Uint8Array.from(atob(value), (char) => char.charCodeAt(0));+ return new TextDecoder().decode(bytes);+};++/**+ * Pick the HTML document out of a `resources/read` result. Prefers the entry+ * matching `uri`; accepts text or base64 blob contents.+ */+export const pickAppResource = (+ result: ReadResourceResult | undefined,+ uri: string,+): McpAppResource | undefined => {+ const contents = result?.contents ?? [];+ const content = contents.find((item) => item.uri === uri) ?? contents[0];+ if (!content) return;++ let html: string | undefined;+ if ('text' in content && typeof content.text === 'string') html = content.text;+ else if ('blob' in content && typeof content.blob === 'string') html = decodeBase64(content.blob);+ if (!html) return;++ const meta = (content._meta as { ui?: McpUiResourceMeta } | undefined)?.ui;++ return { html, meta };+};++/** Only http(s) origins without CSP-breaking characters make it into the policy. */+const sanitizeSources = (sources: string[] | undefined) =>+ (sources ?? []).filter((source) => /^(?:https?|wss?):\/\/[\w*.:-]+(?:\/[\w./-]*)?$/.test(source));++/**+ * CSP for the view document, built from the domains the resource declares.+ * Undeclared means no network access, per the MCP Apps spec.+ */+export const buildAppCsp = (csp: McpUiResourceCsp | undefined): string => {+ const resources = sanitizeSources(csp?.resourceDomains).join(' ');+ const connect = sanitizeSources(csp?.connectDomains).join(' ');+ const frames = sanitizeSources(csp?.frameDomains).join(' ');+ const inline = `'unsafe-inline'`;++ return [+ `default-src 'none'`,+ `script-src ${inline} ${resources}`.trim(),+ `style-src ${inline} ${resources}`.trim(),+ `img-src data: blob: ${resources}`.trim(),+ `font-src data: ${resources}`.trim(),+ `media-src data: blob: ${resources}`.trim(),+ `connect-src ${connect || `'none'`}`,+ `frame-src ${frames || `'none'`}`,+ `base-uri 'none'`,+ `form-action 'none'`,+ ].join('; ');+};++/**+ * The view iframe's `allow` policy: these features stay off whatever the+ * resource's `_meta.ui.permissions` declares. Nothing asks the user before a+ * view would use them (desktop grants any request in the main window, and on+ * the web a grant to LobeHub covers every later view), so a server's+ * declaration alone must not reach the camera, microphone, location or+ * clipboard.+ */+export const APP_IFRAME_ALLOW = [+ `camera 'none'`,+ `microphone 'none'`,+ `geolocation 'none'`,+ `clipboard-write 'none'`,+].join('; ');++const escapeAttribute = (value: string) => value.replaceAll('&', '&').replaceAll('"', '"');++/**+ * Put the CSP `<meta>` ahead of every byte the app controls; a policy declared+ * after a script would not apply to that script. Searching the app's markup for+ * its `<head>` is not safe: a `<head>` inside a comment, or a script before the+ * real head, would run unrestricted.+ *+ * The parser places the leading `<meta>` in the implied `<head>`, where the+ * policy applies, and merges the app's own `<html>`/`<head>` into those+ * elements. Its doctype would then be ignored, so ours keeps standards mode.+ */+export const injectCsp = (html: string, csp: string): string =>+ `<!doctype html><meta http-equiv="Content-Security-Policy" content="${escapeAttribute(csp)}">${html}`;++/**+ * The message a view posts (`ui/message`), tagged with the view so its bubble+ * reads as a follow-up from that view rather than something the user typed.+ */+export const toAppMessage = (+ text: string,+ identifier: string,+): { message: string; metadata: Pick<MessageMetadata, 'mcpAppSource'> } => ({+ message: text,+ metadata: { mcpAppSource: { identifier } },+});++/** Map LobeHub's tool call envelope back to the MCP `CallToolResult` a view expects. */+export const toCallToolResult = (+ result:+ | (Pick<MCPToolCallResult, 'content' | 'success'> & { state?: MCPToolCallResult['state'] })+ | undefined,+): CallToolResult => {+ const state = result?.state as (CallToolResult & { mcpApp?: unknown }) | undefined;++ if (!state || !Array.isArray(state.content)) {+ return {+ content: [{ text: result?.content ?? '', type: 'text' }],+ isError: result ? !result.success : true,+ };+ }++ const { mcpApp: _mcpApp, ...rest } = state;+ void _mcpApp;++ return rest;+};diff --git a/src/features/MCPApp/viewAgent.test.ts b/src/features/MCPApp/viewAgent.test.tsnew file mode 100644index 00000000000..071a6e0b25c--- /dev/null+++ b/src/features/MCPApp/viewAgent.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import type { State } from '@/features/Conversation/store/initialState';++import { mcpAppAgentIdSelector } from './viewAgent';++const groupState = (dbMessages: unknown[]) =>+ // A group conversation's context carries the supervisor+ ({ context: { agentId: 'supervisor' }, dbMessages }) as unknown as State;++describe('mcpAppAgentIdSelector', () => {+ it('acts as the member whose message carries the result, not the group supervisor', () => {+ const s = groupState([{ agentId: 'member', id: 'tool-msg', role: 'tool' }]);++ expect(mcpAppAgentIdSelector('tool-msg')(s)).toBe('member');+ });++ it('finds the member whose turn holds the result inside compressed history', () => {+ const s = groupState([+ {+ compressedMessages: [+ { id: 'state-row', role: 'tool' },+ {+ agentId: 'member',+ children: [{ id: 'block', tools: [{ id: 'call', result_msg_id: 'tool-msg' }] }],+ id: 'assistant',+ role: 'assistantGroup',+ },+ ],+ id: 'compressed',+ role: 'compressedGroup',+ },+ ]);++ expect(mcpAppAgentIdSelector('tool-msg')(s)).toBe('member');+ });++ it("falls back to the conversation's agent when the message names none", () => {+ expect(mcpAppAgentIdSelector('tool-msg')(groupState([{ id: 'tool-msg', role: 'tool' }]))).toBe(+ 'supervisor',+ );+ expect(mcpAppAgentIdSelector(undefined)(groupState([]))).toBe('supervisor');+ });+});diff --git a/src/features/MCPApp/viewAgent.ts b/src/features/MCPApp/viewAgent.tsnew file mode 100644index 00000000000..914f9cc83f4--- /dev/null+++ b/src/features/MCPApp/viewAgent.ts@@ -0,0 +1,43 @@+import type { State as ConversationState } from '@/features/Conversation/store/initialState';++interface MessageNode {+ agentId?: string | null;+ children?: MessageNode[];+ compressedMessages?: MessageNode[];+ id: string;+ tools?: { result?: { id?: string } | null; result_msg_id?: string }[] | null;+}++const holdsResult = (node: MessageNode, messageId: string) =>+ node.id === messageId ||+ !!node.tools?.some((tool) => tool.result_msg_id === messageId || tool.result?.id === messageId);++/**+ * The message that carries a tool result: its own row, or, once the turn is+ * compressed, the parsed assistant group inside the compressed history whose+ * tool calls hold it (one agent's run each).+ */+const findProducer = (nodes: MessageNode[], messageId: string): MessageNode | undefined => {+ for (const node of nodes) {+ if (holdsResult(node, messageId)) return node;+ if (node.children?.some((child) => holdsResult(child, messageId))) return node;+ const nested = node.compressedMessages && findProducer(node.compressedMessages, messageId);+ if (nested) return nested;+ }+ return undefined;+};++/**+ * The agent a tool result's view acts as: the one whose message carries the+ * result. In a group conversation that is the member who ran the tool, not the+ * conversation's own agent (the supervisor), so its connectors, approval rules+ * and calls resolve as that member's runs do.+ */+export const mcpAppAgentIdSelector =+ (messageId: string | undefined) =>+ (s: ConversationState): string | undefined =>+ (messageId+ ? findProducer(s.dbMessages as unknown as MessageNode[], messageId)?.agentId+ : undefined) ||+ s.context.agentId ||+ undefined;diff --git a/src/features/MCPApp/viewToolResult.test.ts b/src/features/MCPApp/viewToolResult.test.tsnew file mode 100644index 00000000000..1a5983592e1--- /dev/null+++ b/src/features/MCPApp/viewToolResult.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { withoutStoredMedia } from './viewToolResult';++const text = { text: 'sunny', type: 'text' as const };++describe('withoutStoredMedia', () => {+ it('leaves out media the chat stored as a reference, without reading it', () => {+ const result = withoutStoredMedia({+ content: [+ text,+ { data: 'https://files.example.com/a.png', mimeType: 'image/png', type: 'image' },+ { data: 'desktop://mcp/audio/2026/a.mp3', mimeType: 'audio/mpeg', type: 'audio' },+ // A server's own reference to an authenticated endpoint is never followed+ { data: '/trpc/lambda/user.getUserState', mimeType: 'image/png', type: 'image' },+ ],+ });++ expect(result.content).toEqual([text]);+ });++ it('keeps media that is base64, as MCP defines it', () => {+ const image = { data: 'aGk=', mimeType: 'image/png', type: 'image' as const };++ expect(withoutStoredMedia({ content: [text, image] }).content).toEqual([text, image]);+ });+});diff --git a/src/features/MCPApp/viewToolResult.ts b/src/features/MCPApp/viewToolResult.tsnew file mode 100644index 00000000000..eaebc6ba124--- /dev/null+++ b/src/features/MCPApp/viewToolResult.ts@@ -0,0 +1,20 @@+import type { CallToolResult } from '@modelcontextprotocol/client';++// MCP image and audio `data` is base64; anything else is a reference, not media+const BASE64 = /^[\d+/a-z]+={0,2}$/i;++/**+ * The tool result as the view gets it. The chat stores a result's image and+ * audio as uploaded URLs or desktop files, which are not the base64 `data` MCP+ * defines, so those blocks are left out rather than handed over broken. They+ * are never dereferenced: a reference in a result may come from the MCP server+ * itself and point anywhere, and the host would read it with the user's+ * cookies or file access. A view that needs the media calls the tool, which+ * returns it raw.+ */+export const withoutStoredMedia = (result: CallToolResult): CallToolResult => ({+ ...result,+ content: result.content.filter(+ (block) => (block.type !== 'image' && block.type !== 'audio') || BASE64.test(block.data),+ ),+});diff --git a/src/libs/mcp/client.auth.test.ts b/src/libs/mcp/client.auth.test.tsindex 3655250bde7..415373d39e6 100644--- a/src/libs/mcp/client.auth.test.ts+++ b/src/libs/mcp/client.auth.test.ts@@ -8,6 +8,7 @@ vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({...(await importOriginal<object>()),Client: class {connect = connect;+ setNotificationHandler = vi.fn();},}));diff --git a/src/libs/mcp/client.mcpApp.test.ts b/src/libs/mcp/client.mcpApp.test.tsnew file mode 100644index 00000000000..a0d512e19c3--- /dev/null+++ b/src/libs/mcp/client.mcpApp.test.ts@@ -0,0 +1,205 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { MCPClient } from './client';+import { MCP_APPS_CLIENT_CAPABILITIES } from './mcpApp';++const { clientOptions, listTools, notificationHandlers } = vi.hoisted(() => ({+ clientOptions: [] as unknown[],+ listTools: vi.fn(),+ // The handlers each client registered, by notification method+ notificationHandlers: new Map<string, () => void>(),+}));++vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ Client: class {+ getProtocolEra = () => 'legacy';+ listTools = listTools;+ setNotificationHandler = (method: string, handler: () => void) =>+ notificationHandlers.set(method, handler);+ constructor(_info: unknown, options?: unknown) {+ clientOptions.push(options);+ }+ },+}));++const params = { name: 'weather', type: 'http' as const, url: 'https://mcp.example.com/mcp' };++beforeEach(() => {+ clientOptions.length = 0;+ listTools.mockReset();+});++afterEach(() => {+ vi.useRealTimers();+});++describe('MCPClient MCP Apps capability', () => {+ it('announces the MCP Apps extension only when asked to', () => {+ new MCPClient(params);+ new MCPClient(params, { mcpApps: false });+ new MCPClient(params, { mcpApps: true });++ expect(+ clientOptions.map((options) => (options as { capabilities?: unknown }).capabilities),+ ).toEqual([undefined, undefined, MCP_APPS_CLIENT_CAPABILITIES]);+ });+});++describe('MCPClient.getToolUiResourceUri', () => {+ it('lists tools once and reads the view from the cached map', async () => {+ listTools.mockResolvedValue({+ tools: [+ { _meta: { ui: { resourceUri: 'ui://weather/view' } }, name: 'forecast' },+ { name: 'search' },+ ],+ });+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.getToolUiResourceUri('forecast')).resolves.toBe('ui://weather/view');+ await expect(client.getToolUiResourceUri('search')).resolves.toBeUndefined();+ expect(listTools).toHaveBeenCalledTimes(1);+ });++ it('does not list tools again on every call after a failed listing', async () => {+ listTools.mockRejectedValue(new Error('upstream 500'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.getToolUiResourceUri('forecast')).resolves.toBeUndefined();+ await expect(client.getToolUiResourceUri('forecast')).resolves.toBeUndefined();+ await expect(client.getToolUiResourceUri('forecast')).resolves.toBeUndefined();++ expect(listTools).toHaveBeenCalledTimes(1);+ consoleError.mockRestore();+ });++ it('lists tools again once the retry window after a failed listing has passed', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ listTools.mockRejectedValueOnce(new Error('upstream 500'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.getToolUiResourceUri('forecast')).resolves.toBeUndefined();++ // The transient failure is over, but nothing else on this client lists tools+ listTools.mockResolvedValue({+ tools: [{ _meta: { ui: { resourceUri: 'ui://weather/view' } }, name: 'forecast' }],+ });+ vi.setSystemTime(new Date('2026-01-01T00:00:30Z'));+ await expect(client.getToolUiResourceUri('forecast')).resolves.toBeUndefined();+ expect(listTools).toHaveBeenCalledTimes(1);++ vi.setSystemTime(new Date('2026-01-01T00:01:00Z'));+ await expect(client.getToolUiResourceUri('forecast')).resolves.toBe('ui://weather/view');+ expect(listTools).toHaveBeenCalledTimes(2);++ // Once a listing succeeded, it is not retried even after the window+ vi.setSystemTime(new Date('2026-01-01T01:00:00Z'));+ await expect(client.getToolUiResourceUri('forecast')).resolves.toBe('ui://weather/view');+ expect(listTools).toHaveBeenCalledTimes(2);+ consoleError.mockRestore();+ });++ it('picks views up again once a later listing succeeds', async () => {+ listTools.mockRejectedValueOnce(new Error('upstream 500'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const client = new MCPClient(params, { mcpApps: true });+ await client.getToolUiResourceUri('forecast');++ // e.g. a manifest refresh on the same session+ listTools.mockResolvedValue({+ tools: [{ _meta: { ui: { resourceUri: 'ui://weather/view' } }, name: 'forecast' }],+ });+ await client.listTools();++ await expect(client.getToolUiResourceUri('forecast')).resolves.toBe('ui://weather/view');+ consoleError.mockRestore();+ });+});++describe('MCPClient.isToolCallableByApp', () => {+ it('refuses tools whose visibility leaves out the app, and allows the default', async () => {+ listTools.mockResolvedValue({+ tools: [+ { _meta: { ui: { visibility: ['model'] } }, name: 'delete_all' },+ { _meta: { ui: { visibility: ['app'] } }, name: 'refresh' },+ { _meta: { ui: { visibility: ['model', 'app'] } }, name: 'forecast' },+ { name: 'search' },+ ],+ });+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolCallableByApp('delete_all')).resolves.toBe(false);+ await expect(client.isToolCallableByApp('refresh')).resolves.toBe(true);+ await expect(client.isToolCallableByApp('forecast')).resolves.toBe(true);+ await expect(client.isToolCallableByApp('search')).resolves.toBe(true);+ expect(listTools).toHaveBeenCalledTimes(1);+ });++ it('refuses while the tools can not be listed', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ listTools.mockRejectedValue(new Error('offline'));+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolCallableByApp('search')).resolves.toBe(false);+ });+});++describe('MCPClient.isToolHiddenFromModel', () => {+ it('names the tools only views may call, from the same listing', async () => {+ listTools.mockResolvedValue({+ tools: [+ { _meta: { ui: { visibility: ['app'] } }, name: 'load_page' },+ { _meta: { ui: { visibility: ['model', 'app'] } }, name: 'forecast' },+ { name: 'search' },+ ],+ });+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolHiddenFromModel('load_page')).resolves.toBe(true);+ await expect(client.isToolHiddenFromModel('forecast')).resolves.toBe(false);+ await expect(client.isToolHiddenFromModel('search')).resolves.toBe(false);+ expect(listTools).toHaveBeenCalledTimes(1);+ });++ it("lets the model's calls run while the tools can not be listed", async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ listTools.mockRejectedValue(new Error('offline'));+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolHiddenFromModel('load_page')).resolves.toBe(false);+ });+});++describe('web MCPClient after the server changes its tools', () => {+ it('lists them again for visibility and views once it says they changed', async () => {+ listTools.mockResolvedValueOnce({+ tools: [{ _meta: { ui: { resourceUri: 'ui://old', visibility: ['app'] } }, name: 'page' }],+ });+ const client = new MCPClient(params, { mcpApps: true });+ await expect(client.isToolCallableByApp('page')).resolves.toBe(true);++ // The server takes the tool from views and moves its view+ listTools.mockResolvedValueOnce({+ tools: [{ _meta: { ui: { resourceUri: 'ui://new', visibility: ['model'] } }, name: 'page' }],+ });+ notificationHandlers.get('notifications/tools/list_changed')?.();++ await expect(client.isToolCallableByApp('page')).resolves.toBe(false);+ await expect(client.getToolUiResourceUri('page')).resolves.toBe('ui://new');+ await expect(client.isToolHiddenFromModel('page')).resolves.toBe(false);+ expect(listTools).toHaveBeenCalledTimes(2);+ });+});++describe('web MCPClient.isToolCallableByApp for names the listing did not name', () => {+ it('refuses them: only tools the server offered to views run', async () => {+ listTools.mockResolvedValueOnce({ tools: [{ name: 'search' }] });+ const client = new MCPClient(params, { mcpApps: true });++ await expect(client.isToolCallableByApp('search')).resolves.toBe(true);+ await expect(client.isToolCallableByApp('not_listed')).resolves.toBe(false);+ });+});diff --git a/src/libs/mcp/client.sdkErrors.test.ts b/src/libs/mcp/client.sdkErrors.test.tsindex 13d9516710a..1ddc18ff7e1 100644--- a/src/libs/mcp/client.sdkErrors.test.ts+++ b/src/libs/mcp/client.sdkErrors.test.ts@@ -44,6 +44,18 @@ describe('MCP SDK v2 error handling', () => {await expect(httpClient().callTool('test', {})).rejects.toMatchObject({ status: 404 });});+ it('reports a legacy HTTP 404 on a resource read as a stale session', async () => {+ vi.spyOn(Client.prototype, 'getProtocolEra').mockReturnValue('legacy');+ vi.spyOn(Client.prototype, 'readResource').mockRejectedValue(httpError(404));+ await expect(httpClient().readResource('ui://app')).rejects.toThrow('NoValidSessionId');+ });++ it('passes a modern HTTP 404 on a resource read through unchanged', async () => {+ vi.spyOn(Client.prototype, 'getProtocolEra').mockReturnValue('modern');+ vi.spyOn(Client.prototype, 'readResource').mockRejectedValue(httpError(404));+ await expect(httpClient().readResource('ui://app')).rejects.toMatchObject({ status: 404 });+ });+it('returns a completed tool failure for unsupported input_required', async () => {vi.spyOn(Client.prototype, 'callTool').mockRejectedValue(new SdkError(SdkErrorCode.UnsupportedResultType, 'input_required', {diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.tsindex 37f4036dbbe..dc6cb9230cc 100644--- a/src/libs/mcp/client.ts+++ b/src/libs/mcp/client.ts@@ -1,6 +1,7 @@import { spawn } from 'node:child_process';import { BRANDING_NAME } from '@lobechat/business-const';+import { getMcpToolVisibility, isMcpToolVisibleTo } from '@lobechat/const/mcpApp';import { toRecord } from '@lobechat/utils/object';import {Client,@@ -15,6 +16,7 @@ import { type Progress, type Transport } from '@modelcontextprotocol/client';import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';import debug from 'debug';+import { getToolUiResourceUri, isToolVisibleToApp, MCP_APPS_CLIENT_CAPABILITIES } from './mcpApp';import {type MCPClientParams,type MCPError,@@ -33,6 +35,8 @@ const MCP_TOOL_TIMEOUT = (() => {const val = Number(process.env.MCP_TOOL_TIMEOUT);return Number.isFinite(val) && val > 0 ? val : 60_000;})();+// How long a failed tool listing counts as "no views" before the next result lists again+const UI_RESOURCE_LIST_RETRY_MS = 60_000;/*** Pre-check stdio command to capture detailed error information@@ -166,16 +170,37 @@ async function preCheckStdioCommand(params: {});}+export interface MCPClientOptions {+ /**+ * Advertise MCP Apps (SEP-1865) during `initialize`, so servers expose their+ * interactive views. Off: the client announces itself as it did before MCP+ * Apps, and servers answer as they would any other client.+ */+ mcpApps?: boolean;+}+export class MCPClient {private mcp: Client;private transport: Transport;private params: MCPClientParams;+ /** tool name → `ui://` resource URI, filled from the last successful `listTools` */+ private uiResourceUris?: Map<string, string>;+ /**+ * The tools a view may call (`_meta.ui.visibility` with "app", or unset), from+ * the same listing. An allow-list: a name the listing didn't name is refused.+ */+ private appVisibleTools?: Set<string>;+ /** Tools only views may call (`_meta.ui.visibility` without "model"), from the same listing */+ private modelHiddenTools?: Set<string>;+ /** When the last `getToolUiResourceUri` listing failed, while no listing has succeeded */+ private uiResourceListFailedAt?: number;- constructor(params: MCPClientParams) {+ constructor(params: MCPClientParams, { mcpApps = false }: MCPClientOptions = {}) {this.params = params;this.mcp = new Client({ name: 'lobehub-mcp-client', version: '1.0.0' },{+ ...(mcpApps ? { capabilities: MCP_APPS_CLIENT_CAPABILITIES } : {}),// Stdio stays legacy: auto would spawn a sibling probe process and can// wait the entire probe timeout on servers that ignore unknown requests.versionNegotiation: { mode: params.type === 'http' ? 'auto' : 'legacy' },@@ -183,6 +208,11 @@ export class MCPClient {inputRequired: { autoFulfill: false },},);+ // A server whose tools changed (a view's visibility, its `ui://` resource)+ // voids what its last listing taught; the next lookup lists them again+ this.mcp.setNotificationHandler('notifications/tools/list_changed', () =>+ this.forgetToolListing(),+ );switch (params.type) {case 'http': {@@ -371,6 +401,20 @@ export class MCPClient {try {log('Listing tools...');const { tools } = await this.mcp.listTools();+ this.uiResourceUris = new Map(+ tools.flatMap((tool) => {+ const uri = getToolUiResourceUri(tool);+ return uri ? [[tool.name, uri] as const] : [];+ }),+ );+ this.appVisibleTools = new Set(+ tools.filter((tool) => isToolVisibleToApp(tool)).map((tool) => tool.name),+ );+ this.modelHiddenTools = new Set(+ tools+ .filter((tool) => !isMcpToolVisibleTo(getMcpToolVisibility(tool._meta), 'model'))+ .map((tool) => tool.name),+ );log('Listed %d MCP tool(s)', tools.length);return tools as McpTool[];} catch (e) {@@ -444,6 +488,72 @@ export class MCPClient {return manifest;}+ /**+ * The MCP Apps `ui://` resource a tool renders its result with, if any.+ * Lists tools once per client to learn it. A failed listing counts as "no+ * views" for `UI_RESOURCE_LIST_RETRY_MS` instead of being retried on every+ * call, then the next call lists again. On the server nothing else refreshes+ * the map: manifests are listed on a separate client without MCP Apps.+ */+ async getToolUiResourceUri(toolName: string): Promise<string | undefined> {+ await this.ensureToolUiListed();++ return this.uiResourceUris?.get(toolName);+ }++ /**+ * Whether a view may call `toolName`: the listing named it, with a+ * `_meta.ui.visibility` that includes "app" or is unset. Unknown while the+ * tools can't be listed, which counts as no: a view's call is refused rather+ * than run unchecked.+ */+ async isToolCallableByApp(toolName: string): Promise<boolean> {+ await this.ensureToolUiListed();+ return !!this.appVisibleTools?.has(toolName);+ }++ /**+ * Whether the server keeps `toolName` from the model (`_meta.ui.visibility`+ * without "model"): only its views may call it. Unknown while the tools+ * can't be listed, which counts as no, so the model's calls keep running.+ */+ async isToolHiddenFromModel(toolName: string): Promise<boolean> {+ await this.ensureToolUiListed();++ return !!this.modelHiddenTools?.has(toolName);+ }++ private forgetToolListing() {+ this.uiResourceUris = undefined;+ this.appVisibleTools = undefined;+ this.modelHiddenTools = undefined;+ this.uiResourceListFailedAt = undefined;+ }++ /** List tools once per client for their MCP Apps metadata; see {@link getToolUiResourceUri}. */+ private async ensureToolUiListed() {+ const failedAt = this.uiResourceListFailedAt;+ if (+ !this.uiResourceUris &&+ (failedAt === undefined || Date.now() - failedAt >= UI_RESOURCE_LIST_RETRY_MS)+ ) {+ await this.listTools();+ this.uiResourceListFailedAt = this.uiResourceUris ? undefined : Date.now();+ }+ }++ async readResource(uri: string) {+ log('Reading resource: %s', uri);+ try {+ return await this.mcp.readResource({ uri });+ } catch (e) {+ if (this.isNoValidSessionError(e)) {+ throw new Error('NoValidSessionId', { cause: e });+ }+ throw e;+ }+ }+async callTool(toolName: string, args: any): Promise<ToolCallResult> {log('Calling MCP tool: %O', { timeout: MCP_TOOL_TIMEOUT, toolName });try {diff --git a/src/libs/mcp/index.ts b/src/libs/mcp/index.tsindex 4a38ad3a95d..fb3a0bbc66f 100644--- a/src/libs/mcp/index.ts+++ b/src/libs/mcp/index.ts@@ -1,3 +1,4 @@export * from './client';+export * from './mcpApp';export * from './types';export * from './utils';diff --git a/src/libs/mcp/mcpApp.test.ts b/src/libs/mcp/mcpApp.test.tsnew file mode 100644index 00000000000..51c11e9b748--- /dev/null+++ b/src/libs/mcp/mcpApp.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from 'vitest';++import {+ canServeMcpAppHere,+ getMcpAppFromState,+ getToolUiResourceUri,+ isToolVisibleToApp,+ unwrapMcpToolState,+} from './mcpApp';++describe('getToolUiResourceUri', () => {+ it('reads the nested and the deprecated flat key', () => {+ expect(getToolUiResourceUri({ _meta: { ui: { resourceUri: 'ui://a' } } })).toBe('ui://a');+ expect(getToolUiResourceUri({ _meta: { 'ui/resourceUri': 'ui://b' } })).toBe('ui://b');+ });++ it('ignores missing and non-ui:// URIs', () => {+ expect(getToolUiResourceUri({})).toBeUndefined();+ expect(getToolUiResourceUri({ _meta: { ui: { resourceUri: 'https://x' } } })).toBeUndefined();+ });+});++describe('getMcpAppFromState', () => {+ it('returns the stored view reference', () => {+ expect(getMcpAppFromState({ content: [], mcpApp: { resourceUri: 'ui://a' } })).toEqual({+ resourceUri: 'ui://a',+ });+ });++ it('finds the reference in server AgentRuntime results, nested one level deeper', () => {+ const state = {+ content: 'sunny',+ state: { content: [], mcpApp: { resourceUri: 'ui://a' } },+ success: true,+ };++ expect(getMcpAppFromState(state)).toEqual({ resourceUri: 'ui://a' });+ expect(unwrapMcpToolState(state)).toBe(state.state);+ });++ it('never unwraps a state a server nested in its own result', () => {+ // A client call's state is the server's result; the SDK keeps its extra fields+ const serverResult = {+ content: [{ text: 'ok', type: 'text' }],+ state: {+ content: [{ data: '/api/auth/get-session', mimeType: 'image/png', type: 'image' }],+ mcpApp: { resourceUri: 'ui://forged' },+ },+ };++ expect(unwrapMcpToolState(serverResult)).toBe(serverResult);+ expect(getMcpAppFromState(serverResult)).toBeUndefined();+ });++ it('ignores states without a valid reference', () => {+ expect(getMcpAppFromState(undefined)).toBeUndefined();+ expect(getMcpAppFromState({ mcpApp: { resourceUri: 'javascript:alert(1)' } })).toBeUndefined();+ });+});++describe('isToolVisibleToApp', () => {+ it('follows _meta.ui.visibility, which defaults to model and app', () => {+ expect(isToolVisibleToApp({ _meta: { ui: { visibility: ['model'] } } })).toBe(false);+ expect(isToolVisibleToApp({ _meta: { ui: { visibility: [] } } })).toBe(false);+ expect(isToolVisibleToApp({ _meta: { ui: { visibility: ['app'] } } })).toBe(true);+ expect(isToolVisibleToApp({ _meta: { ui: {} } })).toBe(true);+ expect(isToolVisibleToApp({})).toBe(true);+ });+});++describe('MCP App views from a desktop', () => {+ it('reads the desktop that produced a local view', () => {+ expect(+ getMcpAppFromState({ content: [], mcpApp: { deviceId: 'dev-a', resourceUri: 'ui://a' } }),+ ).toEqual({ deviceId: 'dev-a', resourceUri: 'ui://a' });+ });++ it('serves a local view only on the desktop that produced it', () => {+ const local = { deviceId: 'dev-a', resourceUri: 'ui://a' };++ expect(canServeMcpAppHere(local, 'dev-a')).toBe(true);+ expect(canServeMcpAppHere(local, 'dev-b')).toBe(false);+ // Web, or a desktop that can't tell which one it is+ expect(canServeMcpAppHere(local, undefined)).toBe(false);+ expect(canServeMcpAppHere(local, null)).toBe(false);+ // A view the server reads is served anywhere+ expect(canServeMcpAppHere({ resourceUri: 'ui://a' }, undefined)).toBe(true);+ });+});diff --git a/src/libs/mcp/mcpApp.ts b/src/libs/mcp/mcpApp.tsnew file mode 100644index 00000000000..3b965d5cf91--- /dev/null+++ b/src/libs/mcp/mcpApp.ts@@ -0,0 +1,112 @@+/**+ * MCP Apps (SEP-1865) helpers shared by the MCP client and the chat UI.+ *+ * A tool opts into an interactive UI by pointing `_meta.ui.resourceUri` at a+ * `ui://` resource. After the call we stash that URI on the tool result state+ * (`state.mcpApp`) so the conversation can fetch the HTML and render it.+ */++import { getMcpToolVisibility, isMcpToolVisibleTo } from '@lobechat/const/mcpApp';++/** Capability key a client advertises to tell servers it can render MCP Apps. */+export const MCP_APPS_EXTENSION_ID = 'io.modelcontextprotocol/ui';+export const MCP_APP_MIME_TYPE = 'text/html;profile=mcp-app';++/** Client capabilities that advertise MCP Apps support during `initialize`. */+export const MCP_APPS_CLIENT_CAPABILITIES = {+ extensions: { [MCP_APPS_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME_TYPE] } },+};++export interface McpAppToolState {+ /**+ * The desktop whose local MCP process (stdio, localhost / LAN) produced the+ * result. Its view and the view's calls run in that process, so only that+ * desktop can serve them.+ */+ deviceId?: string;+ resourceUri: string;+ /**+ * The MCP server that produced the result (`getMcpServerFingerprint`). The+ * view is only read from that server: the identifier may resolve to another+ * one now, which must not get this result's arguments and data.+ */+ server?: string;+}++const isUiUri = (value: unknown): value is string =>+ typeof value === 'string' && value.startsWith('ui://');++/**+ * Read the UI resource URI a tool declares. Supports the current nested+ * `_meta.ui.resourceUri` and the deprecated flat `_meta["ui/resourceUri"]`.+ */+export const getToolUiResourceUri = (tool: { _meta?: unknown } | undefined): string | undefined => {+ const meta = tool?._meta as Record<string, any> | undefined;+ if (!meta) return;++ const uri = meta.ui?.resourceUri ?? meta['ui/resourceUri'];++ return isUiUri(uri) ? uri : undefined;+};++/**+ * Whether a view may call this tool (`tools/call` from the app). Its+ * `_meta.ui.visibility` lists who may: unset means `["model", "app"]`, and a+ * tool without `"app"` must be refused to views.+ */+export const isToolVisibleToApp = (tool: { _meta?: unknown } | undefined): boolean =>+ isMcpToolVisibleTo(getMcpToolVisibility(tool?._meta), 'app');++/**+ * Whether this tool may be in the model's tool list. A tool whose+ * `_meta.ui.visibility` leaves out `"model"` exists only for its view.+ */+export const isToolVisibleToModel = (tool: { _meta?: unknown } | undefined): boolean =>+ isMcpToolVisibleTo(getMcpToolVisibility(tool?._meta), 'model');++/**+ * The raw MCP tool result state. Server AgentRuntime calls persist the whole+ * processed result (`{ content, state, success }`) as the plugin state, so the+ * MCP result (with `mcpApp`) sits one level deeper there than on client calls.+ *+ * Only that host envelope is unwrapped, recognized by its text `content` and+ * boolean `success`. A client call's state is the server's own result, whose+ * `content` is an array, and the SDK keeps any extra field it returns: a+ * `state` it nests there is the server's, not ours, and is never unwrapped.+ */+export const unwrapMcpToolState = <T = any>(state: T): T => {+ const envelope = state as+ { content?: unknown; state?: { content?: unknown }; success?: unknown } | undefined;+ const inner = envelope?.state;+ const isHostEnvelope =+ typeof envelope?.content === 'string' && typeof envelope?.success === 'boolean';++ return isHostEnvelope && inner && typeof inner === 'object' && Array.isArray(inner.content)+ ? (inner as T)+ : state;+};++/** Read the MCP App reference a tool call stored on its result state. */+export const getMcpAppFromState = (state: unknown): McpAppToolState | undefined => {+ const mcpApp = (+ unwrapMcpToolState(state) as+ { mcpApp?: { deviceId?: unknown; resourceUri?: unknown; server?: unknown } } | undefined+ )?.mcpApp;+ if (!isUiUri(mcpApp?.resourceUri)) return;++ return {+ ...(typeof mcpApp.deviceId === 'string' && { deviceId: mcpApp.deviceId }),+ resourceUri: mcpApp.resourceUri,+ ...(typeof mcpApp.server === 'string' && { server: mcpApp.server }),+ };+};++/**+ * Whether this client can serve a result's view: one from a desktop's local+ * MCP process only on that desktop (`currentDeviceId` is this desktop's+ * stable device id, if any).+ */+export const canServeMcpAppHere = (+ mcpApp: McpAppToolState,+ currentDeviceId: string | null | undefined,+): boolean => !mcpApp.deviceId || mcpApp.deviceId === currentDeviceId;diff --git a/src/libs/mcp/types.ts b/src/libs/mcp/types.tsindex 0fc722be18d..57f469eb6c9 100644--- a/src/libs/mcp/types.ts+++ b/src/libs/mcp/types.ts@@ -8,6 +8,8 @@ interface InputSchema {}export interface McpTool {+ /** Server metadata, e.g. MCP Apps `ui.resourceUri` / `ui.visibility` */+ _meta?: Record<string, unknown>;description: string;inputSchema: InputSchema;name: string;diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 7847403f2a6..89c7e724844 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -548,6 +548,22 @@ export const fileKeys = {// header is `portal:` not `document:`.// =========================================================================+// ---- MCP Apps (interactive tool result views) -----------------------------+export const mcpAppKeys = {+ resource: def(+ 'mcpApp:resource',+ (+ identifier: string,+ uri: string,+ {+ agentId,+ onThisDevice = false,+ server,+ }: { agentId?: string; onThisDevice?: boolean; server?: string },+ ) => ['mcpApp:resource', identifier, uri, agentId ?? null, onThisDevice, server ?? null],+ ),+};+// ---- api key (settings/apikey) -------------------------------------------export const apiKeyKeys = {list: def('apiKey:list', () => ['apiKey:list']),diff --git a/src/services/mcp.mcpApp.test.ts b/src/services/mcp.mcpApp.test.tsnew file mode 100644index 00000000000..52ddc9f2064--- /dev/null+++ b/src/services/mcp.mcpApp.test.ts@@ -0,0 +1,719 @@+import { getMcpServerFingerprint } from '@lobechat/const/mcpApp';+import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mcpService } from './mcp';++const {+ connectorCall,+ connectorEdit,+ connectorRead,+ connectors,+ environment,+ ipcCall,+ ipcListTools,+ ipcRead,+ relayCall,+ relayRead,+ plugins,+ toolState,+} = vi.hoisted(() => ({+ connectorCall: vi.fn(),+ connectorEdit: vi.fn(),+ connectorRead: vi.fn(),+ connectors: new Map<string, unknown>(),+ environment: { deviceGatewayConfigured: false, isDesktop: true },+ ipcCall: vi.fn(),+ ipcListTools: vi.fn(),+ ipcRead: vi.fn(),+ plugins: new Map<string, unknown>(),+ relayCall: vi.fn(),+ relayRead: vi.fn(),+ // The tool store as the service reads it: plugins are visible once loaded.+ toolState: {+ ensureConfirmedConnectors: vi.fn(async (_agentId?: string) => {}),+ pluginsLoaded: true,+ refreshPlugins: vi.fn(async () => {+ toolState.pluginsLoaded = true;+ }),+ },+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ get isDesktop() {+ return environment.isDesktop;+ },+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ callTool: { mutate: connectorCall },+ getForEdit: { query: connectorEdit },+ readUiResource: { query: connectorRead },+ },+ },+ // The relay read is a mutation only: plugin credentials must never go out in a GET URL+ toolsClient: { mcp: { callTool: { mutate: relayCall }, readUiResource: { mutate: relayRead } } },+}));++vi.mock('@/store/serverConfig/store', () => ({+ getServerConfigStoreState: () => ({+ featureFlags: { enableMcpApps: true },+ serverConfig: { deviceGatewayConfigured: environment.deviceGatewayConfigured },+ }),+}));++const { resolveGatewayDeviceId } = vi.hoisted(() => ({+ resolveGatewayDeviceId: vi.fn(async (): Promise<string | undefined> => 'this-desktop'),+}));++vi.mock('@/store/electron', () => ({+ getElectronStoreState: () => ({ resolveGatewayDeviceId }),+}));++vi.mock('@/utils/electron/ipc', () => ({+ ensureElectronIpc: () => ({+ mcp: { callTool: ipcCall, listTools: ipcListTools, readUiResource: ipcRead },+ }),+}));++vi.mock('./discover', () => ({+ discoverService: {+ reportPluginCall: vi.fn().mockResolvedValue(undefined),+ safeInjectMPToken: vi.fn(),+ },+}));++vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => toolState }));++vi.mock('@/store/tool/selectors', () => ({+ pluginSelectors: {+ getCustomPluginById: () => () => undefined,+ getInstalledPluginById: (id: string) => () =>+ toolState.pluginsLoaded ? plugins.get(id) : undefined,+ isInstalledPluginsServerConfirmed: () => toolState.pluginsLoaded,+ },+}));++vi.mock('@/store/tool/slices/connector/selectors', () => ({+ connectorSelectors: {+ connectorByIdentifierForAgent: (id: string, agentId?: string) => () =>+ connectors.get(`${agentId}:${id}`),+ },+}));++// Each case runs on the desktop, with the plugins loaded, unless it says otherwise+beforeEach(() => {+ environment.deviceGatewayConfigured = false;+ environment.isDesktop = true;+ toolState.pluginsLoaded = true;+});++const view = { contents: [{ text: '<html />', uri: 'ui://app' }] };+// The servers the results in these cases came from+// `httpPlugin` sends the `x-key` header, which is part of which server it reaches+const LOCAL = await getMcpServerFingerprint({+ headers: { 'x-key': 'k' },+ type: 'http',+ url: 'http://127.0.0.1:3000/mcp',+});+const REMOTE = await getMcpServerFingerprint({+ headers: { 'x-key': 'k' },+ type: 'http',+ url: 'https://mcp.example.com/mcp',+});+const REMOTE_BARE = await getMcpServerFingerprint({+ type: 'http',+ url: 'https://mcp.example.com/mcp',+});+const STDIO = await getMcpServerFingerprint({+ args: ['mcp.js'],+ command: 'node',+ env: { TOKEN: 'fresh-secret' },+ type: 'stdio',+});+const LINEAR = await getMcpServerFingerprint({ type: 'http', url: 'https://mcp.linear.app/mcp' });+const httpPlugin = (url: string) => ({+ customParams: { mcp: { headers: { 'x-key': 'k' }, type: 'http', url } },+});++describe('mcpService.readMcpAppResource on desktop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ plugins.clear();+ connectors.clear();+ ipcRead.mockResolvedValue(serializeMcpIpcPayload(view));+ relayRead.mockResolvedValue(view);+ });++ it('reads views of localhost / LAN http servers over IPC, not the server relay', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));++ await expect(+ mcpService.readMcpAppResource('local', 'ui://app', { onThisDevice: true, server: LOCAL }),+ ).resolves.toEqual(view);++ expect(relayRead).not.toHaveBeenCalled();+ expect(deserializeMcpIpcPayload(ipcRead.mock.calls[0][0])).toEqual({+ http: {+ headers: { 'x-key': 'k' },+ name: 'local',+ url: 'http://127.0.0.1:3000/mcp',+ },+ uri: 'ui://app',+ });+ });++ it('reads a view of a LAN server on the server relay when the server produced its result', async () => {+ // A self-hosted server without a device gateway runs private http servers itself+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));++ await expect(+ mcpService.readMcpAppResource('local', 'ui://app', { server: LOCAL }),+ ).resolves.toEqual(view);++ expect(ipcRead).not.toHaveBeenCalled();+ expect(relayRead).toHaveBeenCalledWith(expect.objectContaining({ uri: 'ui://app' }));+ });++ it('reads no view once only the plugin headers changed, which may route to another server', async () => {+ plugins.set('remote', {+ customParams: {+ mcp: { headers: { 'x-key': 'other' }, type: 'http', url: 'https://mcp.example.com/mcp' },+ },+ });++ await expect(+ mcpService.readMcpAppResource('remote', 'ui://app', { server: REMOTE }),+ ).resolves.toBeUndefined();+ expect(relayRead).not.toHaveBeenCalled();+ });++ it("reads a server-run result's view with the runtime's params, which its fingerprint names", async () => {+ // The runtime ran it without the plugin settings this client merges into headers+ const runtime = { name: 'remote', type: 'http', url: 'https://mcp.example.com/mcp' };+ plugins.set('remote', {+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com/mcp' } },+ manifest: { mcpParams: runtime },+ settings: { 'x-api-key': 'secret' },+ });++ await expect(+ mcpService.readMcpAppResource('remote', 'ui://app', { server: REMOTE_BARE }),+ ).resolves.toEqual(view);+ expect(relayRead).toHaveBeenCalledWith({ params: runtime, uri: 'ui://app' });+ });++ it('loads the installed plugins first when the conversation was opened cold', async () => {+ plugins.set('remote', httpPlugin('https://mcp.example.com/mcp'));+ toolState.pluginsLoaded = false;++ await expect(+ mcpService.readMcpAppResource('remote', 'ui://app', { agentId: 'agt_1', server: REMOTE }),+ ).resolves.toEqual(view);++ expect(toolState.refreshPlugins).toHaveBeenCalledTimes(1);+ expect(connectorRead).not.toHaveBeenCalled();+ expect(relayRead).toHaveBeenCalledWith(expect.objectContaining({ uri: 'ui://app' }));+ });++ it("loads the installed plugins in a cold conversation when only the plugin's tool row is", async () => {+ plugins.set('remote', httpPlugin('https://mcp.example.com/mcp'));+ // The endpoint-less row a plugin's tools sync to, loaded before the plugins+ connectors.set('agt_1:remote', { id: 'conn_1', identifier: 'remote', isEnabled: true });+ toolState.pluginsLoaded = false;++ await expect(+ mcpService.readMcpAppResource('remote', 'ui://app', { agentId: 'agt_1', server: REMOTE }),+ ).resolves.toEqual(view);++ expect(toolState.refreshPlugins).toHaveBeenCalledTimes(1);+ expect(connectorRead).not.toHaveBeenCalled();+ expect(relayRead).toHaveBeenCalledWith(expect.objectContaining({ uri: 'ui://app' }));+ });++ it("reads a headerless plugin's view with the runtime's params, so on its session", async () => {+ plugins.set('remote', {+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com/mcp' } },+ });++ await mcpService.readMcpAppResource('remote', 'ui://app', { server: REMOTE_BARE });++ // The runtime's manifest params carry no `headers` key, and sessions are keyed by params+ expect(relayRead.mock.calls[0][0].params).not.toHaveProperty('headers');+ });++ it('keeps public http servers on the server relay', async () => {+ plugins.set('remote', httpPlugin('https://mcp.example.com/mcp'));++ await expect(+ mcpService.readMcpAppResource('remote', 'ui://app', { server: REMOTE }),+ ).resolves.toEqual(view);++ expect(ipcRead).not.toHaveBeenCalled();+ expect(relayRead).toHaveBeenCalledWith({+ params: expect.objectContaining({ headers: { 'x-key': 'k' } }),+ uri: 'ui://app',+ });+ });+});++describe('mcpService tool discovery on desktop with MCP Apps on', () => {+ it("lists a local server's tools on a session that announces MCP Apps", async () => {+ // A server may list the tools only its views call just to such a client+ ipcListTools.mockResolvedValue(serializeMcpIpcPayload([]));++ await mcpService.listLocalMcpTools({ stdio: { command: 'dash-mcp', name: 'dash' } });++ expect(deserializeMcpIpcPayload(ipcListTools.mock.calls[0][0])).toMatchObject({+ mcpApps: true,+ });+ });+});++describe('mcpService.readMcpAppResource for stdio connectors', () => {+ const stdioConnector = {+ id: 'conn_1',+ identifier: 'files',+ isEnabled: true,+ mcpConnectionType: 'stdio',+ };+ const detail = {+ ...stdioConnector,+ mcpStdioConfig: { args: ['mcp.js'], command: 'node', env: { TOKEN: 'fresh-secret' } },+ };++ beforeEach(() => {+ vi.clearAllMocks();+ plugins.clear();+ connectors.clear();+ connectors.set('undefined:files', stdioConnector);+ connectorEdit.mockResolvedValue(detail);+ ipcRead.mockResolvedValue(serializeMcpIpcPayload(view));+ });++ it('reads the view on the desktop with the fresh stdio configuration', async () => {+ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', { onThisDevice: true, server: STDIO }),+ ).resolves.toEqual(view);++ expect(connectorEdit).toHaveBeenCalledWith({ id: 'conn_1' });+ expect(deserializeMcpIpcPayload(ipcRead.mock.calls[0][0])).toEqual({+ env: { TOKEN: 'fresh-secret' },+ params: { args: ['mcp.js'], command: 'node', name: 'files', type: 'stdio' },+ uri: 'ui://app',+ });+ expect(connectorRead).not.toHaveBeenCalled();+ });++ it('does not read once the connector is disabled or loses its command', async () => {+ for (const current of [+ { ...detail, isEnabled: false },+ { ...detail, mcpStdioConfig: undefined },+ ]) {+ connectorEdit.mockResolvedValueOnce(current);++ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', { onThisDevice: true, server: STDIO }),+ ).resolves.toBeUndefined();+ }+ expect(ipcRead).not.toHaveBeenCalled();+ });++ it("loads the agent's own stdio connector in a cold conversation before choosing the route", async () => {+ connectors.clear();+ // Only known once the agent's tools are loaded+ toolState.ensureConfirmedConnectors.mockImplementationOnce(async (agentId?: string) => {+ connectors.set(`${agentId}:files`, stdioConnector);+ });++ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', {+ agentId: 'agt_1',+ onThisDevice: true,+ server: STDIO,+ }),+ ).resolves.toEqual(view);++ expect(toolState.ensureConfirmedConnectors).toHaveBeenCalledWith('agt_1');+ expect(connectorRead).not.toHaveBeenCalled();+ expect(deserializeMcpIpcPayload(ipcRead.mock.calls[0][0])).toMatchObject({+ params: { command: 'node', name: 'files', type: 'stdio' },+ });+ });++ it("fails the read, so it is retried, when the agent's own connectors can't be loaded", async () => {+ // The base connector of the same identifier is loaded; the agent's own copy is not+ connectors.set('agt_1:files', stdioConnector);+ toolState.ensureConfirmedConnectors.mockRejectedValueOnce(new Error('offline'));++ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', {+ agentId: 'agt_1',+ onThisDevice: true,+ server: STDIO,+ }),+ ).rejects.toThrow('offline');++ // Never read from the base connector meanwhile+ expect(connectorEdit).not.toHaveBeenCalled();+ expect(ipcRead).not.toHaveBeenCalled();+ expect(connectorRead).not.toHaveBeenCalled();+ expect(relayRead).not.toHaveBeenCalled();+ });++ it('reads no view once the connector runs another command than the one that produced it', async () => {+ connectorEdit.mockResolvedValueOnce({+ ...detail,+ mcpStdioConfig: { args: ['other.js'], command: 'node', env: {} },+ });++ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', { onThisDevice: true, server: STDIO }),+ ).resolves.toBeUndefined();+ expect(ipcRead).not.toHaveBeenCalled();+ });++ it('reads no view once only the connector environment changed, which may pick another server', async () => {+ connectorEdit.mockResolvedValueOnce({+ ...detail,+ mcpStdioConfig: { ...detail.mcpStdioConfig, env: { TOKEN: 'fresh-secret', URL: 'b' } },+ });++ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', { onThisDevice: true, server: STDIO }),+ ).resolves.toBeUndefined();+ expect(ipcRead).not.toHaveBeenCalled();+ });++ it('falls back without a request off the desktop, where nothing can run the command', async () => {+ environment.isDesktop = false;++ await expect(+ mcpService.readMcpAppResource('files', 'ui://app', { onThisDevice: true, server: STDIO }),+ ).resolves.toBeUndefined();++ expect(connectorEdit).not.toHaveBeenCalled();+ expect(connectorRead).not.toHaveBeenCalled();+ expect(ipcRead).not.toHaveBeenCalled();+ });+});++describe('mcpService MCP App calls for agents', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ plugins.clear();+ connectors.clear();+ connectorRead.mockResolvedValue(view);+ connectorCall.mockResolvedValue({ content: 'ok', success: true });+ });++ it("reads an agent's connector view on the server, which checks the result's server", async () => {+ connectors.set('agt_1:agent-app', {+ isEnabled: true,+ mcpServerUrl: 'https://mcp.example.com/mcp',+ });++ await expect(+ mcpService.readMcpAppResource('agent-app', 'ui://app', { agentId: 'agt_1', server: REMOTE }),+ ).resolves.toEqual(view);++ expect(connectorRead).toHaveBeenCalledWith({+ agentId: 'agt_1',+ identifier: 'agent-app',+ server: REMOTE,+ uri: 'ui://app',+ });+ });++ it('reads no view for a result that came from another server than the identifier reaches now', async () => {+ // The connector that produced it was disabled; a plugin of the same identifier remains+ connectors.set('agt_1:shared', {+ isEnabled: false,+ mcpServerUrl: 'https://mcp.example.com/mcp',+ });+ plugins.set('shared', httpPlugin('https://other.example.com/mcp'));++ await expect(+ mcpService.readMcpAppResource('shared', 'ui://app', { agentId: 'agt_1', server: REMOTE }),+ ).resolves.toBeUndefined();+ // Nor for a result that names no server+ await expect(+ mcpService.readMcpAppResource('shared', 'ui://app', { agentId: 'agt_1' }),+ ).resolves.toBeUndefined();++ expect(relayRead).not.toHaveBeenCalled();+ expect(ipcRead).not.toHaveBeenCalled();+ expect(connectorRead).not.toHaveBeenCalled();+ });++ it('sends the agent with connector tool calls', async () => {+ connectors.set('agt_1:linear', {+ isEnabled: true,+ mcpServerUrl: 'https://mcp.linear.app/mcp',+ });++ await mcpService.invokeMcpToolCall(+ { apiName: 'list', arguments: '{}', id: 't1', identifier: 'linear', type: 'mcp' },+ { agentId: 'agt_1' },+ );++ expect(connectorCall).toHaveBeenCalledWith(+ { agentId: 'agt_1', args: '{}', identifier: 'linear', toolName: 'list' },+ expect.anything(),+ );+ });++ it("marks a view's connector call so the server checks the tool's visibility", async () => {+ connectors.set('agt_1:linear', {+ isEnabled: true,+ mcpServerUrl: 'https://mcp.linear.app/mcp',+ });++ await mcpService.invokeMcpToolCall(+ { apiName: 'list', arguments: '{}', id: 't1', identifier: 'linear', type: 'mcp' },+ { agentId: 'agt_1', fromMcpApp: true, server: LINEAR },+ );++ expect(connectorCall).toHaveBeenCalledWith(+ {+ agentId: 'agt_1',+ args: '{}',+ fromApp: true,+ identifier: 'linear',+ server: LINEAR,+ toolName: 'list',+ },+ expect.anything(),+ );+ });+});++describe('mcpService.invokeMcpToolCall on desktop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ plugins.clear();+ connectors.clear();+ ipcCall.mockResolvedValue(serializeMcpIpcPayload({ content: 'ok', success: true }));+ });++ // A view whose result this desktop's own MCP process produced+ const localView = { fromMcpApp: true, onThisDevice: true, server: LOCAL };+ const refresh = {+ apiName: 'refresh',+ arguments: '{"city":"Paris"}',+ id: 't1',+ identifier: 'local',+ type: 'mcp',+ } as const;++ it('calls localhost / LAN http servers over IPC for a view, not the server relay', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));++ await mcpService.invokeMcpToolCall(refresh, localView);++ expect(relayCall).not.toHaveBeenCalled();+ expect(deserializeMcpIpcPayload(ipcCall.mock.calls[0][0])).toEqual({+ args: { city: 'Paris' },+ fromApp: true,+ http: { headers: { 'x-key': 'k' }, name: 'local', url: 'http://127.0.0.1:3000/mcp' },+ mcpApps: true,+ toolName: 'refresh',+ });+ });++ it("marks a view's relay call so the server checks the tool's visibility", async () => {+ plugins.set('remote', httpPlugin('https://mcp.example.com/mcp'));+ relayCall.mockResolvedValue({ content: 'ok', success: true });++ await mcpService.invokeMcpToolCall(+ { ...refresh, identifier: 'remote' },+ { fromMcpApp: true, server: REMOTE },+ );++ expect(relayCall).toHaveBeenCalledWith(+ expect.objectContaining({ fromApp: true, toolName: 'refresh' }),+ expect.anything(),+ );+ });++ it('refuses a view call once the plugin reaches another server than the view came from', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:4000/mcp'));++ await expect(mcpService.invokeMcpToolCall(refresh, localView)).rejects.toThrow(+ 'another server',+ );+ expect(ipcCall).not.toHaveBeenCalled();+ expect(relayCall).not.toHaveBeenCalled();+ });++ it('runs a view call to a LAN server on the server relay when the server produced its result', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));+ relayCall.mockResolvedValue({ content: 'ok', success: true });++ await mcpService.invokeMcpToolCall(refresh, { fromMcpApp: true, server: LOCAL });++ expect(ipcCall).not.toHaveBeenCalled();+ expect(relayCall).toHaveBeenCalledWith(+ expect.objectContaining({ fromApp: true, toolName: 'refresh' }),+ expect.anything(),+ );+ });++ it('refuses a view call to a cloud server, whose gateway cannot check visibility', async () => {+ plugins.set('cloud', { customParams: { mcp: { type: 'cloud' } } });++ await expect(+ mcpService.invokeMcpToolCall({ ...refresh, identifier: 'cloud' }, { fromMcpApp: true }),+ ).rejects.toThrow("can't be called from an interactive view");+ expect(relayCall).not.toHaveBeenCalled();+ });++ it('does not dispatch a cancelled view call over IPC', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));+ const request = new AbortController();+ request.abort();++ await expect(+ mcpService.invokeMcpToolCall(refresh, { ...localView, signal: request.signal }),+ ).rejects.toThrow();+ expect(ipcCall).not.toHaveBeenCalled();+ });++ it('records this desktop on a view its local MCP process marked', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));+ ipcCall.mockResolvedValueOnce(+ serializeMcpIpcPayload({+ content: 'ok',+ state: { content: [], mcpApp: { resourceUri: 'ui://dash/view' } },+ success: true,+ }),+ );++ const result = await mcpService.invokeMcpToolCall(refresh, localView);++ // Only this desktop can serve it: the view and its calls run in its process+ expect(result?.state?.mcpApp).toEqual({+ deviceId: 'this-desktop',+ resourceUri: 'ui://dash/view',+ });+ });++ it("offers no view when this desktop's id can't be resolved", async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));+ resolveGatewayDeviceId.mockResolvedValueOnce(undefined);+ ipcCall.mockResolvedValueOnce(+ serializeMcpIpcPayload({+ content: 'ok',+ state: { content: [], mcpApp: { resourceUri: 'ui://dash/view' } },+ success: true,+ }),+ );++ const result = await mcpService.invokeMcpToolCall(refresh, localView);++ // Unmarked, any desktop opening the conversation would serve it+ expect(result?.state).toEqual({ content: [] });+ });++ it('keeps conversation calls to localhost / LAN http servers on their existing route', async () => {+ plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));+ relayCall.mockResolvedValue({ content: 'ok', success: true });++ await mcpService.invokeMcpToolCall(refresh, {});++ expect(ipcCall).not.toHaveBeenCalled();+ expect(relayCall).toHaveBeenCalledWith(+ expect.objectContaining({ toolName: 'refresh' }),+ expect.anything(),+ );+ });+});++describe('mcpService.invokeMcpToolCall for stdio connectors behind a device gateway', () => {+ const stdioConnector = {+ id: 'conn_1',+ identifier: 'files',+ isEnabled: true,+ mcpConnectionType: 'stdio',+ };+ const detail = {+ ...stdioConnector,+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['mcp.js'], command: 'node', env: { TOKEN: 'fresh-secret' } },+ tools: [{ permission: 'auto', toolName: 'list' }],+ };+ const stdioView = { fromMcpApp: true, onThisDevice: true, server: STDIO };+ const list = {+ apiName: 'list',+ arguments: '{"dir":"/tmp"}',+ id: 't1',+ identifier: 'files',+ type: 'mcp',+ } as const;++ beforeEach(() => {+ vi.clearAllMocks();+ plugins.clear();+ connectors.clear();+ connectors.set('undefined:files', stdioConnector);+ environment.deviceGatewayConfigured = true;+ connectorEdit.mockResolvedValue(detail);+ connectorCall.mockResolvedValue({ content: 'server', success: true });+ ipcCall.mockResolvedValue(serializeMcpIpcPayload({ content: 'ok', success: true }));+ });++ it('runs a view call on this desktop, where its view was read', async () => {+ await expect(mcpService.invokeMcpToolCall(list, stdioView)).resolves.toEqual({+ content: 'ok',+ success: true,+ });++ expect(connectorCall).not.toHaveBeenCalled();+ expect(deserializeMcpIpcPayload(ipcCall.mock.calls[0][0])).toEqual({+ args: { dir: '/tmp' },+ env: { TOKEN: 'fresh-secret' },+ fromApp: true,+ mcpApps: true,+ params: { args: ['mcp.js'], command: 'node', name: 'files', type: 'stdio' },+ toolName: 'list',+ });+ });++ it('does not dispatch a view call cancelled while its connector was read', async () => {+ const request = new AbortController();+ connectorEdit.mockImplementation(async () => {+ request.abort();+ return detail;+ });++ await expect(+ mcpService.invokeMcpToolCall(list, { ...stdioView, signal: request.signal }),+ ).rejects.toThrow();+ expect(ipcCall).not.toHaveBeenCalled();+ });++ it('still refuses a view call to a tool the connector disabled', async () => {+ connectorEdit.mockResolvedValue({+ ...detail,+ tools: [{ permission: 'disabled', toolName: 'list' }],+ });++ await expect(mcpService.invokeMcpToolCall(list, stdioView)).rejects.toThrow(+ 'unavailable or disabled',+ );+ expect(ipcCall).not.toHaveBeenCalled();+ });++ it('keeps conversation calls on the gateway route', async () => {+ await mcpService.invokeMcpToolCall(list, {});++ expect(ipcCall).not.toHaveBeenCalled();+ expect(connectorCall).toHaveBeenCalledWith(+ { agentId: undefined, args: '{"dir":"/tmp"}', identifier: 'files', toolName: 'list' },+ expect.anything(),+ );+ });+});diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.tsindex fd570ed18fd..d9bcb4345e8 100644--- a/src/services/mcp.test.ts+++ b/src/services/mcp.test.ts@@ -9,6 +9,7 @@ const mockElectronIpc = {callTool: vi.fn(),getStreamableMcpServerManifest: vi.fn(),getStdioMcpServerManifest: vi.fn(),+ listTools: vi.fn(),validMcpServerInstallable: vi.fn(),},};@@ -20,6 +21,7 @@ const environment = vi.hoisted(() => ({vi.mock('@/store/serverConfig/store', () => ({getServerConfigStoreState: () => ({+ featureFlags: { enableMcpApps: false },serverConfig: { deviceGatewayConfigured: environment.deviceGatewayConfigured },}),}));@@ -105,6 +107,9 @@ describe('MCPService', () => {environment.isDesktop = false;environment.deviceGatewayConfigured = undefined;mockGetToolStoreState.mockReturnValue({});+ // Like the real selectors: a lookup function that finds no plugin by default+ mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => undefined);+ mockPluginSelectors.getCustomPluginById.mockReturnValue(() => undefined);});describe('invokeMcpToolCall', () => {@@ -198,6 +203,8 @@ describe('MCPService', () => {expect(superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0])).toEqual({args: { path: 'test.txt' },env: detail.mcpStdioConfig.env,+ // MCP Apps off for this user: the desktop session doesn't announce them+ mcpApps: false,params: { command: 'node', args: ['mcp.js'], name: payload.identifier, type: 'stdio' },toolName: 'read_file',});@@ -231,6 +238,11 @@ describe('MCPService', () => {{ ...detail, isEnabled: false },{ ...detail, tools: [] },{ ...detail, tools: [{ toolName: 'read_file', permission: 'disabled' }] },+ // Only its view may call it, and this call came from the model+ {+ ...detail,+ tools: [{ metadata: { visibility: ['app'] }, permission: 'auto', toolName: 'read_file' }],+ },])('rejects a newly disabled connector or unavailable tool before IPC', async (current) => {const { lambdaClient } = await import('@/libs/trpc/client');vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(current as never);@@ -743,6 +755,21 @@ describe('MCPService', () => {});});+ describe('listLocalMcpTools', () => {+ it('returns every tool the desktop main process lists, with its visibility', async () => {+ const tools = [{ inputSchema: { type: 'object' }, name: 'load_page', visibility: ['app'] }];+ mockElectronIpc.mcp.listTools.mockResolvedValue(superjson.serialize(tools));+ const input = { stdio: { command: 'dash-mcp', name: 'dash' } };++ await expect(mcpService.listLocalMcpTools(input)).resolves.toEqual(tools);+ expect(superjson.deserialize(mockElectronIpc.mcp.listTools.mock.calls[0][0])).toEqual({+ ...input,+ // MCP Apps off for this user: listed on a session that doesn't announce them+ mcpApps: false,+ });+ });+ });+describe('getStdioMcpServerManifest', () => {it('should call ipc mcp.getStdioMcpServerManifest with stdio parameters', async () => {const mockManifest: ToolManifest = {@@ -778,7 +805,11 @@ describe('MCPService', () => {expect(result).toEqual(mockManifest);const callArg = vi.mocked(mockElectronIpc.mcp.getStdioMcpServerManifest).mock.calls[0][0];- expect(superjson.deserialize(callArg as any)).toEqual({ ...stdioParams, metadata });+ expect(superjson.deserialize(callArg as any)).toEqual({+ ...stdioParams,+ mcpApps: false,+ metadata,+ });});it('should handle abort signal for stdio manifest', async () => {@@ -811,6 +842,7 @@ describe('MCPService', () => {const callArg = vi.mocked(mockElectronIpc.mcp.getStdioMcpServerManifest).mock.calls[0][0];expect(superjson.deserialize(callArg as any)).toEqual({...stdioParams,+ mcpApps: false,metadata: undefined,});});@@ -843,6 +875,7 @@ describe('MCPService', () => {const callArg = vi.mocked(mockElectronIpc.mcp.getStdioMcpServerManifest).mock.calls[0][0];expect(superjson.deserialize(callArg as any)).toEqual({...stdioParams,+ mcpApps: false,metadata: undefined,});});diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 2cd9c9265cd..0ffd72919d5 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -1,4 +1,9 @@import { CURRENT_VERSION, isDesktop } from '@lobechat/const';+import {+ getMcpServerFingerprint,+ isSyncedMcpToolVisibleTo,+ type McpServerAddress,+} from '@lobechat/const/mcpApp';import {type ChatToolPayload,type CheckMcpInstallResult,@@ -9,10 +14,12 @@ import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utilimport { toRecord } from '@lobechat/utils/object';import { type PluginManifest } from '@lobehub/market-sdk';import { type CallReportRequest } from '@lobehub/market-types';+import { type ReadResourceResult } from '@modelcontextprotocol/client';import { type MCPToolCallResult } from '@/libs/mcp';import { getMCPConnectionErrorType } from '@/libs/mcp/utils';import { toolsClient } from '@/libs/trpc/client';+import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { getServerConfigStoreState } from '@/store/serverConfig/store';import { ensureElectronIpc } from '@/utils/electron/ipc';@@ -33,10 +40,159 @@ function calculateObjectSizeBytes(obj: any): number {}}+/** A tool a local MCP server lists, as the desktop main process reports it. */+export interface LocalMcpTool {+ description?: string;+ inputSchema?: Record<string, unknown>;+ name: string;+ /** The tool's MCP Apps `_meta.ui.visibility`, when it declares one. */+ visibility?: string[];+}++/**+ * IPC and cloud-gateway calls can't be cancelled once sent, so a request+ * cancelled during the awaits before them must stop here.+ */+const throwIfAborted = (signal?: AbortSignal) => {+ if (!signal?.aborted) return;++ throw signal.reason instanceof Error+ ? signal.reason+ : new DOMException('The tool call was cancelled', 'AbortError');+};++/**+ * A view this machine's MCP process (stdio, localhost / LAN) marked on its+ * result can only be served here, where the view and its calls run: record+ * which desktop that is, so another one falls back to the plain result.+ */+const markLocalView = async <T>(result: T): Promise<T> => {+ const state = (result as { state?: { mcpApp?: { deviceId?: string } } } | undefined)?.state;+ if (!state?.mcpApp) return result;++ const { getElectronStoreState } = await import('@/store/electron');+ const deviceId = await getElectronStoreState().resolveGatewayDeviceId();+ // Unmarked would read as a view any client can serve: offer none instead+ if (deviceId) state.mcpApp.deviceId = deviceId;+ else delete state.mcpApp;++ return result;+};++/**+ * Whether `address` is the MCP server a view came from (`server`, a+ * `getMcpServerFingerprint`). A view is read, and its calls run, on no other.+ */+const isViewServer = async (server: string | undefined, address: McpServerAddress) =>+ !!server && (await getMcpServerFingerprint(address)) === server;++const VIEW_SERVER_MOVED = 'This view came from another server than the tool reaches now';++/**+ * The params, of a plugin's two current ones, that reach the server a view came+ * from: as configured here (its settings merged in), or as the server's runtime+ * ran it (`manifest.mcpParams`). The view is read, and calls, with exactly those.+ */+const pickViewServerParams = async (+ server: string | undefined,+ plugin: { manifest?: unknown },+ configured: any,+): Promise<any | undefined> => {+ const runtime = (plugin.manifest as { mcpParams?: { type?: string } } | undefined)?.mcpParams;+ for (const params of [configured, runtime]) {+ if (params?.type !== 'http' && params?.type !== 'stdio') continue;+ if (await isViewServer(server, params)) return params;+ }+ return undefined;+};+const VIEW_SITE_MISMATCH = "This view's server runs elsewhere than this call would";++/** The user's `mcp_apps` flag: whether sessions on this machine announce MCP Apps. */+const isMcpAppsOn = () => {+ const state = getServerConfigStoreState();+ return !!state && serverConfigSelectors.enableMcpApps(state);+};++/**+ * Build the MCP client params for an installed/custom plugin: its stored+ * connection plus the user's plugin settings as HTTP headers or stdio env.+ */+const buildPluginMcpParams = (+ plugin: { customParams?: { mcp?: any } | null; settings?: unknown },+ identifier: string,+) => {+ const connection = plugin.customParams?.mcp;+ const settingsEntries = plugin.settings+ ? Object.entries(plugin.settings as Record<string, any>).filter(+ ([, value]) => value !== undefined && value !== null,+ )+ : [];+ const pluginSettings =+ settingsEntries.length > 0+ ? settingsEntries.reduce<Record<string, unknown>>((acc, [key, value]) => {+ acc[key] = value;++ return acc;+ }, {})+ : undefined;++ const params = {+ ...connection,+ name: identifier,+ } as any;++ if (connection?.type === 'http') {+ const headers = { ...connection.headers, ...pluginSettings };+ // Left out when empty, as the runtime's manifest params leave it: MCP+ // sessions are cached by these params, so `{}` would open a second one+ if (Object.keys(headers).length > 0) params.headers = headers;+ }++ if (connection?.type === 'stdio') {+ params.env = {+ ...connection?.env,+ ...pluginSettings,+ };+ }++ return { params, pluginSettings };+};+class MCPService {async invokeMcpToolCall(payload: ChatToolPayload,- { signal, topicId }: { signal?: AbortSignal; topicId?: string },+ {+ agentId,+ fromMcpApp,+ onThisDevice,+ server,+ signal,+ topicId,+ }: {+ /** Resolve connectors the way this agent's conversation does (agent-owned first). */+ agentId?: string;+ /**+ * The call is an MCP App view's `tools/call`, not the model's:+ * - only tools whose `_meta.ui.visibility` includes "app" run, which the+ * process holding the MCP session (server or desktop main) checks;+ * - on desktop, servers only this machine can reach (stdio connectors,+ * localhost / LAN http plugins) run over IPC whether or not a device+ * gateway is configured, as the view's HTML was read the same way.+ * Conversation calls keep their existing route.+ */+ fromMcpApp?: boolean;+ /**+ * With `fromMcpApp`: the view's result came from this desktop's own MCP+ * process (it carries this device's id), so its calls run there too;+ * otherwise on the server. A URL alone can't tell a server-side+ * `localhost` from this machine's.+ */+ onThisDevice?: boolean;+ /** With `fromMcpApp`: the server the view came from; its calls reach no other. */+ server?: string;+ signal?: AbortSignal;+ topicId?: string;+ },) {await discoverService.safeInjectMPToken();@@ -45,26 +201,37 @@ class MCPService {const s = getToolStoreState();const { identifier, arguments: args, apiName } = payload;+ // Calls run on this machine announce MCP Apps only under the user's flag+ const mcpApps = isMcpAppsOn();// Connector-first: HTTP connectors use their server-held credentials.// Standalone desktop stdio connectors use local IPC; configured device- // gateways keep the existing server route.+ // gateways keep the existing server route for conversation calls.// Only connectors with a real MCP endpoint are routed here — Lobehub/Composio// skills synced into the connector store have no mcpServerUrl and keep their// original executor path.const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');- const connector = connectorSelectors.connectorByIdentifier(identifier)(s);- if (- connector &&- connector.isEnabled &&- (connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')- ) {+ const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ const installPlugin = pluginSelectors.getInstalledPluginById(identifier)(s);+ const customPlugin = pluginSelectors.getCustomPluginById(identifier)(s);++ const plugin = installPlugin || customPlugin;++ // An agent's own connectors may not be loaded on the client yet; with no+ // plugin to fall back to, let the server resolve the identifier for the agent.+ const isConnector = connector+ ? connector.isEnabled && (!!connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')+ : !!agentId && !plugin;+ if (isConnector) {const { lambdaClient } = await import('@/libs/trpc/client');- if (+ const runsHere =+ connector &&isDesktop &&connector.mcpConnectionType === 'stdio' &&- getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured === false- ) {+ (fromMcpApp || getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured === false);+ // A view's calls run where its result was produced+ if (fromMcpApp && !!runsHere !== !!onThisDevice) throw new Error(VIEW_SITE_MISMATCH);+ if (runsHere) {// Persisted connector projections omit env secrets and may be stale.// This protected read retains the connector's credential ownership gate.const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });@@ -73,14 +240,31 @@ class MCPService {if (!tool || tool.permission === 'disabled') {throw new Error(`Tool '${apiName}' is unavailable or disabled for this connector`);}+ if (!fromMcpApp && !isSyncedMcpToolVisibleTo(tool, 'model')) {+ throw new Error(`Tool '${apiName}' can only be called from its interactive view`);+ }const config = detail.mcpStdioConfig;if (detail.mcpConnectionType !== 'stdio' || !config?.command) {throw new Error('Connector does not have a stdio command configured');}+ if (+ fromMcpApp &&+ !(await isViewServer(server, {+ args: config.args ?? [],+ command: config.command,+ env: config.env,+ type: 'stdio',+ }))+ ) {+ throw new Error(VIEW_SERVER_MOVED);+ }+ throwIfAborted(signal);const result = await ensureElectronIpc().mcp.callTool(serializeMcpIpcPayload({args: safeParseJSON(args) ?? {},env: config.env,+ ...(fromMcpApp && { fromApp: true }),+ mcpApps,params: {args: config.args ?? [],command: config.command,@@ -90,11 +274,18 @@ class MCPService {toolName: apiName,}),);- return deserializeMcpIpcPayload<MCPToolCallResult>(result);+ return markLocalView(deserializeMcpIpcPayload<MCPToolCallResult>(result));}try {return (await lambdaClient.connector.callTool.mutate(- { args, identifier, toolName: apiName },+ {+ agentId,+ args,+ // The server checks the view's server against the connector it resolves+ ...(fromMcpApp && { fromApp: true, server }),+ identifier,+ toolName: apiName,+ },{ signal },)) as MCPToolCallResult;} catch (error) {@@ -113,49 +304,26 @@ class MCPService {}}- const installPlugin = pluginSelectors.getInstalledPluginById(identifier)(s);- const customPlugin = pluginSelectors.getCustomPluginById(identifier)(s);-- const plugin = installPlugin || customPlugin;-if (!plugin) return;const connection = plugin.customParams?.mcp;- const settingsEntries = plugin.settings- ? Object.entries(plugin.settings as Record<string, any>).filter(- ([, value]) => value !== undefined && value !== null,- )- : [];- const pluginSettings =- settingsEntries.length > 0- ? settingsEntries.reduce<Record<string, unknown>>((acc, [key, value]) => {- acc[key] = value;-- return acc;- }, {})- : undefined;-- const params = {- ...connection,- name: identifier,- } as any;-- if (connection?.type === 'http') {- params.headers = {- ...connection.headers,- ...pluginSettings,- };- }-- if (connection?.type === 'stdio') {- params.env = {- ...connection?.env,- ...pluginSettings,- };- }+ const configured = buildPluginMcpParams(plugin, identifier);+ const { pluginSettings } = configured;const isStdio = plugin?.customParams?.mcp?.type === 'stdio';const isCloud = plugin?.customParams?.mcp?.type === 'cloud';+ // A view's calls reach the server its result came from, never another+ // (cloud servers refuse view calls below)+ let params = configured.params;+ if (fromMcpApp && !isCloud) {+ params = await pickViewServerParams(server, plugin, configured.params);+ if (!params) throw new Error(VIEW_SERVER_MOVED);+ }+ // A view's call to an http server runs where its result was produced: over+ // IPC when this desktop's process produced it (a localhost / LAN endpoint+ // only it reaches), else on the server, which may reach its own LAN+ const isLocalHttp =+ !!fromMcpApp && isDesktop && plugin?.customParams?.mcp?.type === 'http' && !!onThisDevice;const isCustomPlugin = !!customPlugin;// Build meta for server-side reporting@@ -177,11 +345,21 @@ class MCPService {// (IPC layer serializes the whole payload into a JSON envelope).args: isDesktop && isStdio ? (safeParseJSON(args) ?? {}) : args,env: connection?.type === 'stdio' ? params.env : (pluginSettings ?? connection?.env),+ ...(fromMcpApp && { fromApp: true }),meta,params,toolName: apiName,};+ // Cloud servers refuse view calls below+ // Stdio runs only on this desktop, which then marked the result as its own+ if (fromMcpApp && isStdio && !(isDesktop && onThisDevice)) {+ throw new Error(VIEW_SITE_MISMATCH);+ }++ // Before the timing starts: a call cancelled here never ran, so isn't reported+ throwIfAborted(signal);+// Record call start timeconst callStartTime = Date.now();let success = false;@@ -190,6 +368,11 @@ class MCPService {let result: MCPToolCallResult | undefined;try {+ // Cloud servers render no views, and their gateway can't check visibility+ if (isCloud && fromMcpApp) {+ throw new Error(`Tool '${apiName}' can't be called from an interactive view`);+ }+// For cloud type, call via cloud gatewayif (isCloud) {// Parse args@@ -208,9 +391,20 @@ class MCPService {} else if (isDesktop && isStdio) {// For desktop and stdio, use IPC (main process)// Note: IPC doesn't support AbortSignal yet- const serialized = serializeMcpIpcPayload(data);+ const serialized = serializeMcpIpcPayload({ ...data, mcpApps });+ const serializedResult = await ensureElectronIpc().mcp.callTool(serialized as any);+ result = await markLocalView(deserializeMcpIpcPayload(serializedResult) as any);+ } else if (isLocalHttp) {+ // Same routing as the manifest fetch: the server relay can't reach it+ const serialized = serializeMcpIpcPayload({+ args: safeParseJSON(args) ?? {},+ fromApp: true,+ http: { auth: params.auth, headers: params.headers, name: params.name, url: params.url },+ mcpApps,+ toolName: apiName,+ });const serializedResult = await ensureElectronIpc().mcp.callTool(serialized as any);- result = deserializeMcpIpcPayload(serializedResult) as any;+ result = await markLocalView(deserializeMcpIpcPayload(serializedResult) as any);} else {// For other types, use the toolsClientresult = await toolsClient.mcp.callTool.mutate(data, { signal });@@ -228,8 +422,8 @@ class MCPService {} finally {// HTTP/SSE/streamable types: reporting is handled by server-side via mcp.callTool// Cloud type: reporting is handled by server-side via market.callCloudMcpEndpoint- // Only report from frontend for stdio types (desktop only)- if (isStdio) {+ // Only report from frontend for calls that ran on this machine (desktop only)+ if (isStdio || isLocalHttp) {const callEndTime = Date.now();const callDurationMs = callEndTime - callStartTime;@@ -269,6 +463,161 @@ class MCPService {}}+ /**+ * Read the MCP Apps `ui://` resource (HTML view) a tool result renders with,+ * from the same server the tool ran on: `server` names it+ * (`getMcpServerFingerprint`), and the identifier must still resolve to it.+ * Returns undefined when it doesn't, or when that server can't serve views+ * from here (cloud plugins, stdio off desktop).+ */+ async readMcpAppResource(+ identifier: string,+ uri: string,+ {+ agentId,+ onThisDevice = false,+ server,+ }: {+ agentId?: string;+ /**+ * The result came from this desktop's own MCP process (it carries this+ * device's id): read the view there, over IPC. Otherwise it came from the+ * server, which reads it. Never the other one: a URL can't tell a+ * server-side `localhost` from this machine's.+ */+ onThisDevice?: boolean;+ server?: string;+ },+ ): Promise<ReadResourceResult | undefined> {+ // A result that doesn't name its server can't be matched to one+ if (!server) return;+ const reaches = (address: McpServerAddress) => isViewServer(server, address);++ const { pluginSelectors } = await import('@/store/tool/selectors');+ const { getToolStoreState } = await import('@/store/tool/store');+ let s = getToolStoreState();++ // An agent's own connectors (e.g. a stdio one only it has) may not be loaded+ // in a conversation opened cold; without them the view would be read from+ // the base connector, or sent to the server route. If they can't be loaded,+ // the read fails, so its fetcher retries rather than settling on no view;+ // it is never read from another server meanwhile.+ if (agentId) {+ await s.ensureConfirmedConnectors(agentId);+ s = getToolStoreState();+ }++ const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');+ const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ // Same test as `invokeMcpToolCall`: only an enabled connector with its own+ // endpoint serves the view. Any other (e.g. the endpoint-less row a plugin's+ // tools are synced to) leaves it to the plugin.+ const connectorServes =+ !!connector?.isEnabled &&+ (!!connector.mcpServerUrl || connector.mcpConnectionType === 'stdio');++ // A conversation opened cold has not loaded the installed plugins yet, and an+ // unloaded list would lose a plugin's view or send it to the connector route.+ // Load the server's records first, as the tool call did before it ran.+ if (!connectorServes && !pluginSelectors.isInstalledPluginsServerConfirmed(s)) {+ await s.refreshPlugins();+ s = getToolStoreState();+ }++ // Stdio connectors run on a desktop app, never on the server, so only the+ // desktop can read their view: it spawns the same command over IPC.+ if (connectorServes && connector?.mcpConnectionType === 'stdio') {+ if (!isDesktop || !onThisDevice) return;++ const { lambdaClient } = await import('@/libs/trpc/client');+ // Persisted connector projections omit env secrets and may be stale.+ // This protected read retains the connector's credential ownership gate.+ const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });+ const config = detail.mcpStdioConfig;+ if (!detail.isEnabled || detail.mcpConnectionType !== 'stdio' || !config?.command) return;+ if (+ !(await reaches({+ args: config.args ?? [],+ command: config.command,+ env: config.env,+ type: 'stdio',+ }))+ ) {+ return;+ }++ const result = await ensureElectronIpc().mcp.readUiResource(+ serializeMcpIpcPayload({+ env: config.env,+ params: {+ args: config.args ?? [],+ command: config.command,+ name: detail.identifier,+ type: 'stdio',+ },+ uri,+ }) as any,+ );+ return deserializeMcpIpcPayload(result) as ReadResourceResult;+ }++ const plugin =+ pluginSelectors.getInstalledPluginById(identifier)(s) ||+ pluginSelectors.getCustomPluginById(identifier)(s);++ // Same resolution as `invokeMcpToolCall`: the view comes from the connector+ // the tool ran on. The agent's lists are loaded by now, so an identifier+ // with no connector here has none on the server either.+ if (connectorServes) {+ if (onThisDevice) return;+ const { lambdaClient } = await import('@/libs/trpc/client');+ // The server checks `server` against the connector it resolves+ return (await lambdaClient.connector.readUiResource.query({+ agentId,+ identifier,+ server,+ uri,+ })) as ReadResourceResult;+ }++ const type = plugin?.customParams?.mcp?.type;+ if (!plugin || (type !== 'http' && type !== 'stdio')) return;++ const params = await pickViewServerParams(+ server,+ plugin,+ buildPluginMcpParams(plugin, identifier).params,+ );+ if (!params) return;++ // A result this desktop's process produced (stdio, or a localhost / LAN+ // endpoint only it reaches) has its view read here over IPC; any other on+ // the server relay. Stdio never runs on the server.+ const isLocalHttp = type === 'http' && onThisDevice;+ if (type === 'stdio' || isLocalHttp) {+ if (!isDesktop || !onThisDevice) return;++ const input = isLocalHttp+ ? {+ http: {+ auth: params.auth,+ headers: params.headers,+ name: params.name,+ url: params.url,+ },+ uri,+ }+ : { env: params.env, params, uri };+ const result = await ensureElectronIpc().mcp.readUiResource(+ serializeMcpIpcPayload(input) as any,+ );+ return deserializeMcpIpcPayload(result) as ReadResourceResult;+ }++ // POST: the params carry the plugin's auth and headers+ return (await toolsClient.mcp.readUiResource.mutate({ params, uri })) as ReadResourceResult;+ }+async getStreamableMcpServerManifest(params: {auth?: {@@ -287,7 +636,8 @@ class MCPService {// This avoids accessing user local services through remote server in productionif (isDesktop && isLocalOrPrivateUrl(params.url)) {// Note: IPC doesn't support AbortSignal yet- const serialized = serializeMcpIpcPayload(params);+ // With MCP Apps on, the tools only views call are listed and kept too+ const serialized = serializeMcpIpcPayload({ ...params, mcpApps: isMcpAppsOn() });const serializedResult = await ensureElectronIpc().mcp.getStreamableMcpServerManifest(serialized as any,);@@ -298,6 +648,30 @@ class MCPService {return toolsClient.mcp.getStreamableMcpServerManifest.query(params, { signal });}+ /**+ * Every tool a server only this machine can reach (stdio or local-network+ * HTTP) lists, including view-only ones, with each tool's MCP Apps+ * visibility. Desktop only.+ */+ async listLocalMcpTools(+ params:+ | {+ http: {+ auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };+ headers?: Record<string, string>;+ name: string;+ url: string;+ };+ }+ | { stdio: { args?: string[]; command: string; env?: Record<string, string>; name: string } },+ ): Promise<LocalMcpTool[]> {+ const serializedResult = await ensureElectronIpc().mcp.listTools(+ // With MCP Apps on, a server may list its view-only tools only then+ serializeMcpIpcPayload({ ...params, mcpApps: isMcpAppsOn() }) as any,+ );+ return deserializeMcpIpcPayload<LocalMcpTool[]>(serializedResult);+ }+async getStdioMcpServerManifest(stdioParams: {args?: string[];@@ -310,7 +684,8 @@ class MCPService {) {void _signal;// Note: IPC doesn't support AbortSignal yet- const serialized = serializeMcpIpcPayload({ ...stdioParams, metadata });+ // With MCP Apps on, the tools only views call are listed and kept too+ const serialized = serializeMcpIpcPayload({ ...stdioParams, mcpApps: isMcpAppsOn(), metadata });const serializedResult = await ensureElectronIpc().mcp.getStdioMcpServerManifest(serialized as any,);diff --git a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.tsindex 10e191dc8a5..54b16777284 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts@@ -363,6 +363,23 @@ describe('internal_executeClientTool', () => {});describe('MCP fallback', () => {+ it("resolves connectors for the run's agent, like the agent's runs do", async () => {+ hasExecutorMock.mockReturnValue(false);+ invokeMcpToolCallMock.mockResolvedValue({ content: 'ok', success: true });+ const { action } = setup();++ await action.internal_executeClientTool(+ makeData({ agentId: 'agt_1', apiName: 'echo', identifier: 'mcp-demo' } as any),+ { operationId: 'op-1' },+ );++ // A connector linked to an agent serves only that agent+ expect(invokeMcpToolCallMock).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ agentId: 'agt_1' }),+ );+ });+it('routes to mcpService when no builtin executor registered', async () => {hasExecutorMock.mockReturnValue(false);invokeMcpToolCallMock.mockResolvedValue({diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.tsindex c94886a8e66..4e9ece56917 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.ts@@ -114,6 +114,16 @@ describe('sendMessage: the gateway persists the user message a client-runtime semetadata: { contextSelections: [quote('queued')], steer: true },},],+ [+ 'a follow-up an MCP App view posted',+ {+ context,+ contextSelections: [quote('view')],+ editorData,+ message: 'What should I wear in Paris?',+ metadata: { mcpAppSource: { identifier: 'weather-demo' } },+ },+ ],])('%s', async (_label, params) => {const clientRow = await sendThroughClientRuntime(params);vi.restoreAllMocks();diff --git a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.tsindex 218a5d4ee03..2509b2b5195 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts@@ -258,6 +258,8 @@ export class ClientToolExecutionActionImpl {type: 'default',},{+ // Resolve connectors as this agent's runs do: a linked one serves only its agent+ agentId: agentId ?? operation?.context?.agentId ?? undefined,signal: operation?.abortController?.signal,topicId: operation?.context?.topicId ?? undefined,},diff --git a/src/store/chat/slices/operation/types.mcpAppSource.test.ts b/src/store/chat/slices/operation/types.mcpAppSource.test.tsnew file mode 100644index 00000000000..dd41596fc26--- /dev/null+++ b/src/store/chat/slices/operation/types.mcpAppSource.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { mergeQueuedMessages } from '@/store/chat/slices/operation/types';++const queued = (id: string, createdAt: number, identifier?: string) => ({+ content: id,+ createdAt,+ id,+ interruptMode: 'soft' as const,+ ...(identifier ? { metadata: { mcpAppSource: { identifier } } } : {}),+});++describe('mergeQueuedMessages MCP App source', () => {+ it('names the view when every merged message came from it', () => {+ expect(+ mergeQueuedMessages([queued('q1', 1, 'weather'), queued('q2', 2, 'weather')]).metadata+ ?.mcpAppSource,+ ).toEqual({ identifier: 'weather' });+ });++ it('drops the view once a typed message or another view is merged in', () => {+ expect(+ mergeQueuedMessages([queued('q1', 1, 'weather'), queued('q2', 2)]).metadata?.mcpAppSource,+ ).toBeUndefined();+ expect(+ mergeQueuedMessages([queued('q1', 1, 'weather'), queued('q2', 2, 'maps')]).metadata+ ?.mcpAppSource,+ ).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex a58966963ec..2a2e3234b0b 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -4,6 +4,7 @@ import type {MessageMetadata,UploadFileItem,} from '@lobechat/types';+import { mergeMcpAppSource } from '@lobechat/types';import type { QueuedFollowUpRequest } from '@/services/aiAgent';@@ -471,6 +472,13 @@ export const mergeQueuedMessages = (messages: QueuedMessage[]): MergedQueuedMess...(pageSelections.length ? { pageSelections } : undefined),};}, undefined);+ // The spread above keeps the last view; a merge keeps it only when every+ // message came from that view.+ if (metadata) {+ delete metadata.mcpAppSource;+ const mcpAppSource = mergeMcpAppSource(sorted.map((m) => m.metadata?.mcpAppSource));+ if (mcpAppSource) metadata.mcpAppSource = mcpAppSource;+ }// If any queued message pins the runtime, propagate it — a "server topic"// follow-up must stay on its rails even after merge.diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.test.ts b/src/store/chat/slices/plugin/actions/pluginTypes.test.tsnew file mode 100644index 00000000000..c429c35acd6--- /dev/null+++ b/src/store/chat/slices/plugin/actions/pluginTypes.test.ts@@ -0,0 +1,67 @@+import type { ChatToolPayload } from '@lobechat/types';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { mcpService } from '@/services/mcp';+import { useChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++vi.mock('@/utils/localStorage', () => {+ class AsyncLocalStorage<State> {+ getFromLocalStorageSync(): State {+ return {} as State;+ }++ async getFromLocalStorage(): Promise<State> {+ return {} as State;+ }++ async saveToLocalStorage(): Promise<void> {+ return undefined;+ }+ }++ return { AsyncLocalStorage };+});++vi.mock('@/services/message', () => ({+ messageService: { updateMessageError: vi.fn(), updateToolMessage: vi.fn() },+}));++const messageId = 'message-id';+const payload = {+ apiName: 'list',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'linear',+ type: 'mcp',+} as ChatToolPayload;++afterEach(() => {+ vi.restoreAllMocks();+});++describe('invokeMCPTypePlugin', () => {+ it("resolves connectors for the message's agent, like the agent's runs do", async () => {+ const invoke = vi+ .spyOn(mcpService, 'invokeMcpToolCall')+ .mockResolvedValue({ content: 'ok', state: { content: [] }, success: true } as any);+ useChatStore.setState({+ dbMessagesMap: {+ [messageMapKey({ agentId: 'agt_1' })]: [+ // No topic: the oversized-result archive (a server call) stays out of it+ { agentId: 'agt_1', id: messageId, role: 'tool' } as any,+ ],+ },+ messageOperationMap: {},+ messagesMap: { [messageMapKey({ agentId: 'agt_1' })]: [] },+ operations: {},+ optimisticUpdateToolMessage: vi.fn().mockResolvedValue(undefined),+ replaceMessages: vi.fn(),+ });++ await useChatStore.getState().invokeMCPTypePlugin(messageId, payload);++ // A connector linked to an agent serves only that agent+ expect(invoke).toHaveBeenCalledWith(payload, expect.objectContaining({ agentId: 'agt_1' }));+ });+});diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex e8b275f9e20..1f30b2e55b6 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -337,6 +337,8 @@ export class PluginTypesActionImpl {try {const result = await mcpService.invokeMcpToolCall(payload, {+ // Resolve connectors as this agent's runs do: a linked one serves only its agent+ agentId: message?.agentId ?? undefined,signal: abortController?.signal,topicId: message?.topicId,});diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.tsindex 6478682b575..d7b91517593 100644--- a/src/store/serverConfig/selectors.ts+++ b/src/store/serverConfig/selectors.ts@@ -18,6 +18,8 @@ export const serverConfigSelectors = {enableTopicPreview: (s: ServerConfigStore) => s.featureFlags.enableTopicPreview === true,enableLobehubSkill: (s: ServerConfigStore) => s.serverConfig.enableLobehubSkill || false,enableMagicLink: (s: ServerConfigStore) => s.serverConfig.enableMagicLink || false,+ /** Runtime flag `mcp_apps`: MCP Apps views in the conversation. */+ enableMcpApps: (s: ServerConfigStore) => s.featureFlags.enableMcpApps === true,enableMarketTrustedClient: (s: ServerConfigStore) =>s.serverConfig.enableMarketTrustedClient || false,enablePageCollab: (s: ServerConfigStore) => s.serverConfig.enablePageCollab || false,diff --git a/src/store/tool/slices/connector/action.localSync.test.ts b/src/store/tool/slices/connector/action.localSync.test.tsnew file mode 100644index 00000000000..b9711972180--- /dev/null+++ b/src/store/tool/slices/connector/action.localSync.test.ts@@ -0,0 +1,88 @@+import type * as LobeConst from '@lobechat/const';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { mcpService } from '@/services/mcp';++import { useToolStore } from '../../store';+import { initialConnectorState } from './initialState';++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<typeof LobeConst>()),+ isDesktop: true,+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ getForEdit: { query: vi.fn() },+ list: { query: vi.fn().mockResolvedValue([]) },+ syncTools: { mutate: vi.fn() },+ syncToolsFromClientById: { mutate: vi.fn() },+ },+ },+}));++vi.mock('@/services/mcp', () => ({ mcpService: { listLocalMcpTools: vi.fn() } }));++const listedTools = [+ { description: 'Show it', inputSchema: { type: 'object' }, name: 'show_dashboard' },+ { inputSchema: { type: 'object' }, name: 'load_page', visibility: ['app'] },+];++describe('syncConnectorTools on desktop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useToolStore.setState({ ...initialConnectorState });+ vi.mocked(mcpService.listLocalMcpTools).mockResolvedValue(listedTools);+ });++ it.each([+ [+ 'stdio',+ { mcpConnectionType: 'stdio', mcpStdioConfig: { args: [], command: 'dash-mcp' } },+ { stdio: { args: [], command: 'dash-mcp', env: undefined, name: 'dash' } },+ ],+ [+ 'local HTTP',+ { mcpConnectionType: 'http', mcpServerUrl: 'http://localhost:4000/mcp' },+ { http: { name: 'dash', url: 'http://localhost:4000/mcp' } },+ ],+ ])(+ 'syncs every %s tool, view-only ones included, with its visibility',+ async (_, detail, listInput) => {+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({+ credentials: null,+ identifier: 'dash',+ metadata: null,+ ...detail,+ } as any);++ const { result } = renderHook(() => useToolStore());+ await act(async () => {+ await result.current.syncConnectorTools('c1');+ });++ expect(mcpService.listLocalMcpTools).toHaveBeenCalledWith(expect.objectContaining(listInput));+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'c1',+ tools: [+ {+ description: 'Show it',+ inputSchema: { type: 'object' },+ toolName: 'show_dashboard',+ visibility: undefined,+ },+ {+ description: undefined,+ inputSchema: { type: 'object' },+ toolName: 'load_page',+ visibility: ['app'],+ },+ ],+ });+ expect(lambdaClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ },+ );+});diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex b5096fdf652..2f93c0529f7 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -10,7 +10,7 @@ import {} from '@/libs/replica';import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';import { lambdaClient } from '@/libs/trpc/client';-import { mcpService } from '@/services/mcp';+import { type LocalMcpTool, mcpService } from '@/services/mcp';import type { StoreSetter } from '@/store/types';import type { ToolStore } from '../../store';@@ -89,6 +89,9 @@ const fetchAgentBoundConnectorList = (): Promise<AgentBoundConnector[]> =>const fetchAgentConnectorList = ({ agentId }: { agentId: string }): Promise<ConnectorWithTools[]> =>lambdaClient.connector.listByAgent.query({ agentId }) as unknown as Promise<ConnectorWithTools[]>;+/** The base connector list's entry among the server-confirmed lists */+const BASE_LIST_KEY = '#base';+export const createConnectorSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>new ConnectorActionImpl(set, get, _api);@@ -105,6 +108,9 @@ export class ConnectorActionImpl {/** One connector lives in the base list, the aggregate and per-agent buckets. */readonly #connectorRows;readonly #connectors;+ /** `${scope}|${list}` entries the server answered in this session (not painted from storage) */+ readonly #confirmed = new Set<string>();+ readonly #confirming = new Map<string, Promise<void>>();readonly #get: () => ToolStore;readonly #set: Setter;@@ -166,6 +172,11 @@ export class ConnectorActionImpl {this.#connectors.ensureScope(scope);this.#agentBoundConnectors.ensureScope(scope);this.#agentConnectors.ensureScope(scope);+ // The lists were dropped with the scope, so were their confirmations:+ // coming back to a scope must load its lists from the server again+ for (const id of this.#confirmed) {+ if (!id.startsWith(`${scope}|`)) this.#confirmed.delete(id);+ }};/**@@ -209,8 +220,12 @@ export class ConnectorActionImpl {fetchConnectors = async (): Promise<void> => {const scope = cacheScope.get();const pending = this.#connectors.fetch(LIST_PARAMS, { fresh: true });- if (!this.#get().isConnectorsInit) await this.#connectors.hydrate(LIST_PARAMS, scope);- await pending;+ // Awaited together, so a request that fails while storage paints is still handled+ const [, result] = await Promise.all([+ this.#get().isConnectorsInit ? undefined : this.#connectors.hydrate(LIST_PARAMS, scope),+ pending,+ ]);+ if (result.applied) this.#confirmed.add(`${scope}|${BASE_LIST_KEY}`);};/**@@ -220,9 +235,18 @@ export class ConnectorActionImpl {* (delete / sync / permission reset) updates that list too. On base-only* pages `isAgentBoundInit` is false, so this stays a single query.*/+ /** Agents whose own connectors are loaded, so every write keeps them current. */+ #loadedAgentIds = (): string[] => {+ const init = this.#get().agentConnectorsInit;+ return Object.keys(init).filter((agentId) => init[agentId]);+ };+#refreshConnectorLists = async (): Promise<void> => {const tasks = [this.fetchConnectors()];if (this.#get().isAgentBoundInit) tasks.push(this.fetchAgentBoundConnectors());+ // The per-agent lists decide what a view's tool call needs (approval,+ // availability), so they must not keep a connector's old state either+ for (const agentId of this.#loadedAgentIds()) tasks.push(this.fetchAgentConnectors(agentId));await Promise.all(tasks);};@@ -249,9 +273,58 @@ export class ConnectorActionImpl {const scope = cacheScope.get();const params = { agentId };const pending = this.#agentConnectors.fetch(params, { fresh: true });- if (!this.#get().agentConnectorsInit[agentId])- await this.#agentConnectors.hydrate(params, scope);- await pending;+ // Awaited together, so a request that fails while storage paints is still handled+ const [, result] = await Promise.all([+ this.#get().agentConnectorsInit[agentId]+ ? undefined+ : this.#agentConnectors.hydrate(params, scope),+ pending,+ ]);+ if (result.applied) this.#confirmed.add(`${scope}|${agentId}`);+ };++ /**+ * Whether the base connector list (and `agentId`'s own, if given) came from+ * the server in this cache scope. A list painted from storage is not: its+ * permissions may be stale, so nothing that authorizes a call may trust it.+ */+ isConnectorListConfirmed = (agentId?: string): boolean => {+ const scope = cacheScope.get();+ return (+ this.#confirmed.has(`${scope}|${BASE_LIST_KEY}`) &&+ (!agentId || this.#confirmed.has(`${scope}|${agentId}`))+ );+ };++ /**+ * Load the connector lists from the server unless this cache scope already+ * has, for callers that resolve an identifier the way an agent's runs do and+ * act on what they find (a view's tool-call policy, its resource read): the+ * base list, and `agentId`'s own tools if given. Joins a load in flight.+ *+ * `revalidate` loads them even when confirmed, for a caller that authorizes+ * by them: a permission may have changed since, in another tab or by another+ * workspace member.+ */+ ensureConfirmedConnectors = async (+ agentId?: string,+ { revalidate = false }: { revalidate?: boolean } = {},+ ): Promise<void> => {+ const confirm = (key: string, load: () => Promise<void>) => {+ const id = `${cacheScope.get()}|${key}`;+ if (!revalidate && this.#confirmed.has(id)) return;+ let loading = this.#confirming.get(id);+ if (!loading) {+ loading = load().finally(() => this.#confirming.delete(id));+ this.#confirming.set(id, loading);+ }+ return loading;+ };++ await Promise.all([+ confirm(BASE_LIST_KEY, this.fetchConnectors),+ agentId ? confirm(agentId, () => this.fetchAgentConnectors(agentId)) : undefined,+ ]);};/** Copy a user connector into an agent-owned, independently editable row. */@@ -398,16 +471,19 @@ export class ConnectorActionImpl {const isLocalHttp = !!detail.mcpServerUrl && isLocalOrPrivateUrl(detail.mcpServerUrl);if (!isStdio && !isLocalHttp) return false;- let api: Array<{ description?: string; name: string; parameters?: Record<string, unknown> }>;+ // The full tool list, not a manifest: a manifest leaves out view-only+ // tools, yet a view's call must find its tool synced.+ let tools: LocalMcpTool[];if (isStdio) {if (!detail.mcpStdioConfig?.command) throw new Error('Connector is missing stdio config');- const manifest = await mcpService.getStdioMcpServerManifest({- args: detail.mcpStdioConfig.args ?? [],- command: detail.mcpStdioConfig.command,- env: detail.mcpStdioConfig.env ?? undefined,- name: detail.identifier,+ tools = await mcpService.listLocalMcpTools({+ stdio: {+ args: detail.mcpStdioConfig.args ?? [],+ command: detail.mcpStdioConfig.command,+ env: detail.mcpStdioConfig.env ?? undefined,+ name: detail.identifier,+ },});- api = manifest.api ?? [];} else {const credentials = detail.credentials;const auth =@@ -423,21 +499,18 @@ export class ConnectorActionImpl {const customHeaders = detail.metadata?.customHeaders as Record<string, string> | undefined;const headers =headerCreds || customHeaders ? { ...headerCreds, ...customHeaders } : undefined;- const manifest = await mcpService.getStreamableMcpServerManifest({- auth,- headers,- identifier: detail.identifier,- url: detail.mcpServerUrl!,+ tools = await mcpService.listLocalMcpTools({+ http: { auth, headers, name: detail.identifier, url: detail.mcpServerUrl! },});- api = manifest.api ?? [];}await lambdaClient.connector.syncToolsFromClientById.mutate({id,- tools: api.map((a) => ({- description: a.description,- inputSchema: a.parameters,- toolName: a.name,+ tools: tools.map((tool) => ({+ description: tool.description,+ inputSchema: tool.inputSchema,+ toolName: tool.name,+ visibility: tool.visibility,})),});return true;@@ -515,17 +588,22 @@ export class ConnectorActionImpl {tools: c.tools.map((t) => (t.id === toolId ? { ...t, permission } : t)),}));- const base = this.#connectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools);- const bound = this.#agentBoundConnectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools);+ const overlays = [+ this.#connectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools),+ this.#agentBoundConnectors.beginOptimistic(CONNECTOR_LIST_KEY, patchTools),+ // A loaded agent list may hold the same tool, and a view's tool call+ // reads its permission there+ ...this.#loadedAgentIds().map((agentId) =>+ this.#agentConnectors.beginOptimistic(agentId, patchTools),+ ),+ ];try {await lambdaClient.connector.updateToolPermission.mutate({ permission, toolId });- base.commit();- bound.commit();+ for (const overlay of overlays) overlay.commit();} catch {// Roll back the overlays, then rebuild from the server.- base.rollback();- bound.rollback();+ for (const overlay of overlays) overlay.rollback();await this.#refreshConnectorLists();}};diff --git a/src/store/tool/slices/connector/replica.test.ts b/src/store/tool/slices/connector/replica.test.tsindex 64d9f7eb147..bc0a32bf1bc 100644--- a/src/store/tool/slices/connector/replica.test.ts+++ b/src/store/tool/slices/connector/replica.test.ts@@ -31,6 +31,7 @@ vi.mock('@/libs/trpc/client', () => ({list: { query: vi.fn() },listAgentBound: { query: vi.fn() },listByAgent: { query: vi.fn() },+ resetPermissions: { mutate: vi.fn() },updateToolPermission: { mutate: vi.fn() },},},@@ -143,6 +144,88 @@ describe('connector slice replica', () => {expect(useToolStore.getState().isConnectorsInit).toBe(false);});+ it('loads the base and an agent list from the server once, for callers acting on them', async () => {+ listQuery.mockResolvedValue([connector('c1')]);+ listByAgentQuery.mockResolvedValue([connector('c1', 'needs_approval')]);++ await useToolStore.getState().ensureConfirmedConnectors('a1');+ await useToolStore.getState().ensureConfirmedConnectors('a1');++ expect(listQuery).toHaveBeenCalledTimes(1);+ expect(listByAgentQuery).toHaveBeenCalledTimes(1);+ expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(true);+ expect(useToolStore.getState().agentConnectors.a1).toHaveLength(1);+ });++ it('loads confirmed lists again for a caller that revalidates', async () => {+ listQuery.mockResolvedValue([connector('c1')]);+ listByAgentQuery.mockResolvedValue([connector('c1')]);+ await useToolStore.getState().ensureConfirmedConnectors('a1');++ listByAgentQuery.mockResolvedValue([connector('c1', 'needs_approval')]);+ await useToolStore.getState().ensureConfirmedConnectors('a1', { revalidate: true });++ expect(listQuery).toHaveBeenCalledTimes(2);+ expect(listByAgentQuery).toHaveBeenCalledTimes(2);+ expect(useToolStore.getState().agentConnectors.a1[0].tools[0].permission).toBe(+ 'needs_approval',+ );+ });++ it('does not count a list painted from storage as confirmed until the server answers', async () => {+ // A stored copy may hold permissions the server has since tightened+ await agentConnectorsResource.storage!.set(+ { queryKey: AGENT_STORAGE_KEY, scope },+ { data: [connector('c1', 'auto')], updatedAt: 1 },+ );+ listQuery.mockResolvedValue([]);+ let answer!: (rows: unknown[]) => void;+ listByAgentQuery.mockImplementation(() => new Promise((resolve) => (answer = resolve)));++ const ensured = useToolStore.getState().ensureConfirmedConnectors('a1');+ await vi.waitFor(() => expect(useToolStore.getState().agentConnectorsInit.a1).toBe(true));+ expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(false);++ answer([connector('c1', 'needs_approval')]);+ await ensured;+ expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(true);+ expect(useToolStore.getState().agentConnectors.a1[0].tools[0].permission).toBe(+ 'needs_approval',+ );+ });++ it('loads the lists again after leaving a scope and coming back to it', async () => {+ listQuery.mockResolvedValue([connector('c1')]);+ listByAgentQuery.mockResolvedValue([connector('c1')]);+ await useToolStore.getState().ensureConfirmedConnectors('a1');+ const home = scope;++ const elsewhere = `${scope.split(':')[0]}:ws-2`;+ useScope(elsewhere);+ broadcastCacheScope(elsewhere);+ useScope(home);+ broadcastCacheScope(home);++ // Switching dropped the lists, so their confirmations can't stand+ expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(false);+ listByAgentQuery.mockClear();+ await useToolStore.getState().ensureConfirmedConnectors('a1');+ expect(listByAgentQuery).toHaveBeenCalledTimes(1);+ expect(useToolStore.getState().agentConnectors.a1).toHaveLength(1);+ });++ it('leaves a list unconfirmed when the server fails, and tries again next time', async () => {+ listQuery.mockResolvedValue([]);+ listByAgentQuery.mockRejectedValueOnce(new Error('offline'));++ await expect(useToolStore.getState().ensureConfirmedConnectors('a1')).rejects.toThrow();+ expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(false);++ listByAgentQuery.mockResolvedValueOnce([]);+ await useToolStore.getState().ensureConfirmedConnectors('a1');+ expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(true);+ });+// These resources have no `useSync` mount: nothing re-renders them on a scope// switch, so the engine would keep the previous identity's views — and their// init flags, which is what makes every gated consumer skip the fetch for the@@ -260,6 +343,49 @@ describe('connector slice replica', () => {expect(useToolStore.getState().connectors[0].tools[0].permission).toBe('auto');});+ it("changes a tool's permission in a loaded agent's list too, and rolls it back there", async () => {+ listQuery.mockResolvedValue([connector('c1', 'auto')]);+ listByAgentQuery.mockResolvedValue([connector('c1', 'auto')]);+ await useToolStore.getState().fetchConnectors();+ await useToolStore.getState().fetchAgentConnectors('a1');++ updateToolPermissionMutation.mockResolvedValueOnce(undefined);+ await useToolStore.getState().updateToolPermission('c1-tool', 'needs_approval');+ // A view's tool call reads the agent's list: it must not keep allowing the tool+ expect(useToolStore.getState().agentConnectors.a1[0].tools[0].permission).toBe(+ 'needs_approval',+ );++ let rejectWrite!: (error: unknown) => void;+ updateToolPermissionMutation.mockImplementation(+ () => new Promise((_resolve, reject) => (rejectWrite = reject)),+ );+ listByAgentQuery.mockResolvedValue([connector('c1', 'needs_approval')]);+ const operation = useToolStore.getState().updateToolPermission('c1-tool', 'auto');+ expect(useToolStore.getState().agentConnectors.a1[0].tools[0].permission).toBe('auto');++ rejectWrite(new Error('boom'));+ await operation;+ expect(useToolStore.getState().agentConnectors.a1[0].tools[0].permission).toBe(+ 'needs_approval',+ );+ });++ it("refreshes a loaded agent's list after a connector write", async () => {+ listQuery.mockResolvedValue([connector('c1')]);+ listByAgentQuery.mockResolvedValue([connector('c1')]);+ await useToolStore.getState().fetchConnectors();+ await useToolStore.getState().fetchAgentConnectors('a1');+ listByAgentQuery.mockClear();++ vi.mocked(lambdaClient.connector.resetPermissions.mutate).mockResolvedValueOnce(+ undefined as any,+ );+ await useToolStore.getState().resetConnectorPermissions('c1');++ expect(listByAgentQuery).toHaveBeenCalledWith({ agentId: 'a1' });+ });+it('keeps a deleted connector mounted until the server confirms, then drops it everywhere', async () => {listQuery.mockResolvedValue([connector('c1')]);listAgentBoundQuery.mockResolvedValue([connector('c1')]);diff --git a/src/store/tool/slices/connector/selectors.runtime.test.ts b/src/store/tool/slices/connector/selectors.runtime.test.tsindex 2b0e79b9381..1e871665be1 100644--- a/src/store/tool/slices/connector/selectors.runtime.test.ts+++ b/src/store/tool/slices/connector/selectors.runtime.test.ts@@ -61,3 +61,32 @@ describe('marketplace MCP runtime manifests', () => {).toEqual([]);});});++describe('connectorSelectors.connectorByIdentifierForAgent', () => {+ const state = (connectors: ConnectorWithTools[], agentConnectors = {}) =>+ ({ agentConnectors, connectors }) as unknown as ToolStore;+ const mountedBy = (agentId: string) =>+ connector({ id: 'base', metadata: { mountedByAgentId: agentId } });++ it('does not hand one agent a base connector another agent mounted', () => {+ const s = state([mountedBy('agt_b')]);++ expect(connectorSelectors.connectorByIdentifierForAgent('oauth-market', 'agt_a')(s)).toBe(+ undefined,+ );+ // Nor a call that names no agent at all+ expect(connectorSelectors.connectorByIdentifierForAgent('oauth-market')(s)).toBe(undefined);+ });++ it('resolves a base connector that is free or mounted by this agent', () => {+ expect(+ connectorSelectors.connectorByIdentifierForAgent(+ 'oauth-market',+ 'agt_a',+ )(state([mountedBy('agt_a')]))?.id,+ ).toBe('base');+ expect(+ connectorSelectors.connectorByIdentifierForAgent('oauth-market')(state([connector({})]))?.id,+ ).toBe('c1');+ });+});diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex 65e96848a44..6ada04601b2 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -90,6 +90,37 @@ const agentConnectors =(s: ToolStore): ConnectorWithTools[] =>s.agentConnectors?.[agentId] ?? [];+/**+ * The connector a conversation of `agentId` resolves `identifier` to, mirroring+ * the server's agent-aware resolution: the agent's own row first (agent-owned+ * over mounted), else the base connector. Agent tools are only known once that+ * agent's list has loaded.+ */+/** Mounted (locked) to an agent other than `agentId`; without one, to any agent. */+const isMountedByAnotherAgent = (connector: ConnectorWithTools, agentId?: string) => {+ const mountedBy = connector.metadata?.mountedByAgentId;++ return typeof mountedBy === 'string' && mountedBy !== '' && mountedBy !== agentId;+};++const connectorByIdentifierForAgent =+ (identifier: string, agentId?: string) =>+ (s: ToolStore): ConnectorWithTools | undefined => {+ const agentRows = agentId+ ? (s.agentConnectors?.[agentId] ?? []).filter((c) => c.identifier === identifier)+ : [];++ return (+ agentRows.find((c) => c.agentId === agentId) ??+ agentRows[0] ??+ // A base connector another agent mounted serves only that agent, as the+ // server's scope rule has it (`ConnectorModel.scopePredicate`)+ (s.connectors ?? []).find(+ (c) => c.identifier === identifier && !isMountedByAnotherAgent(c, agentId),+ )+ );+ };+const isAgentConnectorsInit =(agentId: string) =>(s: ToolStore): boolean =>@@ -129,6 +160,7 @@ export const connectorSelectors = {connectedConnectors,connectorById,connectorByIdentifier,+ connectorByIdentifierForAgent,connectorList,isAgentConnectorsInit,connectorToolsGrouped,diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.tsindex 7e0e598a68a..aab1ea1ca07 100644--- a/src/store/tool/slices/connector/types.ts+++ b/src/store/tool/slices/connector/types.ts@@ -6,6 +6,8 @@ export interface ConnectorTool {displayName: string | null;id: string;inputSchema: Record<string, unknown> | null;+ /** Synced metadata; `visibility` is the MCP tool's `_meta.ui.visibility`. */+ metadata?: Record<string, unknown> | null;permission: ConnectorToolPermission;toolName: string;userConnectorId: string;diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.tsindex b2a3fbafc0e..58bbdff6d12 100644--- a/src/store/tool/slices/plugin/action.ts+++ b/src/store/tool/slices/plugin/action.ts@@ -1,11 +1,14 @@import { type Schema, type ValidationResult } from '@cfworker/json-schema';import { type LobeTool } from '@lobechat/types';+import { type ReadResourceResult } from '@modelcontextprotocol/client';import { type SWRResponse } from 'swr';import { MESSAGE_CANCEL_FLAT } from '@/const/message';import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';import { useClientDataSWR } from '@/libs/swr';+import { mcpAppKeys } from '@/libs/swr/keys';+import { mcpService } from '@/services/mcp';import { pluginService } from '@/services/plugin';import { type StoreSetter } from '@/store/types';import { type PluginInstallError } from '@/types/tool/plugin';@@ -216,6 +219,28 @@ export class PluginActionImpl {useFetchInstalledPlugins = (enable: boolean): ReplicaSyncResult =>this.#installedPlugins.useSync(INSTALLED_PLUGINS_PARAMS, { enabled: enable });+ /**+ * The `ui://` resource (HTML view) an MCP App tool result renders with, read+ * from `server`, the one the tool ran on, as `agentId`'s runs resolve it, and+ * where it ran (`onThisDevice`). The HTML is only the view's: it stays in this+ * request's cache, not in the store.+ */+ useFetchMcpAppResource = (+ identifier: string,+ resourceUri: string,+ {+ agentId,+ onThisDevice = false,+ server,+ }: { agentId?: string; onThisDevice?: boolean; server?: string },+ ): SWRResponse<ReadResourceResult | undefined> =>+ useClientDataSWR(+ mcpAppKeys.resource(identifier, resourceUri, { agentId, onThisDevice, server }),+ () =>+ mcpService.readMcpAppResource(identifier, resourceUri, { agentId, onThisDevice, server }),+ { revalidateOnFocus: false, revalidateOnReconnect: false },+ );+useCheckPluginsIsInstalled = (enable: boolean, plugins: string[]): SWRResponse => {return useClientDataSWR(enable ? plugins : null, this.#get().checkPluginsIsInstalled);};diff --git a/src/store/tool/slices/plugin/selectors.ts b/src/store/tool/slices/plugin/selectors.tsindex a518609d230..11710a0a773 100644--- a/src/store/tool/slices/plugin/selectors.ts+++ b/src/store/tool/slices/plugin/selectors.ts@@ -23,6 +23,10 @@ const installedPlugins = (s: ToolStoreState) => s.installedPlugins;const isInstalledPluginsCacheOnly = (s: ToolStoreState) =>s.installedPluginsReplica?.entries[INSTALLED_PLUGINS_KEY]?.source === 'storage';+/** Whether the list holds the server's full records (not unloaded, not the cached projection). */+const isInstalledPluginsServerConfirmed = (s: ToolStoreState) =>+ s.installedPluginsReplica?.entries[INSTALLED_PLUGINS_KEY]?.source === 'server';+/*** The full installed-plugin records — settings and MCP connection included —* that tool assembly, tool execution, edit forms and writes may act on. Empty@@ -142,6 +146,7 @@ export const pluginSelectors = {installedPluginMetaList,installedPlugins,isInstalledPluginsCacheOnly,+ isInstalledPluginsServerConfirmed,isPluginHasUI,isPluginInstalled,storeAndInstallPluginsIdList,