Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧩 feat: MCP Apps support (#13831)
Dustin Healy7b27e7941e11
diff --git a/Dockerfile b/Dockerfileindex ccf6f27073..d89e6c60f5 100644--- a/Dockerfile+++ b/Dockerfile@@ -56,6 +56,7 @@ RUN \COPY --chown=node:node . .+ARG VITE_MCP_SANDBOX_URL=RUN \# React client build with configurable memoryNODE_OPTIONS="--max-old-space-size=${NODE_MAX_OLD_SPACE_SIZE}" npm run frontend && \diff --git a/Dockerfile.multi b/Dockerfile.multiindex 57c6e9b5b9..2e83773454 100644--- a/Dockerfile.multi+++ b/Dockerfile.multi@@ -87,6 +87,7 @@ COPY --from=client-package-build /app/packages/client/dist /app/packages/client/COPY --from=client-package-build /app/packages/client/src /app/packages/client/srcCOPY --from=client-package-build /app/packages/client/tailwind.preset.cjs /app/packages/client/tailwind.preset.cjsCOPY --from=client-package-build /app/packages/client/tailwind.compat.cjs /app/packages/client/tailwind.compat.cjs+ARG VITE_MCP_SANDBOX_URL=ARG NODE_MAX_OLD_SPACE_SIZEENV NODE_OPTIONS="--max-old-space-size=${NODE_MAX_OLD_SPACE_SIZE}"RUN npm run build@@ -119,6 +120,7 @@ COPY --from=data-provider-build /app/packages/data-provider/dist ./packages/dataCOPY --from=data-schemas-build /app/packages/data-schemas/dist ./packages/data-schemas/distCOPY --from=api-package-build /app/packages/api/dist ./packages/api/distCOPY --from=client-build /app/client/dist ./client/dist+COPY --from=client-build /app/client/public/mcp-sandbox.html ./client/public/mcp-sandbox.html# Propagate build metadata into runtime env so /api/config can expose it.# Declared here (after the heavy install/copy steps) so that commit/date# changing on every CI run does not bust the cache for those layers.diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.jsindex e94e2b1de0..cc7ef068af 100644--- a/api/app/clients/tools/util/handleTools.js+++ b/api/app/clients/tools/util/handleTools.js@@ -28,6 +28,7 @@ const {codeExecutionAuthHeaders,getCodeFileLocation,resolveCodeExecutionContext,+ resolveMCPClientCapabilityProfile,} = require('@librechat/api');const {AuthType,@@ -37,6 +38,7 @@ const {EToolResources,PermissionTypes,AgentCapabilities,+ resolveMCPAppsPolicy,} = require('librechat-data-provider');const {availableTools,@@ -625,6 +627,15 @@ const loadTools = async ({const loadedTools = (await Promise.all(toolPromises)).flatMap((plugin) => plugin || []);const safeUser = createSafeUser(options.req?.user);+ const admittedAppConfig = options.req?.config;+ const admittedMCPAppsPolicy = resolveMCPAppsPolicy(+ admittedAppConfig?.mcpSettings?.apps,+ admittedAppConfig?.mcpAppSandbox,+ admittedAppConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ admittedAppConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ admittedAppConfig?.mcpAppSandbox?.url,+ );+ const capabilityProfile = resolveMCPClientCapabilityProfile(admittedMCPAppsPolicy);const requestScopedConnections =options.requestScopedConnections ?? getMCPRequestContext(options.req, options.res);/**@@ -652,33 +663,89 @@ const loadTools = async ({}),});- loadedTools.push(- ...(await loadMCPTools({- userId: user,- requestedTools: requestedMCPTools,- availableTools: options.mcpAvailableTools,- createTools: createMCPTools,- createTool: createMCPTool,- getAvailableTools: getMCPServerTools,- context: {- mcpPermissionContext,- signal,- user: safeUser,- userMCPAuthMap,- configServers,- requestBody: options.requestBody ?? options.req?.body,- requestScopedConnections,- res: options.res,- upstreamTokenProvider,- upstreamTokenProviderResolver,- oboIdentityContext,- streamId: options.req?._resumableStreamId || null,- jobCreatedAt: options.jobCreatedAt,- model: agent?.model ?? model,- provider: agent?.provider ?? endpoint,- },- })),- );+ for (const [serverName, toolConfigs] of Object.entries(requestedMCPTools)) {+ index++;+ /** @type {LCAvailableTools} */+ let availableTools = options.mcpAvailableTools?.[serverName];+ for (const config of toolConfigs) {+ try {+ if (failedMCPServers.has(serverName)) {+ continue;+ }+ const mcpParams = {+ mcpPermissionContext,+ index,+ signal,+ user: safeUser,+ userMCPAuthMap,+ configServers,+ requestBody: options.requestBody ?? options.req?.body,+ requestScopedConnections,+ res: options.res,+ upstreamTokenProvider,+ mcpApps: admittedMCPAppsPolicy,+ upstreamTokenProviderResolver,+ oboIdentityContext,+ streamId: options.req?._resumableStreamId || null,+ jobCreatedAt: options.jobCreatedAt,+ model: agent?.model ?? model,+ serverName: config.serverName,+ provider: agent?.provider ?? endpoint,+ config: config.config,+ };++ if (config.type === 'all' && toolConfigs.length === 1) {+ /** Handle async loading for single 'all' tool config */+ mcpToolPromises.push(+ createMCPTools(mcpParams).catch((error) => {+ logger.error(`Error loading ${serverName} tools:`, error);+ return null;+ }),+ );+ continue;+ }+ if (!availableTools) {+ try {+ availableTools = await getMCPServerTools(+ safeUser.id,+ serverName,+ config.config,+ capabilityProfile,+ );+ } catch (error) {+ logger.error(`Error fetching available tools for MCP server ${serverName}:`, error);+ }+ }++ /** Handle synchronous loading */+ const mcpTool =+ config.type === 'all'+ ? await createMCPTools(mcpParams)+ : await createMCPTool({+ ...mcpParams,+ availableTools,+ toolKey: config.toolKey,+ onAvailableTools: (tools) => {+ availableTools = tools;+ },+ });++ if (Array.isArray(mcpTool)) {+ loadedTools.push(...mcpTool);+ } else if (mcpTool) {+ loadedTools.push(mcpTool);+ } else {+ failedMCPServers.add(serverName);+ logger.warn(+ `MCP tool creation failed for "${config.toolKey}", server may be unavailable or unauthenticated.`,+ );+ }+ } catch (error) {+ logger.error(`Error loading MCP tool for server ${serverName}:`, error);+ }+ }+ }+ loadedTools.push(...(await Promise.all(mcpToolPromises)).flatMap((plugin) => plugin || []));return { loadedTools, toolContextMap, dynamicToolContextMap, primedCodeFiles };};diff --git a/api/app/clients/tools/util/handleTools.test.js b/api/app/clients/tools/util/handleTools.test.jsindex f1c885690c..75433afdff 100644--- a/api/app/clients/tools/util/handleTools.test.js+++ b/api/app/clients/tools/util/handleTools.test.js@@ -94,7 +94,7 @@ jest.mock('~/config', () => ({const { Calculator } = require('@librechat/agents');const { Tools, Constants } = require('librechat-data-provider');-const { ASK_USER_QUESTION_TOOL_NAME } = require('@librechat/api');+const { ASK_USER_QUESTION_TOOL_NAME, STANDARD_MCP_CAPABILITY_PROFILE } = require('@librechat/api');const { User } = require('~/db/models');const PluginService = require('~/server/services/PluginService');@@ -571,6 +571,7 @@ describe('Tool Handlers', () => {fakeUser._id.toString(),serverName,serverConfig,+ STANDARD_MCP_CAPABILITY_PROFILE,);expect(mockCreateMCPTool).toHaveBeenCalledWith(expect.objectContaining({@@ -615,6 +616,14 @@ describe('Tool Handlers', () => {req: {user: { id: fakeUser._id.toString(), role: 'USER' },body: {},+ config: {+ mcpSettings: { apps: true },+ mcpAppSandbox: {+ maxPersistedAppBytes: 2048,+ maxAdmissionRequestsPerMinute: 12,+ url: 'https://sandbox.example.com',+ },+ },},},});@@ -629,6 +638,13 @@ describe('Tool Handlers', () => {expect.objectContaining({toolKey: normalizedKey,serverName: rawServerName,+ mcpApps: expect.objectContaining({+ enabled: true,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 2048,+ maxAdmissionRequestsPerMinute: 12,+ sandboxUrl: 'https://sandbox.example.com',+ }),}),);});diff --git a/api/jest.config.js b/api/jest.config.jsindex d0cabf39c5..588ee04231 100644--- a/api/jest.config.js+++ b/api/jest.config.js@@ -8,6 +8,7 @@ const esModules = ['@langchain/langgraph-checkpoint','@langchain/langgraph-sdk','@mistralai/mistralai',+ '@modelcontextprotocol/ext-apps','uuid','sanitize-html','htmlparser2',diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.jsindex b94e7f3e7a..c3c3262cf9 100644--- a/api/server/controllers/agents/__tests__/callbacks.spec.js+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js@@ -9,6 +9,14 @@ jest.mock('@librechat/api', () => ({sendEvent: jest.fn(),writeAttachmentEvent: jest.fn(),createOwnedToolEndHandler: jest.fn((callback) => ({ handle: callback })),+ getAttachmentOwnership: jest.fn((metadata) => {+ const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id;+ const stepId = metadata?.stepId;+ return {+ ...(typeof agentId === 'string' && agentId.length > 0 ? { agentId } : {}),+ ...(typeof stepId === 'string' && stepId.length > 0 ? { stepId } : {}),+ };+ }),GenerationJobManager: {emitChunk: jest.fn(),},@@ -684,6 +692,69 @@ describe('createToolEndCallback', () => {},);+ it.each(['createToolEndCallback', 'createResponsesToolEndCallback'])(+ '%s preserves distinct UI owners when provider tool-call IDs repeat',+ async (factoryName) => {+ const { getAttachmentOwnership, writeAttachmentEvent } = require('@librechat/api');+ const tracker = { nextSequence: jest.fn().mockReturnValueOnce(1).mockReturnValueOnce(2) };+ res.headersSent = true;+ res.writableEnded = false;+ const toolEndCallback = require('../callbacks')[factoryName]({+ req,+ res,+ tracker,+ artifactPromises,+ });++ for (const [agentId, stepId] of [+ ['agent-a', 'step-a'],+ ['agent-b', 'step-b'],+ ]) {+ await toolEndCallback(+ {+ output: {+ tool_call_id: 'call_0',+ artifact: {+ [Tools.ui_resources]: {+ data: [{ uri: `ui://${agentId}`, resourceId: agentId }],+ },+ },+ },+ },+ {+ run_id: 'run456',+ thread_id: 'thread789',+ executingAgentId: agentId,+ stepId,+ },+ );+ }++ const results = await Promise.all(artifactPromises);+ expect(+ results.map(({ agentId, stepId, toolCallId, ui_resources }) => ({+ agentId,+ stepId,+ toolCallId,+ resourceId: ui_resources[0].resourceId,+ })),+ ).toEqual([+ { agentId: 'agent-a', stepId: 'step-a', toolCallId: 'call_0', resourceId: 'agent-a' },+ { agentId: 'agent-b', stepId: 'step-b', toolCallId: 'call_0', resourceId: 'agent-b' },+ ]);+ expect(getAttachmentOwnership).toHaveBeenCalledTimes(2);++ if (factoryName === 'createResponsesToolEndCallback') {+ expect(writeAttachmentEvent.mock.calls.map((call) => call[2])).toEqual(results);+ } else {+ const emitted = res.write.mock.calls.map(([event]) =>+ JSON.parse(event.match(/^event: attachment\ndata: (.+)\n\n$/)[1]),+ );+ expect(emitted).toEqual(results);+ }+ },+ );+describe('ui_resources artifact handling', () => {it('should process ui_resources artifact and return attachment when headers not sent', async () => {const toolEndCallback = createToolEndCallback({ req, res, artifactPromises });diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.jsindex d762976f31..cba7336418 100644--- a/api/server/controllers/agents/callbacks.js+++ b/api/server/controllers/agents/callbacks.js@@ -33,6 +33,7 @@ const {shouldSignalSandboxStart,getToolInputValidationDetails,captureSubagentIdentity,+ getAttachmentOwnership,collectToolCallIds,createToolTimingAdapter,} = require('@librechat/api');@@ -45,15 +46,6 @@ function isHostFileAuthoringArtifact(artifact) {return artifact?.[HOST_FILE_AUTHORING_ARTIFACT_KEY] === true;}-function getAttachmentOwnership(metadata) {- const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id;- const stepId = metadata?.stepId;- return {- ...(typeof agentId === 'string' && agentId.length > 0 ? { agentId } : {}),- ...(typeof stepId === 'string' && stepId.length > 0 ? { stepId } : {}),- };-}-function addStatefulWorkspaceChange(attachment, artifact, executionProfile) {if (!attachment || executionProfile !== 'stateful' || !isHostFileAuthoringArtifact(artifact)) {return attachment;@@ -1018,6 +1010,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo(async () => {const attachment = {type: Tools.ui_resources,+ ...getAttachmentOwnership(metadata),messageId: metadata.run_id,toolCallId: output.tool_call_id,conversationId: metadata.thread_id,@@ -1391,6 +1384,7 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises })const attachment = {type: Tools.ui_resources,toolCallId: output.tool_call_id,+ ...getAttachmentOwnership(metadata),[Tools.ui_resources]: output.artifact[Tools.ui_resources].data,};// For Responses API, always emit attachment during streamingdiff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.jsindex 5287f81be6..e81d00aee4 100644--- a/api/server/controllers/mcp.js+++ b/api/server/controllers/mcp.js@@ -32,6 +32,7 @@ const {PermissionTypes,MCP_USER_INPUT_FIELDS,MCPServerUserInputSchema,+ resolveMCPAppsPolicy,} = require('librechat-data-provider');const {resolveConfigServers,@@ -136,6 +137,13 @@ const getMCPTools = async (req, res) => {}const mcpConfig = await resolveAllMcpConfigs(userId, req.user);+ const mcpApps = resolveMCPAppsPolicy(+ req.config?.mcpSettings?.apps,+ undefined,+ req.config?.mcpAppSandbox?.maxPersistedAppBytes,+ req.config?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ req.config?.mcpAppSandbox?.url,+ );/*** A server whose normalized name is claimed by an earlier server produces* IDENTICAL model-facing tool keys — selecting its tools would silently@@ -186,6 +194,7 @@ const getMCPTools = async (req, res) => {oboIdentityContext,signal: catalogAbortController.signal,recoveryPolicy: req.config?.mcpSettings?.catalogRecovery,+ mcpApps,});} finally {res.off('close', abortCatalogLoad);diff --git a/api/server/controllers/mcpApps.js b/api/server/controllers/mcpApps.jsnew file mode 100644index 0000000000..de43bf1f57--- /dev/null+++ b/api/server/controllers/mcpApps.js@@ -0,0 +1,76 @@+const fs = require('fs');+const path = require('path');+const { logger, getTenantId } = require('@librechat/data-schemas');+const { CacheKeys, resolveMCPAppCspLimits } = require('librechat-data-provider');+const {+ createAuthIdentityContext,+ createMCPAppsController,+ prepareMCPAuthorizationMutation,+} = require('@librechat/api');+const { getMCPManager, getFlowStateManager, getMCPServersRegistry } = require('~/config');+const { getAppConfig, invalidateCachedTools } = require('~/server/services/Config');+const { createOpenIDSessionTokenProvider } = require('~/server/services/OpenIDSessionRefresh');+const {+ clearMCPAuthorizationFenceRetry,+ persistMCPAuthorizationFenceRetry,+} = require('~/server/services/MCPAuthorizationFenceRetry');+const {+ findPluginAuthsByKeys,+ findToken,+ createToken,+ updateToken,+ deleteTokens,+} = require('~/models');+const { getLogStores } = require('~/cache');++module.exports = createMCPAppsController({+ logger,+ sandboxPath: path.resolve(__dirname, '../../../client/public/mcp-sandbox.html'),+ sandboxFrameAncestors: process.env.MCP_SANDBOX_FRAME_ANCESTORS,+ readSandboxFile: fs.readFileSync,+ getManager: getMCPManager,+ getFlowManager: () => getFlowStateManager(getLogStores(CacheKeys.FLOWS)),+ getAppConfig: (req) =>+ getAppConfig({+ role: req.user?.role,+ userId: req.user?.id,+ tenantId: req.user?.tenantId,+ failClosed: true,+ }),+ getSandboxCspLimits: async () => {+ const appConfig = await getAppConfig({ baseOnly: true, failClosed: true });+ return resolveMCPAppCspLimits(appConfig?.mcpAppSandbox);+ },+ ensureConfigServers: (mcpConfig) => getMCPServersRegistry().ensureConfigServers(mcpConfig),+ getAllServerConfigs: (userId, configServers, role) =>+ getMCPServersRegistry().getAllServerConfigs(userId, configServers, role),+ recoverServerConfig: (serverName, config, userId) =>+ getMCPServersRegistry().recoverServerConfig(serverName, config, userId),+ isAppServerConfig: (serverName, config) =>+ getMCPServersRegistry().isAppServerConfig(serverName, config),+ resolveCachedAppServerConfig: (args) =>+ getMCPServersRegistry().resolveCachedAppServerConfig(args),+ findPluginAuthsByKeys,+ tokenMethods: { findToken, createToken, updateToken, deleteTokens },+ createOAuthCredentialsChanging: (req) => {+ const recoveryPolicy = req.config?.mcpSettings?.catalogRecovery;+ return (scope) =>+ prepareMCPAuthorizationMutation(scope, {+ invalidateRecoveryGeneration: invalidateCachedTools,+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,+ clearLocalRecovery: (userId, serverName, generation) =>+ getMCPManager()?.clearCatalogRecoveryState?.(userId, serverName, generation),+ retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,+ attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,+ });+ },+ createUpstreamTokenProvider: (req, res, user) =>+ createOpenIDSessionTokenProvider({+ req,+ res,+ user,+ identityContext: createAuthIdentityContext({ user, tenantId: getTenantId() }),+ tokenPreference: 'access_token',+ }),+});diff --git a/api/server/controllers/mcpApps.test.js b/api/server/controllers/mcpApps.test.jsnew file mode 100644index 0000000000..096d0f2a5b--- /dev/null+++ b/api/server/controllers/mcpApps.test.js@@ -0,0 +1,204 @@+const mockController = {+ readMCPResource: jest.fn(),+ listMCPResources: jest.fn(),+ listMCPResourceTemplates: jest.fn(),+ appToolCall: jest.fn(),+ validateMCPApp: jest.fn(),+ serveMCPSandbox: jest.fn(),+ requireMCPAppsEnabled: jest.fn(),+};++jest.mock('@librechat/data-schemas', () => ({+ logger: { error: jest.fn() },+ getTenantId: jest.fn(),+}));+jest.mock('@librechat/api', () => ({+ createAuthIdentityContext: jest.fn(),+ createMCPAppsController: jest.fn(() => mockController),+ prepareMCPAuthorizationMutation: jest.fn(),+}));+jest.mock('~/config', () => ({+ getMCPManager: jest.fn(),+ getFlowStateManager: jest.fn(),+ getMCPServersRegistry: jest.fn(),+}));+jest.mock('~/server/services/Config', () => ({+ getAppConfig: jest.fn(),+ invalidateCachedTools: jest.fn(),+}));+jest.mock('~/server/services/OpenIDSessionRefresh', () => ({+ createOpenIDSessionTokenProvider: jest.fn(),+}));+jest.mock('~/models', () => ({+ findPluginAuthsByKeys: jest.fn(),+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+}));+jest.mock('~/cache', () => ({ getLogStores: jest.fn() }));+jest.mock('~/server/services/MCPAuthorizationFenceRetry', () => ({+ clearMCPAuthorizationFenceRetry: jest.fn(),+ persistMCPAuthorizationFenceRetry: jest.fn(),+}));++const fs = require('fs');+const { CacheKeys } = require('librechat-data-provider');+const { getTenantId } = require('@librechat/data-schemas');+const {+ createAuthIdentityContext,+ createMCPAppsController,+ prepareMCPAuthorizationMutation,+} = require('@librechat/api');+const { getMCPManager, getFlowStateManager, getMCPServersRegistry } = require('~/config');+const { getAppConfig, invalidateCachedTools } = require('~/server/services/Config');+const { createOpenIDSessionTokenProvider } = require('~/server/services/OpenIDSessionRefresh');+const models = require('~/models');+const { getLogStores } = require('~/cache');+const {+ clearMCPAuthorizationFenceRetry,+ persistMCPAuthorizationFenceRetry,+} = require('~/server/services/MCPAuthorizationFenceRetry');++describe('MCP Apps controller wiring', () => {+ const originalAncestors = process.env.MCP_SANDBOX_FRAME_ANCESTORS;++ beforeEach(() => jest.clearAllMocks());+ afterEach(() => {+ if (originalAncestors === undefined) {+ delete process.env.MCP_SANDBOX_FRAME_ANCESTORS;+ } else {+ process.env.MCP_SANDBOX_FRAME_ANCESTORS = originalAncestors;+ }+ });++ it('exports the typed controller handlers and binds server dependencies', async () => {+ process.env.MCP_SANDBOX_FRAME_ANCESTORS = 'https://host.example.com';+ const ensureConfigServers = jest.fn().mockResolvedValue({ srv: { type: 'sse' } });+ const getAllServerConfigs = jest.fn().mockResolvedValue({ srv: { type: 'sse' } });+ const recoverServerConfig = jest.fn().mockResolvedValue({ type: 'sse' });+ const isAppServerConfig = jest.fn().mockResolvedValue(true);+ const resolveCachedAppServerConfig = jest.fn().mockResolvedValue({+ serverConfig: { type: 'sse' },+ connectionOwner: 'operator',+ });+ getLogStores.mockReturnValue('flow-store');+ getFlowStateManager.mockReturnValue('flow-manager');+ getMCPServersRegistry.mockReturnValue({+ ensureConfigServers,+ getAllServerConfigs,+ recoverServerConfig,+ isAppServerConfig,+ resolveCachedAppServerConfig,+ });+ getAppConfig.mockResolvedValue({ mcpSettings: { apps: true } });+ getTenantId.mockReturnValue('tenant-1');+ createAuthIdentityContext.mockReturnValue('identity-context');+ createOpenIDSessionTokenProvider.mockReturnValue('provider');++ jest.isolateModules(() => {+ expect(require('./mcpApps')).toBe(mockController);+ });++ expect(createMCPAppsController).toHaveBeenCalledTimes(1);+ const dependencies = createMCPAppsController.mock.calls[0][0];+ const request = {+ user: { id: 'user-1', role: 'USER', tenantId: 'tenant-1' },+ config: {+ mcpSettings: {+ catalogRecovery: {+ authorizationFenceRetryMs: [0, 25],+ authorizationFenceTimeoutMs: 750,+ },+ },+ },+ };+ const response = {};++ expect(dependencies.getManager).toBe(getMCPManager);+ expect(dependencies.readSandboxFile).toBe(fs.readFileSync);+ expect(dependencies.sandboxFrameAncestors).toBe('https://host.example.com');+ expect(dependencies.getFlowManager()).toBe('flow-manager');+ expect(getLogStores).toHaveBeenCalledWith(CacheKeys.FLOWS);+ await expect(dependencies.getAppConfig(request)).resolves.toEqual({+ mcpSettings: { apps: true },+ });+ expect(getAppConfig).toHaveBeenCalledWith({+ role: 'USER',+ userId: 'user-1',+ tenantId: 'tenant-1',+ failClosed: true,+ });+ await expect(dependencies.getSandboxCspLimits()).resolves.toEqual({+ maxSourcesPerDirective: 32,+ maxSerializedLength: 4096,+ });+ expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true, failClosed: true });+ await expect(dependencies.ensureConfigServers({ srv: { type: 'sse' } })).resolves.toEqual({+ srv: { type: 'sse' },+ });+ expect(ensureConfigServers).toHaveBeenCalledWith({ srv: { type: 'sse' } });+ await expect(+ dependencies.getAllServerConfigs('user-1', { srv: { type: 'sse' } }, 'USER'),+ ).resolves.toEqual({ srv: { type: 'sse' } });+ expect(getAllServerConfigs).toHaveBeenCalledWith('user-1', { srv: { type: 'sse' } }, 'USER');+ await expect(+ dependencies.recoverServerConfig('srv', { type: 'sse', inspectionFailed: true }, 'user-1'),+ ).resolves.toEqual({ type: 'sse' });+ expect(recoverServerConfig).toHaveBeenCalledWith(+ 'srv',+ { type: 'sse', inspectionFailed: true },+ 'user-1',+ );+ await expect(dependencies.isAppServerConfig('srv', { type: 'sse' })).resolves.toBe(true);+ expect(isAppServerConfig).toHaveBeenCalledWith('srv', { type: 'sse' });+ const cachedArgs = {+ serverName: 'srv',+ userId: 'user-1',+ role: 'USER',+ mcpConfig: {},+ };+ await expect(dependencies.resolveCachedAppServerConfig(cachedArgs)).resolves.toEqual({+ serverConfig: { type: 'sse' },+ connectionOwner: 'operator',+ });+ expect(resolveCachedAppServerConfig).toHaveBeenCalledWith(cachedArgs);+ expect(dependencies.findPluginAuthsByKeys).toBe(models.findPluginAuthsByKeys);+ expect(dependencies.tokenMethods).toEqual({+ findToken: models.findToken,+ createToken: models.createToken,+ updateToken: models.updateToken,+ deleteTokens: models.deleteTokens,+ });+ const onOAuthCredentialsChanging = dependencies.createOAuthCredentialsChanging(request);+ const scope = { userId: 'user-1', serverName: 'srv' };+ await onOAuthCredentialsChanging(scope);+ expect(prepareMCPAuthorizationMutation).toHaveBeenCalledWith(scope, {+ invalidateRecoveryGeneration: invalidateCachedTools,+ persistPublicationRetry: persistMCPAuthorizationFenceRetry,+ clearPublicationRetry: clearMCPAuthorizationFenceRetry,+ clearLocalRecovery: expect.any(Function),+ retryDelaysMs: [0, 25],+ attemptTimeoutMs: 750,+ });+ const publicationDependencies = prepareMCPAuthorizationMutation.mock.calls[0][1];+ const manager = { clearCatalogRecoveryState: jest.fn() };+ getMCPManager.mockReturnValue(manager);+ publicationDependencies.clearLocalRecovery('user-1', 'srv', 'generation-2');+ expect(manager.clearCatalogRecoveryState).toHaveBeenCalledWith('user-1', 'srv', 'generation-2');+ expect(dependencies.createUpstreamTokenProvider(request, response, request.user)).toBe(+ 'provider',+ );+ expect(createOpenIDSessionTokenProvider).toHaveBeenCalledWith({+ req: request,+ res: response,+ user: request.user,+ identityContext: 'identity-context',+ tokenPreference: 'access_token',+ });+ expect(createAuthIdentityContext).toHaveBeenCalledWith({+ user: request.user,+ tenantId: 'tenant-1',+ });+ });+});diff --git a/api/server/middleware/limiters/mcpAppAdmissionLimiter.js b/api/server/middleware/limiters/mcpAppAdmissionLimiter.jsnew file mode 100644index 0000000000..993c4961bd--- /dev/null+++ b/api/server/middleware/limiters/mcpAppAdmissionLimiter.js@@ -0,0 +1,10 @@+const { limiterCache, createMCPAppAdmissionRateLimiter } = require('@librechat/api');+const { getMCPServersRegistry } = require('~/config');+const logViolation = require('~/cache/logViolation');++module.exports = createMCPAppAdmissionRateLimiter({+ store: limiterCache('mcp_app_admission_limiter'),+ getLimit: () => getMCPServersRegistry().getMCPAppsPolicy().maxAdmissionRequestsPerMinute,+ logViolation,+ score: process.env.TOOL_CALL_VIOLATION_SCORE,+});diff --git a/api/server/middleware/limiters/mcpAppLimiters.test.js b/api/server/middleware/limiters/mcpAppLimiters.test.jsnew file mode 100644index 0000000000..85707cc8f8--- /dev/null+++ b/api/server/middleware/limiters/mcpAppLimiters.test.js@@ -0,0 +1,60 @@+const mockCreateMCPAppRateLimiter = jest.fn((kind) => `${kind}-limiter`);+const mockCreateMCPAppAdmissionRateLimiter = jest.fn(() => 'admission-limiter');+const mockLimiterCache = jest.fn((key) => `${key}-store`);+const mockLogViolation = jest.fn();+const mockGetMCPAppsPolicy = jest.fn(() => ({ maxAdmissionRequestsPerMinute: 240 }));++jest.mock('@librechat/api', () => ({+ createMCPAppRateLimiter: (...args) => mockCreateMCPAppRateLimiter(...args),+ createMCPAppAdmissionRateLimiter: (...args) => mockCreateMCPAppAdmissionRateLimiter(...args),+ limiterCache: (...args) => mockLimiterCache(...args),+}));++jest.mock('~/cache/logViolation', () => mockLogViolation);+jest.mock('~/config', () => ({+ getMCPServersRegistry: () => ({ getMCPAppsPolicy: mockGetMCPAppsPolicy }),+}));++describe('MCP App limiter wiring', () => {+ const previousScore = process.env.TOOL_CALL_VIOLATION_SCORE;++ beforeAll(() => {+ process.env.TOOL_CALL_VIOLATION_SCORE = '7';+ });++ afterAll(() => {+ if (previousScore === undefined) {+ delete process.env.TOOL_CALL_VIOLATION_SCORE;+ } else {+ process.env.TOOL_CALL_VIOLATION_SCORE = previousScore;+ }+ });++ it.each([+ ['resource', './mcpAppResourceLimiter', 'mcp_app_resource_limiter'],+ ['toolCall', './mcpAppToolCallLimiter', 'mcp_app_tool_call_limiter'],+ ])('wires the %s limiter with its independent store', (kind, modulePath, cacheKey) => {+ expect(require(modulePath)).toBe(`${kind}-limiter`);+ expect(mockLimiterCache).toHaveBeenCalledWith(cacheKey);+ expect(mockCreateMCPAppRateLimiter).toHaveBeenCalledWith(kind, {+ store: `${cacheKey}-store`,+ logViolation: mockLogViolation,+ score: '7',+ });+ });++ it('wires one shared pre-admission limiter to the registry base policy', () => {+ expect(require('./mcpAppAdmissionLimiter')).toBe('admission-limiter');+ expect(mockLimiterCache).toHaveBeenCalledWith('mcp_app_admission_limiter');+ expect(mockCreateMCPAppAdmissionRateLimiter).toHaveBeenCalledWith({+ store: 'mcp_app_admission_limiter-store',+ getLimit: expect.any(Function),+ logViolation: mockLogViolation,+ score: '7',+ });++ const [[{ getLimit }]] = mockCreateMCPAppAdmissionRateLimiter.mock.calls;+ expect(getLimit()).toBe(240);+ expect(mockGetMCPAppsPolicy).toHaveBeenCalledTimes(1);+ });+});diff --git a/api/server/middleware/limiters/mcpAppResourceLimiter.js b/api/server/middleware/limiters/mcpAppResourceLimiter.jsnew file mode 100644index 0000000000..d815187a37--- /dev/null+++ b/api/server/middleware/limiters/mcpAppResourceLimiter.js@@ -0,0 +1,8 @@+const { limiterCache, createMCPAppRateLimiter } = require('@librechat/api');+const logViolation = require('~/cache/logViolation');++module.exports = createMCPAppRateLimiter('resource', {+ store: limiterCache('mcp_app_resource_limiter'),+ logViolation,+ score: process.env.TOOL_CALL_VIOLATION_SCORE,+});diff --git a/api/server/middleware/limiters/mcpAppToolCallLimiter.js b/api/server/middleware/limiters/mcpAppToolCallLimiter.jsnew file mode 100644index 0000000000..4fc91a0df0--- /dev/null+++ b/api/server/middleware/limiters/mcpAppToolCallLimiter.js@@ -0,0 +1,8 @@+const { limiterCache, createMCPAppRateLimiter } = require('@librechat/api');+const logViolation = require('~/cache/logViolation');++module.exports = createMCPAppRateLimiter('toolCall', {+ store: limiterCache('mcp_app_tool_call_limiter'),+ logViolation,+ score: process.env.TOOL_CALL_VIOLATION_SCORE,+});diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.jsindex dc38482309..3608dd4cc0 100644--- a/api/server/routes/__tests__/config.spec.js+++ b/api/server/routes/__tests__/config.spec.js@@ -178,6 +178,7 @@ describe('GET /api/config', () => {expect(response.body).not.toHaveProperty('sharePointPickerSharePointScope');expect(response.body).not.toHaveProperty('conversationImportMaxFileSize');expect(response.body).not.toHaveProperty('insightsEnabled');+ expect(response.body).not.toHaveProperty('mcpApps');});it('should strip authenticated-only informational fields from unauthenticated response (#12688)', async () => {@@ -356,6 +357,7 @@ describe('GET /api/config', () => {userId: 'user123',idOnTheSource: undefined,tenantId: 'fallback-tenant',+ failClosed: true,});});@@ -371,6 +373,52 @@ describe('GET /api/config', () => {userId: 'user123',idOnTheSource: undefined,tenantId: 'user-tenant',+ failClosed: true,+ });+ });++ it.each([+ [undefined, { enabled: false, legacyHtmlEnabled: true }],+ [true, { enabled: true, legacyHtmlEnabled: true }],+ [false, { enabled: false, legacyHtmlEnabled: false }],+ ])('publishes the authenticated MCP Apps policy for raw apps=%s', async (apps, expected) => {+ mockGetAppConfig.mockResolvedValue({+ ...baseAppConfig,+ mcpSettings: apps === undefined ? {} : { apps },+ });+ const app = createApp(mockUser);++ const response = await request(app).get('/api/config');++ expect(response.statusCode).toBe(200);+ expect(response.body.mcpApps).toEqual({+ ...expected,+ cspLimits: { maxSourcesPerDirective: 32, maxSerializedLength: 4096 },+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ });+ });++ it('publishes deployment-owned MCP App sandbox limits', async () => {+ mockGetAppConfig.mockResolvedValue({+ ...baseAppConfig,+ mcpSettings: { apps: true },+ mcpAppSandbox: {+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ maxSourcesPerDirective: 64,+ maxSerializedLength: 8192,+ maxAdmissionRequestsPerMinute: 480,+ },+ });+ const response = await request(createApp(mockUser)).get('/api/config');++ expect(response.body.mcpApps).toEqual({+ enabled: true,+ legacyHtmlEnabled: true,+ cspLimits: { maxSourcesPerDirective: 64, maxSerializedLength: 8192 },+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 480,+ sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',});});@@ -813,6 +861,9 @@ describe('GET /api/config', () => {expect(response.statusCode).toBe(500);expect(response.body).toHaveProperty('error');+ expect(mockGetAppConfig).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'user123', failClosed: true }),+ );});});diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.jsindex 974560068d..27e4b4596b 100644--- a/api/server/routes/__tests__/mcp.spec.js+++ b/api/server/routes/__tests__/mcp.spec.js@@ -43,6 +43,12 @@ const mockLoadMCPServerCatalogs = jest.fn().mockResolvedValue({serverTools: new Map(),serversWithoutTools: [],});+const defaultMCPAppsPolicy = {+ enabled: false,+ legacyHtmlEnabled: true,+ maxAdmissionRequestsPerMinute: 240,+ maxPersistedAppBytes: 1048576,+};jest.mock('@librechat/api', () => {const actual = jest.requireActual('@librechat/api');@@ -189,6 +195,11 @@ jest.mock('~/server/middleware', () => ({canAccessMCPServerResource: () => (req, res, next) => next(),}));+jest.mock(+ '~/server/middleware/limiters/mcpAppAdmissionLimiter',+ () => (_req, _res, next) => next(),+);+jest.mock('~/server/services/Tools/mcp', () => ({reinitMCPServer: jest.fn(),loadMCPServerCatalogs: (...args) => mockLoadMCPServerCatalogs(...args),@@ -330,6 +341,20 @@ describe('MCP Routes', () => {cacheService.invalidateCachedTools.mockReset().mockResolvedValue(undefined);});+ it.each([+ '/app/validate',+ '/resources/read',+ '/resources/list',+ '/resources/templates/list',+ '/app-tool-call',+ ])('places the shared App admission limiter immediately after JWT auth on %s', (path) => {+ const routeLayer = mcpRouter.stack.find((layer) => layer.route?.path === path);+ const admissionLimiter = require('~/server/middleware/limiters/mcpAppAdmissionLimiter');++ expect(routeLayer).toBeDefined();+ expect(routeLayer.route.stack[1].handle).toBe(admissionLimiter);+ });+describe('GET /:serverName/oauth/initiate', () => {const { MCPOAuthHandler } = require('@librechat/api');const { getLogStores } = require('~/cache');@@ -3588,6 +3613,7 @@ describe('MCP Routes', () => {oboIdentityContext: expect.any(Object),signal: expect.any(AbortSignal),recoveryPolicy,+ mcpApps: defaultMCPAppsPolicy,});});@@ -3641,6 +3667,8 @@ describe('MCP Routes', () => {upstreamTokenProvider: expect.any(Function),oboIdentityContext: expect.any(Object),signal: expect.any(AbortSignal),+ recoveryPolicy: undefined,+ mcpApps: defaultMCPAppsPolicy,});});@@ -3758,6 +3786,8 @@ describe('MCP Routes', () => {upstreamTokenProvider: expect.any(Function),oboIdentityContext: expect.any(Object),signal: expect.any(AbortSignal),+ recoveryPolicy: undefined,+ mcpApps: defaultMCPAppsPolicy,});});diff --git a/api/server/routes/config.js b/api/server/routes/config.jsindex 7ca103e9af..9d2632203a 100644--- a/api/server/routes/config.js+++ b/api/server/routes/config.js@@ -18,7 +18,12 @@ const {resolveCodeEnvironmentMoveVersion,isPasskeyEnabled,} = require('@librechat/api');-const { EModelEndpoint, defaultSocialLogins } = require('librechat-data-provider');+const {+ DEFAULT_MCP_APP_CSP_LIMITS,+ EModelEndpoint,+ defaultSocialLogins,+ resolveMCPAppsPolicy,+} = require('librechat-data-provider');const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas');const { hasCapability, hasConfigCapability } = require('~/server/middleware/roles/capabilities');const { getLdapConfig } = require('~/server/services/Config/ldap');@@ -251,7 +256,10 @@ router.get('/', async function (req, res) {return res.status(200).send(payload);}- const appConfig = await getAppConfig(getAppConfigOptionsFromUser(req.user));+ const appConfig = await getAppConfig({+ ...getAppConfigOptionsFromUser(req.user),+ failClosed: true,+ });const codeEnvironmentDecisionVersion = resolveCodeEnvironmentDecisionVersion(process.env.CODE_ENVIRONMENT_DECISION_VERSION,);@@ -318,8 +326,14 @@ router.get('/', async function (req, res) {insightsEnabled: isEnabled(process.env.ENABLE_INSIGHTS),compactionEnabled: appConfig?.summarization?.enabled !== false,...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}),- ...codeEnvironmentMoveCapabilities,- ...(codeEnvironmentTransitionVersion != null ? { codeEnvironmentTransitionVersion } : {}),+ mcpApps: resolveMCPAppsPolicy(+ appConfig?.mcpSettings?.apps,+ appConfig?.mcpAppSandbox ?? DEFAULT_MCP_APP_CSP_LIMITS,+ appConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ appConfig?.mcpAppSandbox?.url,+ ),+ ...(codeEnvironmentMoveVersion != null ? { codeEnvironmentMoveVersion } : {}),...(cloudFront ? { cloudFront } : {}),...(rum ? { rum } : {}),fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED),diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.jsindex 2b0da05553..a96e3bbafa 100644--- a/api/server/routes/mcp.js+++ b/api/server/routes/mcp.js@@ -6,6 +6,7 @@ const {Permissions,PermissionBits,PermissionTypes,+ resolveMCPAppsPolicy,} = require('librechat-data-provider');const {getBasePath,@@ -42,6 +43,18 @@ const {getMCPServerById,getMCPTools,} = require('~/server/controllers/mcp');+const {+ readMCPResource,+ listMCPResources,+ listMCPResourceTemplates,+ appToolCall,+ validateMCPApp,+ serveMCPSandbox,+ requireMCPAppsEnabled,+} = require('~/server/controllers/mcpApps');+const mcpAppAdmissionLimiter = require('~/server/middleware/limiters/mcpAppAdmissionLimiter');+const mcpAppToolCallLimiter = require('~/server/middleware/limiters/mcpAppToolCallLimiter');+const mcpAppResourceLimiter = require('~/server/middleware/limiters/mcpAppResourceLimiter');const {getOAuthReconnectionManager,getMCPServersRegistry,@@ -987,6 +1000,13 @@ router.post(}),oboIdentityContext,recoveryPolicy: req.config?.mcpSettings?.catalogRecovery,+ mcpApps: resolveMCPAppsPolicy(+ req.config?.mcpSettings?.apps,+ undefined,+ req.config?.mcpAppSandbox?.maxPersistedAppBytes,+ req.config?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ req.config?.mcpAppSandbox?.url,+ ),});if (!result) {@@ -1312,4 +1332,82 @@ router.delete((req, res) => deleteMCPServerController(req, res, maybeUninstallOAuthMCP),);+// --- MCP Apps Support ---++/**+ * Validate that a persisted MCP App still targets its originating server configuration+ * @route POST /api/mcp/app/validate+ */+router.post(+ '/app/validate',+ requireJwtAuth,+ mcpAppAdmissionLimiter,+ checkMCPUsePermissions,+ requireMCPAppsEnabled,+ mcpAppResourceLimiter,+ validateMCPApp,+);++/**+ * Read a UI resource from an MCP server+ * @route POST /api/mcp/resources/read+ */+router.post(+ '/resources/read',+ requireJwtAuth,+ mcpAppAdmissionLimiter,+ checkMCPUsePermissions,+ requireMCPAppsEnabled,+ mcpAppResourceLimiter,+ readMCPResource,+);++/**+ * List resources available on an MCP server+ * @route POST /api/mcp/resources/list+ */+router.post(+ '/resources/list',+ requireJwtAuth,+ mcpAppAdmissionLimiter,+ checkMCPUsePermissions,+ requireMCPAppsEnabled,+ mcpAppResourceLimiter,+ listMCPResources,+);++/**+ * List resource templates available on an MCP server+ * @route POST /api/mcp/resources/templates/list+ */+router.post(+ '/resources/templates/list',+ requireJwtAuth,+ mcpAppAdmissionLimiter,+ checkMCPUsePermissions,+ requireMCPAppsEnabled,+ mcpAppResourceLimiter,+ listMCPResourceTemplates,+);++/**+ * Proxy tool calls from MCP App iframe to MCP server+ * @route POST /api/mcp/app-tool-call+ */+router.post(+ '/app-tool-call',+ requireJwtAuth,+ mcpAppAdmissionLimiter,+ checkMCPUsePermissions,+ requireMCPAppsEnabled,+ mcpAppToolCallLimiter,+ appToolCall,+);++/**+ * Serve the sandbox proxy HTML for MCP Apps+ * @route GET /api/mcp/sandbox+ */+router.get('/sandbox', serveMCPSandbox);+module.exports = router;diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 61750ac982..dee92df897 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -42,11 +42,15 @@ const {isOAuthServer,isAbortError,isDirectOpenIDBearerRecoveryEnabled,+ createMCPStructuredTool,buildMCPDomainValidationConfig,OpenIDReauthRequiredError,MCPAuthenticationRefreshError,MCPAuthenticationRejectedError,prepareMCPAuthorizationMutation,+ resolveMCPClientCapabilityProfile,+ getMCPConnectionPoolKey,+ getMCPUserConnectionPoolKey,} = require('@librechat/api');const {Time,@@ -54,7 +58,7 @@ const {Constants,Permissions,PermissionTypes,- isAssistantsEndpoint,+ resolveMCPAppsPolicy,} = require('librechat-data-provider');const {getOAuthReconnectionManager,@@ -387,6 +391,14 @@ async function healMcpToolNames({ req, tools, toolDefinitions, accessibleServerNasync function getAssistantToolDefinitions({ req, res, tools }) {const registry = getMCPServersRegistry();const appConfig = await getAppConfigForRequest(req);+ const mcpApps = resolveMCPAppsPolicy(+ appConfig?.mcpSettings?.apps,+ undefined,+ appConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ appConfig?.mcpAppSandbox?.url,+ );+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);const oboIdentityContext = createAuthIdentityContext({user: req.user,tenantId: getTenantId(),@@ -409,14 +421,13 @@ async function getAssistantToolDefinitions({ req, res, tools }) {ensureConfigServers: (mcpConfig) => registry.ensureConfigServers(mcpConfig),getAllServerConfigs: (userId, configServers, role) =>registry.getAllServerConfigs(userId, configServers, role),- getMCPServerTools,+ getMCPServerTools: (userId, serverName, serverConfig) =>+ getMCPServerTools(userId, serverName, serverConfig, capabilityProfile),getServerToolFunctionsSnapshot: async (userId, serverName, serverConfig, options) =>- (await getMCPManager()?.getServerToolFunctionsSnapshot(- userId,- serverName,- serverConfig,- options,- )) ?? {+ (await getMCPManager()?.getServerToolFunctionsSnapshot(userId, serverName, serverConfig, {+ ...options,+ capabilityProfile,+ })) ?? {tools: null,},recoverServerTools: async (serverName, serverConfig) => {@@ -433,10 +444,11 @@ async function getAssistantToolDefinitions({ req, res, tools }) {upstreamTokenProvider,oboIdentityContext,recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,+ mcpApps,});return result?.availableTools ?? null;},- cacheMCPServerTools,+ cacheMCPServerTools: (params) => cacheMCPServerTools({ ...params, capabilityProfile }),},);}@@ -756,6 +768,7 @@ function resolveToolCallUserId({ effectiveUser, capturedUser, invocationUserId,* @param {Record<string, Record<string, string>>} [params.userMCPAuthMap]* @param {import('@librechat/api').RequestScopedMCPConnectionStore} [params.requestScopedConnections]* @param {import('@librechat/api').ParsedServerConfig} [params.serverConfig] - Used to bypass reconnect throttling for request-scoped servers.+ * @param {import('librechat-data-provider').TMCPAppsPolicy} [params.mcpApps]* @returns { Promise<Array<typeof tool | { _call: (toolInput: Object | string) => unknown}>> } An object with `_call` method to execute the tool input.*/async function reconnectServer({@@ -775,7 +788,9 @@ async function reconnectServer({streamId = null,jobCreatedAt,recoveryPolicy,+ mcpApps,}) {+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);logger.debug('[MCP][reconnectServer] Starting reconnect', {userId: user?.id,hasUserMCPAuthMap: Boolean(userMCPAuthMap),@@ -785,7 +800,7 @@ async function reconnectServer({// would stub out healthy tools for messages sent within the throttle window.const requestScoped = serverConfig ? requiresEphemeralUserConnection(serverConfig) : false;if (!requestScoped) {- const throttleKey = `${user.id}:${serverName}`;+ const throttleKey = getMCPUserConnectionPoolKey(user.id, serverName, capabilityProfile);const now = Date.now();const lastAttempt = lastReconnectAttempts.get(throttleKey) ?? 0;if (now - lastAttempt < RECONNECT_THROTTLE_MS) {@@ -841,6 +856,7 @@ async function reconnectServer({upstreamTokenProvider,upstreamTokenProviderResolver,recoveryPolicy,+ mcpApps,oboIdentityContext,streamId,jobCreatedAt,@@ -874,6 +890,7 @@ async function reconnectServer({* @param {import('@librechat/api').UpstreamTokenProvider} [params.upstreamTokenProvider] - Live upstream-token closure for OBO, built at the request boundary.* @param {import('@librechat/api').UpstreamTokenProviderResolver} [params.upstreamTokenProviderResolver]* @param {import('@librechat/api').AuthIdentityContext} [params.oboIdentityContext] - Non-template-visible OBO identity context built from the real request user.+ * @param {import('librechat-data-provider').TMCPAppsPolicy} [params.mcpApps] - Request-admitted MCP Apps policy.* @returns { Promise<Array<typeof tool | { _call: (toolInput: Object | string) => unknown}>> } An object with `_call` method to execute the tool input.*/async function createMCPTools({@@ -892,6 +909,7 @@ async function createMCPTools({upstreamTokenProvider,upstreamTokenProviderResolver,oboIdentityContext,+ mcpApps,streamId = null,jobCreatedAt,}) {@@ -940,6 +958,7 @@ async function createMCPTools({streamId,jobCreatedAt,recoveryPolicy,+ mcpApps,});if (result === null) {logger.debug('[MCP] Reconnect throttled; skipping tool creation');@@ -977,6 +996,7 @@ async function createMCPTools({upstreamTokenProvider,upstreamTokenProviderResolver,oboIdentityContext,+ mcpApps,config: serverConfig,});if (toolInstance) {@@ -1007,6 +1027,7 @@ async function createMCPTools({* @param {import('@librechat/api').UpstreamTokenProvider} [params.upstreamTokenProvider] - Live upstream-token closure for OBO, built at the request boundary.* @param {import('@librechat/api').UpstreamTokenProviderResolver} [params.upstreamTokenProviderResolver]* @param {import('@librechat/api').AuthIdentityContext} [params.oboIdentityContext] - Non-template-visible OBO identity context built from the real request user.+ * @param {import('librechat-data-provider').TMCPAppsPolicy} [params.mcpApps] - Request-admitted MCP Apps policy.* @param {string} [params.serverName] - Resolved raw MCP server name from tool loading.* @param {(availableTools: LCAvailableTools) => void} [params.onAvailableTools]* @param {number} [params.jobCreatedAt] - The generation epoch that owns emitted events.@@ -1029,12 +1050,14 @@ async function createMCPTool({upstreamTokenProvider,upstreamTokenProviderResolver,oboIdentityContext,+ mcpApps,serverName: resolvedServerName,onAvailableTools,streamId = null,jobCreatedAt,recoveryPolicy,}) {+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);/** `loadTools` already resolved the server for this key; parsing is the fallback. */const [parsedToolName, parsedServerName] = splitMCPToolKey(toolKey,@@ -1071,6 +1094,7 @@ async function createMCPTool({}const requestScopedTools = serverConfig ? requiresEphemeralUserConnection(serverConfig) : false;const useMissingToolCache = !requestScopedTools;+ const missingToolCacheKey = getMCPConnectionPoolKey(toolKey, capabilityProfile);if (serverConfig?.url) {const appConfig = await getAppConfig({@@ -1141,7 +1165,7 @@ async function createMCPTool({/** @type {LCFunctionTool | undefined} */let toolEntry = findToolEntry(availableTools);if (!toolEntry) {- const cachedAt = useMissingToolCache ? missingToolCache.get(toolKey) : undefined;+ const cachedAt = useMissingToolCache ? missingToolCache.get(missingToolCacheKey) : undefined;if (cachedAt && Date.now() - cachedAt < MISSING_TOOL_TTL_MS) {logger.debug('[MCP] Tool is in negative cache; returning unavailable stub');return createUnavailableToolStub(toolName, serverName);@@ -1165,6 +1189,7 @@ async function createMCPTool({streamId,jobCreatedAt,...(recoveryPolicy && { recoveryPolicy }),+ mcpApps,});if (result?.availableTools) {onAvailableTools?.(result.availableTools);@@ -1172,7 +1197,7 @@ async function createMCPTool({toolEntry = findToolEntry(result?.availableTools);if (!toolEntry && useMissingToolCache) {- missingToolCache.set(toolKey, Date.now());+ missingToolCache.set(missingToolCacheKey, Date.now());evictStale(missingToolCache, MISSING_TOOL_TTL_MS);}}@@ -1208,6 +1233,7 @@ async function createMCPTool({upstreamTokenProvider,upstreamTokenProviderResolver,oboIdentityContext,+ mcpApps,streamId,jobCreatedAt,recoveryPolicy,@@ -1230,6 +1256,7 @@ function createToolInstance({upstreamTokenProvider: capturedUpstreamTokenProvider = null,upstreamTokenProviderResolver: capturedUpstreamTokenProviderResolver = null,oboIdentityContext: capturedOboIdentityContext = null,+ mcpApps: capturedMCPApps,streamId = null,jobCreatedAt,recoveryPolicy,@@ -1361,11 +1388,8 @@ function createToolInstance({upstreamTokenProvider: capturedUpstreamTokenProvider,upstreamTokenProviderResolver: capturedUpstreamTokenProviderResolver,oboIdentityContext: capturedOboIdentityContext,+ mcpApps: capturedMCPApps,});-- if (isAssistantsEndpoint(provider) && Array.isArray(result)) {- return result[0];- }return result;} catch (error) {/** A user Stop aborts every in-flight call at once, and that rejection is@@ -1438,7 +1462,7 @@ function createToolInstance({}};- const toolInstance = tool(_call, {+ const toolInstance = createMCPStructuredTool(_call, {schema,name: normalizedToolKey,description: description || '',@@ -1483,6 +1507,15 @@ async function getMCPSetupData(userId, options = {}) {const { role, tenantId } = options;const appConfig = options.appConfig ?? (await getAppConfig({ role, tenantId, userId }));+ const capabilityProfile = resolveMCPClientCapabilityProfile(+ resolveMCPAppsPolicy(+ appConfig?.mcpSettings?.apps,+ undefined,+ appConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ appConfig?.mcpAppSandbox?.url,+ ),+ );const configServers = await registry.ensureConfigServers(appConfig?.mcpConfig || {});const mcpConfig = role? await registry.getAllServerConfigs(userId, configServers, role)@@ -1494,11 +1527,11 @@ async function getMCPSetupData(userId, options = {}) {// Use getLoaded() instead of getAll() to avoid forcing connection creation.// getAll() creates connections for all servers, which is problematic for servers// that require user context (e.g., those with {{LIBRECHAT_USER_ID}} placeholders).- appConnections = (await mcpManager.appConnections?.getLoaded()) || new Map();+ appConnections = await mcpManager.getLoadedAppConnections(capabilityProfile);} catch (error) {logger.error(`[MCP][User: ${userId}] Error getting app connections:`, error);}- const userConnections = mcpManager.getUserConnections(userId) || new Map();+ const userConnections = mcpManager.getUserConnections(userId, capabilityProfile) || new Map();const oauthServers = new Set(Object.entries(mcpConfig).filter(([, config]) => isOAuthServer(config))diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex 487a50730b..622de2c12f 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -43,7 +43,12 @@ jest.mock('@librechat/api', () => {});const { logger } = require('@librechat/data-schemas');-const { MCPOAuthHandler, GenerationJobManager } = require('@librechat/api');+const {+ MCPOAuthHandler,+ GenerationJobManager,+ MCP_APPS_CAPABILITY_PROFILE,+ STANDARD_MCP_CAPABILITY_PROFILE,+} = require('@librechat/api');const { CacheKeys, Constants, Permissions, PermissionTypes } = require('librechat-data-provider');const D = Constants.mcp_delimiter;const {@@ -214,7 +219,7 @@ describe('tests for the new helper functions used by the MCP connection status ebeforeEach(() => {mockGetMCPManager.mockReturnValue({- appConnections: { getLoaded: jest.fn(() => new Map()) },+ getLoadedAppConnections: jest.fn(() => new Map()),getUserConnections: jest.fn(() => new Map()),});mockRegistryInstance.getOAuthServers.mockResolvedValue(new Set());@@ -233,7 +238,7 @@ describe('tests for the new helper functions used by the MCP connection status econst mockUserConnections = new Map([['server2', { status: 'disconnected' }]]);const mockMCPManager = {- appConnections: { getLoaded: jest.fn(() => Promise.resolve(mockAppConnections)) },+ getLoadedAppConnections: jest.fn(() => Promise.resolve(mockAppConnections)),getUserConnections: jest.fn(() => mockUserConnections),};mockGetMCPManager.mockReturnValue(mockMCPManager);@@ -246,8 +251,13 @@ describe('tests for the new helper functions used by the MCP connection status eexpect.any(Object),);expect(mockGetMCPManager).toHaveBeenCalledWith(mockUserId);- expect(mockMCPManager.appConnections.getLoaded).toHaveBeenCalled();- expect(mockMCPManager.getUserConnections).toHaveBeenCalledWith(mockUserId);+ expect(mockMCPManager.getLoadedAppConnections).toHaveBeenCalledWith(+ STANDARD_MCP_CAPABILITY_PROFILE,+ );+ expect(mockMCPManager.getUserConnections).toHaveBeenCalledWith(+ mockUserId,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );expect(result.mcpConfig).toEqual(mockConfigWithOAuth);expect(result.appConnections).toEqual(mockAppConnections);@@ -272,11 +282,30 @@ describe('tests for the new helper functions used by the MCP connection status eexpect(mockRegistryInstance.ensureConfigServers).toHaveBeenCalledWith(appConfig.mcpConfig);});+ it('reports only the request-admitted Apps connection profile', async () => {+ const getLoadedAppConnections = jest.fn(() => Promise.resolve(new Map()));+ const appsConnections = new Map([['server1', { connectionState: 'connected' }]]);+ const getUserConnections = jest.fn(() => appsConnections);+ mockGetMCPManager.mockReturnValue({+ getLoadedAppConnections,+ getUserConnections,+ });++ const result = await getMCPSetupData(mockUserId, {+ appConfig: { mcpConfig: {}, mcpSettings: { apps: true } },+ });++ expect(getLoadedAppConnections).toHaveBeenCalledWith(MCP_APPS_CAPABILITY_PROFILE);+ expect(getUserConnections).toHaveBeenCalledWith(mockUserId, MCP_APPS_CAPABILITY_PROFILE);+ expect(result.appConnections).toEqual(new Map());+ expect(result.userConnections).toBe(appsConnections);+ });+it('should handle null values from MCP manager gracefully', async () => {mockRegistryInstance.getAllServerConfigs.mockResolvedValue(mockConfig);const mockMCPManager = {- appConnections: { getLoaded: jest.fn(() => Promise.resolve(null)) },+ getLoadedAppConnections: jest.fn(() => Promise.resolve(new Map())),getUserConnections: jest.fn(() => null),};mockGetMCPManager.mockReturnValue(mockMCPManager);@@ -1548,42 +1577,91 @@ describe('User parameter passing tests', () => {});describe('createMCPTool', () => {- it('records a typed OBO failure against the scheduled generation before returning an error', async () => {- const user = { id: 'scheduled-owner', role: 'USER' };- const missing = new Error('Unattended provider not configured');- const error = Object.assign(new Error('MCP tool error'), { cause: missing });- const receipt = require('~/server/services/Schedules').recordMCPToolAuthFailure;- require('~/models').getRoleByName.mockResolvedValue({- permissions: { [PermissionTypes.MCP_SERVERS]: { [Permissions.USE]: true } },- });- mockGetMCPManager.mockReturnValue({ callTool: jest.fn().mockRejectedValue(error) });- const tool = await createMCPTool({- user,+ it('preserves the full MCP tuple for the Assistants required-action sink', async () => {+ const mockUser = { id: 'assistants-app-user', role: 'USER' };+ const mockRes = { write: jest.fn(), flush: jest.fn() };+ const mcpApps = { enabled: true, legacyHtmlEnabled: true };+ const artifact = { ui_resources: { data: [{ uri: 'ui://app' }] } };+ const callTool = jest.fn().mockResolvedValue(['ordinary output', artifact]);+ const { getRoleByName } = require('~/models');+ getRoleByName.mockResolvedValue({+ permissions: {+ [PermissionTypes.MCP_SERVERS]: {+ [Permissions.USE]: true,+ },+ },+ });+ mockGetMCPManager.mockReturnValue({ callTool });++ const mcpTool = await createMCPTool({+ res: mockRes,+ user: mockUser,+ config: { url: 'https://assistants.example.com/mcp' },toolKey: `test-tool${D}test-server`,- provider: 'openai',- streamId: 'scheduled-conversation',- jobCreatedAt: 42,- config: { type: 'streamable-http', url: 'https://mcp.example.com' },+ provider: 'assistants',+ mcpApps,+ userMCPAuthMap: {},availableTools: {[`test-tool${D}test-server`]: {- function: { description: 'Test MCP', parameters: { type: 'object', properties: {} } },+ function: {+ description: 'Cached tool',+ parameters: { type: 'object', properties: {} },+ },},},});- await expect(- tool.func({}, undefined, {- configurable: { user },- metadata: { provider: 'openai', thread_id: 'scheduled-conversation', run_id: 'run-1' },- toolCall: {},++ await expect(mcpTool._call({})).resolves.toEqual(['ordinary output', artifact]);+ expect(callTool).toHaveBeenCalledWith(expect.objectContaining({ mcpApps }));+ });++ it('preserves a completed tool result when optional App enrichment observes cancellation', async () => {+ const mockUser = { id: 'completed-result-user', role: 'USER' };+ const mockRes = { write: jest.fn(), flush: jest.fn() };+ const abortController = new AbortController();+ const { getRoleByName } = require('~/models');+ getRoleByName.mockResolvedValue({+ permissions: {+ [PermissionTypes.MCP_SERVERS]: {+ [Permissions.USE]: true,+ },+ },+ });+ mockGetMCPManager.mockReturnValue({+ callTool: jest.fn().mockImplementation(async () => {+ abortController.abort();+ return ['ordinary output', undefined];}),- ).rejects.toThrow();- expect(receipt).toHaveBeenCalledWith({- error,- streamId: 'scheduled-conversation',- jobCreatedAt: 42,- userId: 'scheduled-owner',- serverName: 'test-server',});++ const mcpTool = await createMCPTool({+ res: mockRes,+ user: mockUser,+ config: { url: 'https://completed.example.com/mcp' },+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ userMCPAuthMap: {},+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: {+ description: 'Cached tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ });++ await expect(+ mcpTool.invoke(+ {},+ {+ signal: abortController.signal,+ configurable: { user: mockUser },+ metadata: { provider: 'openai', thread_id: 'thread-1', run_id: 'run-1' },+ toolCall: {},+ },+ ),+ ).resolves.toBe('ordinary output');});it('keeps shared OAuth recovery alive when one tool caller aborts', async () => {@@ -1605,7 +1683,7 @@ describe('User parameter passing tests', () => {return new Promise((resolve, reject) => {const onAbort = () => {signal?.removeEventListener('abort', onAbort);- reject(new Error('tool caller aborted'));+ reject(signal?.reason ?? new DOMException('Aborted', 'AbortError'));};signal?.addEventListener('abort', onAbort, { once: true });sharedRecovery.then(() => {@@ -1652,7 +1730,7 @@ describe('User parameter passing tests', () => {const waiterCall = mcpTool.invoke({}, createConfig(waiterAbort.signal));await new Promise((resolve) => setImmediate(resolve));- ownerAbort.abort();+ ownerAbort.abort(new DOMException('Aborted', 'AbortError'));await expect(ownerCall).rejects.toThrow('Aborted');expect(flowManager.failFlow).not.toHaveBeenCalled();diff --git a/api/server/services/Threads/manage.js b/api/server/services/Threads/manage.jsindex 29a0d502a4..c6dd17b065 100644--- a/api/server/services/Threads/manage.js+++ b/api/server/services/Threads/manage.js@@ -135,6 +135,7 @@ async function saveUserMessage(req, params) {* @param {string} [params.instructions] - Optional: from preset for `instructions` field.* @param {string} [params.spec] - Optional: Model spec identifier.* @param {string} [params.iconURL]+ * @param {import('librechat-data-provider').TAttachment[]} [params.attachments]* Overrides the instructions of the assistant.* @param {string} [params.promptPrefix] - Optional: from preset for `additional_instructions` field.* @return {Promise<{message: Object|null, conversation: Object|null}>} The persisted assistant@@ -159,6 +160,7 @@ async function saveAssistantMessage(req, params) {/* For messages, use the assistant_id instead of model */model: params.assistant_id,content: params.content,+ attachments: params.attachments,sender: 'Assistant',isCreatedByUser: false,text: params.text,diff --git a/api/server/services/Threads/manage.retention.spec.js b/api/server/services/Threads/manage.retention.spec.jsindex b16f2092ea..60e0ee09cf 100644--- a/api/server/services/Threads/manage.retention.spec.js+++ b/api/server/services/Threads/manage.retention.spec.js@@ -60,11 +60,21 @@ describe('Assistants message retention', () => {);// A response must retain the admission policy even if request fields change.req.body.isTemporary = !isTemporary;+ const attachments = [+ {+ type: 'ui_resources',+ messageId: 'assistant-app-message',+ conversationId,+ toolCallId: 'call_1',+ ui_resources: [{ uri: 'ui://app', mimeType: 'text/html;profile=mcp-app' }],+ },+ ];await saveAssistantMessage(req, {...params,messageId: v4(),parentMessageId: userMessage.messageId,content: [],+ attachments,});await checkMessageGaps({openai: {@@ -94,6 +104,7 @@ describe('Assistants message retention', () => {expect(row.isTemporary).toBe(isTemporary);expect(row.expiredAt).toEqual(userMessage.expiredAt);}+ expect(rows.find((row) => row.isCreatedByUser === false)?.attachments).toEqual(attachments);expect(convo.lastResponseAt != null).toBe(!isTemporary);},);diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 51b97957ce..29d4cbc29c 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -66,6 +66,9 @@ const {getTransactionsConfig,checkToolRolePermission,resolveToolRolePermissions,+ splitAssistantMCPToolResult,+ appendAssistantMCPAppArtifact,+ resolveMCPClientCapabilityProfile,} = require('@librechat/api');const {Time,@@ -91,6 +94,7 @@ const {actionDomainSeparator,defaultAgentCapabilities,validateAndParseOpenAPISpec,+ resolveMCPAppsPolicy,} = require('librechat-data-provider');const {createActionTool,@@ -385,13 +389,13 @@ const getRequiredActionContentInspection = (client, input) => {return inspectContentWithTraversal(() => extractToolArgumentContent(selectedInput), { filters });};-const getSafeRequiredActionOutput = (client, currentAction, output) => {+const getRequiredActionOutputDecision = (client, currentAction, output) => {const { finding, traversalError } = getRequiredActionContentInspection(client, {name: currentAction.tool,output,});if (finding == null && traversalError == null) {- return output;+ return { output, accepted: true };}const blockResponse =finding == null ? traversalError.body : contentFilterModelBoundBlockResponse(finding);@@ -400,9 +404,12 @@ const getSafeRequiredActionOutput = (client, currentAction, output) => {source: blockResponse.source,field: blockResponse.field,});- return JSON.stringify(blockResponse);+ return { output: JSON.stringify(blockResponse), accepted: false };};+const getSafeRequiredActionOutput = (client, currentAction, output) =>+ getRequiredActionOutputDecision(client, currentAction, output).output;+/*** Processes return required actions from run.* @param {OpenAIClient | StreamRunManager} client - OpenAI (legacy) or StreamRunManager Client.@@ -492,7 +499,15 @@ async function processRequiredActions(client, requiredActions) {let tool = ToolMap[currentAction.tool] ?? ActionToolMap[currentAction.tool];const handleToolOutput = async (rawOutput) => {- const output = getSafeRequiredActionOutput(client, currentAction, rawOutput);+ const { output: toolOutput, uiResources } = splitAssistantMCPToolResult(+ rawOutput,+ tool?.mcp === true,+ );+ const { output, accepted } = getRequiredActionOutputDecision(+ client,+ currentAction,+ toolOutput,+ );requiredActions[i].output = output;/** @type {FunctionToolCall & PartMetadata} */@@ -555,6 +570,13 @@ async function processRequiredActions(client, requiredActions) {// TODO: to append tool properties to stream, pass metadata rest to addContentData// result: tool.result,});+ if (accepted && uiResources) {+ appendAssistantMCPAppArtifact({+ host: client,+ toolCallId: currentAction.toolCallId,+ uiResources,+ });+ }return {tool_call_id: currentAction.toolCallId,@@ -826,6 +848,14 @@ async function loadToolDefinitionsWrapper({}const appConfig = req.config;+ const mcpApps = resolveMCPAppsPolicy(+ appConfig?.mcpSettings?.apps,+ undefined,+ appConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ appConfig?.mcpAppSandbox?.url,+ );+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);const runtimeRequestBody = requestBody ?? req.body;const hasExpectedMCPTools = agent.tools.some(isExpectedMCPTool);const enabledCapabilities = await resolveAgentCapabilities(req, appConfig, agent.id);@@ -1172,7 +1202,7 @@ async function loadToolDefinitionsWrapper({return mcpAvailableTools[serverName];}- const cached = await getMCPServerTools(userId, serverName, serverConfig);+ const cached = await getMCPServerTools(userId, serverName, serverConfig, capabilityProfile);if (cached) {rememberMCPAvailableTools(serverName, cached);await addPendingOAuthServer();@@ -1206,6 +1236,7 @@ async function loadToolDefinitionsWrapper({upstreamTokenProviderResolver,oboIdentityContext,recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,+ mcpApps,});rememberMCPAvailableTools(serverName, result?.availableTools);@@ -1240,6 +1271,7 @@ async function loadToolDefinitionsWrapper({upstreamTokenProviderResolver,oboIdentityContext,recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,+ mcpApps,});rememberMCPAvailableTools(serverName, result?.availableTools);@@ -1395,6 +1427,7 @@ async function loadToolDefinitionsWrapper({upstreamTokenProviderResolver,oboIdentityContext,recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,+ mcpApps,});if (result?.availableTools && Object.keys(result.availableTools).length > 0) {diff --git a/api/server/services/Tools/mcp.js b/api/server/services/Tools/mcp.jsindex 762c9a3e56..35dfeac193 100644--- a/api/server/services/Tools/mcp.js+++ b/api/server/services/Tools/mcp.js@@ -9,7 +9,7 @@ const {getMissingRuntimeBodyPlaceholderFields,isMCPInitializationError,prepareMCPAuthorizationMutation,- recordScheduledMCPToolAuthFailure,+ resolveMCPClientCapabilityProfile,} = require('@librechat/api');const { CacheKeys, Constants } = require('librechat-data-provider');const { getMCPManager, getMCPServersRegistry, getFlowStateManager } = require('~/config');@@ -51,6 +51,7 @@ const MCP_REINITIALIZE_FAILURE_REASONS = {* @param {import('@librechat/api').AuthIdentityContext} [params.oboIdentityContext] - Non-template-visible OBO identity context built from the real request user.* @param {AbortSignal} [params.signal] - Cancels queued and in-flight catalog reads when the request ends.* @param {import('@librechat/api').MCPServerCatalogRecoveryPolicy} [params.recoveryPolicy]+ * @param {import('librechat-data-provider').TMCPAppsPolicy} [params.mcpApps]*/async function loadMCPServerCatalogs({user,@@ -60,7 +61,9 @@ async function loadMCPServerCatalogs({oboIdentityContext,signal,recoveryPolicy,+ mcpApps,}) {+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);const flowManager = getFlowStateManager(getLogStores(CacheKeys.FLOWS));const tokenMethods = { findToken, updateToken, createToken, deleteTokens };const mcpManager = getMCPManager();@@ -75,7 +78,12 @@ async function loadMCPServerCatalogs({attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,});return loadCatalogs(- { user, servers, signal, recoveryPolicy },+ {+ user,+ servers: servers.map((server) => ({ ...server, capabilityProfile })),+ signal,+ recoveryPolicy,+ },{loadUserMCPAuthMap: (userId, serverNames) =>getUserMCPAuthMap({@@ -150,9 +158,9 @@ async function reinitMCPServer({oboIdentityContext,oauthEnd,recoveryPolicy,- streamId,- jobCreatedAt,+ mcpApps,}) {+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);/** @type {MCPConnection | null} */let connection = null;let serverConfig = providedConfig;@@ -286,6 +294,7 @@ async function reinitMCPServer({upstreamTokenProvider,upstreamTokenProviderResolver,oboIdentityContext,+ capabilityProfile,});logger.info('[MCP Reinitialize] Successfully established connection');@@ -328,6 +337,7 @@ async function reinitMCPServer({upstreamTokenProvider,upstreamTokenProviderResolver,oboIdentityContext,+ capabilityProfile,});if (discoveryResult.tools && discoveryResult.tools.length > 0) {@@ -402,6 +412,7 @@ async function reinitMCPServer({serverConfig,...(publicationGeneration && { publicationGeneration }),...(publicationRevision && { publicationRevision }),+ capabilityProfile,});if (availableTools == null) {tools = null;diff --git a/api/server/services/Tools/mcp.spec.js b/api/server/services/Tools/mcp.spec.jsindex 9e5def2622..a37a36fb2a 100644--- a/api/server/services/Tools/mcp.spec.js+++ b/api/server/services/Tools/mcp.spec.js@@ -1,5 +1,6 @@const { Constants } = require('librechat-data-provider');const { logger } = require('@librechat/data-schemas');+const { STANDARD_MCP_CAPABILITY_PROFILE } = require('@librechat/api');const mockGetConnection = jest.fn();const mockDiscoverServerTools = jest.fn();@@ -269,6 +270,7 @@ describe('reinitMCPServer — customUserVars gating (issue #10969)', () => {tools: [],serverConfig: { type: 'streamable-http', url: 'https://thingy.example.com/mcp' },publicationGeneration: 'generation-current',+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});});diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.jsindex 5e27a91236..3fe4e79273 100644--- a/api/server/services/__tests__/MCP.spec.js+++ b/api/server/services/__tests__/MCP.spec.js@@ -4,6 +4,12 @@ const mockRegistry = {};const mockUpstreamTokenProvider = jest.fn().mockResolvedValue(null);const mockCreateOpenIDSessionTokenProvider = jest.fn(() => mockUpstreamTokenProvider);+const defaultMCPAppsPolicy = {+ enabled: false,+ legacyHtmlEnabled: true,+ maxAdmissionRequestsPerMinute: 240,+ maxPersistedAppBytes: 1048576,+};jest.mock('~/config', () => ({getMCPServersRegistry: jest.fn(() => mockRegistry),@@ -90,7 +96,7 @@ const {cacheMCPServerTools,} = require('~/server/services/Config');const { reinitMCPServer } = require('~/server/services/Tools/mcp');-const { getUserMCPAuthMap } = require('@librechat/api');+const { getUserMCPAuthMap, STANDARD_MCP_CAPABILITY_PROFILE } = require('@librechat/api');const {createMCPTool,healMcpToolNames,@@ -132,7 +138,12 @@ describe('getAssistantToolDefinitions', () => {},accessibleServerNames: ['app-server'],});- expect(getMCPServerTools).toHaveBeenCalledWith('u1', 'app-server', serverConfig);+ expect(getMCPServerTools).toHaveBeenCalledWith(+ 'u1',+ 'app-server',+ serverConfig,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );});it('recovers and re-caches a referenced server when its slice is missing', async () => {@@ -158,6 +169,8 @@ describe('getAssistantToolDefinitions', () => {serverTools: { [toolKey]: mcpDefinition },serverConfig,publicationGeneration: 'connection-generation',+ publicationRevision: undefined,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});});@@ -184,6 +197,8 @@ describe('getAssistantToolDefinitions', () => {serverConfig,userMCPAuthMap,upstreamTokenProvider: mockUpstreamTokenProvider,+ recoveryPolicy: undefined,+ mcpApps: defaultMCPAppsPolicy,oboIdentityContext: {appUserId: 'u1',openidSubject: undefined,diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.jsindex e8156e9f6c..aa7cdef494 100644--- a/api/server/services/__tests__/ToolService.spec.js+++ b/api/server/services/__tests__/ToolService.spec.js@@ -517,6 +517,77 @@ describe('ToolService - Action Capability Gating', () => {);});+ it('submits canonical MCP output and persists its App attachment', async () => {+ const uiResources = [{ uri: 'ui://app', mimeType: 'text/html;profile=mcp-app' }];+ mockLoadToolsUtil.mockResolvedValue({+ loadedTools: [+ {+ name: 'safe_tool',+ mcp: true,+ _call: jest+ .fn()+ .mockResolvedValue(['safe output', { [Tools.ui_resources]: { data: uiResources } }]),+ },+ ],+ toolContextMap: {},+ });+ const client = buildClient(buildFilters('output', 'PRIVATE-OUTPUT'));+ client.responseMessage = {+ messageId: 'message_1',+ conversationId: 'conversation_1',+ attachments: [],+ };+ client.res = { write: jest.fn() };++ await expect(processRequiredActions(client, [buildAction()])).resolves.toEqual({+ tool_outputs: [{ tool_call_id: 'call_1', output: 'safe output' }],+ });++ expect(client.responseMessage.attachments).toEqual([+ expect.objectContaining({+ type: Tools.ui_resources,+ toolCallId: 'call_1',+ [Tools.ui_resources]: uiResources,+ }),+ ]);+ expect(client.res.write).toHaveBeenCalledWith(expect.stringContaining('event: attachment\n'));+ });++ it('omits an MCP App attachment when canonical output is substituted', async () => {+ const privateOutput = 'PRIVATE-OUTPUT';+ mockLoadToolsUtil.mockResolvedValue({+ loadedTools: [+ {+ name: 'safe_tool',+ mcp: true,+ _call: jest+ .fn()+ .mockResolvedValue([+ privateOutput,+ { [Tools.ui_resources]: { data: [{ uri: 'ui://app' }] } },+ ]),+ },+ ],+ toolContextMap: {},+ });+ const client = buildClient(buildFilters('output', privateOutput));+ client.responseMessage = {+ messageId: 'message_1',+ conversationId: 'conversation_1',+ attachments: [],+ };+ client.res = { write: jest.fn() };++ const result = await processRequiredActions(client, [buildAction()]);++ expect(JSON.parse(result.tool_outputs[0].output)).toMatchObject({+ error: 'content_filter_block',+ field: 'output',+ });+ expect(client.responseMessage.attachments).toEqual([]);+ expect(client.res.write).not.toHaveBeenCalled();+ });+it('replaces an uninspectable tool output before UI or model submission', async () => {const deeplyNestedOutput = { visible: 'safe' };let current = deeplyNestedOutput;@@ -1910,6 +1981,7 @@ describe('ToolService - Action Capability Gating', () => {req.user.id,serverName,expect.objectContaining({ requiresOAuth: true }),+ 'standard',);expect(reinitMCPServer).toHaveBeenCalledWith(expect.objectContaining({@@ -1984,6 +2056,7 @@ describe('ToolService - Action Capability Gating', () => {req.user.id,serverName,expect.objectContaining({ requiresOAuth: true }),+ 'standard',);expect(reinitMCPServer).toHaveBeenCalledTimes(1);expect(reinitMCPServer).toHaveBeenCalledWith(@@ -2256,6 +2329,7 @@ describe('ToolService - Action Capability Gating', () => {expect.objectContaining({url: expect.stringContaining('LIBRECHAT_BODY_MESSAGEID'),}),+ 'standard',);});@@ -2451,6 +2525,7 @@ describe('ToolService - Action Capability Gating', () => {expect.objectContaining({url: expect.stringContaining('LIBRECHAT_BODY_MESSAGEID'),}),+ 'standard',);});@@ -2551,6 +2626,7 @@ describe('ToolService - Action Capability Gating', () => {req.user.id,serverName,expect.objectContaining({ url: 'https://config.example.com/mcp' }),+ 'standard',);});});diff --git a/api/server/services/initializeMCPs.js b/api/server/services/initializeMCPs.jsindex cd18896f89..4623037e3d 100644--- a/api/server/services/initializeMCPs.js+++ b/api/server/services/initializeMCPs.js@@ -1,5 +1,6 @@const mongoose = require('mongoose');const { logger } = require('@librechat/data-schemas');+const { resolveMCPAppsPolicy } = require('librechat-data-provider');const {registerShutdownTask,setMCPToolsChangedHandler,@@ -7,6 +8,7 @@ const {setMCPToolsChangedGenerationHandler,setMCPToolsChangedGenerationRenewalHandler,setMCPToolsChangedRevisionHandler,+ createMCPAppBindingCodec,} = require('@librechat/api');const { syncStaticTools, mergeAppTools, getAppConfig, invalidateCachedTools } = require('./Config');const { startMCPAuthorizationFenceRetryWorker } = require('./MCPAuthorizationFenceRetry');@@ -26,10 +28,21 @@ const { createMCPServersRegistry, createMCPManager } = require('~/config');* @param {{ userId?: string, role?: string }} [ctx]*/async function resolveMCPAllowlists(ctx) {- const appConfig = await getAppConfig({ role: ctx?.role, userId: ctx?.userId });+ const appConfig = await getAppConfig({+ role: ctx?.role,+ userId: ctx?.userId,+ failClosed: true,+ });return {allowedDomains: appConfig?.mcpSettings?.allowedDomains,allowedAddresses: appConfig?.mcpSettings?.allowedAddresses,+ mcpApps: resolveMCPAppsPolicy(+ appConfig?.mcpSettings?.apps,+ undefined,+ appConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ appConfig?.mcpAppSandbox?.url,+ ),};}@@ -48,6 +61,7 @@ async function refreshChangedServerTools({serverConfig,publicationGeneration,publicationRevision,+ capabilityProfile,}) {await updateMCPServerTools({userId,@@ -56,6 +70,7 @@ async function refreshChangedServerTools({serverConfig,...(publicationGeneration && { publicationGeneration }),...(publicationRevision && { publicationRevision }),+ capabilityProfile,});const toolCount = tools.length;logger.info(@@ -107,6 +122,13 @@ async function initializeMCPs() {appConfig?.mcpSettings?.allowedDomains,appConfig?.mcpSettings?.allowedAddresses,resolveMCPAllowlists,+ resolveMCPAppsPolicy(+ appConfig?.mcpSettings?.apps,+ undefined,+ appConfig?.mcpAppSandbox?.maxPersistedAppBytes,+ appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,+ appConfig?.mcpAppSandbox?.url,+ ),);} catch (error) {logger.error('[MCP] Failed to initialize MCPServersRegistry:', error);@@ -118,6 +140,7 @@ async function initializeMCPs() {catalogRecoveryMaxStateEntries: appConfig?.mcpSettings?.catalogRecovery?.maxStateEntries,catalogRecoveryMaxDetachedDiscoveries:appConfig?.mcpSettings?.catalogRecovery?.maxDetachedDiscoveries,+ appBindingCodec: createMCPAppBindingCodec(process.env.JWT_SECRET),});startMCPAuthorizationFenceRetryWorker(invalidateCachedTools, {intervalMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryIntervalMs,diff --git a/api/server/services/initializeMCPs.plugins.spec.js b/api/server/services/initializeMCPs.plugins.spec.jsindex c462d8fde0..c5127017da 100644--- a/api/server/services/initializeMCPs.plugins.spec.js+++ b/api/server/services/initializeMCPs.plugins.spec.js@@ -24,6 +24,7 @@ const mockRegisterShutdownTask = jest.fn();const mockSetHandler = jest.fn();jest.mock('@librechat/api', () => ({+ createMCPAppBindingCodec: jest.fn(() => ({ create: jest.fn(), verify: jest.fn() })),get getDeploymentPluginMcpServers() {return mockGetDeploymentPluginMcpServers;},diff --git a/api/server/services/initializeMCPs.spec.js b/api/server/services/initializeMCPs.spec.jsindex 0f1f9250e2..0f76546a16 100644--- a/api/server/services/initializeMCPs.spec.js+++ b/api/server/services/initializeMCPs.spec.js@@ -76,6 +76,7 @@ const mockSetMCPToolsChangedGenerationHandler = jest.fn();const mockSetMCPToolsChangedGenerationRenewalHandler = jest.fn();const mockSetMCPToolsChangedRevisionHandler = jest.fn();const mockRegisterShutdownTask = jest.fn();+const mockAppBindingCodec = { create: jest.fn(), verify: jest.fn() };const mockUpdateMCPServerTools = jest.fn();const mockGetMCPToolsCacheGeneration = jest.fn();const mockRenewMCPToolsCacheGeneration = jest.fn();@@ -83,6 +84,7 @@ const mockGetNextAppToolsPublicationRevision = jest.fn();const mockGetDeploymentPluginMcpServers = jest.fn(() => ({}));jest.mock('@librechat/api', () => ({+ createMCPAppBindingCodec: jest.fn(() => mockAppBindingCodec),get registerShutdownTask() {return mockRegisterShutdownTask;},@@ -150,6 +152,12 @@ describe('initializeMCPs', () => {['localhost'],undefined,expect.any(Function), // per-request allowlist resolver+ {+ enabled: false,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ },);});@@ -167,6 +175,12 @@ describe('initializeMCPs', () => {allowedDomains,undefined,expect.any(Function),+ {+ enabled: false,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ },);});@@ -183,9 +197,63 @@ describe('initializeMCPs', () => {undefined,undefined,expect.any(Function),+ {+ enabled: false,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ },);});+ it.each([+ [+ true,+ {+ enabled: true,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ },+ ],+ [+ false,+ {+ enabled: false,+ legacyHtmlEnabled: false,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ },+ ],+ ])('normalizes the startup MCP Apps policy for apps=%s', async (apps, expected) => {+ mockGetAppConfig.mockResolvedValue({ mcpConfig: null, mcpSettings: { apps } });++ await initializeMCPs();++ expect(mockCreateMCPServersRegistry.mock.calls[0][4]).toEqual(expected);+ });++ it('publishes the base admission ceiling once to the registry policy', async () => {+ mockGetAppConfig.mockResolvedValue({+ mcpConfig: null,+ mcpSettings: { apps: true },+ mcpAppSandbox: {+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ maxAdmissionRequestsPerMinute: 480,+ },+ });++ await initializeMCPs();++ expect(mockCreateMCPServersRegistry.mock.calls[0][4]).toEqual({+ enabled: true,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 480,+ sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ });+ });+it('wires a per-request resolver that reads the merged (non-baseOnly) config', async () => {mockGetAppConfig.mockResolvedValue({mcpConfig: null,@@ -199,14 +267,28 @@ describe('initializeMCPs', () => {// The resolver resolves the request's merged allowlists — not the boot YAML base.mockGetAppConfig.mockResolvedValue({- mcpSettings: { allowedDomains: ['merged.com'], allowedAddresses: ['10.0.0.0/8'] },+ mcpSettings: {+ apps: true,+ allowedDomains: ['merged.com'],+ allowedAddresses: ['10.0.0.0/8'],+ },});const resolved = await resolver({ userId: 'u1', role: 'ADMIN' });- expect(mockGetAppConfig).toHaveBeenLastCalledWith({ role: 'ADMIN', userId: 'u1' });+ expect(mockGetAppConfig).toHaveBeenLastCalledWith({+ role: 'ADMIN',+ userId: 'u1',+ failClosed: true,+ });expect(resolved).toEqual({allowedDomains: ['merged.com'],allowedAddresses: ['10.0.0.0/8'],+ mcpApps: {+ enabled: true,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 1048576,+ maxAdmissionRequestsPerMinute: 240,+ },});});@@ -240,6 +322,7 @@ describe('initializeMCPs', () => {{catalogRecoveryMaxStateEntries: undefined,catalogRecoveryMaxDetachedDiscoveries: undefined,+ appBindingCodec: mockAppBindingCodec,},);});@@ -256,6 +339,7 @@ describe('initializeMCPs', () => {expect(mockCreateMCPManager).toHaveBeenCalledWith(mcpServers, {catalogRecoveryMaxStateEntries: undefined,catalogRecoveryMaxDetachedDiscoveries: undefined,+ appBindingCodec: mockAppBindingCodec,});});@@ -280,6 +364,7 @@ describe('initializeMCPs', () => {{catalogRecoveryMaxStateEntries: 2500,catalogRecoveryMaxDetachedDiscoveries: 8,+ appBindingCodec: mockAppBindingCodec,},);expect(mockStartMCPAuthorizationFenceRetryWorker).toHaveBeenCalledWith(@@ -470,6 +555,7 @@ describe('initializeMCPs', () => {{catalogRecoveryMaxStateEntries: undefined,catalogRecoveryMaxDetachedDiscoveries: undefined,+ appBindingCodec: mockAppBindingCodec,},);});diff --git a/client/jest.config.cjs b/client/jest.config.cjsindex 78dca456e9..28b5f842cb 100644--- a/client/jest.config.cjs+++ b/client/jest.config.cjs@@ -33,6 +33,7 @@ module.exports = {'jest-file-loader','^test/(.*)$': '<rootDir>/test/$1','^~/(.*)$': '<rootDir>/src/$1',+ '^@librechat/client$': '<rootDir>/../packages/client/dist/index.cjs','^librechat-data-provider/react-query$':'<rootDir>/../node_modules/librechat-data-provider/src/react-query',},diff --git a/client/package.json b/client/package.jsonindex d5eb5240b0..048dceec69 100644--- a/client/package.json+++ b/client/package.json@@ -39,6 +39,7 @@"@librechat/client": "*","@marsidev/react-turnstile": "^1.1.0","@mcp-ui/client": "^5.7.0",+ "@modelcontextprotocol/ext-apps": "^1.7.4","@monaco-editor/react": "^4.7.0","@radix-ui/react-accordion": "^1.2.20","@radix-ui/react-alert-dialog": "^1.1.23",diff --git a/client/public/mcp-sandbox.html b/client/public/mcp-sandbox.htmlnew file mode 100644index 0000000000..e026148e68--- /dev/null+++ b/client/public/mcp-sandbox.html@@ -0,0 +1,427 @@+<!doctype html>+<html style="height: 100%; margin: 0">+ <head>+ <meta charset="utf-8" />+ <title>MCP App Sandbox</title>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }+ html,+ body {+ width: 100%;+ height: 100%;+ overflow: hidden;+ background: transparent;+ }+ iframe {+ width: 100%;+ height: 100%;+ border: none;+ display: block;+ background: transparent;+ }+ </style>+ </head>+ <body>+ <script>+ 'use strict';++ // Replaced by the sandbox route with `window.__MCP_SANDBOX_CSP_APPLIED = true;`. The+ // proxy policy is delivered as a response header, while the separately generated View policy+ // is installed before App content. A static copy has neither trusted value, so createInnerFrame+ // refuses to build a frame unless both markers were replaced by the route.+ /*__CSP_APPLIED__*/+ /*__VIEW_CSP__*/++ const SANDBOX_PREFIX = 'ui/notifications/sandbox-';+ const ATTEST_METHOD = 'ui/notifications/sandbox-frame-attest';+ const DETACH_METHOD = 'ui/notifications/sandbox-frame-detach';+ const RESOURCE_READY_METHOD = 'ui/notifications/sandbox-resource-ready';+ const PROXY_READY_METHOD = 'ui/notifications/sandbox-proxy-ready';+ const ATTEST_INTERVAL_MS = 400;+ const ATTEST_TTL_MS = 1200;+ const READY_RETRY_MS = 500;+ const MAX_PENDING_MESSAGES = 50;+ const READY_MAX_RETRIES = 20;+ const DEFAULT_SANDBOX = 'allow-scripts allow-forms';+ const ALLOWED_SANDBOX_TOKENS = ['allow-scripts', 'allow-forms', 'allow-pointer-lock'];++ let innerFrame = null;+ let innerFrameBlobUrl = null;+ let innerFrameNavigated = false;+ let resourceApplied = false;+ let frameLoads = 0;+ let readyInterval = null;+ let readyRetries = 0;+ let attestNonce = null;+ let attestedAt = 0;+ let pendingToInner = [];+ let pendingToParent = [];++ // The parent passes its origin so the dedicated-origin proxy targets only its LibreChat host.+ // Without the parameter, refuse to bridge rather than post host messages to "*".+ const trustedOrigin = (function () {+ try {+ const param = new URLSearchParams(window.location.search).get('parentOrigin');+ if (param) {+ return new URL(param).origin;+ }+ } catch (e) {}+ return null;+ })();++ function postToParent(msg) {+ window.parent.postMessage(msg, trustedOrigin);+ }++ function mintNonce() {+ const bytes = new Uint8Array(16);+ crypto.getRandomValues(bytes);+ let hex = '';+ for (let i = 0; i < bytes.length; i += 1) {+ hex += bytes[i].toString(16).padStart(2, '0');+ }+ return hex;+ }++ // A document that stops attesting is a document that is gone: the heartbeat's interval and the+ // pagehide listener both die with the realm that owns them, so neither survives a top-level+ // navigation of the inner frame. That liveness signal, not the nonce, is what invalidates the+ // bridge; the nonce only excludes a document that never ran our bootstrap. An app that leaks+ // its own nonce to a document it navigates to gains nothing it could not already proxy itself.+ function frameUsable() {+ return (+ !!innerFrame && !!innerFrame.contentWindow && !innerFrameNavigated && frameLoads <= 1+ );+ }++ function attestFresh() {+ return Date.now() - attestedAt < ATTEST_TTL_MS;+ }++ // Hidden pages have their timers throttled to about once a minute, so a backgrounded app goes+ // stale while it is perfectly alive. Hold its traffic instead of dropping it and release it on+ // the next attestation: a navigated document cannot produce the nonce, so it can never trigger+ // a flush, and the queue is discarded the moment the frame detaches or loads again.+ function enqueue(queue, msg) {+ if (queue.length >= MAX_PENDING_MESSAGES) {+ queue.shift();+ }+ queue.push(msg);+ }++ function flushPending() {+ const toInner = pendingToInner;+ const toParent = pendingToParent;+ pendingToInner = [];+ pendingToParent = [];+ for (const msg of toInner) {+ innerFrame.contentWindow.postMessage(msg, '*');+ }+ for (const msg of toParent) {+ postToParent(msg);+ }+ }++ function discardPending() {+ pendingToInner = [];+ pendingToParent = [];+ }++ function stopReadyInterval() {+ if (readyInterval) {+ clearInterval(readyInterval);+ readyInterval = null;+ }+ }++ function releaseInnerFrame() {+ discardPending();+ if (innerFrameBlobUrl) {+ URL.revokeObjectURL(innerFrameBlobUrl);+ innerFrameBlobUrl = null;+ }+ if (innerFrame) {+ innerFrame.remove();+ innerFrame = null;+ }+ }++ function notifyReady() {+ if (!trustedOrigin) {+ console.error('[MCP Sandbox] Missing parentOrigin: refusing to bridge');+ return;+ }+ postToParent({ jsonrpc: '2.0', method: PROXY_READY_METHOD, params: {} });+ readyInterval = setInterval(() => {+ if (innerFrame || readyRetries >= READY_MAX_RETRIES) {+ stopReadyInterval();+ return;+ }+ readyRetries += 1;+ postToParent({ jsonrpc: '2.0', method: PROXY_READY_METHOD, params: {} });+ }, READY_RETRY_MS);+ }++ window.addEventListener('message', (event) => {+ let msg;+ try {+ msg = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;+ } catch {+ return;+ }+ if (!msg || msg.jsonrpc !== '2.0') return;++ if (event.source === window.parent) {+ if (!trustedOrigin || event.origin !== trustedOrigin) {+ return;+ }+ if (msg.method === RESOURCE_READY_METHOD) {+ stopReadyInterval();+ createInnerFrame(msg.params);+ return;+ }+ if (!frameUsable()) {+ return;+ }+ if (!attestFresh()) {+ enqueue(pendingToInner, msg);+ return;+ }+ innerFrame.contentWindow.postMessage(msg, '*');+ return;+ }++ if (!innerFrame || event.source !== innerFrame.contentWindow) {+ return;+ }++ const attested = !!attestNonce && !!msg.params && msg.params.nonce === attestNonce;+ if (msg.method === ATTEST_METHOD) {+ if (attested && frameUsable()) {+ attestedAt = Date.now();+ flushPending();+ }+ return;+ }+ if (msg.method === DETACH_METHOD) {+ if (attested) {+ attestedAt = 0;+ releaseInnerFrame();+ }+ return;+ }+ if (typeof msg.method === 'string' && msg.method.startsWith(SANDBOX_PREFIX)) {+ return;+ }+ if (!frameUsable()) {+ return;+ }+ if (!attestFresh()) {+ enqueue(pendingToParent, msg);+ return;+ }+ postToParent(msg);+ });++ function buildBootstrap(nonce) {+ return (+ '<script>(function(){var N=' ++ JSON.stringify(nonce) ++ ';var post=function(m){parent.postMessage({jsonrpc:"2.0",method:m,params:{nonce:N}},"*")};' ++ 'post(' ++ JSON.stringify(ATTEST_METHOD) ++ ');setInterval(function(){post(' ++ JSON.stringify(ATTEST_METHOD) ++ ')},' ++ ATTEST_INTERVAL_MS ++ ');addEventListener("pagehide",function(){post(' ++ JSON.stringify(DETACH_METHOD) ++ ')},{capture:true});})();<\/script>'+ );+ }++ function buildViewInjection(nonce) {+ const meta = document.createElement('meta');+ meta.httpEquiv = 'Content-Security-Policy';+ meta.content = window.__MCP_VIEW_CSP;+ return meta.outerHTML + buildBootstrap(nonce);+ }++ function createInnerFrame(params) {+ if (+ window.__MCP_SANDBOX_CSP_APPLIED !== true ||+ typeof window.__MCP_VIEW_CSP !== 'string'+ ) {+ console.error(+ '[MCP Sandbox] This document was served without a per-resource CSP: refusing to render',+ );+ return;+ }+ // One resource per sandbox document. Replacing the app in place would leave the previous+ // document's pending messages, blob URL and load events racing the new one.+ if (resourceApplied || !trustedOrigin) {+ return;+ }+ resourceApplied = true;++ const { html, permissions } = params;+ attestNonce = mintNonce();++ innerFrame = document.createElement('iframe');+ const frame = innerFrame;++ innerFrame.addEventListener('load', () => {+ frameLoads += 1;+ // The first load is our blob document. A stale load from an already-released frame must+ // not revoke the live blob URL, and only a second load of the live frame means the app+ // navigated away from our document.+ if (frameLoads <= 1 || frame !== innerFrame) {+ return;+ }+ innerFrameNavigated = true;+ attestedAt = 0;+ releaseInnerFrame();+ });++ // The inner View remains opaque even though its outer proxy has a dedicated origin. This+ // preserves per-View storage isolation and the heartbeat's navigation freshness guarantee.+ // Grant only from an allowlist so a new spec token cannot arrive as a silent capability.+ const requested = new Set(+ String(params.sandbox || DEFAULT_SANDBOX)+ .split(/\s+/)+ .filter(Boolean),+ );+ const granted = ALLOWED_SANDBOX_TOKENS.filter((token) => requested.has(token));+ innerFrame.setAttribute(+ 'sandbox',+ granted.length > 0 ? granted.join(' ') : DEFAULT_SANDBOX,+ );++ const allowParts = [];+ if (permissions && typeof permissions === 'object') {+ if (permissions.geolocation) allowParts.push('geolocation');+ if (permissions.clipboardWrite) allowParts.push('clipboard-write');+ }+ if (allowParts.length > 0) {+ innerFrame.setAttribute('allow', allowParts.join('; '));+ }++ // The bootstrap sits ahead of the app's own <meta charset>, so declare the encoding here+ // rather than let the parser guess from bytes our prefix now precedes.+ const blob = new Blob([injectIntoHead(html, buildViewInjection(attestNonce))], {+ type: 'text/html;charset=utf-8',+ });+ innerFrameBlobUrl = URL.createObjectURL(blob);+ innerFrame.src = innerFrameBlobUrl;+ innerFrame.style.cssText = 'width:100%;height:100%;border:none;display:block';++ document.body.appendChild(innerFrame);+ }++ window.addEventListener('pagehide', () => {+ if (innerFrameBlobUrl) {+ URL.revokeObjectURL(innerFrameBlobUrl);+ }+ });++ function findTagEnd(html, at) {+ let quote = '';+ for (let i = at + 1; i < html.length; i += 1) {+ const char = html[i];+ if (quote) {+ if (char === quote) {+ quote = '';+ }+ continue;+ }+ if (char === '"' || char === "'") {+ quote = char;+ continue;+ }+ if (char === '>') {+ return i;+ }+ }+ return -1;+ }++ function isTagAt(lower, at, name) {+ if (!lower.startsWith('<' + name, at)) {+ return false;+ }+ const after = lower[at + name.length + 1];+ return after === undefined || after === '>' || after === '/' || /\s/.test(after);+ }++ /** Locate only a document-level head in the HTML prolog. The first body/template/unknown token+ * ends the search so a later head can never capture the bootstrap inside inert App content. */+ function findDocumentInjectionPoint(html) {+ const lower = html.toLowerCase();+ let at = 0;+ let fallbackAt = 0;+ let sawDoctype = false;+ let sawHtml = false;++ if (lower.charCodeAt(0) === 0xfeff) {+ at = 1;+ fallbackAt = 1;+ }++ while (at < lower.length) {+ while (at < lower.length && /\s/.test(lower[at])) {+ at += 1;+ }+ fallbackAt = at;+ if (at >= lower.length) {+ return fallbackAt;+ }+ if (lower.startsWith('<!--', at)) {+ const close = lower.indexOf('-->', at + 4);+ if (close === -1) {+ return fallbackAt;+ }+ at = close + 3;+ fallbackAt = at;+ continue;+ }+ if (!sawDoctype && !sawHtml && isTagAt(lower, at, '!doctype')) {+ const end = findTagEnd(lower, at);+ if (end === -1) return fallbackAt;+ sawDoctype = true;+ at = end + 1;+ fallbackAt = at;+ continue;+ }+ if (!sawHtml && isTagAt(lower, at, 'html')) {+ const end = findTagEnd(lower, at);+ if (end === -1) return fallbackAt;+ sawHtml = true;+ at = end + 1;+ fallbackAt = at;+ continue;+ }+ if (isTagAt(lower, at, 'head')) {+ const end = findTagEnd(lower, at);+ return end === -1 ? fallbackAt : end + 1;+ }+ return fallbackAt;+ }+ return fallbackAt;+ }++ function injectIntoHead(html, injection) {+ // The bootstrap must run before any app script, and the app's bytes must reach the blob+ // verbatim: inject, never rewrap. Prefixing a document that opens with a doctype would push+ // the doctype down and flip the app into quirks mode.+ const at = findDocumentInjectionPoint(html);+ return html.slice(0, at) + injection + html.slice(at);+ }++ notifyReady();+ </script>+ </body>+</html>diff --git a/client/src/Providers/MCPAppsPolicyContext.tsx b/client/src/Providers/MCPAppsPolicyContext.tsxnew file mode 100644index 0000000000..97a0e7d61c--- /dev/null+++ b/client/src/Providers/MCPAppsPolicyContext.tsx@@ -0,0 +1,62 @@+import { createContext, useContext, useMemo } from 'react';+import {+ DEFAULT_MCP_APPS_POLICY,+ resolveMCPAppCspLimits,+ type TMCPAppsPolicy,+ type TStartupConfig,+} from 'librechat-data-provider';++type MCPAppsHostContextValue = {+ policy: Readonly<TMCPAppsPolicy>;+ userId?: string;+};++const DEFAULT_MCP_APPS_HOST: MCPAppsHostContextValue = {+ policy: DEFAULT_MCP_APPS_POLICY,+};++const MCPAppsPolicyContext = createContext<MCPAppsHostContextValue>(DEFAULT_MCP_APPS_HOST);++function getPublishedPolicy(+ startupConfig: TStartupConfig | undefined,+ ready: boolean,+): Readonly<TMCPAppsPolicy> {+ const policy = startupConfig?.mcpApps;+ if (+ !ready ||+ typeof policy?.enabled !== 'boolean' ||+ typeof policy.legacyHtmlEnabled !== 'boolean'+ ) {+ return DEFAULT_MCP_APPS_POLICY;+ }+ return { ...policy, cspLimits: resolveMCPAppCspLimits(policy.cspLimits) };+}++export function MCPAppsPolicyProvider({+ children,+ startupConfig,+ ready,+ userId,+}: {+ children: React.ReactNode;+ startupConfig?: TStartupConfig;+ ready: boolean;+ userId?: string;+}) {+ const policy = useMemo(() => getPublishedPolicy(startupConfig, ready), [ready, startupConfig]);+ const authenticatedUserId = typeof userId === 'string' && userId.trim() ? userId : undefined;+ const value = useMemo(+ () => ({ policy, userId: authenticatedUserId }),+ [authenticatedUserId, policy],+ );++ return <MCPAppsPolicyContext.Provider value={value}>{children}</MCPAppsPolicyContext.Provider>;+}++export function useMCPAppsPolicy(): Readonly<TMCPAppsPolicy> {+ return useContext(MCPAppsPolicyContext).policy;+}++export function useMCPAppsHost(): MCPAppsHostContextValue {+ return useContext(MCPAppsPolicyContext);+}diff --git a/client/src/Providers/MessagesViewContext.tsx b/client/src/Providers/MessagesViewContext.tsxindex afe54b5fe4..c07c090614 100644--- a/client/src/Providers/MessagesViewContext.tsx+++ b/client/src/Providers/MessagesViewContext.tsx@@ -6,6 +6,8 @@ interface MessagesViewContextValue {conversation: ReturnType<typeof useChatContext>['conversation'];conversationId: string | null | undefined;+ readOnly: boolean;+/** Submission and control states */isSubmitting: ReturnType<typeof useChatContext>['isSubmitting'];abortScroll: ReturnType<typeof useChatContext>['abortScroll'];@@ -110,6 +112,7 @@ export function MessagesViewProvider({ children }: { children: React.ReactNode }/** Combine all values into final context value */const contextValue = useMemo<MessagesViewContextValue>(() => ({+ readOnly: false,...conversationValues,...submissionStates,...messageOperations,@@ -140,6 +143,11 @@ export function useMessagesViewContext() {return context;}+/** Defaults to read-only when no provider is present, so live auth-bearing app actions stay off. */+export function useIsMessagesViewReadOnly(): boolean {+ return useContext(MessagesViewContext)?.readOnly ?? true;+}+/** Hook for components that only need conversation data */export function useMessagesConversation() {const { conversation, conversationId } = useMessagesViewContext();diff --git a/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsx b/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsxnew file mode 100644index 0000000000..0e354fce28--- /dev/null+++ b/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsx@@ -0,0 +1,184 @@+import { act, render, screen, waitFor } from '@testing-library/react';+import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TStartupConfig } from 'librechat-data-provider';+import { MCPAppsPolicyProvider, useMCPAppsHost, useMCPAppsPolicy } from '../MCPAppsPolicyContext';++function PolicyProbe() {+ const policy = useMCPAppsPolicy();+ return <output>{`${policy.enabled}:${policy.legacyHtmlEnabled}`}</output>;+}++function HostProbe() {+ const { policy, userId } = useMCPAppsHost();+ return <output>{`${policy.enabled}:${policy.legacyHtmlEnabled}:${userId ?? 'none'}`}</output>;+}++function LimitsProbe() {+ const { cspLimits } = useMCPAppsPolicy();+ return (+ <output>{`${cspLimits?.maxSourcesPerDirective}:${cspLimits?.maxSerializedLength}`}</output>+ );+}++function SandboxPolicyProbe() {+ const { sandboxUrl, maxAdmissionRequestsPerMinute } = useMCPAppsPolicy();+ return <output>{`${sandboxUrl ?? 'none'}:${maxAdmissionRequestsPerMinute ?? 'none'}`}</output>;+}++function CachedPolicyProvider({ children }: { children: React.ReactNode }) {+ const { data, isSuccess, error } = useQuery<TStartupConfig>(+ ['startup-policy'],+ () => new Promise<TStartupConfig>(() => undefined),+ { retry: false },+ );+ return (+ <MCPAppsPolicyProvider startupConfig={data} ready={isSuccess && error == null}>+ {children}+ </MCPAppsPolicyProvider>+ );+}++describe('MCPAppsPolicyProvider', () => {+ it('denies executable UI without an authenticated published policy', () => {+ render(<PolicyProbe />);+ expect(screen.getByText('false:false')).toBeInTheDocument();+ });++ it('publishes only a nonempty authenticated host identity', () => {+ const config = {+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+ } as TStartupConfig;+ const { rerender } = render(+ <MCPAppsPolicyProvider startupConfig={config} ready userId=" ">+ <HostProbe />+ </MCPAppsPolicyProvider>,+ );+ expect(screen.getByText('true:true:none')).toBeInTheDocument();++ rerender(+ <MCPAppsPolicyProvider startupConfig={config} ready userId="user-1">+ <HostProbe />+ </MCPAppsPolicyProvider>,+ );+ expect(screen.getByText('true:true:user-1')).toBeInTheDocument();+ });++ it('uses safe defaults for missing or malformed published CSP limits', () => {+ const { rerender } = render(+ <MCPAppsPolicyProvider+ startupConfig={{ mcpApps: { enabled: true, legacyHtmlEnabled: true } } as TStartupConfig}+ ready+ >+ <LimitsProbe />+ </MCPAppsPolicyProvider>,+ );+ expect(screen.getByText('32:4096')).toBeInTheDocument();++ rerender(+ <MCPAppsPolicyProvider+ startupConfig={+ {+ mcpApps: {+ enabled: true,+ legacyHtmlEnabled: true,+ cspLimits: { maxSourcesPerDirective: 0, maxSerializedLength: 8192 },+ },+ } as TStartupConfig+ }+ ready+ >+ <LimitsProbe />+ </MCPAppsPolicyProvider>,+ );+ expect(screen.getByText('32:8192')).toBeInTheDocument();+ });++ it('preserves deployment-owned sandbox startup fields', () => {+ render(+ <MCPAppsPolicyProvider+ startupConfig={+ {+ mcpApps: {+ enabled: true,+ legacyHtmlEnabled: true,+ sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ maxAdmissionRequestsPerMinute: 480,+ },+ } as TStartupConfig+ }+ ready+ >+ <SandboxPolicyProbe />+ </MCPAppsPolicyProvider>,+ );++ expect(+ screen.getByText('https://mcp-sandbox.example.com/api/mcp/sandbox:480'),+ ).toBeInTheDocument();+ });++ it('tracks the startup cache without exposing pending, missing, or malformed policy', async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={queryClient}>+ <CachedPolicyProvider>+ <PolicyProbe />+ </CachedPolicyProvider>+ </QueryClientProvider>,+ );++ expect(screen.getByText('false:false')).toBeInTheDocument();++ act(() => {+ queryClient.setQueryData<TStartupConfig>(['startup-policy'], {+ mcpApps: { enabled: false, legacyHtmlEnabled: true },+ } as TStartupConfig);+ });+ await waitFor(() => expect(screen.getByText('false:true')).toBeInTheDocument());++ act(() => {+ queryClient.setQueryData<TStartupConfig>(['startup-policy'], {+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+ } as TStartupConfig);+ });+ await waitFor(() => expect(screen.getByText('true:true')).toBeInTheDocument());++ act(() => {+ queryClient.setQueryData<TStartupConfig>(['startup-policy'], {+ mcpApps: { enabled: true, legacyHtmlEnabled: 'yes' },+ } as unknown as TStartupConfig);+ });+ await waitFor(() => expect(screen.getByText('false:false')).toBeInTheDocument());+ });++ it('denies executable UI when the startup query fails', async () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ logger: { log: console.log, warn: console.warn, error: jest.fn() },+ });++ function FailedPolicyProvider() {+ const { data, isSuccess, error } = useQuery<TStartupConfig>(+ ['failed-startup-policy'],+ () => Promise.reject(new Error('startup unavailable')),+ { retry: false },+ );+ return (+ <MCPAppsPolicyProvider startupConfig={data} ready={isSuccess && error == null}>+ <PolicyProbe />+ </MCPAppsPolicyProvider>+ );+ }++ render(+ <QueryClientProvider client={queryClient}>+ <FailedPolicyProvider />+ </QueryClientProvider>,+ );++ await waitFor(() =>+ expect(queryClient.getQueryState(['failed-startup-policy'])?.status).toBe('error'),+ );+ expect(screen.getByText('false:false')).toBeInTheDocument();+ });+});diff --git a/client/src/Providers/index.ts b/client/src/Providers/index.tsindex 3e499921fc..f0803f4b15 100644--- a/client/src/Providers/index.ts+++ b/client/src/Providers/index.ts@@ -27,5 +27,6 @@ export * from './UploadModalContext';export * from './ArtifactsContext';export * from './PromptGroupsContext';export * from './MessagesViewContext';+export * from './MCPAppsPolicyContext';export * from './MediaContext';export { default as BadgeRowProvider } from './BadgeRowContext';diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsxindex 7f8ddaddcb..02a1e2e42d 100644--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx@@ -28,6 +28,8 @@ import { AttachmentGroup, StreamingThoughtPeek } from './Parts';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';import { getActivityLabelText } from '~/utils/activityLabels';import { getOutcomeStatus, summarizeSpan } from './outcome';+import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';+import { MCPAppViews } from '~/components/MCPUIResource';import { sandboxStartingByToolCallId } from '~/store';import useClockFormat from '~/hooks/useClockFormat';import { cn, getMessageTimestamp } from '~/utils';@@ -400,7 +402,7 @@ function LivePhaseHeader({{combo !== '' && (<spanid={comboId}- className="shrink-0 text-xs font-normal text-text-secondary"+ className="text-text-secondary shrink-0 text-xs font-normal"data-testid="live-phase-combo">{combo}@@ -418,13 +420,8 @@ function LivePhaseHeader({* the failed rows. Only a stop count has no pill and stays visible.* The verdict is the span's, not the newest line's, so it keeps its* own separator from whatever the row happens to be saying. */}- {failedNote !== '' && <span className="sr-only">· {failedNote}</span>}- {cancelledNote !== '' && (- <>- <span className="mr-1 text-text-secondary">·</span>- <span>{cancelledNote}</span>- </>- )}+ <span className="text-text-secondary mr-1">·</span>+ <span>{detail}</span></span>)}</>@@ -754,6 +751,7 @@ export default function ActivityPhaseGroup({<><SearchVerticals attachments={attachments} /><AttachmentGroup attachments={attachments} />+ <MCPAppViews attachments={attachments} /></>) : null;if (!label && !isLive) {diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsxindex a944fbf037..b6d6df6a36 100644--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx@@ -1,6 +1,6 @@import { memo, useRef, useMemo, useEffect, useCallback, useContext, Fragment } from 'react';import { useStore } from 'jotai';-import { ContentTypes } from 'librechat-data-provider';+import { Constants, ContentTypes, Tools } from 'librechat-data-provider';import type {TMessageContentParts,SearchResultData,@@ -31,6 +31,7 @@ import {getActivityLabelText,} from '~/utils/activityLabels';import WorkspaceChanges, { partitionWorkspaceChanges } from './Parts/WorkspaceChanges';+import { MCPAppSuppressionContext, MCPAppViews } from '~/components/MCPUIResource';import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';import { MediaContext, MessageContext, SearchContext } from '~/Providers';import MemoryArtifacts, { hasMemoryArtifacts } from './MemoryArtifacts';@@ -100,6 +101,52 @@ const getSiblingStepIds = (return siblingStepIds.size === 0 ? undefined : siblingStepIds;};+const buildToolCallStepOwners = (+ content: Array<TMessageContentParts | undefined> | undefined,+): ReadonlyMap<string, readonly ToolCallStepOwner[]> => {+ const owners = new Map<string, ToolCallStepOwner[]>();+ for (const part of content ?? []) {+ if (part == null) {+ continue;+ }+ const toolCallId = getToolCallId(part);+ const stepId = getPartStepId(part);+ if (toolCallId === '' || stepId == null) {+ continue;+ }+ const entries = owners.get(toolCallId) ?? [];+ entries.push({ stepId, agentId: getPartAgentId(part) });+ owners.set(toolCallId, entries);+ }+ return owners;+};++const collectMessageAppAttachments = (+ content: Array<TMessageContentParts | undefined> | undefined,+ attachments: TAttachment[] | undefined,+): TAttachment[] => {+ const attachmentMap = mapAttachments(attachments ?? []);+ const ownersByToolCallId = buildToolCallStepOwners(content);+ const collected = new Set<TAttachment>();+ for (const part of content ?? []) {+ if (part == null) {+ continue;+ }+ const routed = filterAttachmentsForPart(+ attachmentMap[getToolCallId(part)],+ getPartAgentId(part),+ getPartStepId(part),+ getSiblingStepIds(part, ownersByToolCallId),+ );+ for (const attachment of routed ?? []) {+ if (attachment.type === Tools.ui_resources) {+ collected.add(attachment);+ }+ }+ }+ return Array.from(collected);+};+const getToolGroupId = (parts: PartWithIndex[], fallbackScope: number): string => {const firstPart = parts[0];if (!firstPart) {@@ -213,6 +260,8 @@ const PartWithContext = memo(function PartWithContext({type ContentPartsProps = {content: Array<TMessageContentParts | undefined> | undefined;messageId: string;+ /** Client-only parent anchor carried by one response while its server identities hydrate. */+ renderOwnerId?: string;/*** Skill names the user invoked manually via the `$` popover on this turn.* `createdHandler` seeds this on the assistant placeholder from@@ -335,21 +384,7 @@ const ContentPartsBody = memo(function ContentPartsBody({if (toolCallStepOwnersById != null) {return toolCallStepOwnersById;}- const owners = new Map<string, ToolCallStepOwner[]>();- for (const part of content ?? []) {- if (part == null) {- continue;- }- const toolCallId = getToolCallId(part);- const stepId = getPartStepId(part);- if (toolCallId === '' || stepId == null) {- continue;- }- const entries = owners.get(toolCallId) ?? [];- entries.push({ stepId, agentId: getPartAgentId(part) });- owners.set(toolCallId, entries);- }- return owners;+ return buildToolCallStepOwners(content);}, [toolCallStepOwnersById, content]);const attachmentsForPart = useCallback((part: TMessageContentParts): TAttachment[] | undefined =>@@ -1193,38 +1228,117 @@ const ContentPartsBody = memo(function ContentPartsBody({});const ContentParts = memo(function ContentParts(props: ContentPartsProps) {- const { attachments, messageId, conversationId, isSubmitting, isLatestMessage } = props;- const messageContext = useMemo(- () => ({+ const {+ attachments,+ messageId,+ conversationId,+ isCreatedByUser,+ isLatestMessage,+ isSubmitting,+ renderOwnerId,+ } = props;+ const appRenderIdentity = useRef<{+ messageId: string;+ conversationId: string | null | undefined;+ ownerId: string | undefined;+ isLatestMessage: boolean;+ isSubmitting: boolean;+ scope: number;+ } | null>(null);+ const previousIdentity = appRenderIdentity.current;+ const nextIsLatest = isLatestMessage === true;+ /** `clientQueueParentMessageId` follows one response through the local-user → created-user+ * re-key and disappears when `finalHandler` installs the durable response. It is not unique+ * across regenerations, so only an already-active latest response may use it to retain scope. */+ const startsAnotherRun = previousIdentity?.isSubmitting === false && isSubmitting;+ const continuesConversation =+ previousIdentity?.conversationId === conversationId ||+ (previousIdentity?.conversationId === Constants.NEW_CONVO &&+ conversationId != null &&+ conversationId !== Constants.NEW_CONVO);+ const exactIdentity =+ previousIdentity?.messageId === messageId &&+ previousIdentity.conversationId === conversationId &&+ (previousIdentity.ownerId === renderOwnerId ||+ previousIdentity.ownerId == null ||+ renderOwnerId == null);+ const createdIdentityHydration =+ !isCreatedByUser &&+ previousIdentity?.isSubmitting === true &&+ isSubmitting &&+ previousIdentity.isLatestMessage &&+ nextIsLatest &&+ continuesConversation &&+ previousIdentity.ownerId != null &&+ previousIdentity.ownerId === renderOwnerId &&+ previousIdentity.messageId.endsWith('_');+ const durableIdentityHydration =+ !isCreatedByUser &&+ previousIdentity?.isSubmitting === true &&+ !isSubmitting &&+ previousIdentity.isLatestMessage &&+ nextIsLatest &&+ continuesConversation &&+ previousIdentity.ownerId != null &&+ (renderOwnerId == null || renderOwnerId === previousIdentity.ownerId) &&+ !messageId.endsWith('_');+ const continuesResponse =+ !startsAnotherRun && (exactIdentity || createdIdentityHydration || durableIdentityHydration);+ if (previousIdentity == null) {+ appRenderIdentity.current = {messageId,conversationId,- isExpanded: false as const,- isSubmitting: isLatestMessage === true && isSubmitting,- isLatestMessage,- }),- [messageId, conversationId, isSubmitting, isLatestMessage],+ ownerId: renderOwnerId,+ isLatestMessage: nextIsLatest,+ isSubmitting,+ scope: 0,+ };+ } else if (!continuesResponse) {+ appRenderIdentity.current = {+ messageId,+ conversationId,+ ownerId: renderOwnerId,+ isLatestMessage: nextIsLatest,+ isSubmitting,+ scope: previousIdentity.scope + 1,+ };+ } else {+ previousIdentity.messageId = messageId;+ previousIdentity.conversationId = conversationId;+ previousIdentity.ownerId = renderOwnerId ?? previousIdentity.ownerId;+ previousIdentity.isLatestMessage = nextIsLatest;+ previousIdentity.isSubmitting = isSubmitting;+ }+ const appRenderScope = appRenderIdentity.current!.scope;+ const messageAppAttachments = useMemo(+ () => collectMessageAppAttachments(props.content, attachments),+ [props.content, attachments],+ );+ const suppressedAppAttachments = useMemo<ReadonlySet<TAttachment>>(+ () => new Set(messageAppAttachments),+ [messageAppAttachments],);const toolState = useRef<{messageId: string;conversationId: string | null | undefined;disclosures: ToolDisclosures;} | null>(null);- const previous = toolState.current;+ const previousToolState = toolState.current;/** The optimistic assistant id ends in `_`. Finalization replaces it with* the server id, not a new response. Ordinary sibling/conversation switches* get a fresh map, even if a provider reuses the same tool-call ids. */const finalizing =- previous?.messageId.endsWith('_') === true &&+ previousToolState?.messageId.endsWith('_') === true &&!messageId.endsWith('_') &&- props.isLatestMessage === true;+ isLatestMessage === true;if (- previous == null ||- previous.conversationId !== conversationId ||- (previous.messageId !== messageId && !finalizing)+ previousToolState == null ||+ previousToolState.conversationId !== conversationId ||+ (previousToolState.messageId !== messageId && !finalizing)) {toolState.current = { messageId, conversationId, disclosures: new Map() };} else {- previous.messageId = messageId;+ previousToolState.messageId = messageId;}const toolDisclosures = toolState.current!.disclosures;const reasoningState = useRef<{ messageId: string; disclosures: ReasoningDisclosures } | null>(@@ -1250,15 +1364,16 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {const attachmentsByName = useMemo(() => buildAttachmentsByName(attachments), [attachments]);const media = useMemo(() => ({ attachmentsByName }), [attachmentsByName]);return (- <MessageContext.Provider value={messageContext}>- <MediaContext.Provider value={media}>- <ReasoningDisclosureContext.Provider value={reasoningDisclosures}>- <ToolDisclosureContext.Provider value={toolDisclosures}>+ <MediaContext.Provider value={media}>+ <ReasoningDisclosureContext.Provider value={reasoningDisclosures}>+ <ToolDisclosureContext.Provider value={toolDisclosures}>+ <MCPAppSuppressionContext.Provider value={suppressedAppAttachments}><ContentPartsBody {...props} />- </ToolDisclosureContext.Provider>- </ReasoningDisclosureContext.Provider>- </MediaContext.Provider>- </MessageContext.Provider>+ </MCPAppSuppressionContext.Provider>+ <MCPAppViews key={`message-apps-${appRenderScope}`} attachments={messageAppAttachments} />+ </ToolDisclosureContext.Provider>+ </ReasoningDisclosureContext.Provider>+ </MediaContext.Provider>);});diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsxindex 2bfcee3af4..3fa3d84707 100644--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx@@ -1,4 +1,4 @@-import { useMemo, useState, useEffect, useCallback } from 'react';+import React, { useMemo, useState, useEffect, useCallback } from 'react';import { useRecoilValue } from 'recoil';import { Button } from '@librechat/client';import {@@ -14,6 +14,7 @@ import { cn, getToolDisplayLabel, logger, openInNewTab } from '~/utils';import { ToolIcon, getToolIconType, isError } from './ToolOutput';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';import { resolveToolCallPhase } from '~/utils/toolCallPhase';+import { MCPAppViews } from '~/components/MCPUIResource';import { toolPanelSpacingClassName } from './disclosure';import { useToolCallIntent } from './Parts/intent';import { AttachmentGroup } from './Parts';@@ -425,7 +426,7 @@ export default function ToolCall({'border-border-light bg-surface-secondary overflow-hidden rounded-lg border',)}>- <ToolCallInfo input={args ?? ''} output={output} attachments={attachments} />+ <ToolCallInfo input={args ?? ''} output={output} /></div>)}</div>@@ -453,7 +454,10 @@ export default function ToolCall({</div>)}{!hideAttachments && attachments && attachments.length > 0 && (- <AttachmentGroup attachments={attachments} />+ <>+ <AttachmentGroup attachments={attachments} />+ <MCPAppViews attachments={attachments} />+ </>)}</>);diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsxindex 267bf95b3f..d9a976e9a5 100644--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx@@ -27,7 +27,7 @@ import { ToolAuthWarning, ToolAuthWarningContext } from './auth';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';import { AttachmentGroup, ReasoningCompact } from './Parts';import { getOutcomeStatus, summarizeSpan } from './outcome';-import { FOLD_RAIL_CLASSES, ROW_GLYPH_SLOT } from './rows';+import { MCPAppViews } from '~/components/MCPUIResource';import { StackedToolIcons } from './ToolOutput';import { mapAttachments } from '~/utils/map';import { getSourceDomains } from './sources';@@ -639,6 +639,7 @@ export default function ToolCallGroup({<><SearchVerticals attachments={groupAttachments} /><AttachmentGroup attachments={groupAttachments} />+ <MCPAppViews attachments={groupAttachments} /></>)}</div>diff --git a/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx b/client/src/components/Chat/Messages/Content/ToolCallInfo.tsxindex f63f94b322..826192285b 100644--- a/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx@@ -1,13 +1,8 @@import { useState, useMemo } from 'react';import { ChevronDown } from 'lucide-react';-import { Tools } from 'librechat-data-provider';-import type { TAttachment, UIResource } from 'librechat-data-provider';-import UIResourceRenderer, { isSupportedUIResource } from '~/components/MCPUIResource/Renderer';-import { useOptionalMessagesOperations } from '~/Providers';import { useLocalize, useExpandCollapse } from '~/hooks';-import UIResourceCarousel from './UIResourceCarousel';import { OutputRenderer } from './ToolOutput';-import { handleUIAction, cn } from '~/utils';+import { cn } from '~/utils';function isSimpleObject(obj: unknown): obj is Record<string, string | number | boolean | null> {if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {@@ -92,17 +87,8 @@ function InputRenderer({ input }: { input: string }) {}}-export default function ToolCallInfo({- input,- output,- attachments,-}: {- input: string;- output?: string | null;- attachments?: TAttachment[];-}) {+export default function ToolCallInfo({ input, output }: { input: string; output?: string | null }) {const localize = useLocalize();- const { ask } = useOptionalMessagesOperations();const [showParams, setShowParams] = useState(false);const { style: paramsExpandStyle, ref: paramsExpandRef } = useExpandCollapse(showParams);@@ -121,14 +107,6 @@ export default function ToolCallInfo({return input.trim().length > 0;}, [input]);- const uiResources: UIResource[] =- attachments- ?.filter((attachment) => attachment.type === Tools.ui_resources)- .flatMap((attachment) => {- return attachment[Tools.ui_resources] as UIResource[];- })- .filter(isSupportedUIResource) ?? [];-return (<div className="w-full px-3 py-3.5">{output && <OutputRenderer text={output} />}@@ -160,21 +138,6 @@ export default function ToolCallInfo({</div></>)}- {uiResources.length > 0 && (- <>- {(hasParams || output) && <div className="border-border-light my-2 border-t" />}- {uiResources.length > 1 && <UIResourceCarousel uiResources={uiResources} />}- {uiResources.length === 1 && (- <UIResourceRenderer- resource={uiResources[0]}- onUIAction={async (result) => handleUIAction(result, ask)}- htmlProps={{- autoResizeIframe: { width: true, height: true },- }}- />- )}- </>- )}</div>);}diff --git a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsxindex fd1a17272d..3a00e82b2d 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx@@ -32,6 +32,19 @@ jest.mock('~/hooks', () => {};});+jest.mock('~/components/MCPUIResource', () => ({+ MCPAppViews: ({ attachments }: { attachments?: TAttachment[] }) => (+ <>+ {(attachments ?? [])+ .filter((item) => item.type === 'ui_resources')+ .flatMap((item) => item.ui_resources ?? [])+ .map((resource: { resourceId: string; toolName?: string }, index) => (+ <iframe key={`${resource.resourceId}:${index}`} title={`MCP App: ${resource.toolName}`} />+ ))}+ </>+ ),+}));+const LABEL = 'Compared both release paths';const NEXT_LABEL = 'Confirmed the rollback path is clean';@@ -452,6 +465,33 @@ describe('ActivityPhaseGroup', () => {/** Outside the fold: collapsing the card must not take the media with it. */expect(screen.getByTestId('activity-phase-panel')).not.toContainElement(image);});++ test('keeps correlated App views outside the phase panel across disclosure toggles', () => {+ const appAttachment = {+ type: Tools.ui_resources,+ [Tools.ui_resources]: [+ { resourceId: 'alpha', toolName: 'alpha' },+ { resourceId: 'beta', toolName: 'beta' },+ ],+ } as unknown as TAttachment;+ render(+ <ActivityPhaseGroup labelPart={labelPart} hasContent attachments={[appAttachment]}>+ <div data-testid="phase-content" />+ </ActivityPhaseGroup>,+ );++ const frames = screen.getAllByTitle(/MCP App:/);+ expect(frames).toHaveLength(2);+ expect(screen.getByTestId('activity-phase-panel')).not.toContainElement(frames[0]);+ const firstFrame = frames[0];++ const toggle = screen.getByRole('button', { name: LABEL });+ fireEvent.click(toggle);+ fireEvent.click(toggle);++ expect(screen.getAllByTitle(/MCP App:/)).toHaveLength(2);+ expect(screen.getAllByTitle(/MCP App:/)[0]).toBe(firstFrame);+ });});describe('ActivityPhaseGroup failure fast path', () => {diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsxindex 09352da57a..a356861225 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx@@ -1,8 +1,10 @@import React from 'react';import { RecoilRoot } from 'recoil';-import { ContentTypes, Tools } from 'librechat-data-provider';+import { Constants, ContentTypes, Tools } from 'librechat-data-provider';import { act, fireEvent, render, screen, within } from '@testing-library/react';-import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';+import type { EventSubmission, TAttachment, TMessageContentParts } from 'librechat-data-provider';+import useAttachmentHandler from '~/hooks/SSE/useAttachmentHandler';+import useAttachments from '~/hooks/Messages/useAttachments';import ContentParts from '../ContentParts';import { Text } from '../Parts';@@ -36,6 +38,37 @@ jest.mock('~/hooks/MCP', () => {};});+jest.mock('~/components/MCPUIResource', () => {+ const ReactActual = jest.requireActual('react') as typeof React;+ const MCPAppSuppressionContext = ReactActual.createContext<ReadonlySet<TAttachment> | null>(null);+ return {+ MCPAppSuppressionContext,+ MCPAppViews: ({ attachments }: { attachments?: TAttachment[] }) => {+ const suppressed = ReactActual.useContext(MCPAppSuppressionContext);+ const visible = (attachments ?? []).filter((attachment) => !suppressed?.has(attachment));+ if (visible.length === 0) {+ return null;+ }+ return (+ <div+ data-testid="mcp-app-attachments"+ data-owners={visible+ .map((attachment) => {+ const owned = attachment as TAttachment & { agentId?: string; stepId?: string };+ const resources = (attachment.ui_resources ?? []) as Array<{+ resourceId: string;+ }>;+ return `${owned.agentId ?? 'none'}/${owned.stepId ?? 'none'}/${resources+ .map((resource) => resource.resourceId)+ .join('+')}`;+ })+ .join(',')}+ />+ );+ },+ };+});+jest.mock('../ToolOutput', () => ({StackedToolIcons: () => <span data-testid="stacked-icons" />,getMCPServerName: () => '',@@ -502,6 +535,336 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {'1',]);});++ it('routes repeated App call ids by agent and exact-or-fallback host step', () => {+ const content = [+ makeMcpToolCall('call_0', true, 'step-1', 'agent-a'),+ makeTextPart('between calls'),+ makeMcpToolCall('call_0', true, undefined, 'agent-a'),+ makeTextPart('between agents'),+ makeMcpToolCall('call_0', true, 'step-1', 'agent-b'),+ ];+ const appResource = (resourceId: string) => ({+ resourceId,+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ });+ const attachments = [+ {+ type: Tools.ui_resources,+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: [appResource('alpha')],+ },+ {+ type: Tools.ui_resources,+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-2',+ [Tools.ui_resources]: [appResource('beta')],+ },+ {+ type: Tools.ui_resources,+ toolCallId: 'call_0',+ agentId: 'agent-b',+ stepId: 'step-1',+ [Tools.ui_resources]: [appResource('gamma')],+ },+ ] as unknown as TAttachment[];++ renderContentParts({ ...baseProps, content, attachments });++ expect(screen.getAllByTestId('mcp-app-attachments').map((view) => view.dataset.owners)).toEqual(+ ['agent-a/step-1/alpha,agent-a/step-2/beta,agent-b/step-1/gamma'],+ );+ });++ it('retains one App view through created and durable response identity hydration', () => {+ const content = [makeMcpToolCall('call_app', true, 'step-1', 'agent-a')];+ const attachments = [+ {+ type: Tools.ui_resources,+ toolCallId: 'call_app',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: [+ {+ resourceId: 'app',+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ },+ ],+ },+ ] as unknown as TAttachment[];+ const frame = (props: Partial<React.ComponentProps<typeof ContentParts>>) => (+ <RecoilRoot>+ <ContentParts+ {...baseProps}+ content={content}+ attachments={attachments}+ isSubmitting+ isLatestMessage+ messageId="local-user_"+ renderOwnerId="local-user"+ conversationId={String(Constants.NEW_CONVO)}+ {...props}+ />+ </RecoilRoot>+ );+ const { rerender } = render(frame({}));+ const appView = screen.getByTestId('mcp-app-attachments');++ /** `createdHandler` replaces both the user-derived response id and new-chat conversation id,+ * while `clientQueueParentMessageId` keeps this response linked to its submission. */+ rerender(frame({ messageId: 'server-user_', conversationId: 'conversation-1' }));+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);++ /** `finalHandler` installs the durable response and drops the client-only owner anchor. */+ rerender(+ frame({+ messageId: 'server-response',+ conversationId: 'conversation-1',+ renderOwnerId: undefined,+ isSubmitting: false,+ }),+ );+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);+ });++ it('keeps the message-owned App while activity, grouping, and parallel presentation change', () => {+ const appCall = makeMcpToolCall('call_app', true, 'step-1', 'agent-a');+ const otherCall = makeMcpToolCall('call_other', true, 'step-1', 'agent-b');+ const attachment = {+ type: Tools.ui_resources,+ toolCallId: 'call_app',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: [+ {+ resourceId: 'app',+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ },+ ],+ } as unknown as TAttachment;+ const frame = (content: TMessageContentParts[]) => (+ <RecoilRoot>+ <ContentParts+ {...baseProps}+ content={content}+ attachments={[attachment]}+ messageId="response_"+ renderOwnerId="user-parent"+ conversationId="conversation-1"+ isSubmitting+ isLatestMessage+ />+ </RecoilRoot>+ );+ const { rerender } = render(frame([appCall]));+ const appView = screen.getByTestId('mcp-app-attachments');++ /** A second adjacent call changes the sequential card presentation. */+ rerender(frame([appCall, otherCall]));+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);++ /** A server phase marker claims the calls after the App has mounted. */+ rerender(frame([appCall, otherCall, makePhasePart(0, 2, 'Rendered the scene')]));+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);++ /** Discovering a second lane moves the tool rows into parallel columns. */+ const parallel = [+ { ...(appCall as object), agentId: 'agent-a', groupId: 7 },+ { ...(otherCall as object), agentId: 'agent-b', groupId: 7 },+ ] as unknown as TMessageContentParts[];+ rerender(frame(parallel));+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);+ });++ it('remounts an App for a same-parent regeneration and a real sibling switch', () => {+ const content = [makeMcpToolCall('call_app', true, 'step-1', 'agent-a')];+ const attachments = [+ {+ type: Tools.ui_resources,+ toolCallId: 'call_app',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: [+ {+ resourceId: 'app',+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ },+ ],+ },+ ] as unknown as TAttachment[];+ const frame = (props: Partial<React.ComponentProps<typeof ContentParts>>) => (+ <RecoilRoot>+ <ContentParts+ {...baseProps}+ content={content}+ attachments={attachments}+ conversationId="conversation-1"+ {...props}+ />+ </RecoilRoot>+ );+ const { rerender } = render(+ frame({ messageId: 'first-response', renderOwnerId: undefined, isSubmitting: false }),+ );+ const settledView = screen.getByTestId('mcp-app-attachments');++ /** Regeneration deliberately reuses the user-parent anchor, so the settled → submitting+ * transition must rotate scope rather than treating the shared parent as response identity. */+ rerender(+ frame({+ messageId: 'first-response_',+ renderOwnerId: 'same-user-parent',+ isSubmitting: true,+ isLatestMessage: true,+ }),+ );+ const regeneratedView = screen.getByTestId('mcp-app-attachments');+ expect(regeneratedView).not.toBe(settledView);++ rerender(+ frame({+ messageId: 'other-sibling',+ renderOwnerId: undefined,+ isSubmitting: false,+ isLatestMessage: false,+ siblingIdx: 1,+ }),+ );+ expect(screen.getByTestId('mcp-app-attachments')).not.toBe(regeneratedView);+ });++ it('does not carry an active App into another conversation or an unsupported durable transition', () => {+ const content = [makeMcpToolCall('call_app', true, 'step-1', 'agent-a')];+ const attachments = [+ {+ type: Tools.ui_resources,+ toolCallId: 'call_app',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: [+ {+ resourceId: 'app',+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ },+ ],+ },+ ] as unknown as TAttachment[];+ const frame = (props: Partial<React.ComponentProps<typeof ContentParts>>) => (+ <RecoilRoot>+ <ContentParts+ {...baseProps}+ content={content}+ attachments={attachments}+ isSubmitting+ isLatestMessage+ messageId="response_"+ renderOwnerId="user-parent"+ conversationId="conversation-1"+ {...props}+ />+ </RecoilRoot>+ );+ const { rerender } = render(frame({}));+ const originalView = screen.getByTestId('mcp-app-attachments');++ rerender(frame({ messageId: 'other-response_', conversationId: 'conversation-2' }));+ const otherConversationView = screen.getByTestId('mcp-app-attachments');+ expect(otherConversationView).not.toBe(originalView);++ /** A durable id while still submitting is supported only when the response owner remains+ * explicit (the Assistants sync path spreads the initial response). Owner loss belongs to+ * `finalHandler`, which also ends submission. */+ rerender(+ frame({+ messageId: 'unexpected-durable-response',+ conversationId: 'conversation-2',+ renderOwnerId: undefined,+ }),+ );+ expect(screen.getByTestId('mcp-app-attachments')).not.toBe(otherConversationView);+ });++ it('retains resumed App steps through the SSE atom, merge hook, and content router', () => {+ const content = [+ makeMcpToolCall('call_0', true, 'step-1', 'agent-a'),+ makeTextPart('resume boundary'),+ makeMcpToolCall('call_0', true, 'step-2', 'agent-a'),+ ];+ const appResource = (resourceId: string) => ({+ resourceId,+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ });+ const alpha = {+ type: Tools.ui_resources,+ messageId: 'msg1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: [appResource('alpha')],+ } as unknown as TAttachment;+ const beta = {+ type: Tools.ui_resources,+ messageId: 'msg1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-2',+ [Tools.ui_resources]: [appResource('beta')],+ } as unknown as TAttachment;++ const ResumeHarness = () => {+ const handleAttachment = useAttachmentHandler();+ const { attachments } = useAttachments({ messageId: 'msg1', attachments: [alpha] });+ return (+ <>+ <button+ type="button"+ onClick={() => handleAttachment({ data: beta, submission: {} as EventSubmission })}+ >+ {'stream beta'}+ </button>+ <ContentParts {...baseProps} content={content} attachments={attachments} />+ </>+ );+ };++ render(+ <RecoilRoot>+ <ResumeHarness />+ </RecoilRoot>,+ );++ expect(screen.getAllByTestId('mcp-app-attachments').map((view) => view.dataset.owners)).toEqual(+ ['agent-a/step-1/alpha'],+ );++ fireEvent.click(screen.getByRole('button', { name: 'stream beta' }));++ expect(screen.getAllByTestId('mcp-app-attachments').map((view) => view.dataset.owners)).toEqual(+ ['agent-a/step-1/alpha,agent-a/step-2/beta'],+ );+ });+it('keeps a manually expanded completed tool group open when its content index shifts', () => {const content = [makeMcpToolCall('t1'), makeMcpToolCall('t2')];const nextContent = [makeTextPart('streamed preface'), ...content];diff --git a/client/src/components/Chat/Messages/Content/__tests__/Markdown.mcpui.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Markdown.mcpui.test.tsxindex 8bb5e0f3f7..1791811c90 100644--- a/client/src/components/Chat/Messages/Content/__tests__/Markdown.mcpui.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/Markdown.mcpui.test.tsx@@ -1,7 +1,9 @@import React from 'react';import { RecoilRoot } from 'recoil';import { render, screen } from '@testing-library/react';+import type { TStartupConfig } from 'librechat-data-provider';import { useConversationUIResources } from '~/hooks/Messages/useConversationUIResources';+import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';import { UI_RESOURCE_MARKER } from '~/components/MCPUIResource/plugin';import MarkdownLite from '../MarkdownLite';import Markdown from '../Markdown';@@ -11,10 +13,9 @@ jest.mock('~/hooks/Messages/useConversationUIResources', () => ({useConversationUIResources: jest.fn(),}));-// Mock @mcp-ui/client to render identifiable elements for assertionsjest.mock('@mcp-ui/client', () => ({UIResourceRenderer: ({ resource }: any) => (- <div data-testid="ui-resource-renderer" data-resource-uri={resource?.uri} />+ <span data-testid="ui-resource-renderer" data-resource-uri={resource?.uri} />),}));@@ -22,12 +23,24 @@ const mockUseConversationUIResources = useConversationUIResources as jest.Mockedtypeof useConversationUIResources>;+const renderMarkdown = (content: string, legacyHtmlEnabled = true) =>+ render(+ <RecoilRoot>+ <MCPAppsPolicyProvider+ startupConfig={{ mcpApps: { enabled: false, legacyHtmlEnabled } } as TStartupConfig}+ ready+ >+ <Markdown content={content} isLatestMessage={false} />+ </MCPAppsPolicyProvider>+ </RecoilRoot>,+ );+describe('Markdown with MCP UI markers (resource IDs)', () => {beforeEach(() => {jest.clearAllMocks();});- it('renders two UIResourceRenderer components for markers with resource IDs across separate attachments', () => {+ it('renders two legacy UI resources for markers with resource IDs across separate attachments', () => {// Two tool responses, each produced one ui_resources attachmentconst paris = {resourceId: 'abc123',@@ -57,17 +70,59 @@ describe('Markdown with MCP UI markers (resource IDs)', () => {`Browse these weather cards for more details ${UI_RESOURCE_MARKER}{abc123} ${UI_RESOURCE_MARKER}{def456}`,].join('\n');- render(- <RecoilRoot>- <Markdown content={content} isLatestMessage={false} />- </RecoilRoot>,- );+ renderMarkdown(content);const renderers = screen.getAllByTestId('ui-resource-renderer');expect(renderers).toHaveLength(2);expect(renderers[0]).toHaveAttribute('data-resource-uri', 'ui://weather/paris');expect(renderers[1]).toHaveAttribute('data-resource-uri', 'ui://weather/nyc');});++ it('does not mount an App View from a legacy Markdown marker', () => {+ mockUseConversationUIResources.mockReturnValue(+ new Map([+ [+ 'app-resource',+ {+ resourceId: 'app-resource',+ uri: 'ui://weather/app',+ mimeType: 'text/html;profile=mcp-app',+ text: '<div>App View</div>',+ toolName: 'get_weather',+ serverName: 'weather-server',+ },+ ],+ ]) as any,+ );++ renderMarkdown(+ `App resources are rendered with their tool call ${UI_RESOURCE_MARKER}{app-resource}`,+ );++ expect(screen.queryByTestId('ui-resource-renderer')).not.toBeInTheDocument();+ expect(document.querySelector('iframe[data-sandbox-url]')).not.toBeInTheDocument();+ });++ it('does not invoke the legacy renderer for a stored marker while disabled', () => {+ mockUseConversationUIResources.mockReturnValue(+ new Map([+ [+ 'legacy-resource',+ {+ resourceId: 'legacy-resource',+ uri: 'ui://weather/legacy',+ mimeType: 'text/html',+ text: '<div>Stored legacy view</div>',+ },+ ],+ ]) as never,+ );++ renderMarkdown(`Stored result ${UI_RESOURCE_MARKER}{legacy-resource}`, false);++ expect(screen.queryByTestId('ui-resource-renderer')).not.toBeInTheDocument();+ expect(screen.getByText(/Stored result/)).toBeInTheDocument();+ });});describe('Markdown table rendering', () => {diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsxindex d2ef0c0234..225fdd9931 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx@@ -2,6 +2,8 @@ import React from 'react';import { RecoilRoot } from 'recoil';import { Tools, Constants, dataService } from 'librechat-data-provider';import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import type { TStartupConfig } from 'librechat-data-provider';+import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';import { ToolAuthWarningContext } from '../auth';import ToolCall from '../ToolCall';import { logger } from '~/utils';@@ -43,6 +45,8 @@ jest.mock('~/hooks/MCP', () => {const mcpServerNames: string[] = [];return {useMCPIconMap: () => new Map(),+ useAppBridge: jest.fn(),+ useMCPAppFrame: jest.requireActual('~/hooks/MCP/useMCPAppFrame').useMCPAppFrame,useMCPServerNames: () => mcpServerNames,};});@@ -93,6 +97,7 @@ jest.mock('@librechat/client', () => ({{children}</button>),+ Spinner: (props: React.HTMLAttributes<HTMLSpanElement>) => <span {...props} />,}));jest.mock('lucide-react', () => ({@@ -124,6 +129,7 @@ jest.mock('librechat-data-provider', () => {});describe('ToolCall', () => {+ const originalSandboxUrl = process.env.VITE_MCP_SANDBOX_URL;const mockProps = {args: '{"test": "input"}',name: 'testFunction',@@ -132,12 +138,30 @@ describe('ToolCall', () => {isSubmitting: false,};- const renderWithRecoil = (component: React.ReactElement) => {- return render(<RecoilRoot>{component}</RecoilRoot>);+ const renderWithRecoil = (+ component: React.ReactElement,+ mcpApps = { enabled: true, legacyHtmlEnabled: true },+ ) => {+ return render(+ <RecoilRoot>+ <MCPAppsPolicyProvider startupConfig={{ mcpApps } as TStartupConfig} ready userId="user-1">+ {component}+ </MCPAppsPolicyProvider>+ </RecoilRoot>,+ );};beforeEach(() => {jest.clearAllMocks();+ process.env.VITE_MCP_SANDBOX_URL = 'http://sandbox.localhost:3081/api/mcp/sandbox';+ });++ afterAll(() => {+ if (originalSandboxUrl == null) {+ delete process.env.VITE_MCP_SANDBOX_URL;+ } else {+ process.env.VITE_MCP_SANDBOX_URL = originalSandboxUrl;+ }});describe('tool preparation feedback', () => {@@ -225,26 +249,24 @@ describe('ToolCall', () => {renderWithRecoil(<ToolCall {...mockProps} attachments={attachments as any} />);- fireEvent.click(screen.getByTestId('progress-text'));+ expect(screen.getByTestId('attachment-group')).toBeInTheDocument();- const toolCallInfo = screen.getByTestId('tool-call-info');- expect(toolCallInfo).toBeInTheDocument();+ fireEvent.click(screen.getByTestId('progress-text'));- const attachmentsData = toolCallInfo.getAttribute('data-attachments');- expect(attachmentsData).toBe(JSON.stringify(attachments));+ expect(screen.getByTestId('tool-call-info')).toBeInTheDocument();});- it('should pass empty array when no attachments', () => {+ it('should render ToolCallInfo without attachment-group when no attachments', () => {renderWithRecoil(<ToolCall {...mockProps} />);+ expect(screen.queryByTestId('attachment-group')).not.toBeInTheDocument();+fireEvent.click(screen.getByTestId('progress-text'));- const toolCallInfo = screen.getByTestId('tool-call-info');- const attachmentsData = toolCallInfo.getAttribute('data-attachments');- expect(attachmentsData).toBeNull(); // JSON.stringify(undefined) returns undefined, so attribute is not set+ expect(screen.getByTestId('tool-call-info')).toBeInTheDocument();});- it('should pass multiple attachments of different types', () => {+ it('should render AttachmentGroup with all attachments of mixed types', () => {const attachments = [{type: Tools.ui_resources,@@ -268,11 +290,127 @@ describe('ToolCall', () => {renderWithRecoil(<ToolCall {...mockProps} attachments={attachments as any} />);- fireEvent.click(screen.getByTestId('progress-text'));+ const attachmentGroup = screen.getByTestId('attachment-group');+ expect(JSON.parse(attachmentGroup.textContent!)).toEqual(attachments);+ });- const toolCallInfo = screen.getByTestId('tool-call-info');- const attachmentsData = toolCallInfo.getAttribute('data-attachments');- expect(JSON.parse(attachmentsData!)).toEqual(attachments);+ it('renders an iframe for an inline ui:// text resource attached to the tool call', () => {+ const attachments = [+ {+ type: Tools.ui_resources,+ messageId: 'msg1',+ toolCallId: 'tool1',+ conversationId: 'conv1',+ [Tools.ui_resources]: [+ {+ uri: 'ui://test-server/inline.html',+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>inline resource</p>',+ resourceId: 'inline-1',+ toolName: 'test-tool',+ serverName: 'test-server',+ toolArgs: { owner: 'resource' },+ content: [{ type: 'text', text: 'resource result' }],+ structuredContent: { owner: 'resource' },+ },+ ],+ },+ ];++ const { container } = renderWithRecoil(+ <ToolCall+ {...mockProps}+ args={{ owner: 'enclosing leaf' }}+ attachments={attachments as any}+ />,+ );++ // A server-bound inline resource renders through the sandbox bridge (not bare srcDoc),+ // so its App.connect handshake receives tool input/results.+ const iframe = container.querySelector('iframe[data-sandbox-url]');+ expect(iframe).toBeInTheDocument();+ const { useAppBridge } = jest.requireMock('~/hooks/MCP') as { useAppBridge: jest.Mock };+ expect(useAppBridge).toHaveBeenCalledWith(+ expect.objectContaining({+ toolArgs: { owner: 'resource' },+ toolResult: expect.objectContaining({+ content: [{ type: 'text', text: 'resource result' }],+ structuredContent: { owner: 'resource' },+ }),+ }),+ );+ });++ it('keeps ordinary tool content but does not mount a stored App while disabled', () => {+ const attachments = [+ {+ type: Tools.ui_resources,+ [Tools.ui_resources]: [+ {+ uri: 'ui://test-server/stored.html',+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>stored app</p>',+ resourceId: 'stored-app',+ toolName: 'test-tool',+ serverName: 'test-server',+ },+ ],+ },+ ];++ const { container } = renderWithRecoil(+ <ToolCall {...mockProps} attachments={attachments as never} />,+ { enabled: false, legacyHtmlEnabled: false },+ );++ expect(screen.getAllByText('Completed testFunction').length).toBeGreaterThan(0);+ expect(container.querySelector('iframe[data-sandbox-url]')).not.toBeInTheDocument();+ const { useAppBridge } = jest.requireMock('~/hooks/MCP') as { useAppBridge: jest.Mock };+ expect(useAppBridge).not.toHaveBeenCalled();+ });++ it('removes a mounted App when the observed policy is disabled', () => {+ const attachments = [+ {+ type: Tools.ui_resources,+ [Tools.ui_resources]: [+ {+ uri: 'ui://test-server/live.html',+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>live app</p>',+ resourceId: 'live-app',+ toolName: 'test-tool',+ serverName: 'test-server',+ },+ ],+ },+ ];+ const enabledConfig = {+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+ } as TStartupConfig;+ const disabledConfig = {+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ } as TStartupConfig;+ const toolCall = <ToolCall {...mockProps} attachments={attachments as never} />;+ const { container, rerender } = render(+ <RecoilRoot>+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ {toolCall}+ </MCPAppsPolicyProvider>+ </RecoilRoot>,+ );+ expect(container.querySelector('iframe[data-sandbox-url]')).toBeInTheDocument();++ rerender(+ <RecoilRoot>+ <MCPAppsPolicyProvider startupConfig={disabledConfig} ready userId="user-1">+ {toolCall}+ </MCPAppsPolicyProvider>+ </RecoilRoot>,+ );++ expect(container.querySelector('iframe[data-sandbox-url]')).not.toBeInTheDocument();+ expect(screen.getAllByText('Completed testFunction').length).toBeGreaterThan(0);});});@@ -327,6 +465,32 @@ describe('ToolCall', () => {expect(screen.queryByTestId('attachment-group')).not.toBeInTheDocument();});+ it('does not mount an App when a parent attachment owner hides the leaf output', () => {+ const attachments = [+ {+ type: Tools.ui_resources,+ [Tools.ui_resources]: [+ {+ resourceId: 'hidden-app',+ uri: 'ui://demo/hidden',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ text: '<p>Hidden App</p>',+ },+ ],+ },+ ];++ const { container } = renderWithRecoil(+ <ToolCall {...mockProps} attachments={attachments as never} hideAttachments />,+ );++ expect(container.querySelector('iframe[data-sandbox-url]')).not.toBeInTheDocument();+ const { useAppBridge } = jest.requireMock('~/hooks/MCP') as { useAppBridge: jest.Mock };+ expect(useAppBridge).not.toHaveBeenCalled();+ });+it('should render AttachmentGroup when hideAttachments is false explicitly', () => {const attachments = [{@@ -560,7 +724,7 @@ describe('ToolCall', () => {expect(screen.getByTestId('tool-call-info')).toBeInTheDocument();});- it('should handle complex nested attachments', () => {+ it('should render AttachmentGroup with complex nested attachments', () => {const complexAttachments = [{type: Tools.ui_resources,@@ -584,12 +748,6 @@ describe('ToolCall', () => {renderWithRecoil(<ToolCall {...mockProps} attachments={complexAttachments as any} />);- fireEvent.click(screen.getByTestId('progress-text'));-- const toolCallInfo = screen.getByTestId('tool-call-info');- const attachmentsData = toolCallInfo.getAttribute('data-attachments');- expect(JSON.parse(attachmentsData!)).toEqual(complexAttachments);-const attachmentGroup = screen.getByTestId('attachment-group');expect(JSON.parse(attachmentGroup.textContent!)).toEqual(complexAttachments);});diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsxindex f7a811d659..75a8cc6013 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx@@ -100,6 +100,19 @@ jest.mock('~/hooks/MCP', () => {};});+jest.mock('~/components/MCPUIResource', () => ({+ MCPAppViews: ({ attachments }: { attachments?: TAttachment[] }) => (+ <>+ {(attachments ?? [])+ .filter((item) => item.type === 'ui_resources')+ .flatMap((item) => item.ui_resources ?? [])+ .map((resource: { resourceId: string; toolName?: string }, index) => (+ <iframe key={`${resource.resourceId}:${index}`} title={`MCP App: ${resource.toolName}`} />+ ))}+ </>+ ),+}));+jest.mock('../ToolOutput', () => ({StackedToolIcons: ({ toolNames }: { toolNames: string[] }) => (<span data-testid="stacked-icons" data-tool-names={toolNames.join(',')} />@@ -300,6 +313,32 @@ describe('ToolCallGroup image hoisting', () => {expect(group.getAttribute('data-count')).toBe('2');});+ it('keeps correlated App views outside the collapsed panel across disclosure toggles', () => {+ const appAttachment = {+ type: Tools.ui_resources,+ toolCallId: 'call-0',+ agentId: 'agent-a',+ stepId: 'step-a',+ [Tools.ui_resources]: [+ { resourceId: 'alpha', toolName: 'alpha' },+ { resourceId: 'beta', toolName: 'beta' },+ ],+ } as unknown as TAttachment;+ renderGroup({ ...baseProps, groupAttachments: [appAttachment] });++ const frames = screen.getAllByTitle(/MCP App:/);+ expect(frames).toHaveLength(2);+ expect(screen.getByTestId('tool-call-group-panel')).not.toContainElement(frames[0]);+ const firstFrame = frames[0];++ const toggle = screen.getByRole('button');+ fireEvent.click(toggle);+ fireEvent.click(toggle);++ expect(screen.getAllByTitle(/MCP App:/)).toHaveLength(2);+ expect(screen.getAllByTitle(/MCP App:/)[0]).toBe(firstFrame);+ });+it('hoists non-image attachments so they survive collapse', () => {renderGroup({...baseProps,diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsxindex bd47bfdda3..88e0cf0677 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx@@ -1,12 +1,7 @@import React from 'react';-import { Tools } from 'librechat-data-provider';-import { UIResourceRenderer } from '@mcp-ui/client';import { render, screen, fireEvent } from '@testing-library/react';-import type { TAttachment } from 'librechat-data-provider';-import UIResourceCarousel from '~/components/Chat/Messages/Content/UIResourceCarousel';import ToolCallInfo from '~/components/Chat/Messages/Content/ToolCallInfo';-// Mock the dependenciesjest.mock('~/hooks', () => ({useLocalize: () => (key: string) => {const translations: Record<string, string> = {@@ -24,338 +19,79 @@ jest.mock('~/hooks', () => ({}),}));-jest.mock('~/Providers', () => ({- useOptionalMessagesOperations: () => ({- ask: jest.fn(),- }),-}));--jest.mock('@mcp-ui/client', () => ({- UIResourceRenderer: jest.fn(() => null),-}));--jest.mock('../UIResourceCarousel', () => ({- __esModule: true,- default: jest.fn(() => null),-}));-jest.mock('../ToolOutput', () => ({OutputRenderer: ({ text }: { text: string }) => <div data-testid="output-renderer">{text}</div>,}));jest.mock('~/utils', () => ({- handleUIAction: jest.fn(),- cn: (...classes: any[]) => classes.filter(Boolean).join(' '),+ cn: (...classes: string[]) => classes.filter(Boolean).join(' '),}));jest.mock('lucide-react', () => ({- ChevronDown: () => <span>{'ChevronDown'}</span>,+ ChevronDown: () => <span aria-hidden="true" />,}));describe('ToolCallInfo', () => {- const mockProps = {- input: '{"test": "input"}',- };+ const baseProps = { input: '{"query": "test"}' };beforeEach(() => {jest.clearAllMocks();});- describe('ui_resources from attachments', () => {- it('should render single ui_resource from attachments', () => {- const uiResource = {- resourceId: 'resource-1',- uri: 'ui://test/resource-1',- mimeType: 'text/html',- text: 'Test resource',- };-- const attachments: TAttachment[] = [- {- type: Tools.ui_resources,- messageId: 'msg123',- toolCallId: 'tool456',- conversationId: 'conv789',- [Tools.ui_resources]: [uiResource] as any,- },- ];-- render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);-- // Should render UIResourceRenderer for single resource- expect(UIResourceRenderer).toHaveBeenCalledWith(- expect.objectContaining({- resource: uiResource,- onUIAction: expect.any(Function),- htmlProps: {- autoResizeIframe: { width: true, height: true },- },- }),- expect.any(Object),- );-- // Should not render carousel for single resource- expect(UIResourceCarousel).not.toHaveBeenCalled();- });-- it('should render carousel for multiple ui_resources from attachments', () => {- const attachments: TAttachment[] = [- {- type: Tools.ui_resources,- messageId: 'msg1',- toolCallId: 'tool1',- conversationId: 'conv1',- [Tools.ui_resources]: [- {- resourceId: 'resource-1',- uri: 'ui://test/resource-1',- mimeType: 'text/html',- text: 'Resource 1',- },- {- resourceId: 'resource-2',- uri: 'ui://test/resource-2',- mimeType: 'text/html',- text: 'Resource 2',- },- {- resourceId: 'resource-3',- uri: 'ui://test/resource-3',- mimeType: 'text/html',- text: 'Resource 3',- },- ],- },- ];-- render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);-- // Should render carousel for multiple resources- expect(UIResourceCarousel).toHaveBeenCalledWith(- expect.objectContaining({- uiResources: [- expect.objectContaining({ resourceId: 'resource-1' }),- expect.objectContaining({ resourceId: 'resource-2' }),- expect.objectContaining({ resourceId: 'resource-3' }),- ],- }),- expect.any(Object),- );-- // Should not render individual UIResourceRenderer- expect(UIResourceRenderer).not.toHaveBeenCalled();- });-- it('renders a single supported resource without carousel layout', () => {- const attachments: TAttachment[] = [- {- type: Tools.ui_resources,- messageId: 'msg1',- toolCallId: 'tool1',- conversationId: 'conv1',- [Tools.ui_resources]: [- {- resourceId: 'blocked-resource',- uri: 'ui://test/blocked',- mimeType: 'application/vnd.mcp-ui.remote-dom+javascript',- text: 'malicious script',- },- {- resourceId: 'html-resource',- uri: 'ui://test/html',- mimeType: 'text/html',- text: '<p>Supported</p>',- },- ],- },- ];-- render(<ToolCallInfo {...mockProps} attachments={attachments} />);-- expect(UIResourceRenderer).toHaveBeenCalledWith(- expect.objectContaining({- resource: expect.objectContaining({ resourceId: 'html-resource' }),- }),- expect.any(Object),- );- expect(UIResourceCarousel).not.toHaveBeenCalled();- });-- it('omits the resource section when every resource is blocked', () => {- const attachments: TAttachment[] = [- {- type: Tools.ui_resources,- messageId: 'msg1',- toolCallId: 'tool1',- conversationId: 'conv1',- [Tools.ui_resources]: [- {- resourceId: 'blocked-resource',- uri: 'ui://test/blocked',- mimeType: 'text/uri-list',- text: 'https://example.com',- },- ],- },- ];-- render(<ToolCallInfo input="" attachments={attachments} />);-- expect(UIResourceRenderer).not.toHaveBeenCalled();- expect(UIResourceCarousel).not.toHaveBeenCalled();- });-- it('should handle no attachments', () => {- render(<ToolCallInfo {...mockProps} output="Some output" />);-- expect(UIResourceRenderer).not.toHaveBeenCalled();- expect(UIResourceCarousel).not.toHaveBeenCalled();+ describe('output rendering', () => {+ it('renders output text', () => {+ render(<ToolCallInfo {...baseProps} output="Some output" />);+ expect(screen.getByTestId('output-renderer').textContent).toBe('Some output');});- it('should handle empty attachments array', () => {- render(<ToolCallInfo {...mockProps} attachments={[]} />);-- expect(UIResourceRenderer).not.toHaveBeenCalled();- expect(UIResourceCarousel).not.toHaveBeenCalled();+ it('renders nothing when output is absent', () => {+ render(<ToolCallInfo {...baseProps} />);+ expect(screen.queryByTestId('output-renderer')).not.toBeInTheDocument();});- it('should handle attachments with non-ui_resources type', () => {- const attachments: TAttachment[] = [- {- type: Tools.web_search as any,- messageId: 'msg123',- toolCallId: 'tool456',- conversationId: 'conv789',- [Tools.web_search]: {- organic: [],- },- },- ];-- render(<ToolCallInfo {...mockProps} attachments={attachments} />);-- expect(UIResourceRenderer).not.toHaveBeenCalled();- expect(UIResourceCarousel).not.toHaveBeenCalled();+ it('renders null output without crashing', () => {+ render(<ToolCallInfo {...baseProps} output={null} />);+ expect(screen.queryByTestId('output-renderer')).not.toBeInTheDocument();});});- describe('rendering logic', () => {- it('should render output when provided', () => {- render(<ToolCallInfo {...mockProps} output="Some output" />);-- expect(screen.getByTestId('output-renderer')).toBeInTheDocument();- expect(screen.getByTestId('output-renderer').textContent).toBe('Some output');- });-- it('should render parameters toggle when input has JSON content', () => {- render(<ToolCallInfo {...mockProps} output="Some output" />);-+ describe('parameters toggle', () => {+ it('shows toggle when input has JSON content', () => {+ render(<ToolCallInfo {...baseProps} output="output" />);expect(screen.getByText('Parameters')).toBeInTheDocument();});- it('should not render parameters toggle when input is empty', () => {- render(<ToolCallInfo input="" output="Some output" />);-+ it('hides toggle when input is empty', () => {+ render(<ToolCallInfo input="" output="output" />);expect(screen.queryByText('Parameters')).not.toBeInTheDocument();});- it('should toggle parameters visibility when clicking', () => {- render(<ToolCallInfo {...mockProps} output="Some output" />);-- const paramsButton = screen.getByText('Parameters');- expect(paramsButton.closest('button')).toHaveAttribute('aria-expanded', 'false');-- fireEvent.click(paramsButton.closest('button')!);- expect(paramsButton.closest('button')).toHaveAttribute('aria-expanded', 'true');+ it('hides toggle when input is whitespace only', () => {+ render(<ToolCallInfo input=" " output="output" />);+ expect(screen.queryByText('Parameters')).not.toBeInTheDocument();});- it('should render ui_resources section when attachments have ui_resources', () => {- const attachments: TAttachment[] = [- {- type: Tools.ui_resources,- messageId: 'msg123',- toolCallId: 'tool456',- conversationId: 'conv789',- [Tools.ui_resources]: [- {- resourceId: 'resource-1',- uri: 'ui://test/resource-1',- mimeType: 'text/html',- text: 'Test',- },- ],- },- ];-- render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);-- expect(UIResourceRenderer).toHaveBeenCalledWith(- expect.objectContaining({- resource: expect.objectContaining({ resourceId: 'resource-1', text: 'Test' }),- }),- expect.any(Object),- );+ it('toggles expanded state when clicked', () => {+ render(<ToolCallInfo {...baseProps} output="output" />);+ const button = screen.getByText('Parameters').closest('button')!;+ expect(button).toHaveAttribute('aria-expanded', 'false');+ fireEvent.click(button);+ expect(button).toHaveAttribute('aria-expanded', 'true');+ fireEvent.click(button);+ expect(button).toHaveAttribute('aria-expanded', 'false');});});- describe('backward compatibility', () => {- it('should handle output with ui_resources metadata (ignored — uses attachments)', () => {- const output = JSON.stringify([- { type: 'text', text: 'Regular output' },- {- metadata: {- type: 'ui_resources',- data: [{ type: 'text', data: 'UI Resource' }],- },- },- ]);-- render(<ToolCallInfo {...mockProps} output={output} />);-- // Since we now use attachments, ui_resources in output should be ignored- expect(UIResourceRenderer).not.toHaveBeenCalled();- expect(UIResourceCarousel).not.toHaveBeenCalled();+ describe('edge cases', () => {+ it('renders with only input and no output', () => {+ render(<ToolCallInfo {...baseProps} />);+ expect(screen.getByText('Parameters')).toBeInTheDocument();});- it('should prioritize attachments over output ui_resources', () => {- const attachments: TAttachment[] = [- {- type: Tools.ui_resources,- messageId: 'msg123',- toolCallId: 'tool456',- conversationId: 'conv789',- [Tools.ui_resources]: [- {- resourceId: 'attachment-resource',- uri: 'ui://test/attachment-resource',- mimeType: 'text/html',- text: 'From attachments',- },- ],- },- ];-- const output = JSON.stringify([- {- metadata: {- type: 'ui_resources',- data: [{ type: 'output', data: 'From output' }],- },- },- ]);-- render(<ToolCallInfo {...mockProps} output={output} attachments={attachments} />);-- // Should use attachments, not output- expect(UIResourceRenderer).toHaveBeenCalledWith(- expect.objectContaining({- resource: expect.objectContaining({- resourceId: 'attachment-resource',- text: 'From attachments',- }),- }),- expect.any(Object),- );+ it('renders with empty props', () => {+ render(<ToolCallInfo input="" />);+ expect(screen.queryByTestId('output-renderer')).not.toBeInTheDocument();+ expect(screen.queryByText('Parameters')).not.toBeInTheDocument();});});});diff --git a/client/src/components/Chat/Messages/Content/__tests__/UIResourceCarousel.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/UIResourceCarousel.test.tsxindex 0e27711e33..9e519c1263 100644--- a/client/src/components/Chat/Messages/Content/__tests__/UIResourceCarousel.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/UIResourceCarousel.test.tsx@@ -22,6 +22,10 @@ jest.mock('~/hooks', () => ({key === 'com_ui_scroll_left' ? 'Scroll left' : 'Scroll right',}));+jest.mock('~/Providers/MCPAppsPolicyContext', () => ({+ useMCPAppsPolicy: () => ({ enabled: true, legacyHtmlEnabled: true }),+}));+// Mock the UIResourceRenderer componentjest.mock('@mcp-ui/client', () => ({UIResourceRenderer: ({ resource, onUIAction }: any) => (diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsxindex 01fcb3534a..2c6b031501 100644--- a/client/src/components/Chat/Messages/MessageParts.tsx+++ b/client/src/components/Chat/Messages/MessageParts.tsx@@ -185,6 +185,7 @@ function MessageParts(props: TMessageProps) {searchResults={searchResults}manualSkills={message.manualSkills}messageId={message.messageId}+ renderOwnerId={message.clientQueueParentMessageId}authorHeader={isCreatedByUser === true ? undefined : RESUME_AUTHOR_HEADER}setSiblingIdx={setSiblingIdx}isCreatedByUser={message.isCreatedByUser}diff --git a/client/src/components/MCPUIResource/MCPAppFrame.tsx b/client/src/components/MCPUIResource/MCPAppFrame.tsxnew file mode 100644index 0000000000..a32eb8782c--- /dev/null+++ b/client/src/components/MCPUIResource/MCPAppFrame.tsx@@ -0,0 +1,70 @@+import React from 'react';+import { Button, Spinner } from '@librechat/client';+import type { UIResource } from 'librechat-data-provider';+import type { MCPAppFrameState } from '~/hooks/MCP';+import { useLocalize } from '~/hooks';++const OVERLAY_CLASS =+ 'absolute inset-0 flex items-center gap-2 rounded-lg border border-border-light bg-surface-secondary px-4 py-3 text-sm text-text-secondary';++/**+ * The bridge iframe for one MCP App view plus its loading and failure overlays. The surface owns the+ * positioned container (and its definite height); this owns everything that must stay identical+ * across surfaces, including the sandbox tokens and the reveal rule.+ */+export function MCPAppFrame({+ frame,+ resource,+ centered = false,+ spinner = false,+}: {+ frame: MCPAppFrameState;+ resource: UIResource;+ centered?: boolean;+ spinner?: boolean;+}) {+ const localize = useLocalize();+ const overlayClass = centered ? `${OVERLAY_CLASS} justify-center` : OVERLAY_CLASS;++ if (frame.kind !== 'app') {+ return null;+ }++ return (+ <>+ {frame.status === 'loading' && (+ <div className={overlayClass} role="status">+ {spinner && <Spinner className="size-4" aria-hidden="true" />}+ {localize('com_ui_loading_interactive_view')}+ </div>+ )}+ {(frame.status === 'timedOut' || frame.status === 'failed') && (+ <div className={overlayClass} role="alert">+ <span>+ {localize(+ frame.status === 'failed'+ ? 'com_ui_mcp_app_load_error'+ : 'com_ui_mcp_app_failed_to_load',+ )}+ </span>+ {frame.canRetry && (+ <Button type="button" variant="outline" size="sm" onClick={frame.onRetry}>+ {localize('com_ui_retry')}+ </Button>+ )}+ </div>+ )}+ {frame.sandboxUrl && (+ <iframe+ ref={frame.iframeRef}+ data-sandbox-url={frame.sandboxUrl}+ sandbox="allow-scripts allow-same-origin allow-forms"+ className={+ frame.status === 'ready' ? 'visible size-full border-0' : 'invisible size-full border-0'+ }+ title={localize('com_ui_mcp_app_frame_title', { 0: resource.toolName ?? '' })}+ />+ )}+ </>+ );+}diff --git a/client/src/components/MCPUIResource/MCPAppViews.tsx b/client/src/components/MCPUIResource/MCPAppViews.tsxnew file mode 100644index 0000000000..4cd3073ece--- /dev/null+++ b/client/src/components/MCPUIResource/MCPAppViews.tsx@@ -0,0 +1,85 @@+import React, { useMemo } from 'react';+import type { TAttachment, UIResource } from 'librechat-data-provider';+import { useMCPAppsHost } from '~/Providers/MCPAppsPolicyContext';+import { selectToolCallUIResources } from '~/utils/mcpApps';+import { useAppBridge, useMCPAppFrame } from '~/hooks/MCP';+import { MCPAppFrame } from './MCPAppFrame';+import { useLocalize } from '~/hooks';++const DEFAULT_APP_VIEW_HEIGHT = 320;++/**+ * Attachments rendered by a stable ancestor. Presentation components may still receive those+ * attachments for files, search rows, and outcome metadata; only their duplicate App view stands+ * down. Object identity keeps independently owned nested attachments visible.+ */+export const MCPAppSuppressionContext = React.createContext<ReadonlySet<TAttachment> | null>(null);++const MCPAppView = React.memo(function MCPAppView({+ app,+ userId,+}: {+ app: UIResource;+ userId: string;+}) {+ const localize = useLocalize();+ const frame = useMCPAppFrame(app, {+ defaultHeight: DEFAULT_APP_VIEW_HEIGHT,+ toolArgs: app.toolArgs,+ });++ useAppBridge({+ iframeRef: frame.iframeRef,+ resource: app,+ toolArgs: frame.toolArgs,+ toolResult: frame.toolResult,+ userId,+ attempt: frame.attempt,+ active: frame.active,+ onSizeChanged: frame.onSizeChanged,+ onLoaded: frame.onLoaded,+ onTeardown: frame.onTeardown,+ onFailed: frame.onFailed,+ });++ if (frame.status === 'tornDown') {+ return null;+ }+ if (frame.kind === 'unavailable') {+ return (+ <div className="border-border-light bg-surface-secondary text-text-secondary my-2 flex items-center gap-2 rounded-lg border px-4 py-3 text-sm">+ {localize('com_ui_mcp_app_shared_unavailable')}+ </div>+ );+ }+ return (+ <div className="relative my-2 overflow-hidden" style={{ height: frame.height }}>+ <MCPAppFrame frame={frame} resource={app} spinner />+ </div>+ );+});++export function MCPAppViews({ attachments }: { attachments?: TAttachment[] }) {+ const suppressedAttachments = React.useContext(MCPAppSuppressionContext);+ const { policy, userId } = useMCPAppsHost();+ const visibleAttachments = useMemo(+ () =>+ suppressedAttachments == null+ ? attachments+ : attachments?.filter((attachment) => !suppressedAttachments.has(attachment)),+ [attachments, suppressedAttachments],+ );+ const apps = useMemo(() => selectToolCallUIResources(visibleAttachments), [visibleAttachments]);++ if (!policy.enabled || !userId || apps.length === 0) {+ return null;+ }++ return (+ <>+ {apps.map(({ key, resource }) => (+ <MCPAppView key={JSON.stringify([userId, key])} app={resource} userId={userId} />+ ))}+ </>+ );+}diff --git a/client/src/components/MCPUIResource/MCPUIResourceCarousel.tsx b/client/src/components/MCPUIResource/MCPUIResourceCarousel.tsxindex ba81a2f153..22fd8d271a 100644--- a/client/src/components/MCPUIResource/MCPUIResourceCarousel.tsx+++ b/client/src/components/MCPUIResource/MCPUIResourceCarousel.tsx@@ -12,7 +12,6 @@ interface MCPUIResourceCarouselProps {};}-/** Renders multiple MCP UI resources in a carousel. Works in chat, share, and search views. */export function MCPUIResourceCarousel(props: MCPUIResourceCarouselProps) {const { conversationId } = useOptionalMessagesConversation();diff --git a/client/src/components/MCPUIResource/Renderer.tsx b/client/src/components/MCPUIResource/Renderer.tsxindex f5bc460d19..0d14b54d7a 100644--- a/client/src/components/MCPUIResource/Renderer.tsx+++ b/client/src/components/MCPUIResource/Renderer.tsx@@ -1,6 +1,12 @@import { UIResourceRenderer as LegacyUIResourceRenderer } from '@mcp-ui/client';+import {+ isHtmlMediaType,+ isMcpAppMimeType,+ resolveMCPUIResourceMimeType,+} from 'librechat-data-provider';import type { UIResource } from 'librechat-data-provider';import type { ComponentProps } from 'react';+import { useMCPAppsPolicy } from '~/Providers/MCPAppsPolicyContext';type LegacyRendererProps = ComponentProps<typeof LegacyUIResourceRenderer>;@@ -14,10 +20,11 @@ type UIResourceRendererProps = Omit<export function isSupportedUIResource(resource: UIResource | null | undefined,): resource is UIResource {- return (- typeof resource?.mimeType === 'string' &&- resource.mimeType.split(';', 1)[0].trim().toLowerCase() === 'text/html'- );+ if (!resource || (resource.mimeType != null && typeof resource.mimeType !== 'string')) {+ return false;+ }+ const mimeType = resolveMCPUIResourceMimeType(resource.mimeType);+ return !isMcpAppMimeType(mimeType) && isHtmlMediaType(mimeType);}/** Restricts legacy MCP-UI rendering to sandboxed inline HTML resources. */@@ -26,7 +33,9 @@ export default function UIResourceRenderer({htmlProps,...props}: UIResourceRendererProps) {- if (!isSupportedUIResource(resource)) {+ const { legacyHtmlEnabled } = useMCPAppsPolicy();++ if (!legacyHtmlEnabled || !isSupportedUIResource(resource)) {return null;}diff --git a/client/src/components/MCPUIResource/__tests__/MCPAppViews.test.tsx b/client/src/components/MCPUIResource/__tests__/MCPAppViews.test.tsxnew file mode 100644index 0000000000..e844bf8428--- /dev/null+++ b/client/src/components/MCPUIResource/__tests__/MCPAppViews.test.tsx@@ -0,0 +1,257 @@+import React from 'react';+import { render } from '@testing-library/react';+import { Tools } from 'librechat-data-provider';+import type { TAttachment, TStartupConfig, UIResource } from 'librechat-data-provider';+import type { MCPAppFrameState } from '~/hooks/MCP';+import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';+import { MCPAppSuppressionContext, MCPAppViews } from '../MCPAppViews';+import { useAppBridge, useMCPAppFrame } from '~/hooks/MCP';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, values?: Record<number, string>) =>+ key === 'com_ui_mcp_app_frame_title' ? `MCP App: ${values?.[0] ?? ''}` : key,+}));++jest.mock('~/hooks/MCP', () => ({+ useAppBridge: jest.fn(),+ useMCPAppFrame: jest.fn(),+}));++const mockUseAppBridge = useAppBridge as jest.MockedFunction<typeof useAppBridge>;+const mockUseMCPAppFrame = useMCPAppFrame as jest.MockedFunction<typeof useMCPAppFrame>;++const enabledConfig = {+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+} as TStartupConfig;++function app(overrides: Partial<UIResource>): UIResource {+ return {+ resourceId: 'shared-resource',+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ ...overrides,+ };+}++function makeFrameState(+ resource: UIResource,+ toolArgs?: string | Record<string, unknown>,+ overrides: Partial<MCPAppFrameState> = {},+): MCPAppFrameState {+ const { buildAppToolResult } = jest.requireActual('~/utils/mcpApps');+ return {+ iframeRef: { current: null },+ status: 'ready',+ kind: 'app',+ height: 320,+ attempt: 0,+ canRetry: false,+ sandboxUrl: 'http://sandbox.localhost:3081/api/mcp/sandbox',+ inlineHtml: resource.text,+ toolArgs: typeof toolArgs === 'string' ? undefined : toolArgs,+ toolResult: buildAppToolResult(resource),+ active: true,+ onSizeChanged: jest.fn(),+ onLoaded: jest.fn(),+ onTeardown: jest.fn(),+ onFailed: jest.fn(),+ onRetry: jest.fn(),+ ...overrides,+ };+}++function attachment(+ owner: { toolCallId: string; agentId: string; stepId: string },+ resources: UIResource[],+): TAttachment {+ return {+ type: Tools.ui_resources,+ ...owner,+ [Tools.ui_resources]: resources,+ } as unknown as TAttachment;+}++describe('MCPAppViews', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockUseMCPAppFrame.mockImplementation((resource, options) =>+ makeFrameState(resource as UIResource, options.toolArgs),+ );+ });++ it('does not create frame or bridge hooks without both policy and host identity', () => {+ const attachments = [+ attachment({ toolCallId: 'call-1', agentId: 'agent-1', stepId: 'step-1' }, [+ app({ toolArgs: { owner: 'one' } }),+ ]),+ ];++ const { container } = render(+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready>+ <MCPAppViews attachments={attachments} />+ </MCPAppsPolicyProvider>,+ );++ expect(container).toBeEmptyDOMElement();+ expect(mockUseMCPAppFrame).not.toHaveBeenCalled();+ expect(mockUseAppBridge).not.toHaveBeenCalled();+ });++ it('retains every wrapper occurrence and gives each App only its own input and result', () => {+ const alpha = app({+ toolArgs: { owner: 'alpha' },+ content: [{ type: 'text', text: 'alpha result' }],+ structuredContent: { owner: 'alpha' },+ });+ const beta = app({+ toolArgs: { owner: 'beta' },+ content: [{ type: 'text', text: 'beta result' }],+ structuredContent: { owner: 'beta' },+ });+ const attachments = [+ attachment({ toolCallId: 'call-0', agentId: 'agent-alpha', stepId: 'step-alpha' }, [alpha]),+ attachment({ toolCallId: 'call-0', agentId: 'agent-beta', stepId: 'step-beta' }, [beta]),+ ];++ const { container } = render(+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <MCPAppViews attachments={attachments} />+ </MCPAppsPolicyProvider>,+ );++ expect(container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(2);+ expect(mockUseAppBridge).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ resource: alpha,+ userId: 'user-1',+ toolArgs: { owner: 'alpha' },+ toolResult: expect.objectContaining({+ content: [{ type: 'text', text: 'alpha result' }],+ structuredContent: { owner: 'alpha' },+ }),+ }),+ );+ expect(mockUseAppBridge).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ resource: beta,+ userId: 'user-1',+ toolArgs: { owner: 'beta' },+ toolResult: expect.objectContaining({+ content: [{ type: 'text', text: 'beta result' }],+ structuredContent: { owner: 'beta' },+ }),+ }),+ );+ });++ it('keeps legitimate same-owner and same-resource occurrences distinct', () => {+ const attachments = [+ attachment({ toolCallId: 'call-0', agentId: 'agent-alpha', stepId: 'step-alpha' }, [+ app({ toolArgs: { occurrence: 'first' }, content: [{ type: 'text', text: 'first' }] }),+ app({ toolArgs: { occurrence: 'second' }, content: [{ type: 'text', text: 'second' }] }),+ ]),+ ];++ const { container } = render(+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <MCPAppViews attachments={attachments} />+ </MCPAppsPolicyProvider>,+ );++ expect(container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(2);+ expect(mockUseAppBridge.mock.calls.map(([params]) => params.toolArgs)).toEqual([+ { occurrence: 'first' },+ { occurrence: 'second' },+ ]);+ expect(mockUseAppBridge.mock.calls.map(([params]) => params.toolResult?.content)).toEqual([+ [{ type: 'text', text: 'first' }],+ [{ type: 'text', text: 'second' }],+ ]);+ });++ it('preserves an App frame when unrelated wrappers and resources are inserted or reordered', () => {+ const target = app({ resourceId: 'target', toolName: 'target', toolArgs: { target: true } });+ const unrelated = app({+ resourceId: 'unrelated',+ toolName: 'unrelated',+ toolArgs: { unrelated: true },+ });+ const targetAttachment = attachment(+ { toolCallId: 'call-target', agentId: 'agent-a', stepId: 'step-a' },+ [target],+ );+ const unrelatedAttachment = attachment(+ { toolCallId: 'call-other', agentId: 'agent-b', stepId: 'step-b' },+ [unrelated],+ );+ const renderViews = (attachments: TAttachment[]) => (+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <MCPAppViews attachments={attachments} />+ </MCPAppsPolicyProvider>+ );+ const view = render(renderViews([targetAttachment]));+ const targetFrame = view.getByTitle('MCP App: target');++ view.rerender(renderViews([unrelatedAttachment, targetAttachment]));+ expect(view.getByTitle('MCP App: target')).toBe(targetFrame);++ const expandedTargetAttachment = attachment(+ { toolCallId: 'call-target', agentId: 'agent-a', stepId: 'step-a' },+ [unrelated, target],+ );+ view.rerender(renderViews([expandedTargetAttachment, unrelatedAttachment]));+ expect(view.getByTitle('MCP App: target')).toBe(targetFrame);++ view.rerender(renderViews([unrelatedAttachment, targetAttachment]));+ expect(view.getByTitle('MCP App: target')).toBe(targetFrame);+ });++ it('suppresses only attachments owned by an ancestor App surface', () => {+ const owned = attachment({ toolCallId: 'call-owned', agentId: 'agent-a', stepId: 'step-a' }, [+ app({ resourceId: 'owned', toolName: 'owned' }),+ ]);+ const nested = attachment({ toolCallId: 'call-nested', agentId: 'agent-b', stepId: 'step-b' }, [+ app({ resourceId: 'nested', toolName: 'nested' }),+ ]);++ const view = render(+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <MCPAppSuppressionContext.Provider value={new Set([owned])}>+ <MCPAppViews attachments={[owned, nested]} />+ </MCPAppSuppressionContext.Provider>+ </MCPAppsPolicyProvider>,+ );++ expect(view.queryByTitle('MCP App: owned')).not.toBeInTheDocument();+ expect(view.getByTitle('MCP App: nested')).toBeInTheDocument();+ });++ it.each([+ ['default', 320],+ ['compact', 260],+ ['lower clamp', 80],+ ])('uses the hook-owned %s height without a second surface minimum', (_label, height) => {+ mockUseMCPAppFrame.mockImplementationOnce((resource, options) =>+ makeFrameState(resource as UIResource, options.toolArgs, { height }),+ );+ const attachments = [+ attachment({ toolCallId: 'call-1', agentId: 'agent-1', stepId: 'step-1' }, [+ app({ toolName: 'compact' }),+ ]),+ ];++ const view = render(+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <MCPAppViews attachments={attachments} />+ </MCPAppsPolicyProvider>,+ );+ const container = view.getByTitle('MCP App: compact').parentElement;++ expect(container).toHaveStyle({ height: `${height}px` });+ expect(container?.style.minHeight).toBe('');+ });+});diff --git a/client/src/components/MCPUIResource/__tests__/MCPUIResource.test.tsx b/client/src/components/MCPUIResource/__tests__/MCPUIResource.test.tsxindex 430043bccf..07ad987f32 100644--- a/client/src/components/MCPUIResource/__tests__/MCPUIResource.test.tsx+++ b/client/src/components/MCPUIResource/__tests__/MCPUIResource.test.tsx@@ -16,6 +16,9 @@ jest.mock('~/Providers', () => ({useOptionalMessagesConversation: jest.fn(),useOptionalMessagesOperations: jest.fn(),}));+jest.mock('~/Providers/MCPAppsPolicyContext', () => ({+ useMCPAppsPolicy: () => ({ enabled: true, legacyHtmlEnabled: true }),+}));jest.mock('~/hooks', () => ({ useLocalize: jest.fn() }));jest.mock('~/utils', () => ({ handleUIAction: jest.fn() }));diff --git a/client/src/components/MCPUIResource/__tests__/MCPUIResourceCarousel.test.tsx b/client/src/components/MCPUIResource/__tests__/MCPUIResourceCarousel.test.tsxindex 9a5ca934a0..336ddffd5d 100644--- a/client/src/components/MCPUIResource/__tests__/MCPUIResourceCarousel.test.tsx+++ b/client/src/components/MCPUIResource/__tests__/MCPUIResourceCarousel.test.tsx@@ -1,89 +1,64 @@import React from 'react';-import { render, screen } from '@testing-library/react';import { RecoilRoot } from 'recoil';+import { render, screen } from '@testing-library/react';+import type { UIResource } from 'librechat-data-provider';+import { useConversationUIResources } from '~/hooks/Messages/useConversationUIResources';import { MCPUIResourceCarousel } from '../MCPUIResourceCarousel';-import {- useMessageContext,- useOptionalMessagesConversation,- useOptionalMessagesOperations,-} from '~/Providers';+import { useOptionalMessagesConversation } from '~/Providers';-// Mock dependencies-jest.mock('~/Providers');+jest.mock('~/Providers', () => ({+ useOptionalMessagesConversation: jest.fn(),+}));+jest.mock('~/hooks/Messages/useConversationUIResources');jest.mock('../../Chat/Messages/Content/UIResourceCarousel', () => ({__esModule: true,- default: ({ uiResources }: any) => (+ default: ({ uiResources }: { uiResources: UIResource[] }) => (<div data-testid="ui-resource-carousel" data-resource-count={uiResources.length}>- {uiResources.map((resource: any, index: number) => (+ {uiResources.map((resource, index) => (<div key={index} data-testid={`resource-${index}`} data-resource-uri={resource.uri} />))}</div>),}));-const mockUseMessageContext = useMessageContext as jest.MockedFunction<typeof useMessageContext>;const mockUseMessagesConversation = useOptionalMessagesConversation as jest.MockedFunction<typeof useOptionalMessagesConversation>;-const mockUseMessagesOperations = useOptionalMessagesOperations as jest.MockedFunction<- typeof useOptionalMessagesOperations+const mockUseConversationUIResources = useConversationUIResources as jest.MockedFunction<+ typeof useConversationUIResources>;+const makeResource = (id: string, uri: string): UIResource => ({+ resourceId: id,+ uri,+ mimeType: 'text/html',+ toolName: 'test-tool',+ serverName: 'test-server',+});+describe('MCPUIResourceCarousel', () => {- // Store the current test's messages so getMessages can return them- let currentTestMessages: any[] = [];+ const renderWithRecoil = (ui: React.ReactNode) => render(<RecoilRoot>{ui}</RecoilRoot>);beforeEach(() => {jest.clearAllMocks();- currentTestMessages = [];- mockUseMessageContext.mockReturnValue({ messageId: 'msg123' } as any);mockUseMessagesConversation.mockReturnValue({conversation: { conversationId: 'conv123' },conversationId: 'conv123',- } as any);- mockUseMessagesOperations.mockReturnValue({- getMessages: () => currentTestMessages,- ask: jest.fn(),- regenerate: jest.fn(),- handleContinue: jest.fn(),- setMessages: jest.fn(),- } as any);+ } as ReturnType<typeof useOptionalMessagesConversation>);+ mockUseConversationUIResources.mockReturnValue(new Map());});- const renderWithRecoil = (ui: React.ReactNode) => render(<RecoilRoot>{ui}</RecoilRoot>);-describe('multiple resource fetching', () => {- it('should fetch resources by resourceIds across conversation messages', () => {- mockUseMessageContext.mockReturnValue({ messageId: 'msg-current' } as any);- currentTestMessages = [- {- messageId: 'msg-origin',- attachments: [- {- type: 'ui_resources',- ui_resources: [- {- resourceId: 'id-1',- uri: 'ui://test/resource-id1',- mimeType: 'text/html',- text: '<p>Resource via ID 1</p>',- },- {- resourceId: 'id-2',- uri: 'ui://test/resource-id2',- mimeType: 'text/html',- text: '<p>Resource via ID 2</p>',- },- ],- },- ],- },- {- messageId: 'msg-current',- attachments: [],- },- ];+ it('fetches resources by resourceIds from the conversation map', () => {+ const r1 = makeResource('id-1', 'ui://test/resource-id1');+ const r2 = makeResource('id-2', 'ui://test/resource-id2');+ mockUseConversationUIResources.mockReturnValue(+ new Map([+ ['id-1', r1],+ ['id-2', r2],+ ]),+ );renderWithRecoil(<MCPUIResourceCarousel node={{ properties: { resourceIds: ['id-2', 'id-1'] } }} />,@@ -91,7 +66,6 @@ describe('MCPUIResourceCarousel', () => {const carousel = screen.getByTestId('ui-resource-carousel');expect(carousel).toHaveAttribute('data-resource-count', '2');-expect(screen.getByTestId('resource-0')).toHaveAttribute('data-resource-uri','ui://test/resource-id2',@@ -104,13 +78,8 @@ describe('MCPUIResourceCarousel', () => {});describe('error handling', () => {- it('should return null when no attachments', () => {- currentTestMessages = [- {- messageId: 'msg123',- attachments: undefined,- },- ];+ it('returns null when no resources match the given IDs', () => {+ mockUseConversationUIResources.mockReturnValue(new Map());const { container } = renderWithRecoil(<MCPUIResourceCarousel node={{ properties: { resourceIds: ['id1', 'id2'] } }} />,@@ -120,25 +89,10 @@ describe('MCPUIResourceCarousel', () => {expect(screen.queryByTestId('ui-resource-carousel')).not.toBeInTheDocument();});- it('should return null when resources not found', () => {- currentTestMessages = [- {- messageId: 'msg123',- attachments: [- {- type: 'ui_resources',- ui_resources: [- {- resourceId: 'existing-id',- uri: 'ui://test/resource',- mimeType: 'text/html',- text: '<p>Resource content</p>',- },- ],- },- ],- },- ];+ it('returns null when partial resources not found', () => {+ mockUseConversationUIResources.mockReturnValue(+ new Map([['existing-id', makeResource('existing-id', 'ui://test/resource')]]),+ );const { container } = renderWithRecoil(<MCPUIResourceCarousel node={{ properties: { resourceIds: ['non-existent-id'] } }} />,@@ -147,21 +101,15 @@ describe('MCPUIResourceCarousel', () => {expect(container.firstChild).toBeNull();});- it('should return null when no ui_resources attachments', () => {- currentTestMessages = [- {- messageId: 'msg123',- attachments: [- {- type: 'web_search',- web_search: { results: [] },- },- ],- },- ];+ it('returns null when conversationId is absent', () => {+ mockUseMessagesConversation.mockReturnValue({+ conversation: null,+ conversationId: null,+ } as ReturnType<typeof useOptionalMessagesConversation>);+ mockUseConversationUIResources.mockReturnValue(new Map());const { container } = renderWithRecoil(- <MCPUIResourceCarousel node={{ properties: { resourceIds: ['id1', 'id2'] } }} />,+ <MCPUIResourceCarousel node={{ properties: { resourceIds: ['test-id'] } }} />,);expect(container.firstChild).toBeNull();@@ -169,58 +117,22 @@ describe('MCPUIResourceCarousel', () => {});describe('edge cases', () => {- it('should handle empty resourceIds array', () => {- currentTestMessages = [- {- messageId: 'msg123',- attachments: [- {- type: 'ui_resources',- ui_resources: [- {- resourceId: 'test-id',- uri: 'ui://test/resource',- mimeType: 'text/html',- text: '<p>Resource content</p>',- },- ],- },- ],- },- ];-+ it('returns null for empty resourceIds array', () => {const { container } = renderWithRecoil(<MCPUIResourceCarousel node={{ properties: { resourceIds: [] } }} />,);-expect(container.firstChild).toBeNull();});- it('should handle duplicate resource IDs', () => {- currentTestMessages = [- {- messageId: 'msg123',- attachments: [- {- type: 'ui_resources',- ui_resources: [- {- resourceId: 'id-a',- uri: 'ui://test/resource-a',- mimeType: 'text/html',- text: '<p>Resource A content</p>',- },- {- resourceId: 'id-b',- uri: 'ui://test/resource-b',- mimeType: 'text/html',- text: '<p>Resource B content</p>',- },- ],- },- ],- },- ];+ it('passes duplicate IDs through to the carousel', () => {+ const ra = makeResource('id-a', 'ui://test/resource-a');+ const rb = makeResource('id-b', 'ui://test/resource-b');+ mockUseConversationUIResources.mockReturnValue(+ new Map([+ ['id-a', ra],+ ['id-b', rb],+ ]),+ );renderWithRecoil(<MCPUIResourceCarousel@@ -234,28 +146,12 @@ describe('MCPUIResourceCarousel', () => {const resources = screen.getAllByTestId(/resource-\d/);expect(resources).toHaveLength(5);expect(resources[0]).toHaveAttribute('data-resource-uri', 'ui://test/resource-a');- expect(resources[1]).toHaveAttribute('data-resource-uri', 'ui://test/resource-a');expect(resources[2]).toHaveAttribute('data-resource-uri', 'ui://test/resource-b');- expect(resources[3]).toHaveAttribute('data-resource-uri', 'ui://test/resource-b');expect(resources[4]).toHaveAttribute('data-resource-uri', 'ui://test/resource-a');});- it('should handle null messages data', () => {- currentTestMessages = [];-- const { container } = renderWithRecoil(- <MCPUIResourceCarousel node={{ properties: { resourceIds: ['test-id'] } }} />,- );-- expect(container.firstChild).toBeNull();- });-- it('should handle missing conversation', () => {- mockUseMessagesConversation.mockReturnValue({- conversation: null,- conversationId: null,- } as any);- currentTestMessages = [];+ it('returns null for empty messages', () => {+ mockUseConversationUIResources.mockReturnValue(new Map());const { container } = renderWithRecoil(<MCPUIResourceCarousel node={{ properties: { resourceIds: ['test-id'] } }} />,diff --git a/client/src/components/MCPUIResource/__tests__/Renderer.test.tsx b/client/src/components/MCPUIResource/__tests__/Renderer.test.tsxindex b04ced768b..7499ca4804 100644--- a/client/src/components/MCPUIResource/__tests__/Renderer.test.tsx+++ b/client/src/components/MCPUIResource/__tests__/Renderer.test.tsx@@ -1,6 +1,7 @@import { render, screen } from '@testing-library/react';import { UIResourceRenderer as LegacyUIResourceRenderer } from '@mcp-ui/client';-import type { UIResource } from 'librechat-data-provider';+import type { TStartupConfig, UIResource } from 'librechat-data-provider';+import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';import UIResourceRenderer from '../Renderer';jest.mock('@mcp-ui/client', () => ({@@ -13,6 +14,17 @@ const mockLegacyRenderer = LegacyUIResourceRenderer as jest.MockedFunction<typeof LegacyUIResourceRenderer>;+const renderEnabled = (ui: React.ReactElement) =>+ render(+ <MCPAppsPolicyProvider+ startupConfig={{ mcpApps: { enabled: true, legacyHtmlEnabled: true } } as TStartupConfig}+ ready+ userId="user-1"+ >+ {ui}+ </MCPAppsPolicyProvider>,+ );+describe('UIResourceRenderer', () => {beforeEach(() => {jest.clearAllMocks();@@ -22,7 +34,8 @@ describe('UIResourceRenderer', () => {'application/vnd.mcp-ui.remote-dom+javascript','application/vnd.mcp-ui.remote-dom','text/uri-list',- ])('blocks unsafe legacy MIME type %s', (mimeType) => {+ 'text/html;profile=mcp-app',+ ])('blocks MIME type %s from the legacy renderer', (mimeType) => {const resource: UIResource = {resourceId: 'unsafe-resource',uri: 'ui://unsafe',@@ -30,7 +43,7 @@ describe('UIResourceRenderer', () => {text: "root.innerHTML='<img src=x onerror=alert(window.origin)>'",};- const { container } = render(<UIResourceRenderer resource={resource} />);+ const { container } = renderEnabled(<UIResourceRenderer resource={resource} />);expect(container).toBeEmptyDOMElement();expect(mockLegacyRenderer).not.toHaveBeenCalled();@@ -44,7 +57,7 @@ describe('UIResourceRenderer', () => {text: '<p>Malformed resource</p>',};- const { container } = render(<UIResourceRenderer resource={resource} />);+ const { container } = renderEnabled(<UIResourceRenderer resource={resource} />);expect(container).toBeEmptyDOMElement();expect(mockLegacyRenderer).not.toHaveBeenCalled();@@ -59,7 +72,7 @@ describe('UIResourceRenderer', () => {text: '<p>Safe iframe content</p>',};- render(+ renderEnabled(<UIResourceRendererresource={resource}htmlProps={{ sandboxPermissions: 'allow-popups allow-same-origin' }}@@ -85,7 +98,7 @@ describe('UIResourceRenderer', () => {text: '<p>Safe iframe content</p>',};- render(<UIResourceRenderer resource={resource} />);+ renderEnabled(<UIResourceRenderer resource={resource} />);expect(mockLegacyRenderer).toHaveBeenCalledWith(expect.objectContaining({@@ -95,4 +108,50 @@ describe('UIResourceRenderer', () => {expect.any(Object),);});++ it.each([undefined, null])('defaults an absent MIME type (%s) to legacy HTML', (mimeType) => {+ const resource = {+ resourceId: 'legacy-resource',+ uri: 'ui://legacy',+ mimeType,+ text: '<p>Legacy resource</p>',+ } as unknown as UIResource;++ renderEnabled(<UIResourceRenderer resource={resource} />);++ expect(mockLegacyRenderer).toHaveBeenCalledWith(+ expect.objectContaining({+ resource: expect.objectContaining({ mimeType: 'text/html' }),+ }),+ expect.any(Object),+ );+ });++ it('does not reinterpret an explicit empty MIME type as HTML', () => {+ const resource: UIResource = {+ resourceId: 'empty-resource',+ uri: 'ui://empty',+ mimeType: '',+ text: '<p>Explicitly untyped</p>',+ };++ const { container } = renderEnabled(<UIResourceRenderer resource={resource} />);++ expect(container).toBeEmptyDOMElement();+ expect(mockLegacyRenderer).not.toHaveBeenCalled();+ });++ it('does not invoke the legacy SDK without an enabled host policy', () => {+ const resource: UIResource = {+ resourceId: 'stored-html',+ uri: 'ui://legacy/stored',+ mimeType: 'text/html',+ text: '<p>Stored legacy view</p>',+ };++ const { container } = render(<UIResourceRenderer resource={resource} />);++ expect(container).toBeEmptyDOMElement();+ expect(mockLegacyRenderer).not.toHaveBeenCalled();+ });});diff --git a/client/src/components/MCPUIResource/index.ts b/client/src/components/MCPUIResource/index.tsindex 9c42e5f461..1775ac4c3f 100644--- a/client/src/components/MCPUIResource/index.ts+++ b/client/src/components/MCPUIResource/index.ts@@ -1,4 +1,6 @@export { mcpUIResourcePlugin } from './plugin';export { MCPUIResource } from './MCPUIResource';+export { MCPAppFrame } from './MCPAppFrame';+export { MCPAppSuppressionContext, MCPAppViews } from './MCPAppViews';export { MCPUIResourceCarousel } from './MCPUIResourceCarousel';export * from './types';diff --git a/client/src/components/Share/ShareMessagesProvider.tsx b/client/src/components/Share/ShareMessagesProvider.tsxindex 7a958a6f59..a5032974d0 100644--- a/client/src/components/Share/ShareMessagesProvider.tsx+++ b/client/src/components/Share/ShareMessagesProvider.tsx@@ -21,6 +21,8 @@ export function ShareMessagesProvider({ messages, children }: ShareMessagesProvi() => ({conversation: null,conversationId: undefined,+ // Read-only so app bridges never proxy auth-bearing calls against the viewer's MCP servers.+ readOnly: true,// These are required by the context but not used in share viewask: () => {},regenerate: () => {},diff --git a/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx b/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsxnew file mode 100644index 0000000000..2e583a1b4f--- /dev/null+++ b/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx@@ -0,0 +1,1103 @@+import React from 'react';+import { RecoilRoot } from 'recoil';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { fireEvent, render, renderHook, screen, act } from '@testing-library/react';+import type { TStartupConfig, UIResource } from 'librechat-data-provider';+import {+ callMCPAppTool,+ fetchMCPResourceHtml,+ listMCPResources,+ listMCPResourceTemplates,+ readMCPResource,+ validateMCPAppBinding,+} from '~/utils/mcpApps';+import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';+import { MCPAppFrame } from '~/components/MCPUIResource/MCPAppFrame';+import { useMCPAppFrame } from '~/hooks/MCP/useMCPAppFrame';+import { useAppBridge } from '~/hooks/MCP/useAppBridge';+import { useIsMessagesViewReadOnly } from '~/Providers';++type Listener = (params: unknown) => void;+const requestExtra = () => ({ signal: new AbortController().signal });+type RequestHandler = (+ params: Record<string, unknown>,+ extra: ReturnType<typeof requestExtra>,+) => Promise<unknown>;+const mockAsk = jest.fn();++class FakeAppBridge {+ static instances: FakeAppBridge[] = [];++ capabilities: Record<string, unknown>;+ listeners = new Map<string, Listener[]>();+ connected: unknown = null;+ closed = false;+ resourceReady: Array<Record<string, unknown>> = [];+ toolInput: unknown[] = [];+ toolResults: unknown[] = [];+ hostContextChanges: unknown[] = [];+ teardowns = 0;+ onopenlink?: (+ params: { url: string },+ extra: ReturnType<typeof requestExtra>,+ ) => Promise<unknown>;++ oninitialized?: () => Promise<void>;+ oncalltool?: RequestHandler;+ onreadresource?: RequestHandler;+ onlistresources?: RequestHandler;+ onlistresourcetemplates?: RequestHandler;+ onmessage?: RequestHandler;++ constructor(+ _transport: unknown,+ _info: unknown,+ capabilities: Record<string, unknown>,+ _options: unknown,+ ) {+ this.capabilities = capabilities;+ FakeAppBridge.instances.push(this);+ }++ addEventListener(type: string, listener: Listener) {+ const bucket = this.listeners.get(type) ?? [];+ bucket.push(listener);+ this.listeners.set(type, bucket);+ }++ emit(type: string, params: unknown = {}) {+ for (const listener of this.listeners.get(type) ?? []) {+ listener(params);+ }+ }++ async connect(transport: unknown) {+ this.connected = transport;+ }++ close() {+ this.closed = true;+ }++ async sendSandboxResourceReady(params: Record<string, unknown>) {+ this.resourceReady.push(params);+ }++ async sendToolInput(params: unknown) {+ this.toolInput.push(params);+ }++ async sendToolResult(params: unknown) {+ this.toolResults.push(params);+ }++ async sendHostContextChange(params: unknown) {+ this.hostContextChanges.push(params);+ }++ async teardownResource() {+ this.teardowns += 1;+ return {};+ }+}++jest.mock('@modelcontextprotocol/ext-apps/app-bridge', () => ({+ AppBridge: jest.fn(),+ PostMessageTransport: jest.fn().mockImplementation((post: unknown, listen: unknown) => ({+ post,+ listen,+ })),+ buildAllowAttribute: (permissions?: Record<string, unknown>) =>+ ['camera', 'microphone', 'geolocation', 'clipboardWrite']+ .filter((key) => permissions?.[key])+ .map((key) => (key === 'clipboardWrite' ? 'clipboard-write' : key))+ .join('; '),+}));++jest.mock('~/utils/mcpApps', () => ({+ ...jest.requireActual('~/utils/mcpApps'),+ getMCPSandboxUrl: jest.fn(() => 'http://sandbox.localhost:3081/api/mcp/sandbox'),+ fetchMCPResourceHtml: jest.fn(),+ callMCPAppTool: jest.fn(),+ readMCPResource: jest.fn(),+ listMCPResources: jest.fn(),+ listMCPResourceTemplates: jest.fn(),+ validateMCPAppBinding: jest.fn(),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, values?: Record<number, string>) =>+ key === 'com_ui_mcp_app_frame_title' ? `MCP App: ${values?.[0] ?? ''}` : key,+}));++jest.mock('~/Providers', () => ({+ useOptionalMessagesOperations: () => ({ ask: mockAsk }),+ useIsMessagesViewReadOnly: jest.fn(() => false),+ useMCPAppsPolicy: () => ({+ enabled: true,+ legacyHtmlEnabled: true,+ cspLimits: { maxSourcesPerDirective: 32, maxSerializedLength: 4096 },+ }),+}));++const { AppBridge } = jest.requireMock('@modelcontextprotocol/ext-apps/app-bridge') as {+ AppBridge: jest.Mock;+};+const mockFetchHtml = fetchMCPResourceHtml as jest.MockedFunction<typeof fetchMCPResourceHtml>;+const mockCallTool = callMCPAppTool as jest.MockedFunction<typeof callMCPAppTool>;+const mockReadResource = readMCPResource as jest.MockedFunction<typeof readMCPResource>;+const mockListResources = listMCPResources as jest.MockedFunction<typeof listMCPResources>;+const mockListTemplates = listMCPResourceTemplates as jest.MockedFunction<+ typeof listMCPResourceTemplates+>;+const mockValidateBinding = validateMCPAppBinding as jest.MockedFunction<+ typeof validateMCPAppBinding+>;+const mockReadOnly = useIsMessagesViewReadOnly as jest.MockedFunction<+ typeof useIsMessagesViewReadOnly+>;++const SANDBOX_URL =+ 'http://localhost:3080/api/mcp/sandbox?parentOrigin=http%3A%2F%2Flocalhost%3A3080';++const enabledConfig = {+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+} as TStartupConfig;++const makeResource = (overrides: Partial<UIResource> = {}): UIResource =>+ ({+ resourceId: 'r1',+ uri: 'ui://app/main',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'render',+ serverName: 'demo',+ serverBinding: 'binding-demo',+ ...overrides,+ }) as UIResource;++function BridgeFrameHarness({ resource, userId }: { resource: UIResource; userId: string }) {+ const frame = useMCPAppFrame(resource, { defaultHeight: 320, toolArgs: { q: 1 } });+ useAppBridge({+ iframeRef: frame.iframeRef,+ resource,+ toolArgs: frame.toolArgs,+ toolResult: frame.toolResult,+ userId,+ attempt: frame.attempt,+ active: frame.active,+ onSizeChanged: frame.onSizeChanged,+ onLoaded: frame.onLoaded,+ onTeardown: frame.onTeardown,+ onFailed: frame.onFailed,+ });++ return (+ <div data-testid={`surface-${resource.toolName}`} style={{ height: frame.height }}>+ <MCPAppFrame frame={frame} resource={resource} />+ </div>+ );+}++function mountBridge(+ resource: UIResource,+ client: QueryClient,+ callbacks: { onFailed?: () => void; onTeardown?: () => void; userId?: string } = {},+) {+ const iframe = document.createElement('iframe');+ iframe.setAttribute('data-sandbox-url', SANDBOX_URL);+ document.body.appendChild(iframe);+ const iframeRef = { current: iframe };+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ </RecoilRoot>+ );+ const view = renderHook(+ () =>+ useAppBridge({+ iframeRef,+ resource,+ toolArgs: { q: 1 },+ toolResult: { content: [] },+ userId: callbacks.userId,+ attempt: 0,+ onSizeChanged: jest.fn(),+ onLoaded: jest.fn(),+ onTeardown: callbacks.onTeardown ?? jest.fn(),+ onFailed: callbacks.onFailed ?? jest.fn(),+ }),+ { wrapper },+ );+ return { iframe, view };+}++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+};++const latest = () => FakeAppBridge.instances[FakeAppBridge.instances.length - 1];++describe('useAppBridge', () => {+ let client: QueryClient;++ beforeEach(() => {+ FakeAppBridge.instances = [];+ AppBridge.mockImplementation(+ (t: unknown, i: unknown, c: Record<string, unknown>, o: unknown) =>+ new FakeAppBridge(t, i, c, o),+ );+ mockReadOnly.mockReturnValue(false);+ mockAsk.mockReset();+ mockFetchHtml.mockResolvedValue({ html: '<p>app</p>' });+ mockValidateBinding.mockResolvedValue();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ document.body.innerHTML = '';+ document.documentElement.className = '';+ });++ describe('ordering', () => {+ it('retries one failed View through a fresh bridge without replacing its iframe or sibling', async () => {+ const target = makeResource({+ resourceId: 'target',+ uri: 'ui://app/target',+ toolName: 'target',+ });+ const sibling = makeResource({+ resourceId: 'sibling',+ uri: 'ui://app/sibling',+ toolName: 'sibling',+ });+ let targetReads = 0;+ mockFetchHtml.mockImplementation(async (_server, _binding, uri) => {+ if (uri === target.uri && targetReads++ === 0) {+ throw new Error('temporary read failure');+ }+ return { html: `<p>${uri}</p>` };+ });+ const lifecycle: string[] = [];+ let bridgeIndex = 0;+ AppBridge.mockImplementation(+ (+ transport: unknown,+ info: unknown,+ capabilities: Record<string, unknown>,+ options: unknown,+ ) => {+ const current = bridgeIndex++;+ const bridge = new FakeAppBridge(transport, info, capabilities, options);+ if (current === 0) {+ const close = bridge.close.bind(bridge);+ bridge.close = () => {+ lifecycle.push('old-close');+ close();+ };+ } else if (current === 2) {+ const connect = bridge.connect.bind(bridge);+ bridge.connect = async (nextTransport: unknown) => {+ lifecycle.push('new-connect');+ await connect(nextTransport);+ };+ }+ return bridge;+ },+ );++ render(+ <RecoilRoot>+ <QueryClientProvider client={client}>+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <BridgeFrameHarness resource={target} userId="user-1" />+ <BridgeFrameHarness resource={sibling} userId="user-1" />+ </MCPAppsPolicyProvider>+ </QueryClientProvider>+ </RecoilRoot>,+ );+ await flush();++ const firstTargetBridge = FakeAppBridge.instances[0];+ const siblingBridge = FakeAppBridge.instances[1];+ const targetFrame = screen.getByTitle('MCP App: target');+ const siblingFrame = screen.getByTitle('MCP App: sibling');+ expect(targetFrame).toHaveAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms');+ targetFrame.dataset.retryAnchor = 'target';+ siblingFrame.dataset.retryAnchor = 'sibling';+ expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeVisible();++ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ await flush();++ const replacement = FakeAppBridge.instances[2];+ expect(lifecycle).toEqual(['old-close', 'new-connect']);+ expect(firstTargetBridge.closed).toBe(true);+ expect(siblingBridge.closed).toBe(false);+ expect(screen.getByTitle('MCP App: target')).toBe(targetFrame);+ expect(screen.getByTitle('MCP App: sibling')).toBe(siblingFrame);+ expect(targetFrame.dataset.retryAnchor).toBe('target');+ expect(siblingFrame.dataset.retryAnchor).toBe('sibling');++ await act(async () => replacement.emit('sandboxready'));+ await flush();+ await act(async () => replacement.oninitialized?.());+ await flush();++ expect(replacement.toolInput).toEqual([{ arguments: { q: 1 } }]);+ expect(replacement.toolResults).toEqual([{ content: [] }]);+ expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();+ expect(screen.getByTestId('surface-target')).toHaveStyle({ height: '320px' });++ await act(async () => firstTargetBridge.oninitialized?.());+ act(() => firstTargetBridge.emit('sizechange', { height: 999 }));+ expect(firstTargetBridge.toolInput).toHaveLength(0);+ expect(screen.getByTestId('surface-target')).toHaveStyle({ height: '320px' });++ act(() => replacement.emit('sizechange', { height: 260 }));+ expect(screen.getByTestId('surface-target')).toHaveStyle({ height: '260px' });+ expect(+ client+ .getQueryCache()+ .getAll()+ .map((query) => query.queryKey)+ .filter((key) => key[0] === 'mcpAppResourceHtml' && key[3] === target.uri)+ .map((key) => key.at(-1)),+ ).toEqual([0, 1]);+ });++ it('tears down an initialized bridge before replacing its host identity', async () => {+ const iframe = document.createElement('iframe');+ iframe.setAttribute('data-sandbox-url', SANDBOX_URL);+ document.body.appendChild(iframe);+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ </RecoilRoot>+ );+ const view = renderHook(+ ({ userId }: { userId: string }) =>+ useAppBridge({+ iframeRef: { current: iframe },+ resource: makeResource(),+ toolArgs: { q: 1 },+ toolResult: { content: [] },+ userId,+ attempt: 0,+ onSizeChanged: jest.fn(),+ }),+ { wrapper, initialProps: { userId: 'user-alpha' } },+ );+ await flush();+ const first = latest();+ await act(async () => first.oninitialized?.());+ const lifecycle: string[] = [];+ const closeFirst = first.close.bind(first);+ first.close = () => {+ lifecycle.push('old-close');+ closeFirst();+ };+ AppBridge.mockImplementationOnce(+ (t: unknown, i: unknown, c: Record<string, unknown>, o: unknown) => {+ const replacement = new FakeAppBridge(t, i, c, o);+ const connectReplacement = replacement.connect.bind(replacement);+ replacement.connect = async (transport: unknown) => {+ lifecycle.push('new-connect');+ await connectReplacement(transport);+ };+ return replacement;+ },+ );++ view.rerender({ userId: 'user-beta' });+ await flush();++ expect(first.teardowns).toBe(1);+ expect(first.closed).toBe(true);+ expect(FakeAppBridge.instances).toHaveLength(2);+ expect(mockFetchHtml).toHaveBeenCalledTimes(2);+ expect(lifecycle).toEqual(['old-close', 'new-connect']);+ expect(+ client+ .getQueryCache()+ .getAll()+ .map((query) => query.queryKey)+ .filter((key) => key[0] === 'mcpAppResourceHtml')+ .map((key) => key[5]),+ ).toEqual(['user-alpha', 'user-beta']);+ });++ it('connects the transport before the sandbox document is requested', async () => {+ let resolveHtml: (value: { html: string }) => void = () => {};+ mockFetchHtml.mockReturnValue(+ new Promise((resolve) => {+ resolveHtml = resolve;+ }) as ReturnType<typeof fetchMCPResourceHtml>,+ );+ const { iframe } = mountBridge(makeResource(), client);+ await flush();++ expect(latest().connected).not.toBeNull();+ expect(iframe.getAttribute('src')).toBeNull();++ await act(async () => {+ resolveHtml({ html: '<p>app</p>' });+ await Promise.resolve();+ });+ await flush();+ expect(iframe.src).toContain('/api/mcp/sandbox');+ });++ it('validates persisted inline html before assigning or sending it', async () => {+ let resolveValidation: () => void = () => {};+ mockValidateBinding.mockReturnValue(+ new Promise<void>((resolve) => {+ resolveValidation = resolve;+ }),+ );+ const { iframe } = mountBridge(makeResource({ text: '<p>persisted</p>' }), client);+ await flush();++ expect(latest().connected).not.toBeNull();+ expect(iframe.getAttribute('src')).toBeNull();+ expect(latest().resourceReady).toHaveLength(0);+ expect(mockValidateBinding).toHaveBeenCalledWith(+ 'demo',+ 'binding-demo',+ expect.any(AbortSignal),+ );++ await act(async () => {+ resolveValidation();+ await Promise.resolve();+ });+ await flush();+ expect(iframe.src).toContain('/api/mcp/sandbox');++ await act(async () => latest().emit('sandboxready'));+ await flush();+ expect(latest().resourceReady[0].html).toBe('<p>persisted</p>');+ });++ it('keeps unbound persisted html inert', async () => {+ const onFailed = jest.fn();+ const { iframe } = mountBridge(+ makeResource({ serverBinding: undefined, text: '<p>old app</p>' }),+ client,+ { onFailed },+ );+ await flush();++ expect(onFailed).toHaveBeenCalledTimes(1);+ expect(FakeAppBridge.instances).toHaveLength(0);+ expect(mockValidateBinding).not.toHaveBeenCalled();+ expect(iframe.getAttribute('src')).toBeNull();+ expect(iframe.getAttribute('allow')).toBeNull();+ });++ it('cancels an inline binding validation without loading late html', async () => {+ let resolveValidation: () => void = () => {};+ mockValidateBinding.mockReturnValue(+ new Promise<void>((resolve) => {+ resolveValidation = resolve;+ }),+ );+ const { iframe, view } = mountBridge(makeResource({ text: '<p>persisted</p>' }), client);+ await flush();+ const requestSignal = mockValidateBinding.mock.calls[0][2];++ act(() => view.unmount());+ await flush();+ expect(requestSignal?.aborted).toBe(true);++ await act(async () => {+ resolveValidation();+ await Promise.resolve();+ });+ expect(iframe.getAttribute('src')).toBeNull();+ expect(latest().resourceReady).toHaveLength(0);+ });++ it('unloads an old document while a replacement binding is validated', async () => {+ let resolveReplacement: () => void = () => {};+ mockValidateBinding.mockResolvedValueOnce().mockReturnValueOnce(+ new Promise<void>((resolve) => {+ resolveReplacement = resolve;+ }),+ );+ const iframe = document.createElement('iframe');+ iframe.setAttribute('data-sandbox-url', SANDBOX_URL);+ document.body.appendChild(iframe);+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ </RecoilRoot>+ );+ const view = renderHook(+ ({ resource }: { resource: UIResource }) =>+ useAppBridge({+ iframeRef: { current: iframe },+ resource,+ toolArgs: undefined,+ toolResult: undefined,+ attempt: 0,+ onSizeChanged: jest.fn(),+ }),+ {+ wrapper,+ initialProps: {+ resource: makeResource({ serverBinding: 'binding-old', text: '<p>old</p>' }),+ },+ },+ );+ await flush();+ expect(iframe.src).toContain('/api/mcp/sandbox');+ const oldBridge = latest();++ view.rerender({+ resource: makeResource({ serverBinding: 'binding-new', text: '<p>new</p>' }),+ });+ await flush();++ expect(oldBridge.closed).toBe(true);+ expect(iframe.getAttribute('src')).toBeNull();+ expect(mockValidateBinding).toHaveBeenLastCalledWith(+ 'demo',+ 'binding-new',+ expect.any(AbortSignal),+ );++ await act(async () => {+ resolveReplacement();+ await Promise.resolve();+ });+ await flush();+ expect(iframe.src).toContain('/api/mcp/sandbox');+ });++ it('carries the resolved csp to the sandbox response boundary', async () => {+ mockFetchHtml.mockResolvedValue({+ html: '<p>app</p>',+ csp: { connectDomains: ['https://api.example.com'] },+ });+ const { iframe } = mountBridge(makeResource(), client);+ await flush();++ const csp = new URL(iframe.src).searchParams.get('csp');+ expect(JSON.parse(csp as string)).toEqual({ connectDomains: ['https://api.example.com'] });+ });++ it('forwards only permissions supported by the opaque inner frame', async () => {+ mockFetchHtml.mockResolvedValue({+ html: '<p>app</p>',+ permissions: {+ camera: {},+ microphone: {},+ geolocation: {},+ clipboardWrite: {},+ },+ });+ const { iframe } = mountBridge(makeResource(), client);+ await flush();++ expect(iframe.getAttribute('allow')).toBe('geolocation; clipboard-write');+ await act(async () => latest().emit('sandboxready'));+ await flush();+ expect(latest().resourceReady[0].permissions).toEqual({+ geolocation: {},+ clipboardWrite: {},+ });+ });++ it('removes an ineffective media-only allow attribute', async () => {+ mockFetchHtml.mockResolvedValue({+ html: '<p>app</p>',+ permissions: { camera: {}, microphone: {} },+ });+ const { iframe } = mountBridge(makeResource(), client);+ iframe.setAttribute('allow', 'camera; microphone');+ await flush();++ expect(iframe.getAttribute('allow')).toBeNull();+ });++ it('sends the resource once even when the proxy announces twice', async () => {+ mountBridge(makeResource(), client);+ await flush();++ await act(async () => {+ latest().emit('sandboxready');+ latest().emit('sandboxready');+ });+ await flush();+ expect(latest().resourceReady).toHaveLength(1);+ expect(latest().resourceReady[0].html).toBe('<p>app</p>');+ });++ it('attaches no bridge and no src when cancelled mid-fetch', async () => {+ let resolveHtml: (value: { html: string }) => void = () => {};+ mockFetchHtml.mockReturnValue(+ new Promise((resolve) => {+ resolveHtml = resolve;+ }) as ReturnType<typeof fetchMCPResourceHtml>,+ );+ const { iframe, view } = mountBridge(makeResource(), client);+ await flush();+ const requestSignal = mockFetchHtml.mock.calls[0][3];+ act(() => view.unmount());+ await flush();++ expect(requestSignal?.aborted).toBe(true);+ await act(async () => {+ resolveHtml({ html: '<p>app</p>' });+ await Promise.resolve();+ });+ expect(iframe.getAttribute('src')).toBeNull();+ expect(latest().closed).toBe(true);+ });+ });++ describe('refetching changed html (3745939818)', () => {+ it('reads again on a later mount instead of serving a stale document', async () => {+ mockFetchHtml.mockResolvedValueOnce({ html: '<p>v1</p>' });+ const first = mountBridge(makeResource(), client);+ await flush();+ await act(async () => latest().emit('sandboxready'));+ await flush();+ expect(latest().resourceReady[0].html).toBe('<p>v1</p>');+ first.view.unmount();++ mockFetchHtml.mockResolvedValueOnce({ html: '<p>v2</p>' });+ mountBridge(makeResource(), client);+ await flush();+ await act(async () => latest().emit('sandboxready'));+ await flush();++ expect(mockFetchHtml).toHaveBeenCalledTimes(2);+ expect(latest().resourceReady[0].html).toBe('<p>v2</p>');+ });++ it('cancels only the leaving View when peers read the same resource', async () => {+ const requests: Array<{+ signal?: AbortSignal;+ resolve: (value: { html: string }) => void;+ }> = [];+ mockFetchHtml.mockImplementation(+ (_server, _binding, _uri, signal) =>+ new Promise((resolve) => requests.push({ signal, resolve })) as ReturnType<+ typeof fetchMCPResourceHtml+ >,+ );+ const first = mountBridge(makeResource(), client);+ const second = mountBridge(makeResource(), client);+ await flush();+ expect(requests).toHaveLength(2);++ act(() => first.view.unmount());+ await flush();+ expect(requests[0].signal?.aborted).toBe(true);+ expect(requests[1].signal?.aborted).toBe(false);++ await act(async () => requests[1].resolve({ html: '<p>peer survives</p>' }));+ await flush();+ expect(second.iframe.src).toContain('/api/mcp/sandbox');+ });++ it('does not report an old read failure into a replacement View', async () => {+ let rejectFirst: (reason: Error) => void = () => {};+ mockFetchHtml+ .mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ rejectFirst = reject;+ }) as ReturnType<typeof fetchMCPResourceHtml>,+ )+ .mockResolvedValueOnce({ html: '<p>replacement</p>' });+ const iframe = document.createElement('iframe');+ iframe.setAttribute('data-sandbox-url', SANDBOX_URL);+ document.body.appendChild(iframe);+ const firstFailed = jest.fn();+ const replacementFailed = jest.fn();+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ </RecoilRoot>+ );+ const view = renderHook(+ ({ resource, onFailed }: { resource: UIResource; onFailed: () => void }) =>+ useAppBridge({+ iframeRef: { current: iframe },+ resource,+ toolArgs: undefined,+ toolResult: undefined,+ attempt: 0,+ onSizeChanged: jest.fn(),+ onFailed,+ }),+ {+ wrapper,+ initialProps: { resource: makeResource(), onFailed: firstFailed },+ },+ );+ await flush();++ view.rerender({+ resource: makeResource({ resourceId: 'r2', uri: 'ui://app/replacement' }),+ onFailed: replacementFailed,+ });+ await flush();+ rejectFirst(new Error('old read failed'));+ await flush();++ expect(firstFailed).not.toHaveBeenCalled();+ expect(replacementFailed).not.toHaveBeenCalled();+ expect(iframe.src).toContain('/api/mcp/sandbox');+ });+ });++ describe('failure handling', () => {+ it('retries on the next proxy announcement instead of latching', async () => {+ mockFetchHtml.mockRejectedValueOnce(new Error('boom'));+ mountBridge(makeResource(), client);+ await flush();+ expect(latest().resourceReady).toHaveLength(0);++ mockFetchHtml.mockResolvedValueOnce({ html: '<p>after retry</p>' });+ await act(async () => latest().emit('sandboxready'));+ await flush();+ await act(async () => latest().emit('sandboxready'));+ await flush();++ expect(latest().resourceReady).toHaveLength(1);+ expect(latest().resourceReady[0].html).toBe('<p>after retry</p>');+ });++ it('treats empty html as a failure', async () => {+ mockFetchHtml.mockResolvedValue({ html: '' });+ const onFailed = jest.fn();+ const iframe = document.createElement('iframe');+ iframe.setAttribute('data-sandbox-url', SANDBOX_URL);+ document.body.appendChild(iframe);+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ </RecoilRoot>+ );+ renderHook(+ () =>+ useAppBridge({+ iframeRef: { current: iframe },+ resource: makeResource(),+ toolArgs: undefined,+ toolResult: undefined,+ attempt: 0,+ onSizeChanged: jest.fn(),+ onFailed,+ }),+ { wrapper },+ );+ await flush();+ await act(async () => latest().emit('sandboxready'));+ await flush();++ expect(latest().resourceReady).toHaveLength(0);+ expect(onFailed).toHaveBeenCalled();+ });+ });++ describe('read-only views', () => {+ it('never resolves app html from the viewer server for a resourceUri-only app', async () => {+ mockReadOnly.mockReturnValue(true);+ const { iframe } = mountBridge(makeResource(), client);+ await flush();+ await act(async () => latest().emit('sandboxready'));+ await flush();++ expect(mockFetchHtml).not.toHaveBeenCalled();+ expect(iframe.getAttribute('src')).toBeNull();+ expect(latest().resourceReady).toHaveLength(0);+ });++ it('runs inline html with no host-bound capabilities', async () => {+ mockReadOnly.mockReturnValue(true);+ mountBridge(makeResource({ text: '<p>inline</p>' }), client);+ await flush();+ await act(async () => latest().emit('sandboxready'));+ await flush();++ expect(mockFetchHtml).not.toHaveBeenCalled();+ expect(mockValidateBinding).toHaveBeenCalledWith(+ 'demo',+ 'binding-demo',+ expect.any(AbortSignal),+ );+ expect(latest().resourceReady[0].html).toBe('<p>inline</p>');+ expect(latest().capabilities.serverTools).toBeUndefined();+ expect(latest().capabilities.openLinks).toEqual({});+ });+ });++ describe('openLink authorization', () => {+ let openSpy: jest.SpyInstance;++ beforeEach(() => {+ openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);+ });++ it('denies a link before the sandbox document has any policy', async () => {+ let resolveHtml: (value: { html: string }) => void = () => {};+ mockFetchHtml.mockReturnValue(+ new Promise((resolve) => {+ resolveHtml = resolve;+ }) as ReturnType<typeof fetchMCPResourceHtml>,+ );+ mountBridge(+ makeResource({+ csp: { connectDomains: ['https://api.example.com'] },+ } as Partial<UIResource>),+ client,+ );+ await flush();++ await act(async () => {+ await latest().onopenlink?.({ url: 'https://api.example.com/x' }, requestExtra());+ });+ expect(openSpy).not.toHaveBeenCalled();+ await act(async () => {+ resolveHtml({ html: '<p>app</p>' });+ await Promise.resolve();+ });+ });++ it('refuses a link the tool-result copy grants but the delivered policy does not', async () => {+ mockFetchHtml.mockResolvedValue({+ html: '<p>app</p>',+ csp: { connectDomains: ['https://other.example'] },+ });+ mountBridge(+ makeResource({+ csp: { connectDomains: ['https://api.example.com'] },+ } as Partial<UIResource>),+ client,+ );+ await flush();++ let result: unknown;+ await act(async () => {+ result = await latest().onopenlink?.({ url: 'https://api.example.com/x' }, requestExtra());+ });+ expect(result).toEqual({ isError: true });+ expect(openSpy).not.toHaveBeenCalled();++ await act(async () => {+ result = await latest().onopenlink?.({ url: 'https://other.example/x' }, requestExtra());+ });+ expect(result).toEqual({});+ expect(openSpy).toHaveBeenCalledTimes(1);+ expect(openSpy).toHaveBeenCalledWith(+ 'https://other.example/x',+ '_blank',+ 'noopener,noreferrer',+ );+ });++ it('uses the same capped declaration for the sandbox and host link decisions', async () => {+ const connectDomains = Array.from(+ { length: 400 },+ (_unused, index) => `https://host${index}.example.com`,+ );+ mockFetchHtml.mockResolvedValue({ html: '<p>app</p>', csp: { connectDomains } });+ const { iframe } = mountBridge(makeResource(), client);+ await flush();++ const csp = JSON.parse(new URL(iframe.src).searchParams.get('csp') as string);+ expect(csp.connectDomains).toHaveLength(32);+ await act(async () => {+ await latest().onopenlink?.({ url: 'https://host0.example.com/x' }, requestExtra());+ });+ expect(openSpy).toHaveBeenCalledTimes(1);+ await act(async () => {+ await latest().onopenlink?.({ url: 'https://host399.example.com/x' }, requestExtra());+ });+ expect(openSpy).toHaveBeenCalledTimes(1);+ });++ it('denies every link after a failed read', async () => {+ mockFetchHtml.mockRejectedValue(new Error('boom'));+ mountBridge(+ makeResource({+ csp: { connectDomains: ['https://api.example.com'] },+ } as Partial<UIResource>),+ client,+ );+ await flush();++ await act(async () => {+ await latest().onopenlink?.({ url: 'https://api.example.com/x' }, requestExtra());+ });+ expect(openSpy).not.toHaveBeenCalled();+ });++ it('reports cancellation and thrown browser failures', async () => {+ mockFetchHtml.mockResolvedValue({+ html: '<p>app</p>',+ csp: { connectDomains: ['https://api.example.com'] },+ });+ mountBridge(makeResource(), client);+ await flush();+ const controller = new AbortController();+ controller.abort();++ await expect(+ latest().onopenlink?.({ url: 'https://api.example.com/x' }, { signal: controller.signal }),+ ).resolves.toEqual({ isError: true });+ openSpy.mockImplementationOnce(() => {+ throw new Error('browser failure');+ });+ await expect(+ latest().onopenlink?.({ url: 'https://api.example.com/x' }, requestExtra()),+ ).resolves.toEqual({ isError: true });+ });+ });++ describe('host request forwarding', () => {+ it('propagates each SDK request signal to the matching server operation', async () => {+ mockCallTool.mockResolvedValue({ content: [] });+ mockReadResource.mockResolvedValue({ contents: [] });+ mockListResources.mockResolvedValue({ resources: [] });+ mockListTemplates.mockResolvedValue({ resourceTemplates: [] });+ mountBridge(makeResource(), client);+ await flush();+ const extra = requestExtra();++ await latest().oncalltool?.({ name: 'next', arguments: { q: 2 } }, extra);+ await latest().onreadresource?.({ uri: 'ui://detail' }, extra);+ await latest().onlistresources?.({ cursor: 'a' }, extra);+ await latest().onlistresourcetemplates?.({ cursor: 'b' }, extra);++ expect(mockCallTool).toHaveBeenCalledWith(+ 'demo',+ 'binding-demo',+ 'next',+ { q: 2 },+ extra.signal,+ );+ expect(mockReadResource).toHaveBeenCalledWith(+ 'demo',+ 'binding-demo',+ 'ui://detail',+ extra.signal,+ );+ expect(mockListResources).toHaveBeenCalledWith('demo', 'binding-demo', 'a', extra.signal);+ expect(mockListTemplates).toHaveBeenCalledWith('demo', 'binding-demo', 'b', extra.signal);+ });++ it('reports unsupported or rejected message delivery as an error', async () => {+ mountBridge(makeResource(), client);+ await flush();+ const bridge = latest();++ await expect(+ bridge.onmessage?.({ content: [{ type: 'image' }] }, requestExtra()),+ ).resolves.toEqual({ isError: true });+ mockAsk.mockReturnValueOnce(false);+ await expect(+ bridge.onmessage?.({ content: [{ type: 'text', text: 'hello' }] }, requestExtra()),+ ).resolves.toEqual({ isError: true });+ });+ });++ describe('teardown', () => {+ it('does not deliver an awaited teardown completion after the View was disposed', async () => {+ const onTeardown = jest.fn();+ const mounted = mountBridge(makeResource(), client, { onTeardown });+ await flush();+ const bridge = latest();+ await bridge.oninitialized?.();+ let finishTeardown: () => void = () => {};+ bridge.teardownResource = jest.fn(+ () => new Promise<Record<string, never>>((resolve) => (finishTeardown = () => resolve({}))),+ );++ act(() => bridge.emit('requestteardown'));+ act(() => mounted.view.unmount());+ finishTeardown();+ await flush();++ expect(onTeardown).not.toHaveBeenCalled();+ });++ it('disposes the bridge and the theme observer on requestteardown', async () => {+ const onTeardown = jest.fn();+ const iframe = document.createElement('iframe');+ iframe.setAttribute('data-sandbox-url', SANDBOX_URL);+ document.body.appendChild(iframe);+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <RecoilRoot>+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ </RecoilRoot>+ );+ renderHook(+ () =>+ useAppBridge({+ iframeRef: { current: iframe },+ resource: makeResource(),+ toolArgs: undefined,+ toolResult: undefined,+ attempt: 0,+ onSizeChanged: jest.fn(),+ onTeardown,+ }),+ { wrapper },+ );+ await flush();++ const bridge = latest();+ await act(async () => bridge.oninitialized?.());+ await act(async () => bridge.emit('requestteardown'));+ await flush();++ expect(bridge.teardowns).toBeGreaterThan(0);+ expect(bridge.closed).toBe(true);+ expect(onTeardown).toHaveBeenCalled();++ await act(async () => {+ document.documentElement.classList.add('dark');+ await Promise.resolve();+ });+ expect(bridge.hostContextChanges).toHaveLength(0);+ });++ it('pushes theme changes to a live bridge', async () => {+ mountBridge(makeResource(), client);+ await flush();++ await act(async () => {+ document.documentElement.classList.add('dark');+ await Promise.resolve();+ });+ expect(latest().hostContextChanges).toHaveLength(1);+ });+ });++ describe('handshake payloads', () => {+ it('sends tool input before the tool result on initialize', async () => {+ mountBridge(makeResource(), client);+ await flush();+ await act(async () => {+ await latest().oninitialized?.();+ });+ expect(latest().toolInput).toEqual([{ arguments: { q: 1 } }]);+ expect(latest().toolResults).toEqual([{ content: [] }]);+ });++ it('sends tool lifecycle data only once if initialized repeats', async () => {+ mountBridge(makeResource(), client);+ await flush();+ await latest().oninitialized?.();+ await latest().oninitialized?.();+ expect(latest().toolInput).toHaveLength(1);+ expect(latest().toolResults).toHaveLength(1);+ });+ });+});diff --git a/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.ts b/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.tsnew file mode 100644index 0000000000..d6a3538091--- /dev/null+++ b/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.ts@@ -0,0 +1,307 @@+import { act, renderHook } from '@testing-library/react';+import type { UIResource } from 'librechat-data-provider';+import { useMCPAppFrame, APP_REVEAL_TIMEOUT_MS } from '~/hooks/MCP/useMCPAppFrame';+import { MAX_CAROUSEL_VIEW_HEIGHT, MIN_APP_VIEW_HEIGHT } from '~/utils/mcpApps';+import { useMCPAppsPolicy } from '~/Providers/MCPAppsPolicyContext';+import { useIsMessagesViewReadOnly } from '~/Providers';++jest.mock('~/utils/mcpApps', () => ({+ ...jest.requireActual('~/utils/mcpApps'),+ getMCPSandboxUrl: jest.fn(() => 'http://sandbox.localhost:3081/api/mcp/sandbox'),+}));++jest.mock('~/Providers', () => ({+ useIsMessagesViewReadOnly: jest.fn(() => false),+}));++jest.mock('~/Providers/MCPAppsPolicyContext', () => ({+ useMCPAppsPolicy: jest.fn(() => ({ enabled: true, legacyHtmlEnabled: true })),+}));++const mockReadOnly = useIsMessagesViewReadOnly as jest.MockedFunction<+ typeof useIsMessagesViewReadOnly+>;+const mockUseMCPAppsPolicy = useMCPAppsPolicy as jest.MockedFunction<typeof useMCPAppsPolicy>;++const appResource = (overrides: Partial<UIResource> = {}): UIResource =>+ ({+ resourceId: 'r1',+ uri: 'ui://app/main',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'render',+ serverName: 'demo',+ serverBinding: 'binding-demo',+ ...overrides,+ }) as UIResource;++describe('useMCPAppFrame', () => {+ beforeEach(() => {+ mockReadOnly.mockReturnValue(false);+ mockUseMCPAppsPolicy.mockReturnValue({ enabled: true, legacyHtmlEnabled: true });+ });++ describe('kind', () => {+ it('classifies app, static, unavailable and empty resources', () => {+ const app = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ expect(app.result.current.kind).toBe('app');++ const staticView = renderHook(() =>+ useMCPAppFrame(+ appResource({ toolName: undefined, serverName: undefined, text: '<p>x</p>' }),+ { defaultHeight: 100 },+ ),+ );+ expect(staticView.result.current.kind).toBe('static');++ mockReadOnly.mockReturnValue(true);+ const unavailable = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ expect(unavailable.result.current.kind).toBe('unavailable');++ const missing = renderHook(() => useMCPAppFrame(undefined, { defaultHeight: 100 }));+ expect(missing.result.current.kind).toBe('empty');+ });++ it('fails closed when a distinct sandbox origin is not configured', () => {+ const { getMCPSandboxUrl } = jest.requireMock('~/utils/mcpApps') as {+ getMCPSandboxUrl: jest.Mock;+ };+ getMCPSandboxUrl.mockReturnValueOnce(undefined);+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));++ expect(result.current.status).toBe('failed');+ expect(result.current.sandboxUrl).toBeUndefined();+ expect(result.current.canRetry).toBe(false);++ act(() => result.current.onRetry());+ expect(result.current.status).toBe('failed');+ expect(result.current.attempt).toBe(0);+ });++ it('resolves the sandbox from the authenticated runtime policy', () => {+ const runtimeUrl = 'https://mcp-sandbox.example.com/api/mcp/sandbox';+ const { getMCPSandboxUrl } = jest.requireMock('~/utils/mcpApps') as {+ getMCPSandboxUrl: jest.Mock;+ };+ mockUseMCPAppsPolicy.mockReturnValue({+ enabled: true,+ legacyHtmlEnabled: true,+ sandboxUrl: runtimeUrl,+ });++ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));++ expect(getMCPSandboxUrl).toHaveBeenCalledWith(runtimeUrl);+ expect(result.current.sandboxUrl).toBe('http://sandbox.localhost:3081/api/mcp/sandbox');+ });++ it('does not expose a frame or active bridge when Apps are disabled', () => {+ mockUseMCPAppsPolicy.mockReturnValue({ enabled: false, legacyHtmlEnabled: false });+ const { result } = renderHook(() =>+ useMCPAppFrame(appResource({ text: '<p>stored app</p>' }), { defaultHeight: 100 }),+ );++ expect(result.current.kind).toBe('empty');+ expect(result.current.sandboxUrl).toBeUndefined();+ expect(result.current.active).toBe(false);+ });+ });++ describe('height', () => {+ it('is always definite so the iframe height resolves before any size report', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 360 }));+ expect(result.current.height).toBe(360);+ expect(result.current.status).toBe('loading');+ });++ it('clamps a reported size into the surface bounds', () => {+ const { result } = renderHook(() =>+ useMCPAppFrame(appResource(), {+ defaultHeight: 360,+ maxHeight: MAX_CAROUSEL_VIEW_HEIGHT,+ }),+ );++ act(() => result.current.onSizeChanged({ height: 500 }));+ expect(result.current.height).toBe(500);+ expect(result.current.status).toBe('ready');++ act(() => result.current.onSizeChanged({ height: 1_000_000 }));+ expect(result.current.height).toBe(MAX_CAROUSEL_VIEW_HEIGHT);++ act(() => result.current.onSizeChanged({ height: 12 }));+ expect(result.current.height).toBe(MIN_APP_VIEW_HEIGHT);+ });++ it.each([[0], [-5], [Number.NaN], [undefined]])(+ 'leaves an unusable size report (%s) in the loading state',+ (height) => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 360 }));+ act(() => result.current.onSizeChanged({ height }));+ expect(result.current.status).toBe('loading');+ expect(result.current.height).toBe(360);+ },+ );++ it('reports the clamped height to the surface that owns the container', () => {+ const onHeightChange = jest.fn();+ const { result } = renderHook(() =>+ useMCPAppFrame(appResource(), { defaultHeight: 360, onHeightChange }),+ );+ act(() => result.current.onSizeChanged({ height: 400 }));+ expect(onHeightChange).toHaveBeenCalledWith(400);+ });+ });++ describe('reveal budget', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ it('spans the resource read as well as the handshake', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ act(() => {+ jest.advanceTimersByTime(APP_REVEAL_TIMEOUT_MS - 1);+ });+ expect(result.current.status).toBe('loading');++ act(() => {+ jest.advanceTimersByTime(1);+ });+ expect(result.current.status).toBe('timedOut');+ });++ it('is not armed for static or placeholder renders', () => {+ const { result } = renderHook(() =>+ useMCPAppFrame(+ appResource({ toolName: undefined, serverName: undefined, text: '<p>x</p>' }),+ { defaultHeight: 100 },+ ),+ );+ act(() => {+ jest.advanceTimersByTime(APP_REVEAL_TIMEOUT_MS * 2);+ });+ expect(result.current.status).toBe('loading');+ });++ it('is disarmed once the app is ready', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ act(() => result.current.onLoaded());+ act(() => {+ jest.advanceTimersByTime(APP_REVEAL_TIMEOUT_MS * 2);+ });+ expect(result.current.status).toBe('ready');+ });+ });++ describe('status transitions', () => {+ it('reports a read failure separately from the reveal budget', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ act(() => result.current.onFailed());+ expect(result.current.status).toBe('failed');+ });++ it('starts one fresh attempt after a terminal failure', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 320 }));+ act(() => result.current.onFailed());+ expect(result.current.status).toBe('failed');+ expect(result.current.canRetry).toBe(true);+ const staleRetry = result.current.onRetry;++ act(() => result.current.onRetry());+ expect(result.current.status).toBe('loading');+ expect(result.current.height).toBe(320);+ expect(result.current.attempt).toBe(1);+ expect(result.current.canRetry).toBe(false);++ act(() => staleRetry());+ expect(result.current.attempt).toBe(1);+ });++ it('starts one fresh attempt after the reveal budget expires', () => {+ jest.useFakeTimers();+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 320 }));+ act(() => jest.advanceTimersByTime(APP_REVEAL_TIMEOUT_MS));+ expect(result.current.status).toBe('timedOut');++ act(() => result.current.onRetry());+ expect(result.current.status).toBe('loading');+ expect(result.current.height).toBe(320);+ expect(result.current.attempt).toBe(1);+ jest.useRealTimers();+ });++ it('does not downgrade a ready app on a late failure', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ act(() => result.current.onLoaded());+ act(() => result.current.onFailed());+ expect(result.current.status).toBe('ready');+ });++ it('latches teardown so a late load cannot re-mount the bridge', () => {+ const onTornDown = jest.fn();+ const { result } = renderHook(() =>+ useMCPAppFrame(appResource(), { defaultHeight: 100, onTornDown }),+ );+ act(() => result.current.onFailed());+ const staleRetry = result.current.onRetry;+ act(() => result.current.onTeardown());+ expect(result.current.status).toBe('tornDown');+ expect(result.current.active).toBe(false);+ expect(onTornDown).toHaveBeenCalled();++ act(() => result.current.onRetry());+ expect(result.current.status).toBe('tornDown');+ expect(result.current.attempt).toBe(0);++ act(() => staleRetry());+ expect(result.current.status).toBe('tornDown');+ expect(result.current.attempt).toBe(0);++ act(() => result.current.onLoaded());+ act(() => result.current.onSizeChanged({ height: 400 }));+ expect(result.current.status).toBe('tornDown');+ expect(result.current.active).toBe(false);+ });++ it('resets when the html revision changes at a reused identity', () => {+ const { result, rerender } = renderHook(+ ({ resource }: { resource: UIResource }) =>+ useMCPAppFrame(resource, { defaultHeight: 100 }),+ { initialProps: { resource: appResource({ text: '<p>v1</p>' }) } },+ );+ act(() => result.current.onSizeChanged({ height: 500 }));+ expect(result.current.status).toBe('ready');++ rerender({ resource: appResource({ text: '<p>v2</p>' }) });+ expect(result.current.status).toBe('loading');+ expect(result.current.height).toBe(100);+ });+ });++ describe('tool arguments', () => {+ it('resolves the string and object forms to one shape', () => {+ const parsed = renderHook(() =>+ useMCPAppFrame(appResource(), { defaultHeight: 100, toolArgs: '{"a":1}' }),+ );+ expect(parsed.result.current.toolArgs).toEqual({ a: 1 });++ const passthrough = renderHook(() =>+ useMCPAppFrame(appResource(), { defaultHeight: 100, toolArgs: { a: 1 } }),+ );+ expect(passthrough.result.current.toolArgs).toEqual({ a: 1 });++ const malformed = renderHook(() =>+ useMCPAppFrame(appResource(), { defaultHeight: 100, toolArgs: 'not json' }),+ );+ expect(malformed.result.current.toolArgs).toBeUndefined();+ });++ it('falls back to the args persisted on the resource', () => {+ const { result } = renderHook(() =>+ useMCPAppFrame(appResource({ toolArgs: { b: 2 } } as Partial<UIResource>), {+ defaultHeight: 100,+ }),+ );+ expect(result.current.toolArgs).toEqual({ b: 2 });+ });+ });+});diff --git a/client/src/hooks/MCP/index.ts b/client/src/hooks/MCP/index.tsindex b32bca419b..e12ff2f5bb 100644--- a/client/src/hooks/MCP/index.ts+++ b/client/src/hooks/MCP/index.ts@@ -1,4 +1,6 @@export * from './useMCPSelect';+export { useAppBridge } from './useAppBridge';+export * from './useMCPAppFrame';export * from './useVisibleTools';export * from './useMCPServerManager';export * from './useMCPConnectionStatus';diff --git a/client/src/hooks/MCP/useAppBridge.ts b/client/src/hooks/MCP/useAppBridge.tsnew file mode 100644index 0000000000..2f2aaddb85--- /dev/null+++ b/client/src/hooks/MCP/useAppBridge.ts@@ -0,0 +1,503 @@+import { useEffect, useId, useRef } from 'react';+import { QueryKeys } from 'librechat-data-provider';+import { useQueryClient } from '@tanstack/react-query';+import {+ AppBridge,+ PostMessageTransport,+ buildAllowAttribute,+} from '@modelcontextprotocol/ext-apps/app-bridge';+import type { McpUiStyles, McpUiStyleVariableKey } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { UIResource } from 'librechat-data-provider';+import type { AppToolResult } from '~/utils/mcpApps';+import {+ callMCPAppTool,+ fetchMCPResourceHtml,+ readMCPResource,+ listMCPResources,+ listMCPResourceTemplates,+ validateMCPAppBinding,+ getSupportedMCPAppPermissions,+ getInlineResourceHtml,+ isAllowedAppLink,+ withSandboxCsp,+} from '~/utils/mcpApps';+import {+ useOptionalMessagesOperations,+ useIsMessagesViewReadOnly,+ useMCPAppsPolicy,+} from '~/Providers';+import { logger } from '~/utils';++type MessageContentBlock = { type?: string; text?: string };++type SizeParams = { width?: number; height?: number };++type ResolvedResource = {+ html: string;+ csp: UIResource['csp'];+ permissions: UIResource['permissions'];+};++export type UseAppBridgeParams = {+ iframeRef: React.RefObject<HTMLIFrameElement | null>;+ resource: UIResource;+ toolArgs: Record<string, unknown> | undefined;+ toolResult: AppToolResult | undefined;+ userId?: string;+ /** View-owned retry generation. Each attempt gets an isolated bridge and resource query. */+ attempt: number;+ onSizeChanged: (params: SizeParams) => void;+ /** False once the app requested teardown, so the effect disposes instead of re-mounting a bridge. */+ active?: boolean;+ onLoaded?: () => void;+ onTeardown?: () => void;+ onFailed?: () => void;+};++/** Maps the MCP Apps standard host style tokens onto LibreChat's theme CSS variables. Apps keep+ * their own fallbacks for anything omitted, so a partial set is intentional. */+const HOST_STYLE_VAR_MAP: Partial<Record<McpUiStyleVariableKey, string>> = {+ '--color-background-primary': '--surface-primary',+ '--color-background-secondary': '--surface-secondary',+ '--color-background-tertiary': '--surface-tertiary',+ '--color-background-danger': '--surface-destructive',+ '--color-text-primary': '--text-primary',+ '--color-text-secondary': '--text-secondary',+ '--color-text-tertiary': '--text-tertiary',+ '--color-text-danger': '--text-destructive',+ '--color-text-warning': '--text-warning',+ '--color-border-primary': '--border-medium',+ '--color-border-secondary': '--border-light',+ '--color-border-danger': '--border-destructive',+};++function readHostTheme(): 'light' | 'dark' {+ return document.documentElement.classList.contains('dark') ? 'dark' : 'light';+}++function buildHostStyleVariables(): McpUiStyles {+ const computed = getComputedStyle(document.documentElement);+ const variables: Partial<Record<McpUiStyleVariableKey, string>> = {};+ for (const [specVar, lcVar] of Object.entries(HOST_STYLE_VAR_MAP)) {+ const value = computed.getPropertyValue(lcVar).trim();+ if (value) {+ variables[specVar as McpUiStyleVariableKey] = value;+ }+ }+ // The token record is optional/partial by design (apps fall back on any we omit); the generated+ // type requires every key, so assert the mapped subset.+ return variables as McpUiStyles;+}++export function useAppBridge({+ iframeRef,+ resource,+ toolArgs,+ toolResult,+ userId,+ attempt,+ onSizeChanged,+ active = true,+ onLoaded,+ onTeardown,+ onFailed,+}: UseAppBridgeParams) {+ const { ask } = useOptionalMessagesOperations();+ // Read-only views (shared transcripts, /search) must not let the embedded app proxy tool calls+ // or resource reads against the viewer's MCP servers with the viewer's auth.+ const readOnly = useIsMessagesViewReadOnly();+ const { cspLimits } = useMCPAppsPolicy();+ const queryClient = useQueryClient();+ const viewId = useId();+ // The csp actually delivered to the sandbox document, which is what bounds the app's own egress.+ // Host-opened links are authorized against this rather than the tool-result copy, so the host can+ // never open a link the sandbox policy did not grant.+ const effectiveCspRef = useRef<UIResource['csp']>(undefined);+ // The bridge mounts once per resource and reads these only inside its handlers, so a changed+ // callback or tool-call snapshot never tears down the live AppBridge. Synced at render time+ // (idempotent under Strict Mode) rather than via an effect that would only mirror props.+ const askRef = useRef(ask);+ const onSizeChangedRef = useRef(onSizeChanged);+ const onLoadedRef = useRef(onLoaded);+ const onTeardownRef = useRef(onTeardown);+ const onFailedRef = useRef(onFailed);+ askRef.current = ask;+ onSizeChangedRef.current = onSizeChanged;+ onLoadedRef.current = onLoaded;+ onTeardownRef.current = onTeardown;+ onFailedRef.current = onFailed;+ useEffect(() => {+ const iframe = iframeRef.current;+ const serverName = resource.serverName;+ if (!iframe || !serverName || !active) return;+ const serverBinding = resource.serverBinding;+ if (!serverBinding) {+ iframe.removeAttribute('src');+ iframe.removeAttribute('allow');+ onFailedRef.current?.();+ return;+ }+ const frameWindow = iframe.contentWindow;+ if (!frameWindow) return;++ // A retry or binding change must unload the prior document before validating its replacement.+ // The WindowProxy remains stable across the about:blank navigation used by removing src.+ iframe.removeAttribute('src');+ iframe.removeAttribute('allow');+ effectiveCspRef.current = undefined;+ // Unmount, a resource switch, or a teardown can run cleanup while a read or bridge.connect() is+ // still pending; this flag stops the pending continuation from touching a disposed bridge.+ let cancelled = false;+ let resourceSent = false;+ let sendingResource = false;+ let initialized = false;+ let resolved: ResolvedResource | null = null;+ let srcCsp: UIResource['csp'] = undefined;+ const resourceQueryKey = [+ QueryKeys.mcpAppResourceHtml,+ serverName,+ serverBinding,+ resource.uri,+ resource.resourceId,+ userId,+ viewId,+ attempt,+ ] as const;++ const assignSandboxSrc = (csp: UIResource['csp']) => {+ const { url, applied } = withSandboxCsp(+ iframe.getAttribute('data-sandbox-url') ?? '',+ csp,+ cspLimits,+ );+ // srcCsp records what was requested (it guards against reloading the document in a loop);+ // effectiveCspRef records what the sandbox response was actually given.+ srcCsp = csp;+ effectiveCspRef.current = applied;+ if (csp && !applied) {+ logger.warn('[MCP App] Declared csp could not be delivered to the sandbox response');+ }+ iframe.src = url;+ };++ const applyOuterPermissions = (permissions: UIResource['permissions']) => {+ const allowAttr = buildAllowAttribute(+ permissions as Parameters<typeof buildAllowAttribute>[0],+ );+ if (allowAttr) {+ iframe.setAttribute('allow', allowAttr);+ } else {+ iframe.removeAttribute('allow');+ }+ };++ // The WindowProxy identity survives the frame's navigation, so the transport is bound and+ // listening before the sandbox document is even requested: the proxy announces itself as soon as+ // it parses, and an announcement that arrives before the listener exists is a permanent hang.+ const transport = new PostMessageTransport(frameWindow, frameWindow);+ const { locale, timeZone } = Intl.DateTimeFormat().resolvedOptions();+ const bridge = new AppBridge(+ null,+ { name: 'LibreChat', version: '1.0.0' },+ {+ openLinks: {},+ logging: {},+ // Display-only views advertise no host-bound action capabilities so a well-behaved app+ // disables those affordances rather than issuing calls the host ignores.+ ...(!readOnly ? { serverTools: {}, serverResources: {}, message: { text: {} } } : {}),+ },+ {+ hostContext: {+ theme: readHostTheme(),+ platform: 'web',+ locale,+ timeZone,+ displayMode: 'inline',+ availableDisplayModes: ['inline'],+ styles: { variables: buildHostStyleVariables() },+ },+ },+ );++ let lastTheme = readHostTheme();+ const themeObserver = new MutationObserver(() => {+ if (cancelled) {+ return;+ }+ const nextTheme = readHostTheme();+ if (nextTheme === lastTheme) {+ return;+ }+ lastTheme = nextTheme;+ Promise.resolve(+ bridge.sendHostContextChange({+ theme: nextTheme,+ styles: { variables: buildHostStyleVariables() },+ }),+ ).catch((err: unknown) => logger.error('[MCP App] sendHostContextChange failed', err));+ });++ let disposed = false;+ const dispose = () => {+ if (disposed) return;+ disposed = true;+ cancelled = true;+ themeObserver.disconnect();+ bridge.close();+ void queryClient.cancelQueries({ queryKey: resourceQueryKey, exact: true });+ };++ const interactive = !readOnly;++ bridge.onopenlink = async ({ url }, { signal }) => {+ if (signal.aborted) {+ return { isError: true };+ }+ if (!isAllowedAppLink(url, effectiveCspRef.current, cspLimits)) {+ logger.warn('[MCP App] Blocked open-link outside the declared egress domains');+ return { isError: true };+ }+ try {+ window.open(url, '_blank', 'noopener,noreferrer');+ return {};+ } catch (error) {+ logger.error('[MCP App] Failed to open link', error);+ return { isError: true };+ }+ };++ // Host-bound actions (tool calls, resource reads/lists, model messages) run with the viewer's+ // auth, so they are only wired in interactive views, never in shared transcripts or /search.+ if (interactive) {+ bridge.oncalltool = async (params, { signal }) =>+ callMCPAppTool(+ serverName,+ serverBinding,+ params.name,+ (params.arguments as Record<string, unknown>) ?? {},+ signal,+ );++ bridge.onreadresource = async (params, { signal }) =>+ readMCPResource(serverName, serverBinding, params.uri, signal);++ bridge.onlistresources = async (params, { signal }) =>+ listMCPResources(serverName, serverBinding, params?.cursor, signal);++ bridge.onlistresourcetemplates = async (params, { signal }) =>+ listMCPResourceTemplates(serverName, serverBinding, params?.cursor, signal);++ bridge.onmessage = async ({ content }, { signal }) => {+ const text = (content as MessageContentBlock[])+ .filter((block) => block.type === 'text' && typeof block.text === 'string')+ .map((block) => block.text)+ .join('\n');+ if (!text || signal.aborted || cancelled) {+ return { isError: true };+ }+ try {+ const accepted = askRef.current({ text });+ if (accepted === false) {+ return { isError: true };+ }+ return signal.aborted || cancelled ? { isError: true } : {};+ } catch (error) {+ logger.error('[MCP App] Failed to deliver message', error);+ return { isError: true };+ }+ };+ }++ const resolveResource = async (): Promise<ResolvedResource | null> => {+ const inlineHtml = getInlineResourceHtml(resource);+ // Inline mcp-app resources already carry their HTML, so use it directly instead of a+ // resources/read round trip, but validate their persisted server binding before loading it.+ if (inlineHtml) {+ await queryClient.fetchQuery({+ queryKey: resourceQueryKey,+ queryFn: async ({ signal }) => {+ await validateMCPAppBinding(serverName, serverBinding, signal);+ return true;+ },+ staleTime: 0,+ });+ return {+ html: inlineHtml,+ csp: resource.csp,+ permissions: getSupportedMCPAppPermissions(resource.permissions),+ };+ }+ // Read-only views must not resolve app HTML from the viewer's MCP server.+ if (readOnly) {+ logger.debug(+ '[MCP App] Read-only view: skipping server HTML fetch for resourceUri-only app',+ );+ return null;+ }+ const fetched = await queryClient.fetchQuery({+ // The same ui:// URI can carry revised HTML on a later turn, and nothing invalidates this+ // cache entry. The View ID owns cancellation, while the remaining fields retain server,+ // resource, persisted-call, and user scope; zero stale time makes every later mount re-read.+ queryKey: resourceQueryKey,+ queryFn: ({ signal }) =>+ fetchMCPResourceHtml(serverName, serverBinding, resource.uri, signal),+ staleTime: 0,+ });+ return {+ html: fetched.html,+ csp: fetched.csp,+ permissions: getSupportedMCPAppPermissions(fetched.permissions),+ };+ };++ const sendResource = async () => {+ if (resourceSent || sendingResource || cancelled) {+ return;+ }+ sendingResource = true;+ try {+ const next = resolved ?? (await resolveResource());+ if (cancelled || !next) {+ return;+ }+ if (!next.html) {+ throw new Error('Resource returned no HTML');+ }+ resolved = next;+ applyOuterPermissions(next.permissions);+ // A retry that resolved a csp the current sandbox document was not served with would run the+ // app under the restrictive default policy; reload the document with the declared domains+ // and let its own announcement deliver the resource.+ if (next.csp && next.csp !== srcCsp) {+ assignSandboxSrc(next.csp);+ return;+ }+ resourceSent = true;+ await bridge.sendSandboxResourceReady({+ html: next.html,+ csp: next.csp as never,+ permissions: next.permissions as never,+ sandbox: 'allow-scripts allow-forms',+ });+ } catch (err) {+ resourceSent = false;+ logger.error('[MCP App] Failed to send sandbox resource', err);+ if (!cancelled) {+ onFailedRef.current?.();+ }+ } finally {+ sendingResource = false;+ }+ };++ // The proxy re-announces itself until it receives a resource, which is the only retry signal a+ // failed read gets; a latch here strands the frame behind the spinner forever.+ bridge.addEventListener('sandboxready', () => {+ void sendResource();+ });++ bridge.oninitialized = async () => {+ if (cancelled || initialized) {+ return;+ }+ initialized = true;+ // The app handshake completed: treat this as the load signal so apps that never emit a+ // size-change (auto-resize disabled) are still revealed instead of stuck behind the spinner.+ onLoadedRef.current?.();+ // MCP Apps expect tool input exactly once before the result, even for no-argument tools,+ // so apps that initialize from ontoolinput always receive it.+ await bridge+ .sendToolInput({ arguments: toolArgs ?? {} })+ .catch((err: unknown) => logger.error('[MCP App] sendToolInput failed', err));+ if (toolResult && !cancelled) {+ await bridge+ .sendToolResult(toolResult as never)+ .catch((err: unknown) => logger.error('[MCP App] sendToolResult failed', err));+ }+ };++ bridge.addEventListener('sizechange', (params) => {+ if (!cancelled) {+ onSizeChangedRef.current(params);+ }+ });++ bridge.addEventListener('requestteardown', async () => {+ if (initialized) {+ await bridge.teardownResource({}).catch(() => {});+ }+ if (cancelled) {+ return;+ }+ dispose();+ onTeardownRef.current?.();+ });++ bridge.addEventListener('loggingmessage', (event) => {+ const { level, data } = event as { level: string; data: unknown };+ logger.debug('[MCP App]', level, data);+ });++ themeObserver.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class'],+ });++ const start = async () => {+ try {+ await bridge.connect(transport);+ } catch (err) {+ logger.error('[MCP App] bridge.connect failed', err);+ if (!cancelled) {+ onFailedRef.current?.();+ }+ dispose();+ return;+ }+ if (cancelled) {+ bridge.close();+ return;+ }+ // Both sandbox policies are built from this URL before the document loads. The content-level+ // _meta.ui.csp is authoritative, which requires resolving the resource before navigation.+ const next = await resolveResource().catch((err: unknown) => {+ logger.error('[MCP App] Failed to read app resource', err);+ if (!cancelled) {+ onFailedRef.current?.();+ }+ return null;+ });+ if (cancelled) {+ return;+ }+ resolved = next;+ applyOuterPermissions(next?.permissions);+ // A failed read still loads the sandbox document: its re-announcements are the only retry+ // signal, and a later resolve reloads it with the declared domains.+ if (next || !readOnly) {+ assignSandboxSrc(next?.csp);+ }+ };+ void start();++ return () => {+ if (initialized) {+ bridge.teardownResource({}).catch(() => {});+ }+ dispose();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ resource.resourceId,+ resource.serverBinding,+ resource.uri,+ resource.serverName,+ active,+ readOnly,+ userId,+ viewId,+ attempt,+ cspLimits?.maxSourcesPerDirective,+ cspLimits?.maxSerializedLength,+ ]);+}diff --git a/client/src/hooks/MCP/useMCPAppFrame.ts b/client/src/hooks/MCP/useMCPAppFrame.tsnew file mode 100644index 0000000000..c6a16892a8--- /dev/null+++ b/client/src/hooks/MCP/useMCPAppFrame.ts@@ -0,0 +1,203 @@+import { useRef, useMemo, useState, useEffect, useCallback } from 'react';+import type { UIResource } from 'librechat-data-provider';+import type { AppToolResult } from '~/utils/mcpApps';+import {+ getMCPSandboxUrl,+ getResourceKey,+ buildAppToolResult,+ isMcpAppResource,+ getInlineResourceHtml,+ clampAppViewHeight,+} from '~/utils/mcpApps';+import { useMCPAppsPolicy } from '~/Providers/MCPAppsPolicyContext';+import { useIsMessagesViewReadOnly } from '~/Providers';++/** `timedOut` and `failed` are separate only because the user-facing copy differs: one is the reveal+ * budget expiring, the other is a resource read that came back unusable. */+export type MCPAppFrameStatus = 'loading' | 'ready' | 'timedOut' | 'failed' | 'tornDown';++/**+ * `app` runs the App Bridge handshake, `static` is inert srcDoc HTML, `unavailable` is a read-only+ * view of an app whose HTML only the viewer's own server could resolve, and `empty` has nothing to+ * render.+ */+export type MCPAppFrameKind = 'app' | 'static' | 'unavailable' | 'empty';++export type MCPAppFrameOptions = {+ /** Applied when the app has not reported a size, so the iframe's `height:100%` always resolves. */+ defaultHeight: number;+ maxHeight?: number;+ toolArgs?: string | Record<string, unknown>;+ onHeightChange?: (height: number) => void;+ onTornDown?: () => void;+};++export type MCPAppFrameState = {+ iframeRef: React.RefObject<HTMLIFrameElement>;+ status: MCPAppFrameStatus;+ kind: MCPAppFrameKind;+ height: number;+ attempt: number;+ canRetry: boolean;+ sandboxUrl?: string;+ inlineHtml?: string;+ toolArgs?: Record<string, unknown>;+ toolResult?: AppToolResult;+ active: boolean;+ onSizeChanged: (params: { height?: number; width?: number }) => void;+ onLoaded: () => void;+ onTeardown: () => void;+ onFailed: () => void;+ onRetry: () => void;+};++/**+ * Budget for the whole reveal path: the `resources/read`, the sandbox document, and the App Bridge+ * handshake. The read moved ahead of the document load so the per-resource CSP can be delivered as a+ * sandbox request, which put server latency inside this window.+ */+export const APP_REVEAL_TIMEOUT_MS = 20_000;++function parseToolArgs(+ args?: string | Record<string, unknown>,+): Record<string, unknown> | undefined {+ if (args == null) {+ return undefined;+ }+ if (typeof args !== 'string') {+ return args;+ }+ try {+ return JSON.parse(args) as Record<string, unknown>;+ } catch {+ return undefined;+ }+}++/**+ * Render state for one MCP App view, shared by every surface that hosts one. A single status keeps+ * the mutually exclusive states (loaded and timed out, torn down and timed out) unreachable, and+ * scopes the reveal timer to app-backed views so static and placeholder renders never arm it.+ */+export function useMCPAppFrame(+ resource: UIResource | undefined,+ options: MCPAppFrameOptions,+): MCPAppFrameState {+ const { defaultHeight, maxHeight, toolArgs, onHeightChange, onTornDown } = options;+ const iframeRef = useRef<HTMLIFrameElement>(null);+ const readOnly = useIsMessagesViewReadOnly();+ const { enabled: mcpAppsEnabled, sandboxUrl: configuredSandboxUrl } = useMCPAppsPolicy();+ const [status, setStatus] = useState<MCPAppFrameStatus>('loading');+ const [height, setHeight] = useState<number | undefined>(undefined);+ const [attempt, setAttempt] = useState(0);+ const sandboxUrl = useMemo(() => getMCPSandboxUrl(configuredSandboxUrl), [configuredSandboxUrl]);+ const inlineHtml = useMemo(+ () => (resource ? getInlineResourceHtml(resource) : undefined),+ [resource],+ );+ const resourceKey = resource ? getResourceKey(resource) : '';++ // A revised document at a reused resource identity must render from a clean state, or the new HTML+ // is revealed at the previous revision's height.+ useEffect(() => {+ setStatus('loading');+ setHeight(undefined);+ }, [resourceKey, inlineHtml, resource?.serverBinding]);++ const kind: MCPAppFrameKind = useMemo(() => {+ if (!mcpAppsEnabled || !resource) {+ return 'empty';+ }+ if (isMcpAppResource(resource)) {+ return !inlineHtml && readOnly ? 'unavailable' : 'app';+ }+ return inlineHtml ? 'static' : 'empty';+ }, [mcpAppsEnabled, resource, inlineHtml, readOnly]);++ useEffect(() => {+ if (kind === 'app' && !sandboxUrl) {+ setStatus('failed');+ }+ }, [kind, sandboxUrl]);++ useEffect(() => {+ if (kind !== 'app' || status !== 'loading' || !sandboxUrl) {+ return;+ }+ const timer = setTimeout(() => setStatus('timedOut'), APP_REVEAL_TIMEOUT_MS);+ return () => clearTimeout(timer);+ }, [kind, sandboxUrl, status]);++ const onSizeChanged = useCallback(+ (params: { height?: number; width?: number }) => {+ const clamped = clampAppViewHeight(params.height, { max: maxHeight });+ if (clamped == null) {+ return;+ }+ setHeight(clamped);+ setStatus((prev) => (prev === 'tornDown' ? prev : 'ready'));+ onHeightChange?.(clamped);+ },+ [maxHeight, onHeightChange],+ );++ const onLoaded = useCallback(+ () => setStatus((prev) => (prev === 'tornDown' ? prev : 'ready')),+ [],+ );++ const onFailed = useCallback(+ () => setStatus((prev) => (prev === 'loading' ? 'failed' : prev)),+ [],+ );++ const canRetry =+ kind === 'app' && sandboxUrl != null && (status === 'failed' || status === 'timedOut');+ const canRetryRef = useRef(canRetry);+ canRetryRef.current = canRetry;+ const onRetry = useCallback(() => {+ if (!canRetryRef.current) {+ return;+ }+ canRetryRef.current = false;+ setStatus('loading');+ setHeight(undefined);+ setAttempt((current) => current + 1);+ }, []);++ // One-way: a teardown must not be undone by a late load or size report, which would re-mount a+ // bridge onto a resource the app has already released.+ const onTeardown = useCallback(() => {+ canRetryRef.current = false;+ setStatus('tornDown');+ onTornDown?.();+ }, [onTornDown]);++ const resolvedToolArgs = useMemo(+ () => parseToolArgs(toolArgs ?? (resource?.toolArgs as Record<string, unknown> | undefined)),+ [toolArgs, resource?.toolArgs],+ );+ const toolResult = useMemo(+ () => (resource ? buildAppToolResult(resource) : undefined),+ [resource],+ );++ return {+ iframeRef,+ status,+ kind,+ height: height ?? defaultHeight,+ attempt,+ canRetry,+ sandboxUrl: mcpAppsEnabled ? sandboxUrl : undefined,+ inlineHtml,+ toolArgs: resolvedToolArgs,+ toolResult,+ active: mcpAppsEnabled && kind === 'app' && status !== 'tornDown',+ onSizeChanged,+ onLoaded,+ onTeardown,+ onFailed,+ onRetry,+ };+}diff --git a/client/src/hooks/Messages/__tests__/useAttachments.spec.tsx b/client/src/hooks/Messages/__tests__/useAttachments.spec.tsxindex ba3bebd15a..a0de699206 100644--- a/client/src/hooks/Messages/__tests__/useAttachments.spec.tsx+++ b/client/src/hooks/Messages/__tests__/useAttachments.spec.tsx@@ -46,6 +46,19 @@ function makeAttachment(overrides: Partial<AttachmentFixture> = {}): AttachmentF};}+function makeNonFileAttachment(+ overrides: Partial<TAttachment & { agentId?: string; stepId?: string }> = {},+): AttachmentFixture {+ return {+ type: Tools.ui_resources,+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-1',+ messageId,+ ...overrides,+ } as unknown as AttachmentFixture;+}+function setup({attachments,liveMap,@@ -217,6 +230,108 @@ describe('useAttachments', () => {expect(result.current.attachments).toHaveLength(1);});+ it('dedupes an agent-less replay of an agent-owned non-file row', () => {+ const db = makeNonFileAttachment();+ const replay = makeNonFileAttachment({ agentId: undefined });++ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [replay] },+ });++ expect(result.current.attachments).toEqual([db]);+ });++ it('keeps a non-file row owned by a different live agent', () => {+ const db = makeNonFileAttachment();+ const sibling = makeNonFileAttachment({ agentId: 'agent-b' });++ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [sibling] },+ });++ expect(result.current.attachments).toEqual([db, sibling]);+ });++ it('dedupes a non-file replay with the same known agent and step', () => {+ const db = makeNonFileAttachment();+ const replay = makeNonFileAttachment();++ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [replay] },+ });++ expect(result.current.attachments).toEqual([db]);+ });++ it('keeps non-file rows with distinct known steps', () => {+ const db = makeNonFileAttachment({ stepId: 'step-1' });+ const sibling = makeNonFileAttachment({ stepId: 'step-2' });++ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [sibling] },+ });++ expect(result.current.attachments).toEqual([db, sibling]);+ });++ it('keeps a known step conflict when the live agent is missing', () => {+ const db = makeNonFileAttachment({ stepId: 'step-1' });+ const sibling = makeNonFileAttachment({ agentId: undefined, stepId: 'step-2' });++ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [sibling] },+ });++ expect(result.current.attachments).toEqual([db, sibling]);+ });++ it('keeps a known agent conflict when the live step is missing', () => {+ const db = makeNonFileAttachment({ agentId: 'agent-a' });+ const sibling = makeNonFileAttachment({ agentId: 'agent-b', stepId: undefined });++ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [sibling] },+ });++ expect(result.current.attachments).toEqual([db, sibling]);+ });++ it.each([+ [+ 'DB-specific / live missing step',+ makeNonFileAttachment(),+ makeNonFileAttachment({ stepId: undefined }),+ ],+ [+ 'DB-missing / live specific step',+ makeNonFileAttachment({ stepId: undefined }),+ makeNonFileAttachment(),+ ],+ [+ 'DB-specific / live missing agent',+ makeNonFileAttachment(),+ makeNonFileAttachment({ agentId: undefined }),+ ],+ [+ 'DB-missing / live specific agent',+ makeNonFileAttachment({ agentId: undefined }),+ makeNonFileAttachment(),+ ],+ ])('dedupes compatible non-file ownership: %s', (_label, db, replay) => {+ const { result } = setup({+ attachments: [db],+ liveMap: { [messageId]: [replay] },+ });++ expect(result.current.attachments).toEqual([db]);+ });+it('drops live entries with no stable identity at all', () => {const db = makeAttachment({ file_id: 'fid-A' });const anonymous = { messageId } as unknown as AttachmentFixture;diff --git a/client/src/hooks/Messages/useAttachments.ts b/client/src/hooks/Messages/useAttachments.tsindex 0b5fe881d9..a4605c3222 100644--- a/client/src/hooks/Messages/useAttachments.ts+++ b/client/src/hooks/Messages/useAttachments.ts@@ -18,12 +18,30 @@ function agentIdOf(attachment: TAttachment): string | undefined {return (attachment as { agentId?: string }).agentId;}-/**- * Stable identity for merging DB and live attachments. Shared with the- * message renderer, which dedupes the same rows on the same key — two- * definitions of what makes an attachment "the same one" is exactly the drift- * that puts a file on screen twice in one surface and not at all in another.- */+function nonFileBucketKey(attachment: TAttachment): string | undefined {+ if (fileKeyOf(attachment)) {+ return undefined;+ }+ const { type } = attachment as { type?: string };+ const toolCallId = toolCallIdOf(attachment);+ return type != null && toolCallId != null ? `${type}:${toolCallId}` : undefined;+}++/** Missing ownership is a compatibility wildcard for historical rows; two+ * known unequal owners identify distinct executions. */+function nonFileOwnersCompatible(left: TAttachment, right: TAttachment): boolean {+ const leftAgentId = agentIdOf(left);+ const rightAgentId = agentIdOf(right);+ const leftStepId = left.stepId;+ const rightStepId = right.stepId;+ return (+ (leftAgentId == null || rightAgentId == null || leftAgentId === rightAgentId) &&+ (leftStepId == null || rightStepId == null || leftStepId === rightStepId)+ );+}++/** Stable file identity shared with the message renderer. Non-file DB/live+ * reconciliation additionally compares its producer ownership below. */const attachmentKey = attachmentIdentity;/**@@ -76,23 +94,31 @@ export default function useAttachments({* `artifactTypeForAttachment` see the resolved text/textFormat* and route through the proper PanelArtifact card. */const dbKeys = new Set<string>();+ const nonFileBuckets = new Map<string, TAttachment[]>();const merged = attachments.map((db) => {const key = attachmentKey(db);if (!key) {return db;}- dbKeys.add(key);- /** Partial live records must still be reachable by their less-specific- * keys so an overlaid entry isn't re-appended below: bare records (no- * toolCallId) key by plain file key, agent-less records by- * fileKey::toolCallId. */const fileKey = fileKeyOf(db);if (fileKey) {+ /** Partial live file records must still be reachable by their+ * less-specific keys so an overlaid entry isn't re-appended below:+ * bare records key by file key, and agent-less records by+ * fileKey::toolCallId. */+ dbKeys.add(key);dbKeys.add(fileKey);const toolCallId = toolCallIdOf(db);if (toolCallId != null) {dbKeys.add(`${fileKey}::${toolCallId}`);}+ } else {+ const bucketKey = nonFileBucketKey(db);+ if (bucketKey) {+ const bucket = nonFileBuckets.get(bucketKey) ?? [];+ bucket.push(db);+ nonFileBuckets.set(bucketKey, bucket);+ }}const liveEntry = live.find((a) => matchesLiveEntry(db, a));return liveEntry ? ({ ...db, ...liveEntry } as TAttachment) : db;@@ -102,12 +128,22 @@ export default function useAttachments({* message whose DB `attachments` snapshot predates them (the row is* patched post-finalize), so treating the DB list as exhaustive would* make those files vanish until a full reload. Entries whose key is- * already in the DB list (e.g. unkeyed file_search citations replayed- * by the final message event) are duplicates, and entries with no- * stable identity at all cannot be deduped — both are dropped. */+ * compatible DB file key or non-file owner are replay duplicates, while+ * entries with no stable identity at all cannot be reconciled — both are+ * dropped. */const liveOnly = live.filter((a) => {const key = attachmentKey(a);- return key != null && !dbKeys.has(key);+ if (key == null) {+ return false;+ }+ if (fileKeyOf(a)) {+ return !dbKeys.has(key);+ }+ const bucketKey = nonFileBucketKey(a);+ if (!bucketKey) {+ return false;+ }+ return !nonFileBuckets.get(bucketKey)?.some((db) => nonFileOwnersCompatible(db, a));});return liveOnly.length > 0 ? [...merged, ...liveOnly] : merged;}, [attachments, messageAttachmentsMap, messageId]);diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 2285ff5fea..0533cf8bb0 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1784,10 +1784,15 @@"com_ui_live": "live","com_ui_load_more": "Load more","com_ui_loading": "Loading...",+ "com_ui_loading_interactive_view": "Loading interactive view...","com_ui_loading_more_data": "Loading more results","com_ui_locked": "Locked","com_ui_logo": "{{0}} Logo","com_ui_low": "Low",+ "com_ui_mcp_app_failed_to_load": "Interactive view failed to load.",+ "com_ui_mcp_app_frame_title": "MCP App: {{0}}",+ "com_ui_mcp_app_load_error": "Interactive view could not be loaded.",+ "com_ui_mcp_app_shared_unavailable": "MCP Apps aren't viewable in shared conversations.","com_ui_make_production": "Make Production","com_ui_manage": "Manage","com_ui_manage_web_search_api_keys": "Manage Web Search API Keys",diff --git a/client/src/routes/Root.tsx b/client/src/routes/Root.tsxindex 19c7a82f1d..25c264872f 100644--- a/client/src/routes/Root.tsx+++ b/client/src/routes/Root.tsx@@ -22,17 +22,18 @@ import {MOBILE_DRAWER_FULL_WIDTH,MOBILE_PANE_SHIFT,} from '~/components/UnifiedSidebar';-import {- CodeHighlightThrottleContext,- normalizeCodeHighlightThrottleMs,-} from '~/components/Chat/Messages/Content/Parts/useLazyHighlight';import {PromptGroupsProvider,AssistantsMapContext,AgentsMapContext,SetConvoProvider,FileMapContext,+ MCPAppsPolicyProvider,} from '~/Providers';+import {+ CodeHighlightThrottleContext,+ normalizeCodeHighlightThrottleMs,+} from '~/components/Chat/Messages/Content/Parts/useLazyHighlight';import KeyboardShortcutsDialog from '~/components/Nav/KeyboardShortcutsDialog';import KeyboardDeleteDialog from '~/components/Nav/KeyboardDeleteDialog';import { useUserTermsQuery, useGetStartupConfig } from '~/data-provider';@@ -107,7 +108,7 @@ export default function Root() {},[setSidebarExpanded],);- const { isAuthenticated, logout } = useAuthContext();+ const { isAuthenticated, logout, user } = useAuthContext();/** Releases feature-catalog queries after first paint on browser idle. */useCatalogWarmup(isAuthenticated);@@ -127,7 +128,7 @@ export default function Root() {const agentsMap = useAgentsMap({ isAuthenticated });const fileMap = useFileMap({ isAuthenticated });- const { data: config } = useGetStartupConfig();+ const { data: config, isSuccess: isConfigReady, error: configError } = useGetStartupConfig();const { data: termsData } = useUserTermsQuery({enabled: isAuthenticated && config?.interface?.termsOfService?.modalAcceptance === true,});@@ -199,7 +200,13 @@ export default function Root() {* too late and drops too early. */inert={isSmallScreen && (sidebarExpanded || isSliding) ? '' : undefined}>- <Outlet />+ <MCPAppsPolicyProvider+ startupConfig={config}+ ready={isConfigReady && configError == null}+ userId={user?.id}+ >+ <Outlet />+ </MCPAppsPolicyProvider></div>{/* Without the strip the scrim exists only for the travel:through a close that began while the strip was still ondiff --git a/client/src/utils/__tests__/mcpApps.spec.ts b/client/src/utils/__tests__/mcpApps.spec.tsnew file mode 100644index 0000000000..a6cef871f4--- /dev/null+++ b/client/src/utils/__tests__/mcpApps.spec.ts@@ -0,0 +1,532 @@+import { normalizeMCPAppCspDeclaration, request } from 'librechat-data-provider';+import type { UIResource } from 'librechat-data-provider';+import {+ isAllowedAppLink,+ getMCPSandboxUrl,+ getSupportedMCPAppPermissions,+ fetchMCPResourceHtml,+ clampAppViewHeight,+ withSandboxCsp,+ getResourceKey,+ MAX_APP_VIEW_HEIGHT,+ MIN_APP_VIEW_HEIGHT,+ MAX_CAROUSEL_VIEW_HEIGHT,+ MAX_SANDBOX_CSP_PARAM_LENGTH,+} from '~/utils/mcpApps';++describe('getMCPSandboxUrl', () => {+ const original = process.env.VITE_MCP_SANDBOX_URL;++ afterEach(() => {+ if (original == null) {+ delete process.env.VITE_MCP_SANDBOX_URL;+ return;+ }+ process.env.VITE_MCP_SANDBOX_URL = original;+ });++ it.each([undefined, '', '/api/mcp/sandbox', 'javascript:alert(1)', window.location.origin])(+ 'fails closed for missing or non-dedicated configuration %s',+ (value) => {+ if (value == null) {+ delete process.env.VITE_MCP_SANDBOX_URL;+ } else {+ process.env.VITE_MCP_SANDBOX_URL = value;+ }+ expect(getMCPSandboxUrl()).toBeUndefined();+ },+ );++ it('returns an explicit different-origin HTTP URL bound to this host origin', () => {+ process.env.VITE_MCP_SANDBOX_URL = 'http://sandbox.localhost:3081/api/mcp/sandbox?fixed=1';+ const url = new URL(getMCPSandboxUrl() as string);++ expect(url.origin).toBe('http://sandbox.localhost:3081');+ expect(url.searchParams.get('parentOrigin')).toBe(window.location.origin);+ expect(url.searchParams.get('fixed')).toBe('1');+ });++ it('prefers the runtime URL over a different compiled URL', () => {+ process.env.VITE_MCP_SANDBOX_URL =+ 'https://compiled-sandbox.example.com/api/mcp/sandbox?compiled=1';+ const url = new URL(+ getMCPSandboxUrl('https://runtime-sandbox.example.com/api/mcp/sandbox?runtime=1') as string,+ );++ expect(url.origin).toBe('https://runtime-sandbox.example.com');+ expect(url.searchParams.get('runtime')).toBe('1');+ expect(url.searchParams.get('compiled')).toBeNull();+ expect(url.searchParams.get('parentOrigin')).toBe(window.location.origin);+ });++ it.each(['', '/api/mcp/sandbox', 'javascript:alert(1)', window.location.origin, null])(+ 'does not fall back after explicit invalid runtime configuration %s',+ (value) => {+ process.env.VITE_MCP_SANDBOX_URL = 'https://compiled-sandbox.example.com/api/mcp/sandbox';+ expect(getMCPSandboxUrl(value)).toBeUndefined();+ },+ );+});++describe('isAllowedAppLink', () => {+ it('refuses everything when the resource declares no egress domains', () => {+ expect(isAllowedAppLink('https://api.example.com/x', undefined)).toBe(false);+ expect(isAllowedAppLink('https://api.example.com/x', {})).toBe(false);+ });++ it('requires an explicit scheme, because an app document has an opaque origin', () => {+ const csp = { connectDomains: ['api.example.com'] };+ expect(isAllowedAppLink('https://api.example.com/x', csp)).toBe(false);+ expect(isAllowedAppLink('http://api.example.com:8080/x', csp)).toBe(false);+ });++ it('honors a declared scheme exactly, in either direction', () => {+ expect(+ isAllowedAppLink('https://api.example.com/x', {+ connectDomains: ['https://api.example.com'],+ }),+ ).toBe(true);+ expect(+ isAllowedAppLink('http://api.example.com/x', { connectDomains: ['https://api.example.com'] }),+ ).toBe(false);+ expect(+ isAllowedAppLink('https://api.example.com/x', { connectDomains: ['http://api.example.com'] }),+ ).toBe(false);+ expect(+ isAllowedAppLink('http://api.example.com/x', { connectDomains: ['http://api.example.com'] }),+ ).toBe(true);+ });++ it('matches a declared scheme case-insensitively', () => {+ expect(+ isAllowedAppLink('https://api.example.com/x', {+ connectDomains: ['HTTPS://API.EXAMPLE.COM'],+ }),+ ).toBe(true);+ });++ it('does not treat a ws(s) declaration as a navigable link target', () => {+ expect(+ isAllowedAppLink('https://api.example.com/x', { connectDomains: ['wss://api.example.com'] }),+ ).toBe(false);+ expect(+ isAllowedAppLink('http://api.example.com/x', { connectDomains: ['ws://api.example.com'] }),+ ).toBe(false);+ });++ describe('port-part (CSP3 §6.7.2.11)', () => {+ it('matches only the scheme default port when the declaration omits one', () => {+ const csp = { connectDomains: ['https://api.example.com'] };+ expect(isAllowedAppLink('https://api.example.com/x', csp)).toBe(true);+ expect(isAllowedAppLink('https://api.example.com:443/x', csp)).toBe(true);+ expect(isAllowedAppLink('https://api.example.com:8443/x', csp)).toBe(false);+ });++ it('matches the implicit port when the declaration spells it out', () => {+ const csp = { connectDomains: ['https://api.example.com:443'] };+ expect(isAllowedAppLink('https://api.example.com/x', csp)).toBe(true);+ expect(isAllowedAppLink('http://api.example.com:8080/collect?d=1', csp)).toBe(false);+ expect(isAllowedAppLink('https://api.example.com:8443/x', csp)).toBe(false);+ });++ it('matches an exact non-default port only', () => {+ const csp = { connectDomains: ['https://api.example.com:8443'] };+ expect(isAllowedAppLink('https://api.example.com:8443/x', csp)).toBe(true);+ expect(isAllowedAppLink('https://api.example.com/x', csp)).toBe(false);+ });++ it('treats a wildcard port as any port', () => {+ const csp = { connectDomains: ['https://api.example.com:*'] };+ expect(isAllowedAppLink('https://api.example.com/x', csp)).toBe(true);+ expect(isAllowedAppLink('https://api.example.com:8443/x', csp)).toBe(true);+ });+ });++ describe('wildcard host-part (CSP3 §6.7.2.10)', () => {+ const csp = { resourceDomains: ['https://*.example.com'] };++ it('requires at least one subdomain label and never covers the apex', () => {+ expect(isAllowedAppLink('https://cdn.example.com/x', csp)).toBe(true);+ expect(isAllowedAppLink('https://a.b.example.com/x', csp)).toBe(true);+ expect(isAllowedAppLink('https://example.com/x', csp)).toBe(false);+ expect(isAllowedAppLink('https://.example.com/x', csp)).toBe(false);+ });++ it('does not match an unrelated suffix or a trailing-dot host', () => {+ expect(isAllowedAppLink('https://notexample.com/x', csp)).toBe(false);+ expect(isAllowedAppLink('https://cdn.example.com./x', csp)).toBe(false);+ expect(isAllowedAppLink('https://example.com./x', csp)).toBe(false);+ });+ });++ it('authorizes nothing for blanket, keyword, or injection-shaped entries', () => {+ const entries = [+ '*',+ 'https://*',+ 'https:',+ 'data:',+ "'self'",+ "'none'",+ "'unsafe-eval'",+ "'unsafe-inline'",+ "'nonce-abc123'",+ 'https://api.example.com/path',+ 'https://api.example.com;script-src *',+ 'https://api.example.com, https://evil.com',+ '',+ ' ',+ ];+ for (const entry of entries) {+ expect(isAllowedAppLink('https://api.example.com/x', { connectDomains: [entry] })).toBe(+ false,+ );+ }+ });++ it('refuses address literals as link targets while keeping localhost usable', () => {+ expect(+ isAllowedAppLink('http://127.0.0.1:3000/x', { connectDomains: ['http://127.0.0.1:3000'] }),+ ).toBe(false);+ expect(isAllowedAppLink('http://0x7f.1/x', { connectDomains: ['http://0x7f.1'] })).toBe(false);+ expect(isAllowedAppLink('http://[::1]/x', { connectDomains: ['http://[::1]'] })).toBe(false);+ expect(+ isAllowedAppLink('http://localhost:3000/x', { connectDomains: ['http://localhost:3000'] }),+ ).toBe(true);+ });++ it('refuses non-http(s) schemes and malformed urls', () => {+ const csp = { connectDomains: ['https://api.example.com'] };+ expect(isAllowedAppLink('javascript:alert(1)', csp)).toBe(false);+ expect(isAllowedAppLink('not a url', csp)).toBe(false);+ expect(isAllowedAppLink('ws://api.example.com', csp)).toBe(false);+ });++ it('consults resourceDomains and frameDomains as well as connectDomains', () => {+ expect(+ isAllowedAppLink('https://cdn.example.com/x', {+ resourceDomains: ['https://cdn.example.com'],+ }),+ ).toBe(true);+ expect(+ isAllowedAppLink('https://embed.example.com/x', {+ frameDomains: ['https://embed.example.com'],+ }),+ ).toBe(true);+ });++ it('matches a credentialed url on its host', () => {+ expect(+ isAllowedAppLink('https://user:[email protected]/x', {+ connectDomains: ['https://api.example.com'],+ }),+ ).toBe(true);+ });+});++describe('normalizeMCPAppCspDeclaration', () => {+ it('keeps legal host sources, trimmed', () => {+ expect(+ normalizeMCPAppCspDeclaration({+ connectDomains: [+ 'https://api.example.com',+ 'https://*.example.com',+ 'http://localhost:3000',+ 'wss://stream.example.com',+ 'https://a.example.com:*',+ 'HTTPS://API.EXAMPLE.COM',+ '\n https://trimmed.example.com ',+ ],+ }).connectDomains,+ ).toEqual([+ 'https://api.example.com',+ 'https://*.example.com',+ 'http://localhost:3000',+ 'wss://stream.example.com',+ 'https://a.example.com:*',+ 'HTTPS://API.EXAMPLE.COM',+ 'https://trimmed.example.com',+ ]);+ });++ it('drops keywords, blankets and injection-shaped entries', () => {+ const dropped = [+ '*',+ 'https://*',+ 'https:',+ 'data:',+ 'blob:',+ "'self'",+ "'unsafe-inline'",+ "'nonce-abc123'",+ 'evil.com; script-src *',+ 'a.com, b.com',+ 'a.com"',+ "a.com'",+ 'a.com\nscript-src *',+ 'a.com\tb',+ 'https://a.com/x?y=1',+ 'https://a.com/x#f',+ 'https://[::1]',+ 'https://a_b.com',+ 'https://exämple.com',+ ];+ for (const entry of dropped) {+ expect(normalizeMCPAppCspDeclaration({ connectDomains: [entry] })).toEqual({});+ }+ expect(normalizeMCPAppCspDeclaration(undefined)).toEqual({});+ expect(normalizeMCPAppCspDeclaration({ connectDomains: 'https://a.com' })).toEqual({});+ });++ it('contains every entry the link matcher accepts', () => {+ const accepted: Array<[string, string]> = [+ ['https://api.example.com', 'https://api.example.com/x'],+ ['HTTPS://API.EXAMPLE.COM', 'https://api.example.com/x'],+ ['https://*.example.com', 'https://cdn.example.com/x'],+ ['https://api.example.com:8443', 'https://api.example.com:8443/x'],+ ['https://a.example.com:*', 'https://a.example.com:9000/x'],+ ['http://localhost:3000', 'http://localhost:3000/x'],+ ];+ for (const [entry, url] of accepted) {+ expect(isAllowedAppLink(url, { connectDomains: [entry] })).toBe(true);+ expect(normalizeMCPAppCspDeclaration({ connectDomains: [entry] })).toEqual({+ connectDomains: [entry],+ });+ }+ });++ it('caps each directive at the shared effective-policy limit', () => {+ const connectDomains = Array.from(+ { length: 40 },+ (_unused, index) => `https://host${index}.example.com`,+ );+ expect(normalizeMCPAppCspDeclaration({ connectDomains }).connectDomains).toHaveLength(32);+ });++ it('uses an injected effective-policy limit', () => {+ const connectDomains = Array.from(+ { length: 40 },+ (_unused, index) => `https://host${index}.example.com`,+ );+ expect(+ normalizeMCPAppCspDeclaration({ connectDomains }, { maxSourcesPerDirective: 40 })+ .connectDomains,+ ).toHaveLength(40);+ });+});++describe('clampAppViewHeight', () => {+ it('ignores non-positive or non-finite heights', () => {+ expect(clampAppViewHeight(undefined)).toBeUndefined();+ expect(clampAppViewHeight(0)).toBeUndefined();+ expect(clampAppViewHeight(-5)).toBeUndefined();+ expect(clampAppViewHeight(Number.POSITIVE_INFINITY)).toBeUndefined();+ expect(clampAppViewHeight(Number.NaN)).toBeUndefined();+ });++ it('clamps an app-requested height into the surface bounds', () => {+ expect(clampAppViewHeight(500)).toBe(500);+ expect(clampAppViewHeight(12)).toBe(MIN_APP_VIEW_HEIGHT);+ expect(clampAppViewHeight(10_000_000)).toBe(MAX_APP_VIEW_HEIGHT);+ expect(clampAppViewHeight(10_000_000, { max: MAX_CAROUSEL_VIEW_HEIGHT })).toBe(+ MAX_CAROUSEL_VIEW_HEIGHT,+ );+ expect(clampAppViewHeight(12, { max: MAX_CAROUSEL_VIEW_HEIGHT })).toBe(MIN_APP_VIEW_HEIGHT);+ });+});++describe('withSandboxCsp', () => {+ it('carries the declared domains to the sandbox response boundary', () => {+ const { url, applied } = withSandboxCsp(+ 'http://localhost:3080/api/mcp/sandbox?parentOrigin=http%3A%2F%2Fa',+ { connectDomains: ['https://api.example.com'] },+ );+ const parsed = new URL(url);+ expect(parsed.searchParams.get('parentOrigin')).toBe('http://a');+ expect(JSON.parse(parsed.searchParams.get('csp') as string)).toEqual({+ connectDomains: ['https://api.example.com'],+ });+ expect(applied).toEqual({ connectDomains: ['https://api.example.com'] });+ });++ it('leaves the url untouched when the resource declares no csp', () => {+ expect(withSandboxCsp('http://localhost:3080/api/mcp/sandbox', undefined)).toEqual({+ url: 'http://localhost:3080/api/mcp/sandbox',+ applied: undefined,+ });+ });++ it('serializes and returns the same capped effective policy', () => {+ const connectDomains = Array.from(+ { length: 400 },+ (_unused, index) => `https://host${index}.example.com`,+ );+ expect(JSON.stringify({ connectDomains }).length).toBeGreaterThan(MAX_SANDBOX_CSP_PARAM_LENGTH);+ const { url, applied } = withSandboxCsp('http://localhost:3080/api/mcp/sandbox', {+ connectDomains,+ });+ const expected = normalizeMCPAppCspDeclaration({ connectDomains });+ expect(JSON.parse(new URL(url).searchParams.get('csp') as string)).toEqual(expected);+ expect(applied).toEqual(expected);+ });++ it('reports nothing applied when the normalized declaration exceeds the route bound', () => {+ const connectDomains = Array.from(+ { length: 32 },+ (_unused, index) => `https://host${index}.example.com/${'a'.repeat(160)}`,+ );+ const { url, applied } = withSandboxCsp('http://localhost:3080/api/mcp/sandbox', {+ connectDomains,+ });+ expect(url).toBe('http://localhost:3080/api/mcp/sandbox');+ expect(applied).toBeUndefined();+ });++ it('uses the deployment limits for URL serialization and host link policy', () => {+ const connectDomains = Array.from(+ { length: 40 },+ (_unused, index) => `https://api${index}.example.com`,+ );+ const limits = { maxSourcesPerDirective: 40, maxSerializedLength: 8192 };+ const { url, applied } = withSandboxCsp(+ 'http://localhost:3080/api/mcp/sandbox',+ { connectDomains },+ limits,+ );++ expect(new URL(url).searchParams.get('csp')).toContain('api39.example.com');+ expect(isAllowedAppLink('https://api39.example.com/path', applied, limits)).toBe(true);+ });+});++describe('fetchMCPResourceHtml', () => {+ let fetchSpy: jest.SpyInstance;++ afterEach(() => {+ fetchSpy?.mockRestore();+ });++ it('selects only the exact URI with the App MIME and uses only that item metadata', async () => {+ fetchSpy = jest.spyOn(request, 'authenticatedFetch').mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ contents: [+ {+ uri: 'ui://app/main',+ mimeType: 'text/plain',+ text: 'wrong type',+ _meta: { ui: { csp: { connectDomains: ['https://wrong.example'] } } },+ },+ {+ uri: 'ui://app/other',+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>wrong uri</p>',+ _meta: { ui: { permissions: { camera: {} } } },+ },+ {+ uri: 'ui://app/main',+ mimeType: 'text/html; charset=utf-8; profile="mcp-app"',+ text: '<p>selected</p>',+ _meta: {+ ui: {+ csp: { connectDomains: ['https://api.example'] },+ permissions: { clipboardWrite: {} },+ },+ },+ },+ ],+ }),+ } as Response);+ const controller = new AbortController();++ await expect(+ fetchMCPResourceHtml('demo', 'binding-demo', 'ui://app/main', controller.signal),+ ).resolves.toEqual({+ html: '<p>selected</p>',+ csp: { connectDomains: ['https://api.example'] },+ permissions: { clipboardWrite: {} },+ });+ expect(fetchSpy).toHaveBeenCalledWith(+ expect.stringContaining('/api/mcp/resources/read'),+ expect.objectContaining({+ body: JSON.stringify({+ serverName: 'demo',+ serverBinding: 'binding-demo',+ uri: 'ui://app/main',+ }),+ signal: controller.signal,+ }),+ );+ });++ it('decodes a matching base64 App document', async () => {+ fetchSpy = jest.spyOn(request, 'authenticatedFetch').mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ contents: [+ {+ uri: 'ui://app/main',+ mimeType: 'text/html;profile=mcp-app',+ blob: btoa('<p>café</p>'),+ },+ ],+ }),+ } as Response);++ await expect(fetchMCPResourceHtml('demo', 'binding-demo', 'ui://app/main')).resolves.toEqual({+ html: '<p>café</p>',+ csp: undefined,+ permissions: undefined,+ });+ });++ it('rejects a response with no exact URI and App MIME match', async () => {+ fetchSpy = jest.spyOn(request, 'authenticatedFetch').mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ contents: [+ { uri: 'ui://app/other', mimeType: 'text/html;profile=mcp-app', text: '<p>x</p>' },+ ],+ }),+ } as Response);++ await expect(fetchMCPResourceHtml('demo', 'binding-demo', 'ui://app/main')).rejects.toThrow(+ 'no matching HTML document',+ );+ });++ it('rejects a non-successful proxy response', async () => {+ fetchSpy = jest.spyOn(request, 'authenticatedFetch').mockResolvedValue({+ ok: false,+ status: 403,+ } as Response);++ await expect(fetchMCPResourceHtml('demo', 'binding-demo', 'ui://app/main')).rejects.toThrow(+ '(403)',+ );+ });+});++describe('getSupportedMCPAppPermissions', () => {+ it('keeps supported permissions and withholds media from an opaque frame', () => {+ expect(+ getSupportedMCPAppPermissions({+ camera: {},+ microphone: {},+ geolocation: {},+ clipboardWrite: {},+ }),+ ).toEqual({ geolocation: {}, clipboardWrite: {} });+ expect(getSupportedMCPAppPermissions({ camera: {}, microphone: {} })).toBeUndefined();+ expect(getSupportedMCPAppPermissions(undefined)).toBeUndefined();+ });+});++describe('getResourceKey', () => {+ it('prefers the resource id and falls back to the uri', () => {+ expect(getResourceKey({ resourceId: 'r1', uri: 'ui://a' } as UIResource)).toBe('r1');+ expect(getResourceKey({ resourceId: '', uri: 'ui://a' } as UIResource)).toBe('ui://a');+ });+});diff --git a/client/src/utils/__tests__/mcpSandbox.spec.ts b/client/src/utils/__tests__/mcpSandbox.spec.tsnew file mode 100644index 0000000000..eaaf3b0c29--- /dev/null+++ b/client/src/utils/__tests__/mcpSandbox.spec.ts@@ -0,0 +1,596 @@+import fs from 'fs';+import path from 'path';++/**+ * `client/public/mcp-sandbox.html` is a static asset outside the module graph, so it is exercised by+ * evaluating its inline script against a fake `window` (listener isolation per test, a stubbed+ * parent, and the query string the route is called with). The navigation cases it exists for cannot+ * run here: jsdom has no policy containers and no frame navigation, so blob CSP inheritance and the+ * pre-load invalidation window are browser-only.+ */+const SANDBOX_PATH = path.join(__dirname, '../../../public/mcp-sandbox.html');+const SANDBOX_HTML = fs.readFileSync(SANDBOX_PATH, 'utf8');+const PARENT_ORIGIN = 'http://localhost:3080';+const RESOURCE_READY = 'ui/notifications/sandbox-resource-ready';+const PROXY_READY = 'ui/notifications/sandbox-proxy-ready';+const ATTEST = 'ui/notifications/sandbox-frame-attest';+const DETACH = 'ui/notifications/sandbox-frame-detach';++type JsonRpcMessage = {+ jsonrpc: string;+ id?: number;+ method?: string;+ params?: Record<string, unknown>;+ result?: unknown;+};++type FakeEvent = { data: unknown; origin: string; source: unknown };++type Harness = {+ parentPosts: Array<{ msg: JsonRpcMessage; targetOrigin: string }>;+ errors: unknown[][];+ fromParent: (msg: JsonRpcMessage, origin?: string) => void;+ fromInner: (msg: JsonRpcMessage, source?: unknown) => void;+ frame: () => HTMLIFrameElement | null;+ innerPosts: () => JsonRpcMessage[];+ blobs: string[];+ revoked: string[];+ bootstrapNonce: (index?: number) => string;+ attest: () => void;+ deliverResource: (params?: Record<string, unknown>) => void;+ loadFrame: (frame?: HTMLIFrameElement | null) => void;+};++function extractScript(html: string): string {+ const start = html.indexOf('<script>') + '<script>'.length;+ const end = html.lastIndexOf('</script>');+ return html.slice(start, end);+}++const blobs: string[] = [];+const revoked: string[] = [];+const errors: unknown[][] = [];++function installStubs(): () => void {+ const originalBlob = global.Blob;+ const originalCreate = URL.createObjectURL;+ const originalRevoke = URL.revokeObjectURL;+ let counter = 0;+ class CapturingBlob {+ type: string;+ constructor(parts: string[], opts?: { type?: string }) {+ blobs.push(parts.join(''));+ this.type = opts?.type ?? '';+ }+ }+ global.Blob = CapturingBlob as unknown as typeof Blob;+ URL.createObjectURL = () => `blob:mock/${(counter += 1)}`;+ URL.revokeObjectURL = (url: string) => {+ revoked.push(url);+ };+ const errorSpy = jest.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {+ errors.push(args);+ });+ return () => {+ global.Blob = originalBlob;+ URL.createObjectURL = originalCreate;+ URL.revokeObjectURL = originalRevoke;+ errorSpy.mockRestore();+ };+}++function loadSandbox(+ options: {+ parentOrigin?: string | null;+ cspApplied?: boolean;+ viewCspApplied?: boolean;+ } = {},+): Harness {+ const { parentOrigin = PARENT_ORIGIN, cspApplied = true, viewCspApplied = true } = options;+ let source = extractScript(SANDBOX_HTML);+ if (cspApplied) {+ source = source.replace('/*__CSP_APPLIED__*/', 'window.__MCP_SANDBOX_CSP_APPLIED = true;');+ }+ if (viewCspApplied) {+ source = source.replace(+ '/*__VIEW_CSP__*/',+ "window.__MCP_VIEW_CSP = \"default-src 'none'; frame-src 'none'\";",+ );+ }++ const listeners = new Map<string, Array<(event: FakeEvent) => void>>();+ const parentPosts: Harness['parentPosts'] = [];+ const innerPosts: JsonRpcMessage[] = [];++ const parentWindow = {+ postMessage: (msg: JsonRpcMessage, targetOrigin: string) => {+ parentPosts.push({ msg, targetOrigin });+ },+ };++ const fakeWindow: Record<string, unknown> = {+ parent: parentWindow,+ location: {+ search: parentOrigin ? `?parentOrigin=${encodeURIComponent(parentOrigin)}` : '',+ origin: 'null',+ },+ addEventListener: (type: string, handler: (event: FakeEvent) => void) => {+ const bucket = listeners.get(type) ?? [];+ bucket.push(handler);+ listeners.set(type, bucket);+ },+ removeEventListener: () => {},+ };++ const run = new Function('window', source) as (win: unknown) => void;+ run(fakeWindow);++ const dispatch = (event: FakeEvent) => {+ for (const handler of listeners.get('message') ?? []) {+ handler(event);+ }+ };++ const frame = () => document.body.querySelector('iframe');++ const patchInnerPost = () => {+ const current = frame();+ if (!current || !current.contentWindow) {+ return;+ }+ const win = current.contentWindow as unknown as { postMessage: unknown; __patched?: boolean };+ if (win.__patched) {+ return;+ }+ win.postMessage = (msg: JsonRpcMessage) => innerPosts.push(msg);+ win.__patched = true;+ };++ const bootstrapNonce = (index?: number) => {+ const blob = blobs[index ?? blobs.length - 1];+ const match = blob?.match(/var N="([0-9a-f]+)"/);+ return match ? match[1] : '';+ };++ const fromInner = (msg: JsonRpcMessage, source?: unknown) =>+ dispatch({ data: msg, origin: 'null', source: source ?? frame()?.contentWindow });++ return {+ parentPosts,+ errors,+ blobs,+ revoked,+ fromParent: (msg, origin = PARENT_ORIGIN) =>+ dispatch({ data: msg, origin, source: parentWindow }),+ fromInner,+ frame,+ innerPosts: () => innerPosts,+ bootstrapNonce,+ attest: () =>+ fromInner({ jsonrpc: '2.0', method: ATTEST, params: { nonce: bootstrapNonce() } }),+ deliverResource: (params = {}) => {+ dispatch({+ data: {+ jsonrpc: '2.0',+ method: RESOURCE_READY,+ params: { html: '<html><head></head><body>app</body></html>', ...params },+ },+ origin: PARENT_ORIGIN,+ source: parentWindow,+ });+ patchInnerPost();+ },+ loadFrame: (target) => {+ const element = target ?? frame();+ element?.dispatchEvent(new Event('load'));+ },+ };+}++const HOST_REQUEST: JsonRpcMessage = { jsonrpc: '2.0', id: 1, method: 'ui/initialize', params: {} };+const APP_NOTIFICATION: JsonRpcMessage = {+ jsonrpc: '2.0',+ method: 'ui/notifications/size-changed',+ params: { height: 200 },+};++describe('mcp-sandbox.html source', () => {+ it('no longer builds a policy of its own', () => {+ for (const removed of [+ 'http-equiv',+ 'buildCspMeta',+ 'buildCspPolicy',+ 'escapeAttr',+ 'SAFE_HOST_RE',+ 'toDomainList',+ 'applyNavigationPolicy',+ 'beforeunload',+ ]) {+ expect(SANDBOX_HTML).not.toContain(removed);+ }+ });++ it('carries the fail-closed marker the sandbox route substitutes', () => {+ expect(SANDBOX_HTML).toContain('/*__CSP_APPLIED__*/');+ expect(SANDBOX_HTML).toContain('/*__VIEW_CSP__*/');+ expect(SANDBOX_HTML).toContain('window.__MCP_SANDBOX_CSP_APPLIED !== true');+ expect(SANDBOX_HTML).toContain("typeof window.__MCP_VIEW_CSP !== 'string'");+ });+});++describe('mcp-sandbox proxy', () => {+ let restoreStubs: () => void;++ beforeEach(() => {+ jest.useFakeTimers();+ document.body.innerHTML = '';+ blobs.length = 0;+ revoked.length = 0;+ errors.length = 0;+ restoreStubs = installStubs();+ });++ afterEach(() => {+ restoreStubs();+ jest.useRealTimers();+ });++ describe('handshake', () => {+ it('announces itself to the declared parent origin', () => {+ const sandbox = loadSandbox();+ expect(sandbox.parentPosts).toHaveLength(1);+ expect(sandbox.parentPosts[0]).toEqual({+ msg: { jsonrpc: '2.0', method: PROXY_READY, params: {} },+ targetOrigin: PARENT_ORIGIN,+ });+ });++ it('refuses to bridge without a parent origin', () => {+ const sandbox = loadSandbox({ parentOrigin: null });+ expect(sandbox.parentPosts).toHaveLength(0);+ expect(sandbox.errors).toHaveLength(1);+ sandbox.deliverResource();+ expect(sandbox.frame()).toBeNull();+ });++ it('bounds the re-announcement and stops once a frame exists', () => {+ const sandbox = loadSandbox();+ jest.advanceTimersByTime(500 * 40);+ expect(sandbox.parentPosts).toHaveLength(21);++ sandbox.deliverResource();+ const before = sandbox.parentPosts.length;+ jest.advanceTimersByTime(500 * 10);+ expect(sandbox.parentPosts).toHaveLength(before);+ });++ it('ignores a resource delivered from an untrusted origin', () => {+ const sandbox = loadSandbox();+ sandbox.fromParent(+ { jsonrpc: '2.0', method: RESOURCE_READY, params: { html: '<p>x</p>' } },+ 'https://evil.example',+ );+ expect(sandbox.frame()).toBeNull();+ });+ });++ describe('fail-closed csp marker', () => {+ it('builds no frame when the document was served without a per-resource policy', () => {+ const sandbox = loadSandbox({ cspApplied: false });+ sandbox.deliverResource();+ expect(sandbox.frame()).toBeNull();+ expect(sandbox.errors).toHaveLength(1);+ });++ it('builds no frame when the route did not embed the View policy', () => {+ const sandbox = loadSandbox({ viewCspApplied: false });+ sandbox.deliverResource();+ expect(sandbox.frame()).toBeNull();+ expect(sandbox.errors).toHaveLength(1);+ });++ it('builds the frame when the route applied the policy', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ expect(sandbox.frame()).not.toBeNull();+ expect(sandbox.errors).toHaveLength(0);+ });+ });++ describe('inner document', () => {+ it('is one resource per document', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource({ html: '<p>first</p>' });+ const first = sandbox.frame();+ sandbox.deliverResource({ html: '<p>second</p>' });+ expect(sandbox.frame()).toBe(first);+ expect(sandbox.blobs).toHaveLength(1);+ expect(sandbox.revoked).toHaveLength(0);+ });++ it('grants only allowlisted sandbox tokens', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource({+ sandbox:+ 'allow-same-origin allow-top-navigation allow-popups-to-escape-sandbox allow-modals',+ });+ expect(sandbox.frame()?.getAttribute('sandbox')).toBe('allow-scripts allow-forms');+ });++ it('keeps a requested subset of the allowlist', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource({ sandbox: 'allow-scripts allow-same-origin allow-pointer-lock' });+ expect(sandbox.frame()?.getAttribute('sandbox')).toBe('allow-scripts allow-pointer-lock');+ });++ it('withholds media permissions that an opaque inner frame cannot use', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource({+ permissions: { camera: {}, microphone: {}, clipboardWrite: {}, geolocation: {} },+ });+ expect(sandbox.frame()?.getAttribute('allow')).toBe('geolocation; clipboard-write');+ });++ it.each([+ ['<html><head><title>t</title></head><body>a</body></html>', '<head>'],+ ['<!doctype html><body>a</body>', '<!doctype html>'],+ ['<!doctype html><!-- lead --><html><head></head><body>a</body></html>', '<head>'],+ ['<p>bare</p>', ''],+ ])('injects the bootstrap without rewriting the app document (%s)', (html) => {+ const sandbox = loadSandbox();+ sandbox.deliverResource({ html });+ const blob = sandbox.blobs[0];+ const injection =+ blob.match(+ /<meta http-equiv="Content-Security-Policy"[^>]*><script>\(function\(\)\{var N=[\s\S]*?<\/script>/,+ )?.[0] ?? '';+ expect(injection).not.toBe('');+ expect(injection).toContain("frame-src 'none'");+ expect(blob.replace(injection, '')).toBe(html);+ if (/<head/i.test(html)) {+ expect(blob).toMatch(+ /<head[^>]*><meta http-equiv="Content-Security-Policy"[^>]*><script>\(function\(\)\{var N=/,+ );+ }+ if (/^\s*<!doctype/i.test(html)) {+ expect(blob.toLowerCase().indexOf('<!doctype')).toBe(0);+ }+ });++ it.each([+ [+ '<!-- template includes <head> --><html><head></head><body>app</body></html>',+ '<html><head>',+ ],+ ['<!doctype html><!-- <head> --><body>app</body>', '<!-- <head> -->'],+ ['<!doctype html><!-- <head>', '<!doctype html>'],+ [+ '<!doctype html><html><head></head><body><script>var s="<head>";</script></body></html>',+ '<head>',+ ],+ ['<!doctype html><html><body><script>var s="<head>";</script></body></html>', '<html>'],+ ['<!doctype html><HTML><HEAD></HEAD><body>a</body></HTML>', '<HEAD>'],+ ['<!doctype html><html><head data-x="1"></head><body>a</body></html>', '<head data-x="1">'],+ ['<!doctype html><html><body><div title="<head>"></div></body></html>', '<html>'],+ ['<template><head></head></template><p>app</p>', ''],+ ['<!doctype html><!-- lead --><template><head></head></template><p>app</p>', '<!-- lead -->'],+ ['<!doctype html><html><template><template><head></head></template></template>', '<html>'],+ ['<p>bare</p>', ''],+ ])('injects into the document head or active prolog (%s)', (html, marker) => {+ const sandbox = loadSandbox();+ sandbox.deliverResource({ html });+ const blob = sandbox.blobs[0];+ const injection =+ blob.match(+ /<meta http-equiv="Content-Security-Policy"[^>]*><script>\(function\(\)\{var N=[\s\S]*?<\/script>/,+ )?.[0] ?? '';+ expect(injection).not.toBe('');+ const at = marker === '' ? 0 : html.indexOf(marker) + marker.length;+ expect(blob).toBe(html.slice(0, at) + injection + html.slice(at));+ });++ it('keeps a quoted doctype and leading comment ahead of the bootstrap', () => {+ const sandbox = loadSandbox();+ const prefix = '<!-- lead --><!doctype html PUBLIC "example>public" "example>system">';+ const html = `${prefix}<template><head></head></template>`;+ sandbox.deliverResource({ html });+ expect(sandbox.blobs[0]).toMatch(+ /^<!-- lead --><!doctype html PUBLIC "example>public" "example>system"><meta /,+ );+ });++ it('mints a distinct nonce per document', () => {+ const first = loadSandbox();+ first.deliverResource();+ document.body.innerHTML = '';+ const second = loadSandbox();+ second.deliverResource();+ expect(first.bootstrapNonce(0)).toMatch(/^[0-9a-f]{32}$/);+ expect(second.bootstrapNonce(1)).not.toBe(first.bootstrapNonce(0));+ });+ });++ describe('bridge invalidation', () => {+ it('forwards nothing until the injected bootstrap attests', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.fromParent(HOST_REQUEST);+ expect(sandbox.innerPosts()).toHaveLength(0);++ sandbox.attest();+ expect(sandbox.innerPosts()).toEqual([HOST_REQUEST]);+ });++ it('ignores an attestation that cannot produce the nonce', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.fromInner({ jsonrpc: '2.0', method: ATTEST, params: { nonce: 'forged' } });+ sandbox.fromParent(HOST_REQUEST);+ expect(sandbox.innerPosts()).toHaveLength(0);+ });++ it('holds traffic while the heartbeat is throttled and releases it on the next attestation', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();++ jest.advanceTimersByTime(1200);+ sandbox.fromParent(HOST_REQUEST);+ sandbox.fromInner(APP_NOTIFICATION);+ expect(sandbox.innerPosts()).toHaveLength(0);+ expect(+ sandbox.parentPosts.filter((post) => post.msg.method === APP_NOTIFICATION.method),+ ).toHaveLength(0);++ sandbox.attest();+ expect(sandbox.innerPosts()).toEqual([HOST_REQUEST]);+ expect(+ sandbox.parentPosts.filter((post) => post.msg.method === APP_NOTIFICATION.method),+ ).toHaveLength(1);++ sandbox.fromParent(HOST_REQUEST);+ expect(sandbox.innerPosts()).toHaveLength(2);+ });++ it('bounds the hold queue', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ jest.advanceTimersByTime(1200);+ for (let i = 0; i < 60; i += 1) {+ sandbox.fromParent({ ...HOST_REQUEST, id: i });+ }++ sandbox.attest();+ const released = sandbox.innerPosts();+ expect(released).toHaveLength(50);+ expect(released[0].id).toBe(10);+ });++ it('discards held traffic on detach', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ jest.advanceTimersByTime(1200);+ sandbox.fromParent(HOST_REQUEST);+ sandbox.fromInner({+ jsonrpc: '2.0',+ method: DETACH,+ params: { nonce: sandbox.bootstrapNonce() },+ });++ sandbox.attest();+ expect(sandbox.innerPosts()).toHaveLength(0);+ });++ it('tears down on detach and relays nothing the replacement document posts', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ const inner = sandbox.frame()?.contentWindow;++ sandbox.fromInner({+ jsonrpc: '2.0',+ method: DETACH,+ params: { nonce: sandbox.bootstrapNonce() },+ });+ expect(sandbox.frame()).toBeNull();+ expect(sandbox.revoked).toEqual(['blob:mock/1']);++ sandbox.fromInner(APP_NOTIFICATION, inner);+ sandbox.fromParent(HOST_REQUEST);+ expect(sandbox.innerPosts()).toHaveLength(0);+ expect(+ sandbox.parentPosts.filter((post) => post.msg.method === APP_NOTIFICATION.method),+ ).toHaveLength(0);+ });++ it('invalidates on a second load of the live frame', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ sandbox.loadFrame();+ sandbox.fromParent(HOST_REQUEST);+ expect(sandbox.innerPosts()).toHaveLength(1);++ sandbox.loadFrame();+ expect(sandbox.frame()).toBeNull();+ sandbox.fromParent(HOST_REQUEST);+ expect(sandbox.innerPosts()).toHaveLength(1);+ });++ it('does not let a stale generation revoke a live blob url', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ const stale = sandbox.frame() as HTMLIFrameElement;+ sandbox.fromInner({+ jsonrpc: '2.0',+ method: DETACH,+ params: { nonce: sandbox.bootstrapNonce() },+ });+ expect(sandbox.revoked).toHaveLength(1);++ sandbox.loadFrame(stale);+ sandbox.loadFrame(stale);+ expect(sandbox.revoked).toHaveLength(1);+ });+ });++ describe('relay', () => {+ it('relays app traffic up to the declared parent origin', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ sandbox.fromInner(APP_NOTIFICATION);+ const relayed = sandbox.parentPosts.filter(+ (post) => post.msg.method === APP_NOTIFICATION.method,+ );+ expect(relayed).toHaveLength(1);+ expect(relayed[0].targetOrigin).toBe(PARENT_ORIGIN);+ });++ it('relays a response that carries no method', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ sandbox.fromInner({ jsonrpc: '2.0', id: 7, result: {} });+ expect(sandbox.parentPosts.some((post) => post.msg.id === 7)).toBe(true);+ });++ it('never relays the sandbox control namespace up', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ sandbox.fromInner({ jsonrpc: '2.0', method: PROXY_READY, params: {} });+ sandbox.fromInner({ jsonrpc: '2.0', method: RESOURCE_READY, params: { html: '<p>x</p>' } });+ expect(sandbox.parentPosts.filter((post) => post.msg.method === RESOURCE_READY)).toHaveLength(+ 0,+ );+ expect(sandbox.parentPosts.filter((post) => post.msg.method === PROXY_READY)).toHaveLength(1);+ });++ it('drops messages from an unrelated window in both directions', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ const grandchild = { name: 'grandchild' };+ sandbox.fromInner(APP_NOTIFICATION, grandchild);+ expect(+ sandbox.parentPosts.filter((post) => post.msg.method === APP_NOTIFICATION.method),+ ).toHaveLength(0);++ sandbox.fromParent(HOST_REQUEST, 'https://evil.example');+ expect(sandbox.innerPosts()).toHaveLength(0);+ });++ it('ignores non-JSON-RPC traffic', () => {+ const sandbox = loadSandbox();+ sandbox.deliverResource();+ sandbox.attest();+ sandbox.fromInner({ jsonrpc: '1.0', method: 'x' } as JsonRpcMessage);+ sandbox.fromInner('not json' as unknown as JsonRpcMessage);+ expect(sandbox.parentPosts.filter((post) => post.msg.method === 'x')).toHaveLength(0);+ });+ });+});diff --git a/client/src/utils/__tests__/media.spec.ts b/client/src/utils/__tests__/media.spec.tsindex 279e840a9f..1fdeb89128 100644--- a/client/src/utils/__tests__/media.spec.ts+++ b/client/src/utils/__tests__/media.spec.ts@@ -187,6 +187,18 @@ describe('attachmentIdentity', () => {expect(attachmentIdentity(citation)).toBe('file_search:t1');});+ it('keeps non-file artifacts from agents reusing a provider tool id apart', () => {+ const alpha = {+ type: 'ui_resources',+ toolCallId: 'call_0',+ agentId: 'agent-alpha',+ } as unknown as TAttachment;+ const beta = { ...alpha, agentId: 'agent-b' } as TAttachment;++ expect(attachmentIdentity(alpha)).toBe('ui_resources:call_0::agent-alpha');+ expect(attachmentIdentity(beta)).toBe('ui_resources:call_0::agent-b');+ });+it('gives no identity to a row that names no stored file', () => {// Two rows that cannot be told apart are two rows, not one.expect(diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex 283910425e..8fc338b7d0 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -1,6 +1,6 @@import React from 'react';import type { UIActionResult } from '@mcp-ui/client';-import { TAskFunction } from '~/common';+import type { TAskFunction } from '~/common';import logger from './logger';export * from './map';@@ -140,15 +140,9 @@ export const extractContent = (return '';};+/** Converts supported legacy MCP-UI actions into the existing conversation submission path. */export const handleUIAction = async (result: UIActionResult, ask: TAskFunction) => {- const supportedTypes = ['intent', 'tool', 'prompt'];-const { type, payload } = result;-- if (!supportedTypes.includes(type)) {- return;- }-let messageText = '';if (type === 'intent') {@@ -184,6 +178,8 @@ ${prompt}Execute the intention of the prompt that is mentioned in the message using the tools available to you.`;+ } else {+ return;}logger.debug('MCP-UI', 'About to submit message:', messageText);diff --git a/client/src/utils/mcpApps.ts b/client/src/utils/mcpApps.tsnew file mode 100644index 0000000000..d3e8512678--- /dev/null+++ b/client/src/utils/mcpApps.ts@@ -0,0 +1,474 @@+import {+ Tools,+ request,+ apiBaseUrl,+ isMcpAppMimeType,+ MCP_APP_CSP_MAX_LENGTH,+ normalizeMCPAppCspDeclaration,+ resolveMCPAppCspLimits,+} from 'librechat-data-provider';+import type {+ CallToolResult,+ ListResourcesResult,+ ReadResourceResult,+ ListResourceTemplatesResult,+} from '@modelcontextprotocol/sdk/types.js';+import type { MCPAppCspLimits, TAttachment, UIResource } from 'librechat-data-provider';++export type AppToolResult = {+ content: unknown[];+ structuredContent?: Record<string, unknown>;+ isError?: boolean;+ _meta?: Record<string, unknown>;+};++/** Browser capabilities supported by LibreChat's deliberately opaque inner App frame. */+export function getSupportedMCPAppPermissions(+ permissions: UIResource['permissions'],+): UIResource['permissions'] {+ if (!permissions) {+ return undefined;+ }+ const supported: NonNullable<UIResource['permissions']> = {};+ if (permissions.geolocation) {+ supported.geolocation = {};+ }+ if (permissions.clipboardWrite) {+ supported.clipboardWrite = {};+ }+ return Object.keys(supported).length > 0 ? supported : undefined;+}++/**+ * An MCP App resource is server-bound and declares the MCP Apps HTML profile+ * (`text/html;profile=mcp-app`). Only these run the App Bridge handshake; plain `text/html`+ * resources are static and must render through a srcDoc iframe instead.+ */+export function isMcpAppResource(resource: UIResource): boolean {+ // Shared with the server's app-backed classification so the two sides cannot drift: a substring+ // test here accepted mime types the parser refuses to attach bridge fields to.+ return !!resource.toolName && !!resource.serverName && isMcpAppMimeType(resource.mimeType);+}++/**+ * Builds the App Bridge tool result from a UI resource. App-backed resources (toolName ++ * serverName) always produce a result so the app's ontoolresult fires even for empty output,+ * and the tool result's _meta is forwarded for apps that hydrate from it.+ */+export function buildAppToolResult(resource: UIResource): AppToolResult | undefined {+ const sc = resource.structuredContent as Record<string, unknown> | undefined | null;+ const content = (resource.content as unknown[] | undefined) ?? [];+ const meta = resource.resultMeta as Record<string, unknown> | undefined;+ const hasStructured = !!sc && typeof sc === 'object' && !Array.isArray(sc);+ const isAppBacked = !!(resource.toolName && resource.serverName);+ if (+ !hasStructured &&+ content.length === 0 &&+ meta == null &&+ resource.isError !== true &&+ !isAppBacked+ ) {+ return undefined;+ }+ return {+ content,+ ...(hasStructured ? { structuredContent: sc } : {}),+ ...(resource.isError === true ? { isError: true } : {}),+ ...(meta != null ? { _meta: meta } : {}),+ };+}++export function getMCPSandboxUrl(runtimeUrl?: unknown): string | undefined {+ const env = import.meta.env as Record<string, string | undefined>;+ let base = env.VITE_MCP_SANDBOX_URL ?? '';+ if (runtimeUrl !== undefined) {+ base = typeof runtimeUrl === 'string' ? runtimeUrl : '';+ }+ base = base.trim();+ if (!base) {+ return undefined;+ }+ try {+ const url = new URL(base);+ if (+ (url.protocol !== 'http:' && url.protocol !== 'https:') ||+ url.origin === window.location.origin+ ) {+ return undefined;+ }+ url.searchParams.set('parentOrigin', window.location.origin);+ return url.toString();+ } catch {+ return undefined;+ }+}++/** Default route bound retained for mixed-version callers and assertions. */+export const MAX_SANDBOX_CSP_PARAM_LENGTH = MCP_APP_CSP_MAX_LENGTH;++/**+ * The declaration travels on the sandbox URL before load. The route uses the same normalized value+ * for its proxy response policy and the View policy it installs ahead of App content. Returning that+ * normalized value keeps host link decisions within the policy the View actually received.+ */+export function withSandboxCsp(+ sandboxUrl: string,+ csp: UIResource['csp'],+ limits?: MCPAppCspLimits,+): { url: string; applied: UIResource['csp'] } {+ if (!csp) {+ return { url: sandboxUrl, applied: undefined };+ }+ try {+ const effectiveLimits = resolveMCPAppCspLimits(limits);+ const normalized = normalizeMCPAppCspDeclaration(csp, effectiveLimits);+ const serialized = JSON.stringify(normalized);+ if (serialized.length > effectiveLimits.maxSerializedLength) {+ return { url: sandboxUrl, applied: undefined };+ }+ const url = new URL(sandboxUrl, window.location.origin);+ url.searchParams.set('csp', serialized);+ return { url: url.toString(), applied: normalized };+ } catch {+ return { url: sandboxUrl, applied: undefined };+ }+}++/**+ * Stable identity for a UI resource across re-renders. Keying render state by array index lets a+ * removed resource hand its loaded/torn-down state and measured height to whichever resource+ * reconciles onto its index.+ */+export function getResourceKey(resource: UIResource): string {+ return resource.resourceId || resource.uri;+}++export type MCPAppResourceOccurrence = {+ attachment: TAttachment;+ key: string;+ resource: UIResource;+};++/** MCP Apps owned by correlated attachment wrappers. Legacy HTML remains marker-owned. */+export function selectToolCallUIResources(attachments?: TAttachment[]): MCPAppResourceOccurrence[] {+ const occurrences = new Map<string, number>();+ return (attachments ?? []).flatMap((attachment) => {+ if (attachment.type !== Tools.ui_resources) {+ return [];+ }+ const value = attachment[Tools.ui_resources];+ const resources = Array.isArray(value) ? (value as UIResource[]) : [];+ const owner = attachment as TAttachment & {+ toolCallId?: string;+ agentId?: string;+ stepId?: string;+ };+ return resources.flatMap((resource) => {+ if (!isMcpAppResource(resource)) {+ return [];+ }+ const semanticKey = JSON.stringify([+ owner.toolCallId,+ owner.agentId,+ owner.stepId,+ getResourceKey(resource),+ ]);+ const occurrence = occurrences.get(semanticKey) ?? 0;+ occurrences.set(semanticKey, occurrence + 1);+ return [{ attachment, key: JSON.stringify([semanticKey, occurrence]), resource }];+ });+ });+}++async function postMCPAppRequest<T>(+ path: string,+ body: Record<string, unknown>,+ signal?: AbortSignal,+): Promise<T> {+ const response = await request.authenticatedFetch(`${apiBaseUrl()}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ signal,+ });+ if (!response.ok) {+ throw new Error(`MCP App request failed (${response.status})`);+ }+ return (await response.json()) as T;+}++export async function callMCPAppTool(+ serverName: string,+ serverBinding: string,+ toolName: string,+ args: Record<string, unknown>,+ signal?: AbortSignal,+): Promise<CallToolResult> {+ return postMCPAppRequest(+ '/api/mcp/app-tool-call',+ {+ serverName,+ serverBinding,+ toolName,+ arguments: args,+ },+ signal,+ );+}++export async function readMCPResource(+ serverName: string,+ serverBinding: string,+ uri: string,+ signal?: AbortSignal,+): Promise<ReadResourceResult> {+ return postMCPAppRequest('/api/mcp/resources/read', { serverName, serverBinding, uri }, signal);+}++export async function listMCPResources(+ serverName: string,+ serverBinding: string,+ cursor?: string,+ signal?: AbortSignal,+): Promise<ListResourcesResult> {+ return postMCPAppRequest(+ '/api/mcp/resources/list',+ { serverName, serverBinding, cursor },+ signal,+ );+}++export async function listMCPResourceTemplates(+ serverName: string,+ serverBinding: string,+ cursor?: string,+ signal?: AbortSignal,+): Promise<ListResourceTemplatesResult> {+ return postMCPAppRequest(+ '/api/mcp/resources/templates/list',+ { serverName, serverBinding, cursor },+ signal,+ );+}++export async function validateMCPAppBinding(+ serverName: string,+ serverBinding: string,+ signal?: AbortSignal,+): Promise<void> {+ const result = await postMCPAppRequest<{ valid?: boolean }>(+ '/api/mcp/app/validate',+ { serverName, serverBinding },+ signal,+ );+ if (result.valid !== true) {+ throw new Error('MCP App server binding is no longer valid');+ }+}++type ResourceUiMeta = {+ csp?: {+ connectDomains?: string[];+ resourceDomains?: string[];+ frameDomains?: string[];+ baseUriDomains?: string[];+ };+ permissions?: {+ camera?: Record<string, never>;+ microphone?: Record<string, never>;+ geolocation?: Record<string, never>;+ clipboardWrite?: Record<string, never>;+ };+};++/** Decode a base64 resource blob as UTF-8 so non-ASCII HTML is not mojibake (atob yields Latin-1). */+export function decodeBase64Utf8(b64: string): string {+ const bytes = Uint8Array.from(atob(b64), (char) => char.charCodeAt(0));+ return new TextDecoder('utf-8').decode(bytes);+}++/**+ * Upper bound for an app-requested iframe height. The size comes from the sandboxed app, so an+ * unclamped value would let it impose multi-million-pixel layout on the host conversation.+ */+export const MAX_APP_VIEW_HEIGHT = 4000;++/**+ * Lower bound for an app-requested iframe height. A few-pixel height hides the app behind its own+ * chrome with no way for the user to recover it.+ */+export const MIN_APP_VIEW_HEIGHT = 80;++/** Upper bound for a carousel slide, which scrolls horizontally in a fixed-height row. */+export const MAX_CAROUSEL_VIEW_HEIGHT = 720;++/** Clamps an app-reported height, returning undefined when it is not a usable positive number. */+export function clampAppViewHeight(+ height?: number,+ bounds?: { min?: number; max?: number },+): number | undefined {+ if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0) {+ return undefined;+ }+ const min = bounds?.min ?? MIN_APP_VIEW_HEIGHT;+ const max = bounds?.max ?? MAX_APP_VIEW_HEIGHT;+ return Math.min(Math.max(Math.round(height), min), max);+}++/**+ * CSP3 §6.6.2.2 host-source grammar, minus the scheme-less form. `scheme-part` is required because+ * the app document has an opaque origin, so §6.7.2.8's "same scheme as the protected resource" rule+ * has no stable answer; `path-part` is rejected because the sandbox filter drops path-bearing+ * entries, so accepting one here would authorize a link the sandbox policy never granted.+ *+ * `isAllowedAppLink` consumes the shared normalized source list, then authorizes a strict subset of+ * what the browser grants inside the sandbox. Every deviation from CSP3 here narrows.+ */+const APP_LINK_HOST_PATTERN =+ /^(https?|wss?):\/\/(\*\.)?([a-zA-Z0-9](?:[a-zA-Z0-9\-.]*[a-zA-Z0-9])?)(?::(\d{1,5}|\*))?$/i;++const DEFAULT_PORTS: Record<string, string> = { 'http:': '80', 'https:': '443' };++function effectivePort(url: URL): string {+ return url.port || DEFAULT_PORTS[url.protocol] || '';+}++/** IPv6 hosts arrive bracketed from `URL`; IPv4 is four decimal labels. CSP3 §6.7.2.10 step 1+ * compares host-parts label by label, so an address literal can never match a wildcard and only+ * ever matches itself: refuse both rather than reason about `0x7f.1` style spellings. */+function isAddressLiteral(hostname: string): boolean {+ return hostname.startsWith('[') || /^\d+(?:\.\d+)*$/.test(hostname);+}++/**+ * Matches a URL against one declared CSP source, following CSP3 §6.7.2.8-11: the scheme must match+ * exactly (no `http`→`https` widening in either direction), an absent `port-part` matches only the+ * scheme's default port, `port-part = '*'` matches any port, and `*.example.com` requires at least+ * one subdomain label so it never covers the apex.+ */+function urlMatchesDeclaredSource(url: URL, entry: string): boolean {+ const match = APP_LINK_HOST_PATTERN.exec(entry.trim());+ if (!match) {+ return false;+ }+ const [, declaredScheme, wildcard, declaredHost, declaredPort] = match;++ // ws(s) declarations are for sockets, not navigable links.+ const scheme = declaredScheme.toLowerCase();+ if (scheme !== 'http' && scheme !== 'https') {+ return false;+ }+ if (url.protocol !== `${scheme}:`) {+ return false;+ }++ if (+ declaredPort !== '*' &&+ effectivePort(url) !== (declaredPort || DEFAULT_PORTS[`${scheme}:`])+ ) {+ return false;+ }++ const host = url.hostname.toLowerCase();+ const target = declaredHost.toLowerCase();+ // CSP3 compares host-parts label by label, so a trailing dot yields an empty final label that+ // matches nothing; refuse it rather than normalize it into the apex.+ if (!host || host.endsWith('.') || isAddressLiteral(host)) {+ return false;+ }+ if (!wildcard) {+ return host === target;+ }+ return host.length > target.length + 1 && host.endsWith(`.${target}`);+}++/**+ * A host-opened link is not bound by the sandbox CSP, so an app holding proxied MCP data could+ * encode it into a URL and exfiltrate it through the host page. Only hosts the resource declared+ * for egress are opened; a resource declaring none gets no host-opened links, matching the+ * `connect-src 'none'` default applied inside the sandbox.+ */+export function isAllowedAppLink(+ url: string,+ csp: UIResource['csp'],+ limits?: MCPAppCspLimits,+): boolean {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ return false;+ }+ const effective = normalizeMCPAppCspDeclaration(csp, limits);+ const declared = [+ ...(effective.connectDomains ?? []),+ ...(effective.resourceDomains ?? []),+ ...(effective.frameDomains ?? []),+ ];+ return declared.some(+ (entry) => typeof entry === 'string' && urlMatchesDeclaredSource(parsed, entry),+ );+}++/**+ * Inline HTML persisted on a UI resource, carried either as `text` or as a base64 `blob`. Read-only+ * views render only inline HTML, so both encodings must count as persisted or blob-embedded apps+ * would be dropped from shared transcripts.+ */+export function getInlineResourceHtml(resource: UIResource): string | undefined {+ if (typeof resource.text === 'string' && resource.text) {+ return resource.text;+ }+ if (typeof resource.blob === 'string' && resource.blob) {+ try {+ return decodeBase64Utf8(resource.blob);+ } catch {+ return undefined;+ }+ }+ return undefined;+}++export async function fetchMCPResourceHtml(+ serverName: string,+ serverBinding: string,+ uri: string,+ signal?: AbortSignal,+): Promise<{+ html: string;+ csp?: ResourceUiMeta['csp'];+ permissions?: ResourceUiMeta['permissions'];+}> {+ const result = (await readMCPResource(serverName, serverBinding, uri, signal)) as {+ contents?: Array<{+ uri?: string;+ mimeType?: string;+ text?: string;+ blob?: string;+ _meta?: { ui?: ResourceUiMeta };+ }>;+ };+ const item = result?.contents?.find(+ (content) => content.uri === uri && isMcpAppMimeType(content.mimeType),+ );+ const uiMeta = item?._meta?.ui;+ let html = item?.text ?? '';+ if (!html && typeof item?.blob === 'string' && item.blob) {+ try {+ html = decodeBase64Utf8(item.blob);+ } catch {+ html = '';+ }+ }+ if (!html) {+ throw new Error('MCP App resource returned no matching HTML document');+ }+ return {+ html,+ csp: uiMeta?.csp,+ permissions: uiMeta?.permissions,+ };+}diff --git a/client/src/utils/media.ts b/client/src/utils/media.tsindex 93deef8921..2a564c1833 100644--- a/client/src/utils/media.ts+++ b/client/src/utils/media.ts@@ -47,7 +47,7 @@ function ownerOf(attachment: TAttachment): {/*** Stable identity for an attachment: `file_id ?? filepath` scoped by- * `toolCallId` and `agentId`, else `type:toolCallId` for unkeyed tool+ * `toolCallId` and `agentId`, else `type:toolCallId` with the same optional agent scope for unkeyed tool* artifacts like file_search citations. `undefined` means the row has no* stable identity and must never be compared to another — two entries that* cannot be told apart are two entries, not one.@@ -69,7 +69,7 @@ export function attachmentIdentity(attachment: TAttachment): string | undefinedreturn agentId ? `${fileKey}::${toolCallId}::${agentId}` : `${fileKey}::${toolCallId}`;}if (type != null && toolCallId != null) {- return `${type}:${toolCallId}`;+ return agentId ? `${type}:${toolCallId}::${agentId}` : `${type}:${toolCallId}`;}return undefined;}diff --git a/docs/mcp-apps.md b/docs/mcp-apps.mdnew file mode 100644index 0000000000..d1991b4770--- /dev/null+++ b/docs/mcp-apps.md@@ -0,0 +1,242 @@+# MCP Apps++LibreChat renders tool-linked MCP Apps with the official MCP Apps SDK. The MCP server stays behind+LibreChat: a View calls LibreChat's authenticated HTTP routes, and LibreChat forwards the operation+through the MCP connection that owns that server. Browser Views never receive MCP credentials.++This integration targets the+[stable `2026-01-26` MCP Apps protocol](https://github.com/modelcontextprotocol/ext-apps/blob/v1.7.5/specification/2026-01-26/apps.mdx),+implemented by+[`@modelcontextprotocol/ext-apps` 1.7.5](https://github.com/modelcontextprotocol/ext-apps/tree/v1.7.5).+The lockfile is the executable version boundary.++## Support profile++| Area | Supported behavior |+| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |+| App resource | A tool-linked `ui://` resource with `text/html;profile=mcp-app`, supplied as UTF-8 `text` or base64 `blob` |+| MCP connection | Standard shared sessions when Apps are off; profile-separated per-user, MCP OAuth, and direct OpenID sessions when on |+| View operations | Same-server tool calls, resource reads, resource and template listing, text messages, policy-controlled links, and logging |+| Visibility | Model, App, dual-visible, and omitted visibility follow the MCP Apps visibility rules |+| Rendering | Settled Apps render once in a message-owned area below the response; legacy inline HTML keeps its existing adapter |+| History | A stored settled result replays its input, unchanged result, and App document while its originating server binding is valid |+| Search and public share | Search results do not load Apps; public shares omit UI resources and retain ordinary transcript and tool text |+| Unsupported connection profiles | OBO, Graph-token placeholders, and request-body credential placeholders do not offer an interactive App View |++Optional draft features such as sampling, downloads, App-provided tools, state restoration, external+View URLs, and partial tool input are outside this profile.++Set `mcpSettings.apps: true` to enable MCP Apps and legacy inline HTML. When the field is omitted,+new MCP Apps stay disabled while existing legacy inline HTML remains enabled for upgrade+compatibility. An explicit `false` disables both. Authenticated clients fail closed when the+resolved policy is unavailable or malformed; configuration changes take effect when startup+configuration is refreshed, such as after a page reload.+LibreChat advertises the `io.modelcontextprotocol/ui` client capability only on sessions admitted+by that effective Apps policy. Shared operator connections and startup inspection stay on the+standard MCP handshake; an enabled request uses a profile-separated user session so discovery,+tool calls, and App follow-ups observe one capability set without changing server or credential+ownership.+Legacy `ui://` resources use the installed MCP-UI renderer's `text/html` contract. An omitted MIME+type is treated as `text/html`; explicit XHTML and other MIME types remain non-executable to that+renderer while their marker-addressed attachments stay available to custom clients.+Consequently, a new client paired with an older backend that omits the authenticated policy+withholds both MCP Apps and legacy inline HTML. LibreChat's monolithic same-version deployment is+the supported upgrade path.++The deployment-owned sandbox transport limits default to 32 sources per CSP directive and 4,096+serialized characters. Raise them for Apps that declare more origins or a larger CSP payload:++```yaml+mcpAppSandbox:+ url: https://mcp-sandbox.example.com/api/mcp/sandbox+ maxSourcesPerDirective: 64+ maxSerializedLength: 8192+ maxPersistedAppBytes: 2097152+ maxAdmissionRequestsPerMinute: 480+```++These positive-integer settings come only from the base deployment configuration; role, group, and+user overrides cannot change them. Apply a limits change across the server and client deployment,+then reload open chat pages so host link decisions and newly served sandbox responses use the same+snapshot. Request query parameters contain only the normalized CSP declaration and cannot choose+their own limits. `maxPersistedAppBytes` defaults to 1 MiB and can be raised to at most 4 MiB. It+bounds each complete App attachment added to a message, rather than the whole message document. An+oversized full document falls back to a bound URI-only descriptor; if that descriptor is still too+large, LibreChat omits the optional App artifact while preserving ordinary tool output.++`maxAdmissionRequestsPerMinute` defaults to 240 and is a shared per-user ceiling across every App+validation, resource, and tool-call route. LibreChat applies it before principal-scoped configuration+admission. The existing `rateLimits.mcpApps` values remain the more precise resource and tool-call+limits applied after admission.++MCP App browser routes use independent, per-user, one-minute limits. Configure positive integer+values at `rateLimits.mcpApps.resourcesPerMinute` and+`rateLimits.mcpApps.toolCallsPerMinute`; their defaults are 120 and 60 respectively.++## Required sandbox deployment++The chat application and Sandbox Proxy must use different URL origins. Set the proxy URL in the base+LibreChat configuration and allow the chat origin to frame the proxy response:++```yaml+mcpAppSandbox:+ url: https://mcp-sandbox.example.com/api/mcp/sandbox+```++```dotenv+MCP_SANDBOX_FRAME_ANCESTORS=https://chat.example.com+```++The runtime `url` must be an absolute `http:` or `https:` URL whose origin differs from the chat+page. It is delivered only in authenticated startup configuration, so official prebuilt images use+it without rebuilding the client. Missing, invalid, or same-origin values fail closed and show the+View load error. Configuration changes take effect after a page reload.++For compatibility with older servers, a client built with `VITE_MCP_SANDBOX_URL` uses that compiled+URL only when authenticated startup configuration omits `sandboxUrl`. An explicit runtime URL is+authoritative: if it is unusable, the client does not silently fall back to the compiled value. The+build argument remains supported for existing custom images, but runtime YAML is the supported+same-version deployment path.++Route `https://mcp-sandbox.example.com/api/mcp/sandbox` to the LibreChat sandbox handler without+adding authentication or HTML transformation. Preserve its response headers, especially its CSP,+`Cache-Control`, `Cross-Origin-Resource-Policy`, and frame-ancestor policy. The outer proxy iframe+uses `sandbox="allow-scripts allow-same-origin allow-forms"`; the proxy creates an opaque-origin+inner iframe for the server-provided document. Form destinations remain bounded by the resource's+declared `connectDomains` through the sandbox response's `form-action` policy. The dedicated origin+should expose only this sandbox endpoint, not the chat application, session endpoints, or other+authenticated LibreChat routes.++The opaque inner frame supports requested geolocation and clipboard-write delegation. Camera and+microphone requests are withheld because browser media capture requires a non-opaque document+origin; Apps must feature-detect permission availability as required by the MCP Apps protocol.++The outer proxy response CSP is a loader policy that permits its own blob-backed inner frame. Before+the App document runs, the proxy separately installs the View policy as a CSP meta element inside+that inner document. The View policy comes from the selected resource's `_meta.ui.csp`; with no+declaration it defaults to `frame-src 'none'` and restrictive script, style, image, media, connect,+object, and base URI directives. Valid declared domains only widen their corresponding directives.++## Server contract++An App tool declares its View on `_meta.ui.resourceUri` (the deprecated `ui/resourceUri` spelling is+accepted for compatibility). LibreChat reads that exact URI from the same authenticated MCP+connection during the original tool call and persists the selected App-profile document. The tool+result sent to the View remains unchanged, including any embedded resource body; an embedded body+does not replace the required `resources/read` document. MCP tools invoked through Assistants and+Azure Assistants retain the App attachment alongside their canonical model-visible tool text.++Each persisted App also carries an opaque server binding issued from the exact authenticated MCP+target used by the original call. LibreChat validates that binding before loading stored inline HTML+and on every later App operation. Changing the server owner, effective endpoint, command, relevant+custom variables, or configuration generation invalidates existing Views; routine OAuth or bearer+credential refresh does not. Invalidated and older unbound App attachments remain unavailable and+never bind by server name to a replacement configuration. The host does not live-revoke a document+that is already loaded: a remount or page reload validates before loading it again, and every later+App operation validates independently.++Validation of stored inline HTML compares the binding with the current local admitted server target;+it does not connect to the MCP server. A matching persisted document can therefore render while its+server is temporarily offline, although any live View operation still reports that outage. A+URI-only descriptor needs a live bound resource read before it has a document to render.++If the initial read fails or returns no usable exact item, the ordinary tool result remains+successful and LibreChat stores a URI-only unavailable descriptor. An authenticated interactive+history view may retry that document read; noninteractive surfaces do not. LibreChat never retries+the tool or executes the embedded App-profile body as a fallback.++Content-level `_meta.ui` from the selected read result controls that exact document. This profile+does not implement the released SDK's recommended fallback to resource-listing metadata, so servers+should repeat View metadata on the `resources/read` content item. When it is absent, LibreChat uses+the restrictive default; relying only on listing metadata is an interoperability limitation rather+than an invalid server response.++View requests remain bound to the authenticated user and originating server. The browser-facing+operations are:++| Method | Route | Body |+| ------------- | ---------------------------------------- | ---------------------------------------------------- |+| Binding check | `POST /api/mcp/app/validate` | `{ serverName, serverBinding }` |+| Tool call | `POST /api/mcp/app-tool-call` | `{ serverName, serverBinding, toolName, arguments }` |+| Resource read | `POST /api/mcp/resources/read` | `{ serverName, serverBinding, uri }` |+| Resource list | `POST /api/mcp/resources/list` | `{ serverName, serverBinding, cursor? }` |+| Template list | `POST /api/mcp/resources/templates/list` | `{ serverName, serverBinding, cursor? }` |++Successful routes return the raw MCP SDK result. Invalid requests return HTTP 400, missing+authentication returns 401, and a policy without MCP Apps enabled returns 403. An auxiliary+resource read uses the same authenticated server's authority; a View cannot choose another MCP+connection.++A corrected client validates stored inline HTML before loading it. URI-only history combines+binding validation and `resources/read` against one resolved target, avoiding a second lookup. An+older cached client can still display inline HTML after a server upgrade, but corrected backend+routes reject every bridge operation that omits the binding; same-version client/server deployment+remains the supported upgrade model.++Standard MCP OAuth and direct-bearer App callbacks reuse the same bounded connection recovery as+ordinary MCP tool calls. When interactive authorization is required, the user starts it through+LibreChat's existing MCP UI; an App callback does not open a separate authorization flow. Direct+OpenID reauthentication returns the established HTTP 401 `invalid_token` shape, rejected bearer+credentials return 403, temporary refresh failure returns 503, and unexpected failures return a+generic 500 response.++## Reproducible integration fixture++The focused fixture uses the ordinary mock-provider login and conversation flow, disposable Mongo,+a real LibreChat HTTP server, a real networked MCP SDK server, the official browser `App` and host+`AppBridge`, and Chromium. Its tool result includes benign embedded HTML that differs from the+declared resource. The browser verifies one initial `resources/read`, execution of the read-derived+document, delivery of the unchanged tool result, View-originated tool/resource/list/message+operations, and reload from the persisted document without another read. A public share must retain+ordinary transcript and tool text while exposing no UI attachment, frame, or App RPC.++The fixture document begins with a template containing a decoy `head`; successful connection proves+the host bootstrap was inserted into the active document prolog. It also requests camera,+microphone, geolocation, and clipboard-write while asserting that only the two permissions supported+by LibreChat's opaque frame reach either iframe boundary.++A second ordinary App resource permits one link origin; its `openLink` button checks both the SDK+result and the page the host opens. Keeping the first resource's CSP undeclared lets the browser+scenario independently verify the complete restrictive default. The same scenario renders an+ordinary legacy `text/html` resource with the installed `@mcp-ui/client`, verifies its resize+message, and follows a benign tool action through the normal chat/tool flow.++Use Node 24 with the exact lockfile installed and Playwright Chromium available. From the repository+root, run the profile with one command:++```bash+node e2e/mcp-apps/run.mjs+```++The runner builds the client with the chat at `http://127.0.0.1:3080` and the Sandbox Proxy at+`http://localhost:3080`. Those URLs reach the same disposable LibreChat process but have distinct+browser origins. The aliases are only a disposable local substitute for separate deployment+origins. The fixture does not contact an external model or MCP provider.++The browser spec is `e2e/specs/mock/mcp-apps.spec.ts`; the disposable official-SDK server is+`e2e/setup/fake-mcp-app-server.mjs`. Keep `E2E_MCP_APPS=true` scoped to this profile so its server and+configuration do not enter the general mock suite.++The server fixture has a faster transport/contract check that does not build LibreChat:++```bash+node --test e2e/mcp-apps/server.test.mjs+```++## Ownership and protocol boundary++```text+MCP server+ ↕ LibreChat MCP manager and the user's existing connection lifecycle+authenticated App operation routes+ ↕ raw MCP SDK request/results+one AppBridge per settled tool-result View+ ↕ source-bound postMessage+dedicated-origin Sandbox Proxy+ ↕ opaque sandboxed inner View+```++The official SDK supplies the MCP server, browser `App`, `AppBridge`, and transport contracts.+LibreChat owns authentication, same-server authorization, persistence, placement, and sandbox+policy. Its inner frame deliberately retains an opaque origin plus nonce/heartbeat liveness; this is+a documented host design beyond the basic official example and is covered by the browser fixture.diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yamlindex 832c49345a..42c95b746d 100644--- a/e2e/config/librechat.e2e.yaml+++ b/e2e/config/librechat.e2e.yaml@@ -28,23 +28,18 @@ memory:personalize: truetokenLimit: 10000-# Budgets that exist only here, not in the environment, so-# yaml-rate-limits.spec.ts proves librechat.yaml reaches the limiters that route-# modules build while loading. No other spec calls the speech routes.-rateLimits:- stt:- userMax: 2- tts:- userMax: 2+# __E2E_MCP_APP_SANDBOX__mcpSettings:- # Deliberately excludes 127.0.0.1, so the URL-based `e2e-http` server below is blocked+ # __E2E_MCP_APPS_SETTING__+ # Deliberately excludes the e2e-http origin below, so that server is blocked# at boot (stored as inspectionFailed). mcp-allowlist-override.spec.ts adds that origin# via an admin-panel config override and asserts the server reinitializes — proving the# admin override is honored by inspection/connection. stdio servers skip this check.allowedDomains:- https://allowed.example.com- http://127.0.0.1:8767+ # __E2E_MCP_APPS_ALLOWED_DOMAIN__# __E2E_DYNAMIC_MCP_ALLOWED_DOMAIN__actions:@@ -80,6 +75,9 @@ mcpServers:token_url: http://127.0.0.1:8767/tokenclient_id: e2e-oauth-client# __E2E_DYNAMIC_MCP_NETWORK_SERVERS__+ # __E2E_MCP_APPS_SERVER__++# __E2E_MCP_APP_RATE_LIMITS__# Per-endpoint file upload config so both upload UXs get e2e coverage:# - Mock Provider A keeps the legacy 3-way dropdown (chat.spec.ts exercisesdiff --git a/e2e/mcp-apps/run.mjs b/e2e/mcp-apps/run.mjsnew file mode 100644index 0000000000..4276a338f8--- /dev/null+++ b/e2e/mcp-apps/run.mjs@@ -0,0 +1,86 @@+#!/usr/bin/env node++import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { randomBytes } from 'node:crypto';+import { spawn } from 'node:child_process';+import { createRequire } from 'node:module';++const baseUrl = new URL(process.env.E2E_BASE_URL || 'http://127.0.0.1:3080');+const sandboxHost = baseUrl.hostname === 'localhost' ? '127.0.0.1' : 'localhost';+const sandboxUrl = new URL('/api/mcp/sandbox', baseUrl);+sandboxUrl.hostname = sandboxHost;+const runtimeSandboxUrl =+ process.env.E2E_MCP_SANDBOX_URL || process.env.VITE_MCP_SANDBOX_URL || sandboxUrl.href;++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const require = createRequire(path.join(root, 'package.json'));+const { MongoMemoryServer } = require('mongodb-memory-server');+const statePath = path.join(root, 'e2e/.generated/mcp-apps-state.json');++const env = {+ ...process.env,+ E2E_BASE_URL: baseUrl.origin,+ E2E_MCP_APPS: 'true',+ E2E_MCP_APPS_STATE_PATH: statePath,+ E2E_MCP_SANDBOX_URL: runtimeSandboxUrl,+ MCP_SANDBOX_FRAME_ANCESTORS: baseUrl.origin,+ JWT_SECRET: process.env.JWT_SECRET || randomBytes(32).toString('hex'),+ JWT_REFRESH_SECRET: process.env.JWT_REFRESH_SECRET || randomBytes(32).toString('hex'),+ CREDS_KEY: process.env.CREDS_KEY || randomBytes(32).toString('hex'),+ CREDS_IV: process.env.CREDS_IV || randomBytes(16).toString('hex'),+};++const command = (name) => (process.platform === 'win32' ? `${name}.cmd` : name);++function run(executable, args, overrides = {}) {+ return new Promise((resolve, reject) => {+ const child = spawn(command(executable), args, {+ cwd: root,+ env: { ...env, ...overrides },+ stdio: 'inherit',+ });+ child.once('error', reject);+ child.once('exit', (code, signal) => {+ if (code === 0) {+ resolve();+ return;+ }+ reject(new Error(`${executable} exited with ${signal || code || 'an unknown status'}`));+ });+ });+}++const phases = [+ { name: 'true', policy: 'true' },+ { name: 'false', policy: 'false' },+ { name: 'omitted', policy: 'omitted' },+ {+ name: 'quota',+ policy: 'true',+ E2E_MCP_APP_RESOURCE_LIMIT: '2',+ E2E_MCP_APP_TOOL_CALL_LIMIT: '2',+ },+];++let mongo;+try {+ // Build like an official prebuilt image: the browser must receive its Sandbox URL at runtime.+ await run('npm', ['run', 'e2e:prepare'], { VITE_MCP_SANDBOX_URL: '' });+ mongo = await MongoMemoryServer.create({+ instance: { ip: '127.0.0.1', dbName: 'LibreChat-e2e' },+ });+ env.E2E_USE_MEMORY_MONGO = 'false';+ env.MONGO_URI = mongo.getUri('LibreChat-e2e');++ for (const phase of phases) {+ await run('npx', ['playwright', 'test', '--config=e2e/playwright.config.mcp-apps.ts'], {+ E2E_MCP_APPS_PHASE: phase.name,+ E2E_MCP_APPS_POLICY: phase.policy,+ E2E_MCP_APP_RESOURCE_LIMIT: phase.E2E_MCP_APP_RESOURCE_LIMIT || '',+ E2E_MCP_APP_TOOL_CALL_LIMIT: phase.E2E_MCP_APP_TOOL_CALL_LIMIT || '',+ });+ }+} finally {+ await mongo?.stop();+}diff --git a/e2e/mcp-apps/server.test.mjs b/e2e/mcp-apps/server.test.mjsnew file mode 100644index 0000000000..d2be69a88a--- /dev/null+++ b/e2e/mcp-apps/server.test.mjs@@ -0,0 +1,152 @@+import assert from 'node:assert/strict';+import path from 'node:path';+import { once } from 'node:events';+import { spawn } from 'node:child_process';+import test from 'node:test';+import { fileURLToPath } from 'node:url';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const port = Number(process.env.E2E_MCP_APP_TEST_PORT || '18768');+const origin = `http://127.0.0.1:${port}`;++async function waitForReady(child) {+ let output = '';+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8');+ child.stdout.on('data', (chunk) => {+ output += chunk;+ });+ child.stderr.on('data', (chunk) => {+ output += chunk;+ });++ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => {+ clearInterval(poll);+ reject(new Error(`Timed out waiting for MCP App fixture:\n${output}`));+ }, 10_000);+ const poll = setInterval(() => {+ if (output.includes('MCP App fixture listening')) {+ clearInterval(poll);+ clearTimeout(timeout);+ resolve();+ }+ if (child.exitCode != null) {+ clearInterval(poll);+ clearTimeout(timeout);+ reject(new Error(`MCP App fixture exited before readiness:\n${output}`));+ }+ }, 20);+ });+}++test('official SDK fixture exposes App and legacy producers with follow-up operations', async () => {+ const child = spawn(process.execPath, ['e2e/setup/fake-mcp-app-server.mjs'], {+ cwd: root,+ env: { ...process.env, E2E_MCP_APP_PORT: String(port) },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ const client = new Client({ name: 'mcp-app-fixture-test', version: '1.0.0' });++ try {+ await waitForReady(child);+ await client.connect(new StreamableHTTPClientTransport(new URL(`${origin}/mcp`)));++ const tools = await client.listTools();+ const showApp = tools.tools.find((tool) => tool.name === 'show_app');+ const showLinkApp = tools.tools.find((tool) => tool.name === 'show_link_app');+ const showLegacy = tools.tools.find((tool) => tool.name === 'show_legacy');+ const legacyAction = tools.tools.find((tool) => tool.name === 'legacy_action');+ const followUp = tools.tools.find((tool) => tool.name === 'follow_up');+ assert.equal(showApp?._meta?.ui?.resourceUri, 'ui://e2e/app.html');+ assert.equal(showLinkApp?._meta?.ui?.resourceUri, 'ui://e2e/link-app.html');+ assert.ok(showLegacy);+ assert.ok(legacyAction);+ assert.deepEqual(followUp?._meta?.ui?.visibility, ['app']);++ const result = await client.callTool({ name: 'show_app', arguments: { label: 'server-test' } });+ assert.deepEqual(result.structuredContent, { label: 'server-test', stage: 'initial' });+ const embedded = result.content.find((item) => item.type === 'resource');+ assert.equal(embedded?.resource.mimeType, 'text/html;profile=mcp-app');+ assert.match(embedded?.resource.text ?? '', /tool-result-embedded-document/);+ assert.doesNotMatch(embedded?.resource.text ?? '', /resources-read-document/);++ const linkResult = await client.callTool({+ name: 'show_link_app',+ arguments: { label: 'server-test' },+ });+ const linkResource = linkResult.content.find((item) => item.type === 'resource');+ assert.equal(linkResource?.resource.uri, 'ui://e2e/link-app.html');+ assert.deepEqual(linkResource?.resource._meta?.ui?.csp, {+ resourceDomains: [`http://localhost:${port}`],+ });++ const appDocument = await client.readResource({ uri: 'ui://e2e/app.html' });+ assert.match(appDocument.contents[0]?.text ?? '', /resources-read-document/);+ assert.match(+ appDocument.contents[0]?.text ?? '',+ /<meta name="mcp-app-sdk-version" content="1\.7\.5" \/>/,+ );+ assert.match(appDocument.contents[0]?.text ?? '', /name: 'LibreChat E2E App'/);+ const linkDocument = await client.readResource({ uri: 'ui://e2e/link-app.html' });+ assert.match(linkDocument.contents[0]?.text ?? '', /resources-read-document/);+ assert.deepEqual(linkDocument.contents[0]?._meta?.ui?.csp, {+ resourceDomains: [`http://localhost:${port}`],+ });++ const legacyResult = await client.callTool({+ name: 'show_legacy',+ arguments: { label: 'server-test' },+ });+ const legacy = legacyResult.content.find((item) => item.type === 'resource');+ assert.equal(legacy?.resource.uri, 'ui://e2e/legacy.html');+ assert.equal(legacy?.resource.mimeType, 'text/html');+ assert.match(legacy?.resource.text ?? '', /data-testid="legacy-action"/);++ const legacyActionResult = await client.callTool({+ name: 'legacy_action',+ arguments: { label: 'server-test' },+ });+ assert.equal(legacyActionResult.content[0]?.text, 'legacy-action:server-test');++ const listed = await client.listResources();+ assert.deepEqual(listed.resources.map((resource) => resource.uri).sort(), [+ 'ui://e2e/app.html',+ 'ui://e2e/details/current',+ 'ui://e2e/link-app.html',+ ]);+ const detail = await client.readResource({ uri: 'ui://e2e/details/current' });+ assert.equal(detail.contents[0]?.text, 'fixture-detail:current');+ const templates = await client.listResourceTemplates();+ assert.equal(templates.resourceTemplates[0]?.uriTemplate, 'ui://e2e/details/{id}');++ const followUpResult = await client.callTool({+ name: 'follow_up',+ arguments: { label: 'server-test' },+ });+ assert.deepEqual(followUpResult.structuredContent, { followUp: 'server-test' });++ const debug = await fetch(`${origin}/__debug/events`).then((response) => response.json());+ assert.deepEqual(+ debug.events.map((event) => event.method),+ [+ 'tools/call:show_app',+ 'tools/call:show_link_app',+ 'resources/read:show_app',+ 'resources/read:show_link_app',+ 'tools/call:show_legacy',+ 'tools/call:legacy_action',+ 'resources/read:details',+ 'tools/call:follow_up',+ ],+ );+ } finally {+ await client.close().catch(() => undefined);+ child.kill('SIGTERM');+ if (child.exitCode == null) {+ await once(child, 'exit');+ }+ }+});diff --git a/e2e/playwright.config.mcp-apps.ts b/e2e/playwright.config.mcp-apps.tsnew file mode 100644index 0000000000..f8a30cc8d7--- /dev/null+++ b/e2e/playwright.config.mcp-apps.ts@@ -0,0 +1,23 @@+import { defineConfig } from '@playwright/test';+import mockConfig from './playwright.config.mock';++if (process.env.E2E_MCP_APPS !== 'true') {+ throw new Error('The MCP Apps browser fixture requires E2E_MCP_APPS=true');+}++const phase = process.env.E2E_MCP_APPS_PHASE ?? 'standalone';+if (!['standalone', 'true', 'false', 'omitted', 'quota'].includes(phase)) {+ throw new Error(`Unsupported E2E_MCP_APPS_PHASE: ${phase}`);+}++export default defineConfig({+ ...mockConfig,+ globalSetup: phase === 'standalone' || phase === 'true' ? mockConfig.globalSetup : undefined,+ globalTeardown:+ phase === 'standalone' || phase === 'quota' ? mockConfig.globalTeardown : undefined,+ testMatch: /mcp-apps\.spec\.ts/,+ outputDir: `specs/.test-results/mcp-apps-${phase}`,+ fullyParallel: false,+ workers: 1,+ retries: 0,+});diff --git a/e2e/playwright.config.mock.ts b/e2e/playwright.config.mock.tsindex 82a72e816f..a90a5f720b 100644--- a/e2e/playwright.config.mock.ts+++ b/e2e/playwright.config.mock.ts@@ -16,12 +16,15 @@ const serverPath = path.resolve(const mcpHttpServerPath = path.resolve(rootPath, 'e2e/setup/fake-mcp-http-server.js');const mcpOAuthServerPath = path.resolve(rootPath, 'e2e/setup/fake-mcp-oauth-server.js');const dynamicMcpServerPath = path.resolve(rootPath, 'e2e/setup/fake-mcp-dynamic-network-server.js');+const mcpAppServerPath = path.resolve(rootPath, 'e2e/setup/fake-mcp-app-server.mjs');/** Must match the `e2e-http` server URL in e2e/config/librechat.e2e.yaml. */const MCP_HTTP_PORT = process.env.E2E_MCP_HTTP_PORT || '8765';/** Must match the protected OAuth MCP fixture in e2e/config/librechat.e2e.yaml. */const MCP_OAUTH_PORT = process.env.E2E_MCP_OAUTH_PORT || '8767';/** Must match the dynamic Streamable HTTP and SSE URLs in the e2e config template. */const MCP_DYNAMIC_PORT = process.env.E2E_MCP_DYNAMIC_PORT || '8766';+/** Used only by the dedicated MCP Apps browser profile. */+const MCP_APP_PORT = process.env.E2E_MCP_APP_PORT || '8768';const MCP_STATE_PATH =process.env.E2E_MCP_STATE_PATH ||path.resolve(rootPath, 'e2e/specs/.test-results/mcp-tool-state.json');@@ -104,8 +107,37 @@ const configPath = path.resolve(rootPath, 'e2e/.generated/librechat.e2e.yaml');const reportPath = path.resolve(rootPath, 'e2e/playwright-report');const deploymentSkillsPath = path.resolve(rootPath, 'e2e/fixtures/deployment-skills');const enableDynamicMcp = process.env.E2E_MCP_LIST_CHANGED === 'true';+const enableMcpApps = process.env.E2E_MCP_APPS === 'true';+const mcpAppsPolicy = process.env.E2E_MCP_APPS_POLICY;+if (mcpAppsPolicy && !['true', 'false', 'omitted'].includes(mcpAppsPolicy)) {+ throw new Error(`E2E_MCP_APPS_POLICY must be true, false, or omitted; got ${mcpAppsPolicy}`);+}++function positiveIntegerEnv(name: string): number | undefined {+ const raw = process.env[name];+ if (!raw) {+ return undefined;+ }+ const value = Number(raw);+ if (!Number.isInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive integer; got ${raw}`);+ }+ return value;+}++const mcpAppResourceLimit = positiveIntegerEnv('E2E_MCP_APP_RESOURCE_LIMIT');+const mcpAppToolCallLimit = positiveIntegerEnv('E2E_MCP_APP_TOOL_CALL_LIMIT');+if ((mcpAppResourceLimit == null) !== (mcpAppToolCallLimit == null)) {+ throw new Error('MCP App resource and tool-call fixture limits must be supplied together');+}const baseURL = getE2EBaseURL();+const baseUrlObject = new URL(baseURL);+const mcpSandboxHost = baseUrlObject.hostname === 'localhost' ? '127.0.0.1' : 'localhost';+const defaultMcpSandboxUrl = new URL('/api/mcp/sandbox', baseUrlObject);+defaultMcpSandboxUrl.hostname = mcpSandboxHost;+const mcpSandboxUrl = process.env.E2E_MCP_SANDBOX_URL ?? defaultMcpSandboxUrl.href;+process.env.E2E_MCP_SANDBOX_URL = mcpSandboxUrl;const chromiumChannel = process.env.E2E_CHROMIUM_CHANNEL || undefined;/** WebAuthn rejects an IP address as the relying party, so passkey ceremonies reach@@ -167,6 +199,13 @@ const baseEnv = {}: {}),...(enableDynamicMcp ? { E2E_MCP_LIST_CHANGED: 'true', E2E_MCP_STATE_PATH: MCP_STATE_PATH } : {}),+ ...(enableMcpApps+ ? {+ E2E_MCP_APPS: 'true',+ MCP_SANDBOX_FRAME_ANCESTORS:+ process.env.MCP_SANDBOX_FRAME_ANCESTORS ?? 'http://127.0.0.1:3080',+ }+ : {}),/** The Assistants runtime uses the OpenAI SDK directly, outside the agents run hook. */ASSISTANTS_API_KEY: 'e2e-mock-assistants-key',ASSISTANTS_BASE_URL: `http://127.0.0.1:${ASSISTANTS_PORT}/v1`,@@ -232,6 +271,33 @@ function writeRuntimeMockConfig() {].join('\n'),}: { allowedDomain: '', stdioEnv: '', networkServers: '' };+ const mcpAppsConfig = enableMcpApps+ ? {+ setting:+ mcpAppsPolicy === 'omitted'+ ? ''+ : `apps: ${mcpAppsPolicy === 'false' ? 'false' : 'true'}`,+ sandbox: ['mcpAppSandbox:', ` url: ${JSON.stringify(mcpSandboxUrl)}`].join('\n'),+ allowedDomain: `- http://127.0.0.1:${MCP_APP_PORT}`,+ server: [+ 'e2e-app:',+ ' type: streamable-http',+ ` url: http://127.0.0.1:${MCP_APP_PORT}/mcp`,+ ' title: E2E MCP App',+ ' description: Official-SDK MCP App fixture for browser integration tests.',+ ' timeout: 30000',+ ].join('\n '),+ }+ : { setting: '', sandbox: '', allowedDomain: '', server: '' };+ const mcpAppsRateLimits =+ mcpAppResourceLimit != null && mcpAppToolCallLimit != null+ ? [+ 'rateLimits:',+ ' mcpApps:',+ ` resourcesPerMinute: ${mcpAppResourceLimit}`,+ ` toolCallsPerMinute: ${mcpAppToolCallLimit}`,+ ].join('\n')+ : '';const recordProviderBlock = modelFixtureRecording? [`- name: 'Replay Record Provider'`,@@ -255,7 +321,12 @@ function writeRuntimeMockConfig() {).replace('# __E2E_DYNAMIC_MCP_ALLOWED_DOMAIN__', dynamicMcpConfig.allowedDomain).replace('# __E2E_DYNAMIC_MCP_STDIO_ENV__', dynamicMcpConfig.stdioEnv)- .replace('# __E2E_DYNAMIC_MCP_NETWORK_SERVERS__', dynamicMcpConfig.networkServers);+ .replace('# __E2E_DYNAMIC_MCP_NETWORK_SERVERS__', dynamicMcpConfig.networkServers)+ .replace('# __E2E_MCP_APP_SANDBOX__', mcpAppsConfig.sandbox)+ .replace('# __E2E_MCP_APPS_SETTING__', mcpAppsConfig.setting)+ .replace('# __E2E_MCP_APPS_ALLOWED_DOMAIN__', mcpAppsConfig.allowedDomain)+ .replace('# __E2E_MCP_APPS_SERVER__', mcpAppsConfig.server)+ .replace('# __E2E_MCP_APP_RATE_LIMITS__', mcpAppsRateLimits);const codeBridgeURL = process.env.E2E_CODE_BRIDGE_URL;const codeBridgePairing = process.env.E2E_CODE_BRIDGE_ADMIN_TOKEN? [@@ -423,6 +494,19 @@ export default defineConfig({},]: []),+ ...(enableMcpApps+ ? [+ {+ command: `node ${mcpAppServerPath}`,+ cwd: rootPath,+ env: { ...process.env, E2E_MCP_APP_PORT: MCP_APP_PORT },+ url: `http://127.0.0.1:${MCP_APP_PORT}/`,+ stdout: 'pipe' as const,+ timeout: 60_000,+ reuseExistingServer: false,+ },+ ]+ : []),{// Serves the activity-label model call (the custom endpoints' baseURL).command: `node ${labelServerPath}`,diff --git a/e2e/setup/fake-mcp-app-server.mjs b/e2e/setup/fake-mcp-app-server.mjsnew file mode 100644index 0000000000..6c644ef102--- /dev/null+++ b/e2e/setup/fake-mcp-app-server.mjs@@ -0,0 +1,418 @@+#!/usr/bin/env node++import fs from 'node:fs';+import http from 'node:http';+import path from 'node:path';+import { createRequire } from 'node:module';+import { randomUUID } from 'node:crypto';+import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';+import {+ RESOURCE_MIME_TYPE,+ registerAppResource,+ registerAppTool,+} from '@modelcontextprotocol/ext-apps/server';+import { z } from 'zod/v4';++const require = createRequire(import.meta.url);+const HOST = '127.0.0.1';+const PORT = Number(process.env.E2E_MCP_APP_PORT || '8768');+const ORIGIN = `http://${HOST}:${PORT}`;+const LINK_ORIGIN = `http://localhost:${PORT}`;+const APP_URI = 'ui://e2e/app.html';+const LINK_APP_URI = 'ui://e2e/link-app.html';+const LEGACY_URI = 'ui://e2e/legacy.html';+const LEGACY_MIMELESS_URI = 'ui://e2e/legacy-mimeless.html';+const DETAIL_URI = 'ui://e2e/details/current';+const SDK_PATH = require.resolve('@modelcontextprotocol/ext-apps/app-with-deps');+const SDK_SOURCE = fs.readFileSync(SDK_PATH, 'utf8');+const SDK_PACKAGE = JSON.parse(+ fs.readFileSync(path.resolve(path.dirname(SDK_PATH), '../../package.json'), 'utf8'),+);+const appConstructor = SDK_SOURCE.match(/\b([A-Za-z_$][\w$]*) as App\b/)?.[1];+if (!appConstructor) {+ throw new Error('Could not resolve App constructor from the installed ext-apps bundle');+}+const inlineSdkSource = SDK_SOURCE.replace(/export\{[^}]+\};?\s*$/, '').replace(+ /<\/script/gi,+ '<\\/script',+);++const events = [];++function record(method, params = {}) {+ events.push({ method, params });+}++const embeddedToolResultHtml = `<!doctype html>+<html lang="en">+ <head><meta charset="utf-8" /><title>Tool result document</title></head>+ <body><p data-testid="tool-result-document">tool-result-embedded-document</p></body>+</html>`;++const appHtml = `<!doctype html>+<html lang="en">+ <template data-testid="inert-head"><head><title>inert template head</title></head></template>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="mcp-app-sdk-version" content="${SDK_PACKAGE.version}" />+ <title>LibreChat MCP App fixture</title>+ <style>+ body { font: 14px system-ui, sans-serif; margin: 12px; }+ button { margin: 4px; }+ output { display: block; white-space: pre-wrap; }+ </style>+ <body>+ <main data-testid="mcp-app-fixture">+ <p data-testid="document-source">resources-read-document</p>+ <p data-testid="status">connecting</p>+ <p data-testid="input"></p>+ <p data-testid="result"></p>+ <p data-testid="result-content"></p>+ <p data-testid="events"></p>+ <p data-testid="capabilities"></p>+ <button data-testid="call-tool" type="button">Call follow-up tool</button>+ <button data-testid="read-resource" type="button">Read resource</button>+ <button data-testid="list-resources" type="button">List resources</button>+ <button data-testid="send-message" type="button">Send message</button>+ <button data-testid="open-link" type="button">Open permitted link</button>+ <output data-testid="operation"></output>+ </main>+ <script type="module">+ ${inlineSdkSource}++ const byTestId = (id) => document.querySelector('[data-testid="' + id + '"]');+ const write = (id, value) => {+ byTestId(id).textContent = typeof value === 'string' ? value : JSON.stringify(value);+ };+ const run = async (operation) => {+ try {+ write('operation', await operation());+ } catch (error) {+ write('operation', 'error:' + (error instanceof Error ? error.message : String(error)));+ }+ };+ const lifecycleEvents = [];+ const recordLifecycle = (event) => {+ lifecycleEvents.push(event);+ write('events', lifecycleEvents.join(','));+ };++ const app = new ${appConstructor}({ name: 'LibreChat E2E App', version: '1.0.0' }, {}, {+ autoResize: false,+ });+ app.ontoolinput = ({ arguments: args }) => {+ write('input', args);+ recordLifecycle('input');+ };+ app.ontoolresult = (result) => {+ write('result', result.structuredContent ?? result.content);+ write('result-content', result.content);+ recordLifecycle('result');+ };+ app.onteardown = async () => {+ document.documentElement.dataset.tornDown = 'true';+ return {};+ };++ await app.connect();+ const capabilities = app.getHostCapabilities() ?? {};+ write('capabilities', Object.keys(capabilities).sort());+ write('status', 'connected');+ await app.sendSizeChanged({ height: 260, width: 640 });++ byTestId('call-tool').disabled = !capabilities.serverTools;+ byTestId('read-resource').disabled = !capabilities.serverResources;+ byTestId('list-resources').disabled = !capabilities.serverResources;+ byTestId('send-message').disabled = !capabilities.message;+ byTestId('open-link').disabled = !capabilities.openLinks;++ byTestId('call-tool').addEventListener('click', () => run(async () => {+ const result = await app.callServerTool({+ name: 'follow_up',+ arguments: { label: 'from-view' },+ });+ return result.structuredContent;+ }));+ byTestId('read-resource').addEventListener('click', () => run(async () => {+ const result = await app.readServerResource({ uri: '${DETAIL_URI}' });+ return result.contents[0]?.text;+ }));+ byTestId('list-resources').addEventListener('click', () => run(async () => {+ const result = await app.listServerResources();+ return { uris: result.resources.map((resource) => resource.uri).sort() };+ }));+ byTestId('send-message').addEventListener('click', () => run(async () => {+ await app.sendMessage({+ role: 'user',+ content: [{ type: 'text', text: 'E2E_MCP_APP_MESSAGE:from-view' }],+ });+ return 'message-sent';+ }));+ byTestId('open-link').addEventListener('click', () => run(async () => {+ return app.openLink({ url: '${LINK_ORIGIN}/opened' });+ }));+ </script>+ </body>+</html>`;++const appMeta = {+ ui: { permissions: { camera: {}, microphone: {}, geolocation: {}, clipboardWrite: {} } },+};+const linkAppMeta = { ui: { csp: { resourceDomains: [LINK_ORIGIN] } } };++const legacyHtml = `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>LibreChat legacy MCP-UI fixture</title>+ <style>+ body { box-sizing: border-box; font: 14px system-ui, sans-serif; margin: 0; padding: 12px; }+ #expanded { height: 220px; }+ </style>+ </head>+ <body>+ <p data-testid="legacy-status">legacy-ready</p>+ <button data-testid="legacy-action" type="button">Run legacy action</button>+ <div data-testid="legacy-expanded" id="expanded" hidden>legacy-expanded</div>+ <script>+ const sendSize = (height) => window.parent.postMessage({+ type: 'ui-size-change',+ payload: { width: 420, height },+ }, '*');+ setTimeout(() => sendSize(120), 50);+ document.querySelector('[data-testid="legacy-action"]').addEventListener('click', () => {+ document.querySelector('#expanded').hidden = false;+ sendSize(360);+ window.parent.postMessage({+ type: 'tool',+ messageId: 'legacy-action-1',+ payload: {+ toolName: 'legacy_action',+ params: { label: 'legacy-view', proof: 'E2E_LEGACY_ACTION' },+ },+ }, '*');+ });+ </script>+ </body>+</html>`;++const legacyMimelessHtml = `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>LibreChat MIME-less legacy MCP-UI fixture</title>+ <style>body { box-sizing: border-box; font: 14px system-ui, sans-serif; margin: 0; padding: 12px; }</style>+ </head>+ <body>+ <p data-testid="legacy-mimeless-status">legacy-mimeless-ready</p>+ <script>+ setTimeout(() => window.parent.postMessage({+ type: 'ui-size-change',+ payload: { width: 420, height: 140 },+ }, '*'), 50);+ </script>+ </body>+</html>`;++function registerFixtureApp(server, { toolName, uri, meta, resultText }) {+ registerAppTool(+ server,+ toolName,+ {+ description: 'Shows the deterministic LibreChat MCP App integration fixture.',+ inputSchema: { label: z.string() },+ _meta: { ui: { resourceUri: uri, visibility: ['model', 'app'] } },+ },+ async ({ label }) => {+ record(`tools/call:${toolName}`, { label });+ return {+ content: [+ { type: 'text', text: `${resultText}: ${label}` },+ {+ type: 'resource',+ resource: {+ uri,+ mimeType: RESOURCE_MIME_TYPE,+ text: embeddedToolResultHtml,+ _meta: meta,+ },+ },+ ],+ structuredContent: { label, stage: 'initial' },+ };+ },+ );++ registerAppResource(server, `LibreChat E2E App (${toolName})`, uri, { _meta: meta }, async () => {+ record(`resources/read:${toolName}`);+ return {+ contents: [{ uri, mimeType: RESOURCE_MIME_TYPE, text: appHtml, _meta: meta }],+ };+ });+}++function createMcpServer() {+ const server = new McpServer({ name: 'e2e-app', version: '1.0.0' });++ registerFixtureApp(server, {+ toolName: 'show_app',+ uri: APP_URI,+ meta: appMeta,+ resultText: 'E2E MCP App result',+ });+ registerFixtureApp(server, {+ toolName: 'show_link_app',+ uri: LINK_APP_URI,+ meta: linkAppMeta,+ resultText: 'E2E MCP link App result',+ });++ server.registerTool(+ 'show_legacy',+ {+ description: 'Shows the deterministic legacy inline HTML compatibility fixture.',+ inputSchema: { label: z.string() },+ },+ async ({ label }) => {+ record('tools/call:show_legacy', { label });+ return {+ content: [+ { type: 'text', text: `E2E legacy MCP-UI result: ${label}` },+ {+ type: 'resource',+ resource: {+ uri: LEGACY_URI,+ mimeType: 'text/html',+ text: legacyHtml,+ },+ },+ ],+ };+ },+ );++ server.registerTool(+ 'show_legacy_mimeless',+ {+ description: 'Shows a legacy inline HTML resource whose optional MIME is omitted.',+ inputSchema: { label: z.string() },+ },+ async ({ label }) => {+ record('tools/call:show_legacy_mimeless', { label });+ return {+ content: [+ { type: 'text', text: `E2E MIME-less legacy MCP-UI result: ${label}` },+ {+ type: 'resource',+ resource: {+ uri: LEGACY_MIMELESS_URI,+ text: legacyMimelessHtml,+ },+ },+ ],+ };+ },+ );++ server.registerTool(+ 'legacy_action',+ {+ description: 'Records a benign action from the legacy inline HTML fixture.',+ inputSchema: { label: z.string() },+ },+ async ({ label }) => {+ record('tools/call:legacy_action', { label });+ return {+ content: [{ type: 'text', text: `legacy-action:${label}` }],+ };+ },+ );++ registerAppTool(+ server,+ 'follow_up',+ {+ description: 'Returns a deterministic result to the fixture View.',+ inputSchema: { label: z.string() },+ _meta: { ui: { visibility: ['app'] } },+ },+ async ({ label }) => {+ record('tools/call:follow_up', { label });+ return {+ content: [{ type: 'text', text: `follow-up:${label}` }],+ structuredContent: { followUp: label },+ };+ },+ );++ server.registerResource('Fixture details', DETAIL_URI, { mimeType: 'text/plain' }, async () => {+ record('resources/read:details');+ return {+ contents: [{ uri: DETAIL_URI, mimeType: 'text/plain', text: 'fixture-detail:current' }],+ };+ });++ server.registerResource(+ 'Fixture detail template',+ new ResourceTemplate('ui://e2e/details/{id}', { list: undefined }),+ { mimeType: 'text/plain' },+ async (uri, { id }) => ({+ contents: [{ uri: uri.href, mimeType: 'text/plain', text: `fixture-detail:${id}` }],+ }),+ );++ return server;+}++const sessions = new Map();++const httpServer = http.createServer(async (req, res) => {+ const url = new URL(req.url ?? '/', ORIGIN);++ if (req.method === 'GET' && url.pathname === '/') {+ res.writeHead(200, { 'Content-Type': 'text/plain' });+ res.end('ok');+ return;+ }+ if (req.method === 'GET' && url.pathname === '/opened') {+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });+ res.end('<!doctype html><title>Permitted MCP App link</title><p>policy-permitted-open</p>');+ return;+ }+ if (req.method === 'GET' && url.pathname === '/__debug/events') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ events }));+ return;+ }+ if (req.method === 'POST' && url.pathname === '/__debug/reset') {+ events.length = 0;+ res.writeHead(204);+ res.end();+ return;+ }+ if (url.pathname !== '/mcp') {+ res.writeHead(404);+ res.end();+ return;+ }++ const sessionId = req.headers['mcp-session-id'];+ let transport = typeof sessionId === 'string' ? sessions.get(sessionId) : undefined;+ if (!transport) {+ transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });+ await createMcpServer().connect(transport);+ }++ await transport.handleRequest(req, res);+ if (transport.sessionId && !sessions.has(transport.sessionId)) {+ sessions.set(transport.sessionId, transport);+ transport.onclose = () => sessions.delete(transport.sessionId);+ }+});++httpServer.listen(PORT, HOST, () => {+ console.log(`[e2e] MCP App fixture listening on ${ORIGIN}/mcp`);+});diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 9ac45cc30f..2cfc0408c2 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -49,6 +49,12 @@ const EMPTY_SLOW_REPLY_MARKER = 'E2E_EMPTY_SLOW_REPLY:';const EMPTY_REPLY_MARKER = 'E2E_EMPTY_REPLY:';const SLOW_COUNTED_REPLY_MARKER = 'E2E_SLOW_COUNTED_REPLY:';const STEER_TOOL_REPLY_MARKER = 'E2E_STEER_TOOL_REPLY:';+const MCP_APP_MARKER = 'E2E_MCP_APP:';+const MCP_APP_PHASE_MARKER = 'E2E_MCP_APP_PHASE:';+const MCP_LINK_APP_MARKER = 'E2E_MCP_LINK_APP:';+const MCP_LEGACY_MARKER = 'E2E_MCP_LEGACY:';+const MCP_LEGACY_MIMELESS_MARKER = 'E2E_MCP_LEGACY_MIMELESS:';+const MCP_LEGACY_ACTION_MARKER = 'E2E_LEGACY_ACTION';const STEER_SPLIT_REPLY_MARKER = 'E2E_STEER_SPLIT_REPLY:';const STEER_LATE_REPLY_MARKER = 'E2E_STEER_LATE_REPLY:';const ACTIVITY_REPLY_MARKER = 'E2E_ACTIVITY_REPLY:';@@ -106,9 +112,9 @@ const STEER_LATE_FINAL_TEXT = 'E2E steer late reply done';const SLOW_REPLY_CONTINUATION_TEXT = 'E2E slow reply continued';const ACTIVITY_FINAL_TEXT = 'E2E activity reply done';const ACTIVITY_PHASE_FINAL_TEXT = 'E2E activity phase reply done';-const ACTIVITY_FAILED_FINAL_TEXT = 'E2E activity failed reply done';-const SLOW_ECHO_TOOL_NAME_PREFIX = 'slow_echo';+const MCP_APP_PHASE_FINAL_TEXT = 'E2E MCP App phase complete';const STEER_TOOL_NAME_PREFIX = 'remember_fact';+const MCP_APP_TOOL_NAME_PREFIX = 'show_app';const ASK_USER_QUESTION_TOOL_NAME = 'ask_user_question';const SLOW_CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_SLOW_CHUNK_DELAY_MS) || 35;/** The highlight cancellation scenario has to open the code card and stop the@@ -1289,6 +1295,155 @@ function steerToolReplyResponses(label, toolNames) {};}+function mcpAppResponses(label, toolNames) {+ const toolName = Array.from(toolNames).find((name) => name.startsWith(MCP_APP_TOOL_NAME_PREFIX));+ if (!toolName) {+ return { responses: ['E2E MCP App unavailable: show_app was not advertised.'] };+ }+ return {+ responses: ['', `E2E MCP App complete: ${label}`],+ toolCalls: [+ {+ id: `call_e2e_mcp_app_${label}`,+ name: toolName,+ args: { label },+ type: 'tool_call',+ },+ ],+ };+}++/** Two sequential App calls so Provider F creates two labeled activities and+ * one enclosing activity phase through the normal graph lifecycle. */+function mcpAppPhaseResponses(label, toolNames) {+ const toolName = Array.from(toolNames).find((name) => name.startsWith(MCP_APP_TOOL_NAME_PREFIX));+ if (!toolName) {+ return { responses: ['E2E MCP App phase unavailable: show_app was not advertised.'] };+ }+ let invocation = 0;+ return {+ responses: [''],+ resolveInvocation: async () => {+ invocation += 1;+ if (invocation === 1) {+ return {+ response: '',+ toolCalls: [+ {+ id: `call_e2e_mcp_app_phase_alpha_${label}`,+ name: toolName,+ args: { label: `phase alpha ${label}` },+ type: 'tool_call',+ },+ ],+ };+ }+ if (invocation === 2) {+ return {+ response: '',+ toolCalls: [+ {+ id: `call_e2e_mcp_app_phase_beta_${label}`,+ name: toolName,+ args: { label: `phase beta ${label}` },+ type: 'tool_call',+ },+ ],+ };+ }+ return { response: `${MCP_APP_PHASE_FINAL_TEXT}: ${label}` };+ },+ };+}++function mcpLinkAppResponses(label, toolNames) {+ const toolName = Array.from(toolNames).find((name) => name.startsWith('show_link_app'));+ if (!toolName) {+ return { responses: ['E2E MCP link App unavailable: show_link_app was not advertised.'] };+ }+ return {+ responses: ['', `E2E MCP link App complete: ${label}`],+ toolCalls: [+ {+ id: `call_e2e_mcp_link_app_${label}`,+ name: toolName,+ args: { label },+ type: 'tool_call',+ },+ ],+ };+}++function legacyResourceResponses(+ label,+ toolNames,+ { toolPrefix, callIdPrefix, completionPrefix, unavailable },+) {+ const candidates = Array.from(toolNames);+ const toolName =+ candidates.find((name) => name === toolPrefix) ??+ candidates.find(+ (name) =>+ name.startsWith(toolPrefix) &&+ (toolPrefix !== 'show_legacy' || !name.startsWith('show_legacy_mimeless')),+ );+ if (!toolName) {+ return { responses: [unavailable] };+ }+ return {+ responses: [''],+ toolCalls: [+ {+ id: `${callIdPrefix}_${label}`,+ name: toolName,+ args: { label },+ type: 'tool_call',+ },+ ],+ resolveOnStream: (streamMessages) => {+ const toolResult = findLastToolMessageText(streamMessages, 'UI Resource ID:');+ const resourceId = toolResult.match(/UI Resource ID: ([a-f0-9]+)/)?.[1];+ return resourceId ? { responses: [`${completionPrefix}: \\ui{${resourceId}}`] } : null;+ },+ };+}++function mcpLegacyResponses(label, toolNames) {+ return legacyResourceResponses(label, toolNames, {+ toolPrefix: 'show_legacy',+ callIdPrefix: 'call_e2e_mcp_legacy',+ completionPrefix: 'Legacy MCP-UI',+ unavailable: 'E2E legacy MCP-UI unavailable: show_legacy was not advertised.',+ });+}++function mcpLegacyMimelessResponses(label, toolNames) {+ return legacyResourceResponses(label, toolNames, {+ toolPrefix: 'show_legacy_mimeless',+ callIdPrefix: 'call_e2e_mcp_legacy_mimeless',+ completionPrefix: 'MIME-less Legacy MCP-UI',+ unavailable: 'E2E MIME-less legacy MCP-UI unavailable: tool was not advertised.',+ });+}++function mcpLegacyActionResponses(toolNames) {+ const toolName = Array.from(toolNames).find((name) => name.startsWith('legacy_action'));+ if (!toolName) {+ return { responses: ['E2E legacy action unavailable: legacy_action was not advertised.'] };+ }+ return {+ responses: ['', 'E2E legacy action complete'],+ toolCalls: [+ {+ id: 'call_e2e_mcp_legacy_action',+ name: toolName,+ args: { label: 'legacy-view' },+ type: 'tool_call',+ },+ ],+ };+}+/*** Model-visible injection proof: echoes every steer-injected user message the* model actually received (`additional_kwargs.source === 'steer'`, stamped by@@ -3109,6 +3264,35 @@ function resolveResponses({ graph, messages, text, toolNames }) {return steerToolReplyResponses(steerToolLabel, toolNames);}+ const mcpAppLabel = getMarkerValue(text, MCP_APP_MARKER);+ if (mcpAppLabel) {+ return mcpAppResponses(mcpAppLabel, toolNames);+ }++ const mcpAppPhaseLabel = getMarkerValue(text, MCP_APP_PHASE_MARKER);+ if (mcpAppPhaseLabel) {+ return mcpAppPhaseResponses(mcpAppPhaseLabel, toolNames);+ }++ const mcpLinkAppLabel = getMarkerValue(text, MCP_LINK_APP_MARKER);+ if (mcpLinkAppLabel) {+ return mcpLinkAppResponses(mcpLinkAppLabel, toolNames);+ }++ const mcpLegacyLabel = getMarkerValue(text, MCP_LEGACY_MARKER);+ if (mcpLegacyLabel) {+ return mcpLegacyResponses(mcpLegacyLabel, toolNames);+ }++ const mcpLegacyMimelessLabel = getMarkerValue(text, MCP_LEGACY_MIMELESS_MARKER);+ if (mcpLegacyMimelessLabel) {+ return mcpLegacyMimelessResponses(mcpLegacyMimelessLabel, toolNames);+ }++ if (text.includes(MCP_LEGACY_ACTION_MARKER)) {+ return mcpLegacyActionResponses(toolNames);+ }+const provisioningTool = provisioningToolResponses({ text, toolNames });if (provisioningTool) {return provisioningTool;diff --git a/e2e/specs/mock/mcp-apps.spec.ts b/e2e/specs/mock/mcp-apps.spec.tsnew file mode 100644index 0000000000..de4ecf0601--- /dev/null+++ b/e2e/specs/mock/mcp-apps.spec.ts@@ -0,0 +1,1024 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { expect, test } from '@playwright/test';+import { encodeEphemeralAgentId } from 'librechat-data-provider';+import type { FrameLocator, Page, Response, Route } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ getAccessToken,+ messagesView,+ requestJson,+ selectMockEndpoint,+ sendMessage,+ sendMessageAndWaitForCompletion,+} from './helpers';++const MCP_SERVER_TITLE = 'E2E MCP App';+const LEGACY_FRAME_TITLE = 'MCP HTML Resource (Embedded Content)';+const CHAT_ORIGIN = new URL(process.env.E2E_BASE_URL || 'http://127.0.0.1:3080').origin;+const MCP_APP_ORIGIN = `http://127.0.0.1:${process.env.E2E_MCP_APP_PORT || '8768'}`;+const MCP_APP_LINK_ORIGIN = `http://localhost:${process.env.E2E_MCP_APP_PORT || '8768'}`;+const LABEL_SERVER = `http://127.0.0.1:${process.env.E2E_LABEL_PORT || '8889'}`;+const MCP_APP_PHASE_ENDPOINT = { label: 'Mock Provider F', model: 'mock-model-f' };+const MCP_APP_PHASE_AGENT_ID = encodeEphemeralAgentId({+ endpoint: MCP_APP_PHASE_ENDPOINT.label,+ model: MCP_APP_PHASE_ENDPOINT.model,+ sender: MCP_APP_PHASE_ENDPOINT.label,+});+const MCP_APP_PHASE_PARENT_LABEL = 'Rendered two MCP Apps in one activity phase';+const APP_ROUTE_PATHS = new Set([+ '/api/mcp/app/validate',+ '/api/mcp/app-tool-call',+ '/api/mcp/resources/read',+ '/api/mcp/resources/list',+ '/api/mcp/resources/templates/list',+]);+const EXECUTABLE_FRAME_SELECTORS = [+ 'iframe[data-sandbox-url]',+ `iframe[title="${LEGACY_FRAME_TITLE}"]`,+];+const PHASE = process.env.E2E_MCP_APPS_PHASE ?? 'standalone';+const STATE_PATH =+ process.env.E2E_MCP_APPS_STATE_PATH ??+ path.resolve(process.cwd(), 'e2e/.generated/mcp-apps-state.json');++type DebugEvent = { method: string; params: Record<string, unknown> };+type MCPAppsPolicy = {+ enabled: boolean;+ legacyHtmlEnabled: boolean;+ sandboxUrl?: string;+ maxAdmissionRequestsPerMinute?: number;+};+type StoredToolCall = { id?: string; agentId?: string; stepId?: string };+type StoredContentPart = {+ type?: string;+ agentId?: string;+ tool_call?: StoredToolCall;+};+type UIResourceAttachment = {+ type?: string;+ toolCallId?: string;+ agentId?: string;+ stepId?: string;+ ui_resources?: Array<Record<string, unknown>>;+};+type StoredMessage = {+ [key: string]: unknown;+ attachments?: UIResourceAttachment[];+ content?: Array<StoredContentPart | null>;+ isCreatedByUser?: boolean;+};+type PersistedState = {+ conversationId: string;+ label: string;+ retryLabel: string;+ messageFingerprint: string;+ uiFingerprint: string;+};+type SharePayload = {+ shareId: string;+ messages?: Array<{ attachments?: Array<Record<string, unknown>> }>;+};++type RawResult = { json: unknown; status: number; text: string };++const randomLabel = () => `app-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;++function isRoute(response: Response, pathname: string) {+ return response.request().method() === 'POST' && new URL(response.url()).pathname === pathname;+}++async function getPolicy(page: Page, token: string): Promise<MCPAppsPolicy> {+ const config = await requestJson<{ mcpApps: MCPAppsPolicy }>(page, {+ path: '/api/config',+ token,+ });+ return config.mcpApps;+}++async function getMessages(page: Page, token: string, conversationId: string) {+ return requestJson<StoredMessage[]>(page, {+ path: `/api/messages/${encodeURIComponent(conversationId)}`,+ token,+ });+}++function uiResources(messages: StoredMessage[]) {+ return messages.flatMap((message) =>+ (message.attachments ?? [])+ .filter((attachment) => attachment.type === 'ui_resources')+ .flatMap((attachment) => attachment.ui_resources ?? []),+ );+}++function persistedServerBinding(messages: StoredMessage[]): string {+ const binding = uiResources(messages).find(+ (resource) => resource.mimeType === 'text/html;profile=mcp-app',+ )?.serverBinding;+ if (typeof binding !== 'string' || !binding) {+ throw new Error('Expected a persisted MCP App server binding');+ }+ return binding;+}++function canonicalize(value: unknown): unknown {+ if (Array.isArray(value)) {+ return value.map(canonicalize);+ }+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([key, item]) => [key, canonicalize(item)]),+ );+ }+ return value;+}++function fingerprintUI(messages: StoredMessage[]) {+ const resources = uiResources(messages).sort((left, right) =>+ String(left.uri).localeCompare(String(right.uri)),+ );+ return createHash('sha256')+ .update(JSON.stringify(canonicalize(resources)))+ .digest('hex');+}++function fingerprintMessages(messages: StoredMessage[]) {+ return createHash('sha256')+ .update(JSON.stringify(canonicalize(messages)))+ .digest('hex');+}++function writeState(state: PersistedState) {+ fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true });+ fs.writeFileSync(STATE_PATH, `${JSON.stringify(state, null, 2)}\n`);+}++function readState(): PersistedState {+ return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')) as PersistedState;+}++async function trackExecutableEffects(page: Page) {+ const appRequests: string[] = [];+ page.on('request', (request) => {+ const pathname = new URL(request.url()).pathname;+ if (+ pathname === '/api/mcp/sandbox' ||+ (request.method() === 'POST' && APP_ROUTE_PATHS.has(pathname))+ ) {+ appRequests.push(`${request.method()} ${pathname}`);+ }+ });+ await page.addInitScript(+ ({ selectors }) => {+ const state = { app: 0, legacy: 0 };+ Object.defineProperty(window, '__mcpExecutableFrames', { value: state });+ const inspect = (node: Node) => {+ if (!(node instanceof Element)) {+ return;+ }+ for (const [index, selector] of selectors.entries()) {+ const key = index === 0 ? 'app' : 'legacy';+ if (node.matches(selector)) {+ state[key] += 1;+ }+ state[key] += node.querySelectorAll(selector).length;+ }+ };+ new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ mutation.addedNodes.forEach(inspect);+ }+ }).observe(document, { childList: true, subtree: true });+ },+ { selectors: EXECUTABLE_FRAME_SELECTORS },+ );+ return appRequests;+}++async function executableFrameCounts(page: Page) {+ return page.evaluate(() => {+ return (window as typeof window & { __mcpExecutableFrames?: { app: number; legacy: number } })+ .__mcpExecutableFrames;+ });+}++async function rawAuthenticatedRequest(+ page: Page,+ token: string,+ path: string,+ body: Record<string, unknown>,+): Promise<RawResult> {+ return page.evaluate(+ async ({ accessToken, requestBody, urlPath }) => {+ const response = await fetch(urlPath, {+ method: 'POST',+ credentials: 'include',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(requestBody),+ });+ const text = await response.text();+ let json: unknown = null;+ try {+ json = text ? JSON.parse(text) : null;+ } catch {+ json = null;+ }+ return { json, status: response.status, text };+ },+ { accessToken: token, requestBody: body, urlPath: path },+ );+}++async function selectMcpAppServer(page: Page) {+ await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();+ const server = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });+ await expect(server).toBeVisible();+ await server.click();+ await expect(server).toHaveAttribute('aria-checked', 'true');+ await page.keyboard.press('Escape');+}++function appFrame(page: Page, toolName = 'show_app', occurrence = 0): FrameLocator {+ return page+ .locator(`iframe[title="MCP App: ${toolName}"]`)+ .nth(occurrence)+ .contentFrame()+ .locator('iframe')+ .contentFrame();+}++async function expectConnectedApp(+ page: Page,+ label: string,+ toolName = 'show_app',+ occurrence = 0,+) {+ const app = appFrame(page, toolName, occurrence);+ await expect(app.getByTestId('status')).toHaveText('connected', { timeout: 30_000 });+ await expect(app.getByTestId('document-source')).toHaveText('resources-read-document');+ await expect(app.getByTestId('input')).toContainText(`"label":"${label}"`);+ await expect(app.getByTestId('result')).toContainText(`"label":"${label}"`);+ await expect(app.getByTestId('result-content')).toContainText('tool-result-embedded-document');+ await expect(app.getByTestId('events')).toHaveText('input,result');++ const capabilities = app.getByTestId('capabilities');+ await expect(capabilities).toContainText('serverTools');+ await expect(capabilities).toContainText('serverResources');+ await expect(capabilities).toContainText('message');+ await expect(app.getByTestId('call-tool')).toBeEnabled();+ return app;+}++async function expectAppHeight(page: Page, occurrence: number) {+ const outerFrame = page.locator('iframe[title="MCP App: show_app"]').nth(occurrence);+ const container = outerFrame.locator('..');+ await expect(outerFrame).toHaveCSS('height', '260px');+ await expect(container).toHaveCSS('height', '260px');+}++async function expectAppFramesOutsidePanels(page: Page, count: number) {+ const outerFrames = page.locator('iframe[title="MCP App: show_app"]');+ await expect(outerFrames).toHaveCount(count);+ for (let index = 0; index < count; index += 1) {+ await expect(outerFrames.nth(index)).toBeVisible();+ }+ expect(+ await outerFrames.evaluateAll((frames) =>+ frames.every(+ (frame) =>+ frame.closest('[data-testid="activity-phase-panel"]') == null &&+ frame.closest('[data-testid="tool-call-group-panel"]') == null,+ ),+ ),+ ).toBe(true);+ await expect(+ page.locator('[data-testid="activity-phase-panel"] iframe[data-sandbox-url]'),+ ).toHaveCount(0);+ await expect(+ page.locator('[data-testid="tool-call-group-panel"] iframe[data-sandbox-url]'),+ ).toHaveCount(0);+}++async function clickAndExpectRoute(+ page: Page,+ app: FrameLocator,+ buttonTestId: string,+ pathname: string,+) {+ const [response] = await Promise.all([+ page.waitForResponse((candidate) => isRoute(candidate, pathname), { timeout: 30_000 }),+ app.getByTestId(buttonTestId).click(),+ ]);+ expect(response.ok(), `${pathname} should complete through LibreChat`).toBeTruthy();+ return response;+}++async function resetEvents(page: Page) {+ const response = await page.request.post(`${MCP_APP_ORIGIN}/__debug/reset`);+ expect(response.status()).toBe(204);+}++function mcpAppPhaseLabels(label: string) {+ return {+ first: `Rendered alpha MCP App ${label}`,+ second: `Rendered beta MCP App ${label}`,+ };+}++async function configureMcpAppPhaseLabels(page: Page, label: string) {+ const reset = await page.request.post(`${LABEL_SERVER}/__e2e/reset`);+ expect(reset.ok()).toBeTruthy();+ const labels = mcpAppPhaseLabels(label);+ const response = await page.request.post(`${LABEL_SERVER}/__e2e/behavior`, {+ data: {+ phaseLabel: MCP_APP_PHASE_PARENT_LABEL,+ labelsByPrompt: {+ [`phase alpha ${label}`]: labels.first,+ [`phase beta ${label}`]: labels.second,+ },+ },+ });+ expect(response.ok()).toBeTruthy();+ return labels;+}++async function readEvents(page: Page): Promise<DebugEvent[]> {+ const response = await page.request.get(`${MCP_APP_ORIGIN}/__debug/events`);+ expect(response.ok()).toBeTruthy();+ const body = (await response.json()) as { events: DebugEvent[] };+ return body.events;+}++async function createShare(page: Page, conversationId: string): Promise<SharePayload> {+ await page.getByRole('button', { name: 'Export/Share' }).click();+ await page.getByTestId('share-conversation-menu-item').click();+ const dialog = page.getByRole('dialog', { name: 'Share link to chat' });+ await expect(dialog).toBeVisible();++ const [response] = await Promise.all([+ page.waitForResponse(+ (candidate) =>+ candidate.request().method() === 'POST' &&+ new URL(candidate.url()).pathname === `/api/share/${conversationId}`,+ { timeout: 30_000 },+ ),+ dialog.getByRole('button', { name: 'Create a shared link' }).click(),+ ]);+ expect(response.ok()).toBeTruthy();+ return response.json() as Promise<SharePayload>;+}++test.describe('MCP Apps full integration', () => {+ test.skip(process.env.E2E_MCP_APPS !== 'true', 'requires the dedicated MCP Apps fixture profile');++ test('runs an official SDK View, reloads its snapshot, and omits UI from a public share', async ({+ page,+ }, testInfo) => {+ test.skip(!['standalone', 'true'].includes(PHASE));+ test.setTimeout(180_000);+ const label = randomLabel();+ const appRequests: string[] = [];+ page.on('request', (request) => {+ const pathname = new URL(request.url()).pathname;+ if (request.method() === 'POST' && APP_ROUTE_PATHS.has(pathname)) {+ appRequests.push(pathname);+ }+ });++ await resetEvents(page);+ await page.goto(NEW_CHAT_PATH, { timeout: 15_000 });+ const token = await getAccessToken(page);+ expect(await getPolicy(page, token)).toMatchObject({+ enabled: true,+ legacyHtmlEnabled: true,+ sandboxUrl: process.env.E2E_MCP_SANDBOX_URL,+ maxAdmissionRequestsPerMinute: 240,+ });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await selectMcpAppServer(page);++ const sandboxResponse = page.waitForResponse(+ (response) => new URL(response.url()).pathname === '/api/mcp/sandbox',+ { timeout: 60_000 },+ );+ const generation = await sendMessage(page, `E2E_MCP_APP:${label}`);+ expect(generation.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(`E2E MCP App complete: ${label}`)).toBeVisible({+ timeout: 60_000,+ });+ await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(1);+ const outerCsp = (await sandboxResponse).headers()['content-security-policy'];+ expect(outerCsp).toContain('frame-src blob:');+ expect(outerCsp?.split(/[;,\n]+/).map((directive) => directive.trim())).toContain(+ `frame-ancestors ${CHAT_ORIGIN}`,+ );++ const outerFrame = page.locator('iframe[title="MCP App: show_app"]').nth(0);+ const sandboxUrl = await outerFrame.getAttribute('data-sandbox-url');+ expect(sandboxUrl).toBeTruthy();+ expect(new URL(sandboxUrl!).origin).not.toBe(new URL(page.url()).origin);+ expect(new URL(sandboxUrl!).origin).toBe('http://localhost:3080');+ await expect(outerFrame).toHaveAttribute(+ 'sandbox',+ 'allow-scripts allow-same-origin allow-forms',+ );+ await expect(outerFrame).toHaveAttribute('allow', 'geolocation; clipboard-write');++ const innerFrame = page.frameLocator('iframe[title="MCP App: show_app"]').locator('iframe');+ await expect(innerFrame).toHaveAttribute('sandbox', 'allow-scripts allow-forms');+ await expect(innerFrame).toHaveAttribute('allow', 'geolocation; clipboard-write');++ const viewCsp = await appFrame(page)+ .locator('meta[http-equiv="Content-Security-Policy"]')+ .getAttribute('content');+ expect(viewCsp).toContain("default-src 'none'");+ expect(viewCsp).toContain("script-src 'self' 'unsafe-inline'");+ expect(viewCsp).toContain("style-src 'self' 'unsafe-inline'");+ expect(viewCsp).toContain("connect-src 'none'");+ expect(viewCsp).toContain("frame-src 'none'");+ expect(viewCsp).toContain("object-src 'none'");+ expect(viewCsp).not.toContain(MCP_APP_ORIGIN);++ const app = await expectConnectedApp(page, label);+ await clickAndExpectRoute(page, app, 'call-tool', '/api/mcp/app-tool-call');+ await expect(app.getByTestId('operation')).toContainText('"followUp":"from-view"');+ await page.screenshot({ path: testInfo.outputPath('settled-app.png'), fullPage: true });++ await clickAndExpectRoute(page, app, 'read-resource', '/api/mcp/resources/read');+ await expect(app.getByTestId('operation')).toHaveText('fixture-detail:current');++ await clickAndExpectRoute(page, app, 'list-resources', '/api/mcp/resources/list');+ await expect(app.getByTestId('operation')).toContainText('ui://e2e/app.html');+ await expect(app.getByTestId('operation')).toContainText('ui://e2e/details/current');+ await expect(app.getByTestId('operation')).toContainText('ui://e2e/link-app.html');++ const currentConversationId = new URL(page.url()).pathname.split('/').pop();+ expect(currentConversationId).toMatch(/^[0-9a-fA-F-]{36}$/);+ const serverBinding = persistedServerBinding(+ await getMessages(page, token, currentConversationId!),+ );+ const templates = await requestJson<{ resourceTemplates: Array<{ uriTemplate: string }> }>(+ page,+ {+ path: '/api/mcp/resources/templates/list',+ method: 'POST',+ token,+ body: { serverName: 'e2e-app', serverBinding },+ },+ );+ expect(templates.resourceTemplates).toEqual(+ expect.arrayContaining([expect.objectContaining({ uriTemplate: 'ui://e2e/details/{id}' })]),+ );++ const appMessage = 'E2E_MCP_APP_MESSAGE:from-view';+ const nextGeneration = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ /^\/api\/(agents|ask)\//.test(new URL(response.url()).pathname),+ { timeout: 30_000 },+ );+ await app.getByTestId('send-message').click();+ await expect(app.getByTestId('operation')).toHaveText('message-sent');+ expect((await nextGeneration).ok()).toBeTruthy();+ await expect(messagesView(page).getByText(appMessage, { exact: true })).toBeVisible({+ timeout: 30_000,+ });++ let events = await readEvents(page);+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ method: 'tools/call:show_app', params: { label } }),+ expect.objectContaining({+ method: 'tools/call:follow_up',+ params: { label: 'from-view' },+ }),+ expect.objectContaining({ method: 'resources/read:details' }),+ ]),+ );+ expect(events.filter((event) => event.method === 'resources/read:show_app')).toHaveLength(1);++ await expectAppHeight(page, 0);+ await outerFrame.evaluate((frame) => {+ frame.dataset.retrySibling = 'retained';+ });++ const retryLabel = `retry-${label}`;+ const retrySandboxRequests: string[] = [];+ page.on('request', (request) => {+ if (new URL(request.url()).pathname === '/api/mcp/sandbox') {+ retrySandboxRequests.push(request.url());+ }+ });+ let failNextSandbox = true;+ const failFirstSandboxRequest = async (route: Route) => {+ if (!failNextSandbox) {+ await route.continue();+ return;+ }+ failNextSandbox = false;+ await route.fulfill({+ status: 503,+ contentType: 'text/plain',+ body: 'temporary sandbox unavailable',+ });+ };+ await page.route('**/api/mcp/sandbox**', failFirstSandboxRequest);+ const failedSandboxResponse = page.waitForResponse(+ (response) =>+ new URL(response.url()).pathname === '/api/mcp/sandbox' && response.status() === 503,+ { timeout: 30_000 },+ );++ const retryGeneration = await sendMessage(page, `E2E_MCP_APP:${retryLabel}`);+ expect(retryGeneration.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(`E2E MCP App complete: ${retryLabel}`)).toBeVisible({+ timeout: 60_000,+ });+ expect((await failedSandboxResponse).status()).toBe(503);+ await expect(page.locator('iframe[title="MCP App: show_app"]')).toHaveCount(2);++ const retryOuterFrame = page.locator('iframe[title="MCP App: show_app"]').nth(1);+ await retryOuterFrame.evaluate((frame) => {+ frame.dataset.retryTarget = 'retained';+ });+ const retryContainer = retryOuterFrame.locator('..');+ const retryAlert = retryContainer.getByRole('alert');+ await expect(retryAlert).toContainText('Interactive view failed to load.', {+ timeout: 30_000,+ });+ expect(retrySandboxRequests).toHaveLength(1);+ const retryButton = retryAlert.getByRole('button', { name: 'Retry', exact: true });+ await expect(retryButton).toBeVisible();++ const conversationUrl = page.url();+ await page.unroute('**/api/mcp/sandbox**', failFirstSandboxRequest);+ const recoveredSandboxResponse = page.waitForResponse(+ (response) =>+ new URL(response.url()).pathname === '/api/mcp/sandbox' && response.status() === 200,+ { timeout: 30_000 },+ );+ await retryButton.focus();+ await expect(retryButton).toBeFocused();+ await retryButton.press('Enter');++ expect((await recoveredSandboxResponse).ok()).toBeTruthy();+ await expectConnectedApp(page, retryLabel, 'show_app', 1);+ expect(page.url()).toBe(conversationUrl);+ await expect(retryOuterFrame).toHaveAttribute('data-retry-target', 'retained');+ await expect(outerFrame).toHaveAttribute('data-retry-sibling', 'retained');+ await expectConnectedApp(page, label);+ await expectAppHeight(page, 0);+ await expectAppHeight(page, 1);+ await expect.poll(() => retrySandboxRequests.length).toBe(2);++ events = await readEvents(page);+ expect(+ events+ .filter((event) => event.method === 'tools/call:show_app')+ .map((event) => event.params.label),+ ).toEqual([label, retryLabel]);+ expect(events.filter((event) => event.method === 'resources/read:show_app')).toHaveLength(2);++ const linkGeneration = await sendMessage(page, `E2E_MCP_LINK_APP:${label}`);+ expect(linkGeneration.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(`E2E MCP link App complete: ${label}`)).toBeVisible({+ timeout: 60_000,+ });+ await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(3);+ const linkApp = await expectConnectedApp(page, label, 'show_link_app');+ const linkViewCsp = await linkApp+ .locator('meta[http-equiv="Content-Security-Policy"]')+ .getAttribute('content');+ expect(linkViewCsp).toContain(`script-src 'self' 'unsafe-inline' ${MCP_APP_LINK_ORIGIN}`);+ expect(linkViewCsp).toContain("connect-src 'none'");+ expect(linkViewCsp).toContain("frame-src 'none'");++ const popupPromise = page.waitForEvent('popup', { timeout: 30_000 });+ await linkApp.getByTestId('open-link').click();+ const openedPage = await popupPromise;+ await openedPage.waitForLoadState('domcontentloaded');+ expect(new URL(openedPage.url()).origin).toBe(MCP_APP_LINK_ORIGIN);+ expect(new URL(openedPage.url()).pathname).toBe('/opened');+ await expect(openedPage.getByText('policy-permitted-open')).toBeVisible();+ await expect(linkApp.getByTestId('operation')).toHaveText('{}');+ await openedPage.close();+ expect(+ (await readEvents(page)).filter((event) => event.method === 'resources/read:show_link_app'),+ ).toHaveLength(1);++ const legacyGeneration = await sendMessage(page, `E2E_MCP_LEGACY:${label}`);+ expect(legacyGeneration.ok()).toBeTruthy();+ const legacyFrameElement = page.locator(`iframe[title="${LEGACY_FRAME_TITLE}"]`);+ await expect(legacyFrameElement).toHaveCount(1);+ const legacyFrame = page.frameLocator(`iframe[title="${LEGACY_FRAME_TITLE}"]`);+ await expect(legacyFrame.getByTestId('legacy-status')).toHaveText('legacy-ready');+ await expect(legacyFrameElement).toHaveCSS('height', '120px');++ const legacyActionGeneration = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ /^\/api\/(agents|ask)\//.test(new URL(response.url()).pathname),+ { timeout: 30_000 },+ );+ await legacyFrame.getByTestId('legacy-action').click();+ expect((await legacyActionGeneration).ok()).toBeTruthy();+ await expect(legacyFrame.getByTestId('legacy-expanded')).toBeVisible();+ await expect(legacyFrameElement).toHaveCSS('height', '360px');+ await expect(messagesView(page).getByText('E2E legacy action complete')).toBeVisible({+ timeout: 30_000,+ });+ expect(await readEvents(page)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ method: 'tools/call:show_legacy', params: { label } }),+ expect.objectContaining({+ method: 'tools/call:legacy_action',+ params: { label: 'legacy-view' },+ }),+ ]),+ );++ const conversationPath = new URL(page.url()).pathname;+ const conversationId = conversationPath.split('/').pop();+ expect(conversationId).toMatch(/^[0-9a-fA-F-]{36}$/);+ const persistedMessages = await getMessages(page, token, conversationId!);+ const persistedResources = uiResources(persistedMessages);+ expect(persistedResources.map((resource) => resource.uri).sort()).toEqual([+ 'ui://e2e/app.html',+ 'ui://e2e/app.html',+ 'ui://e2e/legacy.html',+ 'ui://e2e/link-app.html',+ ]);+ expect(+ persistedResources+ .filter((resource) => resource.mimeType === 'text/html;profile=mcp-app')+ .every((resource) => typeof resource.serverBinding === 'string'),+ ).toBe(true);+ writeState({+ conversationId: conversationId!,+ label,+ retryLabel,+ messageFingerprint: fingerprintMessages(persistedMessages),+ uiFingerprint: fingerprintUI(persistedMessages),+ });++ await resetEvents(page);+ await page.reload({ waitUntil: 'domcontentloaded' });+ await expectConnectedApp(page, label);+ await expectConnectedApp(page, retryLabel, 'show_app', 1);+ await expectConnectedApp(page, label, 'show_link_app');+ await expectAppHeight(page, 0);+ await expectAppHeight(page, 1);+ await expect(page.locator(`iframe[title="${LEGACY_FRAME_TITLE}"]`)).toHaveCount(1);+ expect(+ (await readEvents(page)).filter((event) => event.method.startsWith('resources/read:show_')),+ ).toEqual([]);++ const share = await createShare(page, conversationId!);+ expect(share.shareId).toBeTruthy();+ const appRequestCountBeforeShare = appRequests.length;++ const shareResponse = page.waitForResponse(+ (response) =>+ response.request().method() === 'GET' &&+ new URL(response.url()).pathname === `/api/share/${share.shareId}`,+ { timeout: 30_000 },+ );+ await page.goto(`/share/${share.shareId}`, { waitUntil: 'domcontentloaded' });+ const publicPayload = (await (await shareResponse).json()) as SharePayload;+ const sharedMessages = JSON.stringify(publicPayload.messages);+ expect(sharedMessages).toContain(`E2E MCP App result: ${label}`);+ expect(sharedMessages).toContain(`E2E MCP App result: ${retryLabel}`);+ expect(sharedMessages).toContain(`E2E MCP link App result: ${label}`);+ expect(sharedMessages).toContain(`E2E legacy MCP-UI result: ${label}`);+ expect(+ publicPayload.messages?.every(+ (message) => !message.attachments?.some((attachment) => attachment.type === 'ui_resources'),+ ),+ ).toBe(true);+ await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(0);+ await expect(page.locator(`iframe[title="${LEGACY_FRAME_TITLE}"]`)).toHaveCount(0);+ expect(appRequests).toHaveLength(appRequestCountBeforeShare);+ });++ test('keeps two labeled phase App results visible and correlated while panels stay closed', async ({+ page,+ }, testInfo) => {+ test.skip(!['standalone', 'true'].includes(PHASE));+ test.setTimeout(180_000);+ const label = randomLabel();+ const alphaLabel = `phase alpha ${label}`;+ const betaLabel = `phase beta ${label}`;+ const alphaToolCallId = `call_e2e_mcp_app_phase_alpha_${label}`;+ const betaToolCallId = `call_e2e_mcp_app_phase_beta_${label}`;+ const childLabels = await configureMcpAppPhaseLabels(page, label);++ await resetEvents(page);+ await page.goto(NEW_CHAT_PATH, { timeout: 15_000 });+ const token = await getAccessToken(page);+ expect(await getPolicy(page, token)).toMatchObject({+ enabled: true,+ legacyHtmlEnabled: true,+ sandboxUrl: process.env.E2E_MCP_SANDBOX_URL,+ });+ await selectMockEndpoint(page, MCP_APP_PHASE_ENDPOINT);+ await selectMcpAppServer(page);++ const generation = await sendMessageAndWaitForCompletion(page, `E2E_MCP_APP_PHASE:${label}`, {+ timeout: 90_000,+ });+ expect(generation.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(`E2E MCP App phase complete: ${label}`)).toBeVisible({+ timeout: 60_000,+ });++ const conversationId = new URL(page.url()).pathname.split('/').pop();+ expect(conversationId).toMatch(/^[0-9a-fA-F-]{36}$/);+ let messages = await getMessages(page, token, conversationId!);+ await expect+ .poll(async () => {+ messages = await getMessages(page, token, conversationId!);+ const serialized = JSON.stringify(messages);+ return (+ serialized.includes(MCP_APP_PHASE_PARENT_LABEL) &&+ serialized.includes(childLabels.first) &&+ serialized.includes(childLabels.second)+ );+ })+ .toBe(true);++ const assistant = messages.find(+ (message) =>+ message.isCreatedByUser === false &&+ JSON.stringify(message).includes(`E2E MCP App phase complete: ${label}`),+ );+ expect(assistant).toBeDefined();+ const toolParts = (assistant?.content ?? []).filter(+ (part): part is StoredContentPart & { tool_call: StoredToolCall & { id: string } } =>+ typeof part?.tool_call?.id === 'string',+ );+ const attachments = (assistant?.attachments ?? []).filter(+ (attachment) => attachment.type === 'ui_resources',+ );+ expect(attachments).toHaveLength(2);++ for (const expected of [+ { id: alphaToolCallId, label: alphaLabel, otherLabel: betaLabel },+ { id: betaToolCallId, label: betaLabel, otherLabel: alphaLabel },+ ]) {+ const part = toolParts.find((candidate) => candidate.tool_call.id === expected.id);+ expect(part, `persisted tool call ${expected.id}`).toBeDefined();+ const stepId = part?.tool_call.stepId;+ expect(stepId).toEqual(expect.any(String));++ const attachment = attachments.find((candidate) => candidate.toolCallId === expected.id);+ expect(attachment, `persisted App attachment ${expected.id}`).toBeDefined();+ expect(attachment).toMatchObject({+ toolCallId: expected.id,+ agentId: MCP_APP_PHASE_AGENT_ID,+ stepId,+ });+ expect(attachment?.ui_resources).toHaveLength(1);+ const serialized = JSON.stringify(attachment?.ui_resources);+ expect(serialized).toContain(expected.label);+ expect(serialized).not.toContain(expected.otherLabel);+ }++ const phaseHeader = messagesView(page).getByRole('button', {+ name: MCP_APP_PHASE_PARENT_LABEL,+ exact: true,+ });+ await expect(phaseHeader).toBeVisible({ timeout: 60_000 });+ await expect(phaseHeader).toHaveAttribute('aria-expanded', 'false');+ await expectAppFramesOutsidePanels(page, 2);++ await expectConnectedApp(page, alphaLabel, 'show_app', 0);+ await expectConnectedApp(page, betaLabel, 'show_app', 1);+ await page.screenshot({+ path: testInfo.outputPath('settled-grouped-apps.png'),+ fullPage: true,+ });++ const initialEvents = await readEvents(page);+ expect(+ initialEvents+ .filter((event) => event.method === 'tools/call:show_app')+ .map((event) => event.params.label),+ ).toEqual([alphaLabel, betaLabel]);+ expect(+ initialEvents.filter((event) => event.method === 'resources/read:show_app'),+ ).toHaveLength(2);++ await page.reload({ waitUntil: 'domcontentloaded' });+ const reloadedHeader = messagesView(page).getByRole('button', {+ name: MCP_APP_PHASE_PARENT_LABEL,+ exact: true,+ });+ await expect(reloadedHeader).toBeVisible({ timeout: 60_000 });+ await expect(reloadedHeader).toHaveAttribute('aria-expanded', 'false');+ await expectAppFramesOutsidePanels(page, 2);+ await expectConnectedApp(page, alphaLabel, 'show_app', 0);+ await expectConnectedApp(page, betaLabel, 'show_app', 1);+ expect(+ (await readEvents(page)).filter((event) => event.method === 'resources/read:show_app'),+ ).toHaveLength(2);+ });++ test('disables all persisted executable UI when Apps are explicitly false', async ({ page }) => {+ test.skip(PHASE !== 'false');+ test.setTimeout(90_000);+ const state = readState();+ const appRequests = await trackExecutableEffects(page);+ let releaseConfig!: () => void;+ const configGate = new Promise<void>((resolve) => {+ releaseConfig = resolve;+ });+ let observePolicy!: (policy: MCPAppsPolicy) => void;+ const observedPolicy = new Promise<MCPAppsPolicy>((resolve) => {+ observePolicy = resolve;+ });+ await page.route('**/api/config', async (route) => {+ const response = await route.fetch();+ const body = (await response.json()) as { mcpApps?: MCPAppsPolicy };+ if (!body.mcpApps) {+ await route.fulfill({ response });+ return;+ }+ observePolicy(body.mcpApps);+ await configGate;+ await route.fulfill({ response });+ });++ const navigation = page.goto(`/c/${state.conversationId}`, { waitUntil: 'domcontentloaded' });+ await expect(observedPolicy).resolves.toMatchObject({+ enabled: false,+ legacyHtmlEnabled: false,+ sandboxUrl: process.env.E2E_MCP_SANDBOX_URL,+ });+ expect(await executableFrameCounts(page)).toEqual({ app: 0, legacy: 0 });+ expect(appRequests).toEqual([]);+ releaseConfig();+ await navigation;+ await page.unroute('**/api/config');++ const token = await getAccessToken(page);+ const persistedMessages = await getMessages(page, token, state.conversationId);+ expect(fingerprintMessages(persistedMessages)).toBe(state.messageFingerprint);+ expect(fingerprintUI(persistedMessages)).toBe(state.uiFingerprint);+ const persistedText = JSON.stringify(persistedMessages);+ expect(persistedText).toContain(`E2E MCP App result: ${state.label}`);+ expect(persistedText).toContain(`E2E MCP App result: ${state.retryLabel}`);+ expect(persistedText).toContain(`E2E MCP link App result: ${state.label}`);+ expect(persistedText).toContain(`E2E legacy MCP-UI result: ${state.label}`);+ await expect(+ messagesView(page).getByText(`E2E MCP App complete: ${state.label}`),+ ).toBeVisible();+ await expect(+ messagesView(page).getByText(`E2E MCP App complete: ${state.retryLabel}`),+ ).toBeVisible();+ await expect(+ messagesView(page).getByText(`E2E MCP link App complete: ${state.label}`),+ ).toBeVisible();+ await expect(messagesView(page).getByText('Legacy MCP-UI:', { exact: true })).toBeVisible();+ await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(0);+ await expect(page.locator(`iframe[title="${LEGACY_FRAME_TITLE}"]`)).toHaveCount(0);+ expect(await executableFrameCounts(page)).toEqual({ app: 0, legacy: 0 });+ expect(appRequests).toEqual([]);+ });++ test('keeps omitted-policy legacy HTML while rejecting new App production', async ({ page }) => {+ test.skip(PHASE !== 'omitted');+ test.setTimeout(120_000);+ const label = randomLabel();+ const appRequests = await trackExecutableEffects(page);++ await resetEvents(page);+ await page.goto(NEW_CHAT_PATH, { timeout: 15_000 });+ const token = await getAccessToken(page);+ expect(await getPolicy(page, token)).toMatchObject({+ enabled: false,+ legacyHtmlEnabled: true,+ sandboxUrl: process.env.E2E_MCP_SANDBOX_URL,+ });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await selectMcpAppServer(page);++ const appGeneration = await sendMessageAndWaitForCompletion(page, `E2E_MCP_APP:${label}`);+ expect(appGeneration.ok()).toBeTruthy();+ await expect(messagesView(page).getByText(`E2E MCP App complete: ${label}`)).toBeVisible({+ timeout: 60_000,+ });+ const eventsAfterApp = await readEvents(page);+ expect(+ eventsAfterApp.filter(+ (event) => event.method === 'tools/call:show_app' && event.params.label === label,+ ),+ ).toHaveLength(1);+ expect(eventsAfterApp.filter((event) => event.method === 'resources/read:show_app')).toEqual(+ [],+ );+ await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(0);++ const appConversationId = new URL(page.url()).pathname.split('/').pop();+ expect(appConversationId).toMatch(/^[0-9a-fA-F-]{36}$/);+ const messagesAfterApp = await getMessages(page, token, appConversationId!);+ expect(JSON.stringify(messagesAfterApp)).toContain(`E2E MCP App result: ${label}`);+ expect(+ uiResources(messagesAfterApp).filter(+ (resource) => resource.mimeType === 'text/html;profile=mcp-app',+ ),+ ).toEqual([]);++ const legacyGeneration = await sendMessageAndWaitForCompletion(+ page,+ `E2E_MCP_LEGACY_MIMELESS:${label}`,+ );+ expect(legacyGeneration.ok()).toBeTruthy();+ await expect(+ messagesView(page).getByText('MIME-less Legacy MCP-UI:', { exact: true }),+ ).toBeVisible({ timeout: 60_000 });+ const legacyElement = page.locator(`iframe[title="${LEGACY_FRAME_TITLE}"]`);+ await expect(legacyElement).toHaveCount(1);+ await expect(+ page+ .frameLocator(`iframe[title="${LEGACY_FRAME_TITLE}"]`)+ .getByTestId('legacy-mimeless-status'),+ ).toHaveText('legacy-mimeless-ready');+ await expect(legacyElement).toHaveCSS('height', '140px');+ const messagesAfterLegacy = await getMessages(page, token, appConversationId!);+ expect(JSON.stringify(messagesAfterLegacy)).toContain(+ `E2E MIME-less legacy MCP-UI result: ${label}`,+ );+ expect(+ uiResources(messagesAfterLegacy).filter(+ (resource) =>+ resource.uri === 'ui://e2e/legacy-mimeless.html' && resource.mimeType === 'text/html',+ ),+ ).toHaveLength(1);+ expect(+ (await readEvents(page)).filter(+ (event) =>+ event.method === 'tools/call:show_legacy_mimeless' && event.params.label === label,+ ),+ ).toHaveLength(1);+ expect((await executableFrameCounts(page))?.app).toBe(0);+ expect((await executableFrameCounts(page))?.legacy).toBe(1);+ expect(appRequests).toEqual([]);+ });++ test('enforces independent configured resource and tool-call quotas', async ({ page }) => {+ test.skip(PHASE !== 'quota');+ test.setTimeout(90_000);+ await resetEvents(page);+ await page.goto(NEW_CHAT_PATH, { timeout: 15_000 });+ const token = await getAccessToken(page);+ expect(await getPolicy(page, token)).toMatchObject({+ enabled: true,+ legacyHtmlEnabled: true,+ sandboxUrl: process.env.E2E_MCP_SANDBOX_URL,+ });+ const state = readState();+ const serverBinding = persistedServerBinding(+ await getMessages(page, token, state.conversationId),+ );++ const resources = async () =>+ rawAuthenticatedRequest(page, token, '/api/mcp/resources/list', {+ serverName: 'e2e-app',+ serverBinding,+ });+ expect((await resources()).status).toBe(200);+ expect((await resources()).status).toBe(200);+ const blockedResource = await resources();+ expect(blockedResource.status).toBe(429);+ expect(blockedResource.json).toEqual({+ message: 'Too many app resource requests. Try again later',+ });++ const toolCall = async () =>+ rawAuthenticatedRequest(page, token, '/api/mcp/app-tool-call', {+ serverName: 'e2e-app',+ serverBinding,+ toolName: 'follow_up',+ arguments: { label: 'quota' },+ });+ expect((await toolCall()).status).toBe(200);+ expect((await toolCall()).status).toBe(200);+ const blockedTool = await toolCall();+ expect(blockedTool.status).toBe(429);+ expect(blockedTool.json).toEqual({+ message: 'Too many app tool call requests. Try again later',+ });+ expect(+ (await readEvents(page)).filter(+ (event) => event.method === 'tools/call:follow_up' && event.params.label === 'quota',+ ),+ ).toHaveLength(2);+ });+});diff --git a/librechat.example.yaml b/librechat.example.yamlindex 8519982b92..d05d649925 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -449,11 +449,10 @@ registration:# - '127.0.0.1:8080'# rateLimits:-# # Shared account budget for all authenticated 2FA management operations.-# # Always active; successful and failed requests count. Uses Redis when enabled.-# # Minimum 3, so enable -> verify -> confirm can complete within one window.-# twoFactorManagement:-# requestsPerFiveMinutes: 7+# # Per-user MCP App browser-route limits. Each limit uses a fixed one-minute window.+# mcpApps:+# resourcesPerMinute: 120+# toolCallsPerMinute: 60# # Authenticated agent-event admission has its own API-key-principal bucket.# agentEvents:# userMax: 40@@ -537,6 +536,9 @@ actions:# Supports wildcards: '*.example.com' matches 'api.example.com', 'staging.example.com', etc.# Supports protocol/port restrictions: 'https://api.example.com:8443' restricts to specific protocol/port.# mcpSettings:+# # New MCP Apps require explicit opt-in. If omitted, legacy inline HTML remains enabled;+# # false disables both MCP Apps and legacy inline HTML.+# apps: true# allowedDomains:# - 'host.docker.internal' # Docker host access (required for Docker setups)# - 'localhost' # Local development@@ -554,6 +556,15 @@ actions:# - 'host.docker.internal:8080'# - '127.0.0.1:8080'+# Deployment-owned MCP App sandbox settings. These cannot be overridden by role, group, or user+# configuration. Set url to a dedicated origin routed to /api/mcp/sandbox. Defaults are shown.+# mcpAppSandbox:+# url: https://mcp-sandbox.example.com/api/mcp/sandbox+# maxSourcesPerDirective: 32+# maxSerializedLength: 4096+# maxPersistedAppBytes: 1048576+# maxAdmissionRequestsPerMinute: 240+# Example MCP Servers Object Structure# mcpServers:# everything:diff --git a/package-lock.json b/package-lock.jsonindex c74a886432..acf939a340 100644--- a/package-lock.json+++ b/package-lock.json@@ -869,6 +869,7 @@"@librechat/client": "*","@marsidev/react-turnstile": "^1.1.0","@mcp-ui/client": "^5.7.0",+ "@modelcontextprotocol/ext-apps": "^1.7.4","@monaco-editor/react": "^4.7.0","@radix-ui/react-accordion": "^1.2.20","@radix-ui/react-alert-dialog": "^1.1.23",@@ -1046,6 +1047,21 @@"react-dom": "^16.8.0 || ^17 || ^18"}},+ "client/node_modules/@mcp-ui/client": {+ "version": "5.7.0",+ "resolved": "https://registry.npmjs.org/@mcp-ui/client/-/client-5.7.0.tgz",+ "integrity": "sha512-+HbPw3VS46WUSWmyJ34ZVnygb81QByA3luR6y0JDbyDZxjYtHw1FcIN7v9WbbE8PrfI0WcuWCSiNOO6sOGbwpQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "*",+ "@quilted/threads": "^3.1.3",+ "@r2wc/react-to-web-component": "^2.0.4",+ "@remote-dom/core": "^1.8.0",+ "@remote-dom/react": "^1.2.2",+ "react": "^18.3.1",+ "react-dom": "^18.3.1"+ }+ },"client/node_modules/@react-spring/web": {"version": "9.7.5","resolved": "https://registry.npmjs.org/@react-spring/web/-/web-9.7.5.tgz",@@ -9849,21 +9865,6 @@"react-dom": "^17.0.2 || ^18.0.0 || ^19.0"}},- "node_modules/@mcp-ui/client": {- "version": "5.7.0",- "resolved": "https://registry.npmjs.org/@mcp-ui/client/-/client-5.7.0.tgz",- "integrity": "sha512-+HbPw3VS46WUSWmyJ34ZVnygb81QByA3luR6y0JDbyDZxjYtHw1FcIN7v9WbbE8PrfI0WcuWCSiNOO6sOGbwpQ==",- "license": "Apache-2.0",- "dependencies": {- "@modelcontextprotocol/sdk": "*",- "@quilted/threads": "^3.1.3",- "@r2wc/react-to-web-component": "^2.0.4",- "@remote-dom/core": "^1.8.0",- "@remote-dom/react": "^1.2.2",- "react": "^18.3.1",- "react-dom": "^18.3.1"- }- },"node_modules/@mermaid-js/parser": {"version": "1.2.1","resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.2.1.tgz",@@ -9911,6 +9912,35 @@"zod-to-json-schema": "^3.25.0"}},+ "node_modules/@modelcontextprotocol/ext-apps": {+ "version": "1.7.5",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-1.7.5.tgz",+ "integrity": "sha512-TjPH2S2y5UEGKhmI6+XGFuqfqOV4ppe1x6DA3txnUaEWkgtA4G5vo14jGKFZmegdkZ1H4QMLyujLvoU1BEdnAg==",+ "license": "MIT",+ "workspaces": [+ "examples/*"+ ],+ "dependencies": {+ "@standard-schema/spec": "^1.1.0"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0",+ "react": "^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",+ "zod": "^3.25.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },"node_modules/@modelcontextprotocol/sdk": {"version": "1.30.0","resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz",@@ -11893,9 +11923,9 @@}},"node_modules/@preact/signals-core": {- "version": "1.11.0",- "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.11.0.tgz",- "integrity": "sha512-jglbibeWHuFRzEWVFY/TT7wB1PppJxmcSfUHcK+2J9vBRtiooMfw6tAPttojNYrrpdGViqAYCbPpmWYlMm+eMQ==",+ "version": "1.14.4",+ "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.4.tgz",+ "integrity": "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA==","license": "MIT","funding": {"type": "opencollective",@@ -11969,12 +11999,12 @@}},"node_modules/@quilted/events": {- "version": "2.1.3",- "resolved": "https://registry.npmjs.org/@quilted/events/-/events-2.1.3.tgz",- "integrity": "sha512-4fHaSLND8rmZ+tce9/4FNmG5UWTRpFtM54kOekf3tLON4ZLLnYzjjldELD35efd7+lT5+E3cdkacqc56d+kCrQ==",+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@quilted/events/-/events-2.1.5.tgz",+ "integrity": "sha512-WUsJtSI2npAVo1WZNl60dagmC7JxBbMqTikvGuAMzGP9ZKPBpLw0AnhaBoX6mmCfvUTylMLDYbMW8zHqSinUfw==","license": "MIT","dependencies": {- "@preact/signals-core": "^1.8.0"+ "@preact/signals-core": "^1.14.2"},"engines": {"node": ">=14.0.0"@@ -12001,18 +12031,18 @@}},"node_modules/@r2wc/core": {- "version": "1.2.0",- "resolved": "https://registry.npmjs.org/@r2wc/core/-/core-1.2.0.tgz",- "integrity": "sha512-vAfiuS5KywtV54SRzc4maEHcpdgeUyJzln+ATpNCOkO+ArIuOkTXd92b5YauVAd0A8B2rV/y9OeVW19vb73bUQ==",+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@r2wc/core/-/core-1.3.1.tgz",+ "integrity": "sha512-x9nMthXsTjqr1alE+boX1Zuzqb6/oFi4wAOdWaWcWKcrwq9M/PATK74c3DFJfRnUOkYWPlsz0e4CsFBXJGStSA==","license": "MIT"},"node_modules/@r2wc/react-to-web-component": {- "version": "2.0.4",- "resolved": "https://registry.npmjs.org/@r2wc/react-to-web-component/-/react-to-web-component-2.0.4.tgz",- "integrity": "sha512-g1dtTTEGETNUimYldTW+2hxY3mmJZjzPEca0vqCutUht2GHmpK9mT5r/urmEI7uSbOkn6HaymosgVy26lvU1JQ==",+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@r2wc/react-to-web-component/-/react-to-web-component-2.1.1.tgz",+ "integrity": "sha512-AXsIdjxK9ALv0ySWjVadUg3uJ5nS8L4H8eZMYaaWuM+9LNj9DP/r4+sMjI+6jZwb7/FqwxRPHQUq8yimQwBfOA==","license": "MIT","dependencies": {- "@r2wc/core": "^1.0.0"+ "@r2wc/core": "^1.3.1"},"peerDependencies": {"react": "^18.0.0 || ^19.0.0",@@ -14596,12 +14626,12 @@}},"node_modules/@remote-dom/core": {- "version": "1.9.0",- "resolved": "https://registry.npmjs.org/@remote-dom/core/-/core-1.9.0.tgz",- "integrity": "sha512-h8OO2NRns2paXO/q5hkfXrwlZKq7oKj9XedGosi7J8OP3+aW7N2Gv4MBBVVQGCfOiZPkOj5m3sQH7FdyUWl7PQ==",+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@remote-dom/core/-/core-1.11.1.tgz",+ "integrity": "sha512-0v29Q7F/iunb2cJm3E7r780X6jcPEFEgetSGisgRssJuoP9217yC1MKLVFNdXRmJYKX+oaugQKqaD2m8XA9dTQ==","license": "MIT","dependencies": {- "@remote-dom/polyfill": "^1.4.4",+ "@remote-dom/polyfill": "^1.5.1","htm": "^3.1.1"},"engines": {@@ -14620,9 +14650,9 @@}},"node_modules/@remote-dom/polyfill": {- "version": "1.4.5",- "resolved": "https://registry.npmjs.org/@remote-dom/polyfill/-/polyfill-1.4.5.tgz",- "integrity": "sha512-V1qkKIl/wXyDO0I+tQDH06cBBNyyViZF3IYorkTTBf58dorqOP5Ta51vCCWeekPgdSOPuEKvHhvu6kAaKqVgww==",+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/@remote-dom/polyfill/-/polyfill-1.5.1.tgz",+ "integrity": "sha512-eaWdIVKZpNfbqspKkRQLVxiFv/7vIw8u0FVA5oy52YANFbO/WVT0GU+PQmRt/QUSijaB36HBAqx7stjo8HGpVQ==","license": "MIT","engines": {"node": ">=14.0.0"diff --git a/packages/api/jest.config.mjs b/packages/api/jest.config.mjsindex 5f6e254f2a..44209a8d14 100644--- a/packages/api/jest.config.mjs+++ b/packages/api/jest.config.mjs@@ -5,6 +5,7 @@ const esModules = ['@langchain/langgraph-checkpoint','@langchain/langgraph-sdk','@mistralai/mistralai',+ '@modelcontextprotocol/ext-apps','domelementtype','domhandler','dom-serializer',diff --git a/packages/api/src/agents/__tests__/load.spec.ts b/packages/api/src/agents/__tests__/load.spec.tsindex 18d199ceda..41deaf4fcc 100644--- a/packages/api/src/agents/__tests__/load.spec.ts+++ b/packages/api/src/agents/__tests__/load.spec.ts@@ -11,6 +11,7 @@ import type {} from 'librechat-data-provider';import type { AppConfig } from '@librechat/data-schemas';import type { LoadAgentParams, LoadAgentDeps } from '../load';+import { STANDARD_MCP_CAPABILITY_PROFILE } from '~/mcp/capabilities';import { loadAddedAgent } from '../added';import { loadAgent } from '../load';@@ -165,7 +166,12 @@ describe('loadAgent', () => {);expect(mockGetMCPServerTools).toHaveBeenCalledTimes(1);- expect(mockGetMCPServerTools).toHaveBeenCalledWith('user123', 'server1', undefined);+ expect(mockGetMCPServerTools).toHaveBeenCalledWith(+ 'user123',+ 'server1',+ undefined,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );expect(result?.tools).toContain(`${Constants.mcp_all}${Constants.mcp_delimiter}body-scoped`);expect(result?.tools).toContain('tool1_mcp_server1');});@@ -335,7 +341,12 @@ describe('loadAgent', () => {deps,);- expect(mockGetMCPServerTools).toHaveBeenCalledWith('user123', 'overlay', overlayConfig);+ expect(mockGetMCPServerTools).toHaveBeenCalledWith(+ 'user123',+ 'overlay',+ overlayConfig,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );expect(result?.tools).toContain('overlay_tool_mcp_overlay');});@@ -870,7 +881,12 @@ describe('loadAgent', () => {deps,);- expect(mockGetMCPServerTools).toHaveBeenCalledWith('user123', 'overlay', overlayConfig);+ expect(mockGetMCPServerTools).toHaveBeenCalledWith(+ 'user123',+ 'overlay',+ overlayConfig,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );expect(result?.tools).toContain('overlay_tool_mcp_overlay');});diff --git a/packages/api/src/agents/added.ts b/packages/api/src/agents/added.tsindex 481c1c26f3..970072af92 100644--- a/packages/api/src/agents/added.ts+++ b/packages/api/src/agents/added.ts@@ -7,9 +7,11 @@ import {getEphemeralSender,appendAgentIdSuffix,encodeEphemeralAgentId,+ resolveMCPAppsPolicy,} from 'librechat-data-provider';import type { Agent, AgentToolOptions, TConversation, TModelSpec } from 'librechat-data-provider';import type { AppConfig } from '@librechat/data-schemas';+import type { MCPClientCapabilityProfile } from '~/mcp/capabilities';import type { ParsedServerConfig } from '~/mcp/types';import {requiresEphemeralUserConnection,@@ -17,6 +19,7 @@ import {validateMCPServerConfig,} from '~/mcp/utils';import { ASK_USER_QUESTION_TOOL_NAME } from '~/agents/hitl/askUserQuestionTool';+import { resolveMCPClientCapabilityProfile } from '~/mcp/capabilities';import { synthesizeBackgroundToolOptions } from '~/agents/background';import { mergeSynthesizedToolOptions } from '~/agents/selection';import { synthesizeIntentToolOptions } from '~/agents/intent';@@ -63,6 +66,7 @@ export interface LoadAddedAgentDeps {userId: string,serverName: string,serverConfig?: ParsedServerConfig,+ capabilityProfile?: MCPClientCapabilityProfile,) => Promise<Record<string, unknown> | null>;/** The MCP servers this user can reach, with the registry's tier precedence* already applied — the resolution behind the client's catalog. Omitted, the@@ -129,6 +133,9 @@ export async function loadAddedAgent(}const appConfig = req.config as AppConfig | undefined;+ const capabilityProfile = resolveMCPClientCapabilityProfile(+ resolveMCPAppsPolicy(appConfig?.mcpSettings?.apps),+ );const ephemeralAgent = rest.ephemeralAgent as| {mcp?: string[];@@ -249,7 +256,7 @@ export async function loadAddedAgent(const serverTools =overlayConfig && requiresEphemeralUserConnection(overlayConfig)? null- : await deps.getMCPServerTools(userId, mcpServer, overlayConfig);+ : await deps.getMCPServerTools(userId, mcpServer, overlayConfig, capabilityProfile);if (!serverTools) {tools.push(`${mcp_all}${mcp_delimiter}${mcpServer}`);addedServers.add(mcpServer);diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 441297c371..be417371db 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -19,6 +19,7 @@ import type { CodeExecutionContext } from './execution';import {createOwnedToolEndHandler,createToolExecuteHandler,+ getAttachmentOwnership,ToolExecuteOptions,} from './handlers';import { markSandboxReady } from './prewarm';@@ -182,6 +183,32 @@ describe('createOwnedToolEndHandler', () => {});});+describe('getAttachmentOwnership', () => {+ it('prefers the executing agent and preserves the graph step', () => {+ expect(+ getAttachmentOwnership({+ executingAgentId: 'executing-agent',+ agentId: 'saved-agent',+ agent_id: 'legacy-agent',+ stepId: 'step-1',+ }),+ ).toEqual({ agentId: 'executing-agent', stepId: 'step-1' });+ });++ it('uses saved and legacy agent identifiers as fallbacks', () => {+ expect(getAttachmentOwnership({ agentId: 'saved-agent' })).toEqual({+ agentId: 'saved-agent',+ });+ expect(getAttachmentOwnership({ agent_id: 'legacy-agent' })).toEqual({+ agentId: 'legacy-agent',+ });+ });++ it('omits empty and non-string ownership values', () => {+ expect(getAttachmentOwnership({ executingAgentId: '', agentId: 1, stepId: null })).toEqual({});+ });+});+describe('createToolExecuteHandler', () => {describe('code execution session context passthrough', () => {it('passes session_id and _injected_files from codeSessionContext to toolCallConfig', async () => {diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 5b34cf83c1..2995e5dce0 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -220,6 +220,19 @@ export interface ToolEndCallbackMetadata {[key: string]: unknown;}+/** Projects the graph-owned agent and step identifiers onto persisted tool attachments. */+export function getAttachmentOwnership(metadata?: ToolEndCallbackMetadata): {+ agentId?: string;+ stepId?: string;+} {+ const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id;+ const stepId = metadata?.stepId;+ return {+ ...(typeof agentId === 'string' && agentId.length > 0 ? { agentId } : {}),+ ...(typeof stepId === 'string' && stepId.length > 0 ? { stepId } : {}),+ };+}+export type ToolEndCallback = (data: ToolEndCallbackData,metadata: ToolEndCallbackMetadata,diff --git a/packages/api/src/agents/load.ts b/packages/api/src/agents/load.tsindex 7ae16333b5..889a1cf5cf 100644--- a/packages/api/src/agents/load.ts+++ b/packages/api/src/agents/load.ts@@ -6,6 +6,7 @@ import {isEphemeralAgentId,getEphemeralSender,encodeEphemeralAgentId,+ resolveMCPAppsPolicy,} from 'librechat-data-provider';import type {AgentModelParameters,@@ -15,6 +16,7 @@ import type {Agent,} from 'librechat-data-provider';import type { AppConfig } from '@librechat/data-schemas';+import type { MCPClientCapabilityProfile } from '~/mcp/capabilities';import type { ParsedServerConfig } from '~/mcp/types';import {requiresEphemeralUserConnection,@@ -22,6 +24,7 @@ import {validateMCPServerConfig,} from '~/mcp/utils';import { ASK_USER_QUESTION_TOOL_NAME } from '~/agents/hitl/askUserQuestionTool';+import { resolveMCPClientCapabilityProfile } from '~/mcp/capabilities';import { synthesizeBackgroundToolOptions } from '~/agents/background';import { mergeSynthesizedToolOptions } from '~/agents/selection';import { synthesizeIntentToolOptions } from '~/agents/intent';@@ -39,6 +42,7 @@ export interface LoadAgentDeps {userId: string,serverName: string,serverConfig?: ParsedServerConfig,+ capabilityProfile?: MCPClientCapabilityProfile,) => Promise<Record<string, unknown> | null>;/** The MCP servers this user can reach, with the registry's tier precedence* already applied — the resolution behind the client's catalog. Omitted, the@@ -79,6 +83,9 @@ export async function loadEphemeralAgent(}const ephemeralAgent: TEphemeralAgent | undefined = req.body?.ephemeralAgent;const userId = req.user?.id ?? '';+ const capabilityProfile = resolveMCPClientCapabilityProfile(+ resolveMCPAppsPolicy(req.config?.mcpSettings?.apps),+ );/** The picker's own selection is narrowed to what the picker may offer; a* spec's servers are the operator's choice and are added after, so pinning a* chat-hidden server to a spec keeps working. */@@ -136,7 +143,7 @@ export async function loadEphemeralAgent(const serverTools =overlayConfig && requiresEphemeralUserConnection(overlayConfig)? null- : await deps.getMCPServerTools(userId, mcpServer, overlayConfig);+ : await deps.getMCPServerTools(userId, mcpServer, overlayConfig, capabilityProfile);if (!serverTools) {tools.push(`${mcp_all}${mcp_delimiter}${mcpServer}`);addedServers.add(mcpServer);diff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex c84b2d2732..f230e48588 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -17,6 +17,7 @@ export * from './auth';export * from './apiKeys';/* MCP */export * from './mcp/mcpConfig';+export * from './mcp/capabilities';export * from './mcp/authority';export * from './mcp/registry/MCPServersRegistry';export * from './mcp/MCPManager';@@ -30,6 +31,11 @@ export * from './mcp/loading';export * from './mcp/openid';export * from './mcp/cache';export * from './mcp/tools';+export * from './mcp/apps';+export * from './mcp/apps/controller';+export * from './mcp/apps/binding';+export * from './mcp/apps/limits';+export * from './mcp/sandbox';export * from './mcp/catalog/store';export * from './mcp/catalog/recovery';export * from './mcp/authorization';diff --git a/packages/api/src/mcp/ConnectionsRepository.ts b/packages/api/src/mcp/ConnectionsRepository.tsindex bd783b1772..0b57bbce37 100644--- a/packages/api/src/mcp/ConnectionsRepository.ts+++ b/packages/api/src/mcp/ConnectionsRepository.ts@@ -1,12 +1,15 @@import { logger } from '@librechat/data-schemas';+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';import type * as t from './types';import {cancelMCPToolsChanged,getMCPAppToolsPublicationGeneration,+ getMCPToolCatalogGeneration,notifyMCPToolsChanged,} from './toolsChanged';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';+import { STANDARD_MCP_CAPABILITY_PROFILE } from './capabilities';import { canUseAppConnection, isUserSourced } from './utils';import { MCPConnection } from './connection';@@ -14,6 +17,7 @@ const CONNECT_CONCURRENCY = 3;interface ConnectionLoadOptions {continueOnError?: boolean;+ expectedConfig?: t.ParsedServerConfig;refreshTools?: boolean;}@@ -28,6 +32,7 @@ interface ConnectionLoadOptions {*/export class ConnectionsRepository {protected connections: Map<string, MCPConnection> = new Map();+ private readonly connectionConfigGenerations = new Map<string, string>();protected oauthOpts: t.OAuthConnectionOptions | undefined;private readonly ownerId: string | undefined;private readonly connectionOperations = new Map<string, Promise<void>>();@@ -60,6 +65,42 @@ export class ConnectionsRepository {return result;}+ private async isExpectedConfigCurrent(+ serverName: string,+ expectedGeneration: string,+ ): Promise<boolean> {+ const currentConfig = await MCPServersRegistry.getInstance().getServerConfig(+ serverName,+ this.ownerId,+ );+ return (+ currentConfig != null &&+ getMCPAppToolsPublicationGeneration(currentConfig) === expectedGeneration+ );+ }++ private configChangedError(serverName: string): McpError {+ return new McpError(+ ErrorCode.InvalidRequest,+ `[MCP] Configuration for server "${serverName}" changed during connection checkout.`,+ );+ }++ private async returnExpectedConnection(+ serverName: string,+ connection: MCPConnection,+ expectedGeneration?: string,+ ): Promise<MCPConnection> {+ if (+ !expectedGeneration ||+ (await this.isExpectedConfigCurrent(serverName, expectedGeneration))+ ) {+ return connection;+ }+ await this.disconnectConnection(serverName);+ throw this.configChangedError(serverName);+ }+/** Checks whether this repository can connect to a specific server */async has(serverName: string): Promise<boolean> {const config = await MCPServersRegistry.getInstance().getServerConfig(serverName, this.ownerId);@@ -71,6 +112,11 @@ export class ConnectionsRepository {return canConnect;}+ /** The connection currently pooled for a server, without loading, validating or creating one. */+ public getPooledConnection(serverName: string): MCPConnection | undefined {+ return this.connections.get(serverName);+ }+/** Gets or creates a connection for the specified server with lazy loading */async get(serverName: string,@@ -89,10 +135,18 @@ export class ConnectionsRepository {if (this.shuttingDown) {return null;}- const serverConfig = await MCPServersRegistry.getInstance().getServerConfig(- serverName,- this.ownerId,- );+ const registry = MCPServersRegistry.getInstance();+ const currentConfig = await registry.getServerConfig(serverName, this.ownerId);+ const expectedGeneration = options.expectedConfig+ ? getMCPAppToolsPublicationGeneration(options.expectedConfig)+ : undefined;+ const currentGeneration = currentConfig+ ? getMCPAppToolsPublicationGeneration(currentConfig)+ : undefined;+ if (expectedGeneration && expectedGeneration !== currentGeneration) {+ throw this.configChangedError(serverName);+ }+ const serverConfig = options.expectedConfig ?? currentConfig;const existingConnection = this.connections.get(serverName);if (!serverConfig || !this.isAllowedToConnectToServer(serverConfig)) {@@ -100,27 +154,29 @@ export class ConnectionsRepository {return null;}if (existingConnection) {- // Check if config was cached/updated since connection was created- if (serverConfig.updatedAt && existingConnection.isStale(serverConfig.updatedAt)) {+ if (+ expectedGeneration &&+ this.connectionConfigGenerations.get(serverName) !== expectedGeneration+ ) {+ await this.disconnectConnection(serverName);+ } else if (serverConfig.updatedAt && existingConnection.isStale(serverConfig.updatedAt)) {logger.info(`${this.prefix()} Existing connection is outdated; recreating`, {connectionCreated: new Date(existingConnection.createdAt).toISOString(),configCachedAt: new Date(serverConfig.updatedAt).toISOString(),});-- // Disconnect stale connectionawait this.disconnectConnection(serverName);- // Fall through to create new connection} else if (await existingConnection.isConnected()) {- return existingConnection;+ return this.returnExpectedConnection(serverName, existingConnection, expectedGeneration);} else {await this.disconnectConnection(serverName);}}- const registry = MCPServersRegistry.getInstance();const { allowedDomains, allowedAddresses, useSSRFProtection } =await registry.resolveAllowlists({ userId: this.ownerId });const publicationGeneration =- this.ownerId === undefined ? getMCPAppToolsPublicationGeneration(serverConfig) : undefined;+ this.ownerId === undefined+ ? getMCPToolCatalogGeneration(serverConfig, STANDARD_MCP_CAPABILITY_PROFILE)+ : undefined;const connection = await MCPConnectionFactory.create({serverName,@@ -129,16 +185,28 @@ export class ConnectionsRepository {useSSRFProtection,allowedDomains,allowedAddresses,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,},this.oauthOpts,);if (this.shuttingDown) {await connection.dispose();- await cancelMCPToolsChanged({ userId: this.ownerId, serverName });+ await cancelMCPToolsChanged({+ userId: this.ownerId,+ serverName,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ });return null;}+ if (expectedGeneration) {+ if (!(await this.isExpectedConfigCurrent(serverName, expectedGeneration))) {+ await connection.dispose();+ throw this.configChangedError(serverName);+ }+ }+let toolsChangedGeneration = 0;let latestToolsChangedPublication = Promise.resolve();@@ -153,11 +221,16 @@ export class ConnectionsRepository {userId: this.ownerId,publicationGeneration,publicationRevision,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});void latestToolsChangedPublication;});this.connections.set(serverName, connection);+ this.connectionConfigGenerations.set(+ serverName,+ getMCPAppToolsPublicationGeneration(serverConfig),+ );if (this.ownerId === undefined && options.refreshTools !== false) {/** The snapshot carries ordering reserved before its own `tools/list`, so this* first-connect publication is ordered against concurrent replicas exactly as a@@ -169,7 +242,7 @@ export class ConnectionsRepository {* dropped in silence, leaving whatever this server last advertised in place. */if (ordering.orderingUnavailable) {await connection.refreshToolList();- return connection;+ return this.returnExpectedConnection(serverName, connection, expectedGeneration);}await notifyMCPToolsChanged({tools: [],@@ -177,8 +250,9 @@ export class ConnectionsRepository {serverConfig,publicationGeneration,publicationRevision: ordering.publicationRevision,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});- return connection;+ return this.returnExpectedConnection(serverName, connection, expectedGeneration);}const initialGeneration = toolsChangedGeneration;const snapshot = await connection.fetchToolsSnapshot();@@ -192,13 +266,14 @@ export class ConnectionsRepository {serverConfig,publicationGeneration,publicationRevision: snapshot.publicationRevision,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});}} else {await connection.refreshToolList();}}- return connection;+ return this.returnExpectedConnection(serverName, connection, expectedGeneration);}/** Gets or creates connections for multiple servers concurrently */@@ -248,17 +323,26 @@ export class ConnectionsRepository {private async disconnectConnection(serverName: string): Promise<void> {const connection = this.connections.get(serverName);if (!connection) {- await cancelMCPToolsChanged({ userId: this.ownerId, serverName });+ await cancelMCPToolsChanged({+ userId: this.ownerId,+ serverName,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ });return;}this.connections.delete(serverName);+ this.connectionConfigGenerations.delete(serverName);try {connection.removeAllListeners?.('toolsChanged');await connection.dispose();} catch {logger.error(`${this.prefix()} Error disposing`);} finally {- await cancelMCPToolsChanged({ userId: this.ownerId, serverName });+ await cancelMCPToolsChanged({+ userId: this.ownerId,+ serverName,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ });}}diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.tsindex 3f6006fa39..0ea25b29a2 100644--- a/packages/api/src/mcp/MCPConnectionFactory.ts+++ b/packages/api/src/mcp/MCPConnectionFactory.ts@@ -93,6 +93,7 @@ export class MCPConnectionFactory {protected readonly allowedAddresses?: string[] | null;protected readonly ephemeralConnection: boolean;protected readonly directBearerRecoveryEnabled: boolean;+ protected readonly capabilityProfile: t.BasicConnectionOptions['capabilityProfile'];// OAuth-related properties (only set when useOAuth is true)protected readonly userId?: string;@@ -420,6 +421,7 @@ export class MCPConnectionFactory {useSSRFProtection: this.useSSRFProtection,allowedAddresses: this.allowedAddresses,ephemeralConnection: this.ephemeralConnection,+ ...(this.capabilityProfile && { capabilityProfile: this.capabilityProfile }),...(this.directBearerRecoveryEnabled && { directBearerRecoveryEnabled: true }),});@@ -579,6 +581,7 @@ export class MCPConnectionFactory {useSSRFProtection: this.useSSRFProtection,allowedAddresses: this.allowedAddresses,ephemeralConnection: this.ephemeralConnection,+ ...(this.capabilityProfile && { capabilityProfile: this.capabilityProfile }),});unauthConnection.on('oauthRequired', () => {@@ -630,6 +633,7 @@ export class MCPConnectionFactory {this.directBearerRecoveryEnabled = isDirectOpenIDBearerRecoveryEnabled(basic.directBearerSourceConfig ?? basic.serverConfig,);+ this.capabilityProfile = basic.capabilityProfile;this.connectionTimeout = options?.connectionTimeout;this.deadlineMs = options?.deadlineMs;this.onOAuthCredentialsChanged = options?.onOAuthCredentialsChanged;@@ -643,12 +647,12 @@ export class MCPConnectionFactory {this.logPrefix = options?.user ? `[MCP][User: ${options.user.id}]` : '[MCP]';this.user = options?.user;+ this.userId = options?.user?.id;this.upstreamTokenProvider = options?.upstreamTokenProvider;this.upstreamTokenProviderResolver = options?.upstreamTokenProviderResolver;if (options != null && 'useOAuth' in options) {this.useOAuth = true;- this.userId = options.user?.id;this.flowManager = options.flowManager;this.tokenMethods = options.tokenMethods;this.oauthStart = options.oauthStart;@@ -772,6 +776,7 @@ export class MCPConnectionFactory {useSSRFProtection: this.useSSRFProtection,allowedAddresses: this.allowedAddresses,ephemeralConnection: this.ephemeralConnection,+ ...(this.capabilityProfile && { capabilityProfile: this.capabilityProfile }),...(this.directBearerRecoveryEnabled && {directBearerRecoveryEnabled: true,}),diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex 54c17f73e0..a96710bf39 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -1,15 +1,18 @@import pick from 'lodash/pick';import { logger } from '@librechat/data-schemas';-import { Permissions, PermissionTypes } from 'librechat-data-provider';import { CallToolResultSchema, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';+import { Permissions, PermissionTypes, DEFAULT_MCP_APPS_POLICY } from 'librechat-data-provider';import type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';import type { TokenMethods, IUser } from '@librechat/data-schemas';+import type { TMCPAppsPolicy } from 'librechat-data-provider';import type {OboTokenResolver,OboTrustChecker,UpstreamTokenProvider,UpstreamTokenProviderResolver,} from '~/mcp/oauth/obo';+import type { MCPAppOperationContext, MCPAppValidationContext } from './apps';+import type { MCPClientCapabilityProfile } from './capabilities';import type { AuthIdentityContext } from '~/utils/identity';import type { GraphTokenResolver } from '~/utils/graph';import type { FlowStateManager } from '~/flow/manager';@@ -26,15 +29,32 @@ import {isUserSourced,requiresEphemeralUserConnection,requiresOAuthMachinery,+ requiresUserScopedConnection,resolveServerInstructions,} from './utils';+import {+ getMCPConnectionPoolKey,+ getMCPUserConnectionPoolKey,+ MCP_APPS_CAPABILITY_PROFILE,+ resolveMCPClientCapabilityProfile,+ STANDARD_MCP_CAPABILITY_PROFILE,+} from './capabilities';+import {+ projectMCPAppRuntimeTarget,+ type MCPAppBindingCodec,+ type MCPAppBindingSubject,+ type MCPAppRuntimeTarget,+} from './apps/binding';import { getMCPAppToolsPublicationGeneration, getMCPToolsChangedGeneration } from './toolsChanged';+import { mcpOptionsContainGraphTokenPlaceholder, preProcessGraphTokens } from '~/utils/graph';import { MCPAuthenticationRejectedError, isMCPTransportAuthenticationError } from './errors';import { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from './openid';import { createLazyOboUpstreamTokenProvider, awaitOboOperation } from '~/mcp/oauth/obo';+import { formatToolContent, selectResolvedAppResource } from './parsers';import { MCPServersInitializer } from './registry/MCPServersInitializer';import { OboTokenResolutionError, resolveOboToken } from '~/mcp/oauth';import { MCPServerCatalogRecoveryTracker } from './catalog/recovery';+import { getToolUiResourceUri, isToolHiddenFromApp } from './apps';import { MCPServerInspector } from './registry/MCPServerInspector';import { MCPServersRegistry } from './registry/MCPServersRegistry';import { UserConnectionManager } from './UserConnectionManager';@@ -42,10 +62,7 @@ import { ConnectionsRepository } from './ConnectionsRepository';import { MCPConnectionFactory } from './MCPConnectionFactory';import { processMCPEnv, isPluginSourced } from '~/utils/env';import { OAuthLifecycleRelay } from './oauth/pending';-import { preProcessGraphTokens } from '~/utils/graph';import { isOwnedAbortError } from '~/utils/errors';-import { withMCPRequestSignal } from './signal';-import { formatToolContent } from './parsers';import { MCPConnection } from './connection';import { mcpConfig } from './mcpConfig';@@ -123,6 +140,7 @@ export class MCPManager extends UserConnectionManager {constructor(catalogRecoveryMaxStateEntries?: number,catalogRecoveryMaxDetachedDiscoveries?: number,+ private readonly appBindingCodec: MCPAppBindingCodec | undefined = undefined,) {super();this.catalogRecoveryTracker = new MCPServerCatalogRecoveryTracker(@@ -131,18 +149,30 @@ export class MCPManager extends UserConnectionManager {);}+ private readonly resourceUriCache = new Map<string, Map<string, { uri: string }>>();++ private readonly appHiddenToolCache = new Map<string, Set<string>>();+ private readonly knownToolNamesCache = new Map<string, Set<string>>();+ /**+ * Stamp of the connection each cache entry was built from, to detect reconnects (createdAt) and+ * live tools/list_changed notifications (toolListVersion) that createdAt alone would miss.+ */+ private readonly toolCacheConnStamp = new Map<string, string>();+/** Creates and initializes the singleton MCPManager instance */public static async createInstance(configs: t.MCPServers,options?: {catalogRecoveryMaxStateEntries?: number;catalogRecoveryMaxDetachedDiscoveries?: number;+ appBindingCodec?: MCPAppBindingCodec;},): Promise<MCPManager> {if (MCPManager.instance) throw new Error('MCPManager has already been initialized.');MCPManager.instance = new MCPManager(options?.catalogRecoveryMaxStateEntries,options?.catalogRecoveryMaxDetachedDiscoveries,+ options?.appBindingCodec,);await MCPManager.instance.initialize(configs);return MCPManager.instance;@@ -164,8 +194,23 @@ export class MCPManager extends UserConnectionManager {return this.catalogRecoveryTracker;}- public clearCatalogRecoveryState(userId: string, serverName?: string, generation?: string): void {- this.catalogRecoveryTracker.clear(userId, serverName, generation);+ /** Returns shared operator sessions only for the standard handshake they negotiated. */+ public async getLoadedAppConnections(+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,+ ): Promise<Map<string, MCPConnection>> {+ if (capabilityProfile !== STANDARD_MCP_CAPABILITY_PROFILE) {+ return new Map();+ }+ return (await this.appConnections?.getLoaded()) ?? new Map();+ }++ public clearCatalogRecoveryState(+ userId: string,+ serverName?: string,+ generation?: string,+ capabilityProfile?: MCPClientCapabilityProfile,+ ): void {+ this.catalogRecoveryTracker.clear(userId, serverName, generation, capabilityProfile);}public override async disconnectUserConnection(@@ -174,30 +219,59 @@ export class MCPManager extends UserConnectionManager {options?: Parameters<UserConnectionManager['disconnectUserConnection']>[2],): Promise<void> {if ((options?.reason ?? 'mutation') === 'mutation') {- this.clearCatalogRecoveryState(userId, serverName);+ this.clearCatalogRecoveryState(userId, serverName, undefined, options?.capabilityProfile);}await super.disconnectUserConnection(userId, serverName, options);}- public override async getUserConnection(+ public override getUserConnection(opts: t.UserMCPConnectionOptions): Promise<MCPConnection> {+ const connectionTarget = this.getSuppliedConnectionTarget(opts);+ if (connectionTarget) {+ return this.getManagedUserConnection(opts, connectionTarget);+ }+ return this.resolveConnectionTarget(opts).then((resolvedTarget) => {+ opts.signal?.throwIfAborted();+ if (!resolvedTarget) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `[MCP] Configuration for server "${opts.serverName}" not found.`,+ );+ }+ return this.getManagedUserConnection(opts, resolvedTarget);+ });+ }++ private async getManagedUserConnection(opts: t.UserMCPConnectionOptions,+ connectionTarget: t.MCPConnectionTarget,): Promise<MCPConnection> {+ const resolvedOpts = {+ ...opts,+ serverConfig: undefined,+ connectionTarget,+ } as t.UserMCPConnectionOptions;const userId = opts.user?.id;if (opts.forceNew || opts.ephemeralConnection || !userId) {- return super.getUserConnection(opts);+ return super.getUserConnection(resolvedOpts);}- const connectionKey = `${userId}:${opts.serverName}`;+ const capabilityProfile = opts.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;+ const connectionKey = getMCPUserConnectionPoolKey(userId, opts.serverName, capabilityProfile);const requestConnection = opts.requestScopedConnections?.connections.get(connectionKey) as| MCPConnection| undefined;- const connection = requestConnection ?? this.userConnections.get(userId)?.get(opts.serverName);+ const connection =+ requestConnection ??+ this.userConnections+ .get(userId)+ ?.get(getMCPConnectionPoolKey(opts.serverName, capabilityProfile));const recovery = connection ? this.oauthRecoveries.get(connection) : undefined;- const providedConfigIsNewer =- connection != null &&- opts.serverConfig?.updatedAt != null &&- connection.isStale(opts.serverConfig.updatedAt);- if (recovery && !providedConfigIsNewer) {+ const requestedConfigGeneration = getMCPAppToolsPublicationGeneration(+ connectionTarget.serverConfig,+ );+ const connectionMatchesTarget =+ connection == null || this.getToolConfigGeneration(connection) === requestedConfigGeneration;+ if (recovery && connectionMatchesTarget) {if (recovery.directBearerRecoveryConsumed && opts.directBearerRecoveryState) {opts.directBearerRecoveryState.attempted = true;opts.directBearerRecoveryState.resolvedConfig =@@ -218,7 +292,7 @@ export class MCPManager extends UserConnectionManager {}}- return super.getUserConnection(opts);+ return super.getUserConnection(resolvedOpts);}/** Runs work against a user connection while preventing recovery from replacing its SDK client. */@@ -346,7 +420,30 @@ export class MCPManager extends UserConnectionManager {return true;}- /** Retrieves an app-level or user-specific connection based on provided arguments */+ private async resolveCheckoutTarget(args: {+ serverName: string;+ user?: IUser;+ connectionTarget?: t.MCPConnectionTarget;+ serverConfig?: t.ParsedServerConfig;+ }): Promise<t.MCPConnectionTarget | undefined> {+ if (args.connectionTarget) {+ return args.connectionTarget;+ }+ const registry = MCPServersRegistry.getInstance();+ const resolvedConfig =+ args.serverConfig ?? (await registry.getServerConfig(args.serverName, args.user?.id));+ if (!resolvedConfig) {+ return undefined;+ }+ return {+ serverConfig: resolvedConfig,+ connectionOwner: (await registry.isAppServerConfig(args.serverName, resolvedConfig))+ ? 'operator'+ : 'principal',+ };+ }++ /** Retrieves an app-level or user-specific connection based on provided arguments. */public async getConnection(args: {serverName: string;@@ -354,41 +451,73 @@ export class MCPManager extends UserConnectionManager {forceNew?: boolean;ephemeralConnection?: boolean;flowManager?: FlowStateManager<MCPOAuthTokens | null>;- /** Pre-resolved config for config-source servers not in YAML/DB */+ /** Pre-resolved connection target for callers that already completed policy selection. */+ connectionTarget?: t.MCPConnectionTarget;+ /** Pre-resolved config retained for ordinary callers. */serverConfig?: t.ParsedServerConfig;/** One-shot direct-bearer recovery budget shared with the invoking tool call. */directBearerRecoveryState?: t.DirectBearerRecoveryState;} & Omit<t.OAuthConnectionOptions, 'useOAuth' | 'user' | 'flowManager'>,): Promise<MCPConnection> {const userId = args.user?.id;- const effectiveConfig =- args.serverConfig ??- (userId- ? await MCPServersRegistry.getInstance().getServerConfig(args.serverName, userId)- : undefined);-- if (effectiveConfig && userId && !canUseAppConnection(effectiveConfig)) {+ const capabilityProfile = args.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;+ const connectionTarget = await this.resolveCheckoutTarget(args);+ if (+ connectionTarget &&+ userId &&+ (connectionTarget.connectionOwner === 'principal' ||+ requiresUserScopedConnection(connectionTarget.serverConfig) ||+ capabilityProfile === MCP_APPS_CAPABILITY_PROFILE)+ ) {return this.getUserConnection({...args,- serverConfig: effectiveConfig,+ capabilityProfile,+ serverConfig: undefined,+ connectionTarget,} as Parameters<typeof this.getUserConnection>[0]);}- //the get method checks if the config is still valid as app level- const existingAppConnection = await this.appConnections!.get(args.serverName);- if (existingAppConnection) {- return existingAppConnection;- } else if (userId) {+ if (+ connectionTarget?.connectionOwner === 'operator' &&+ capabilityProfile === STANDARD_MCP_CAPABILITY_PROFILE &&+ canUseAppConnection(connectionTarget.serverConfig)+ ) {+ const appConnection = await this.appConnections!.get(args.serverName, {+ expectedConfig: connectionTarget.serverConfig,+ });+ if (appConnection) {+ return appConnection;+ }+ } else if (connectionTarget && userId) {return this.getUserConnection({...args,- serverConfig: effectiveConfig,- } as Parameters<typeof this.getUserConnection>[0]);- } else {+ serverConfig: undefined,+ connectionTarget,+ } as Parameters<MCPManager['getUserConnection']>[0]);+ }+ throw new McpError(+ ErrorCode.InvalidRequest,+ `No connection found for server ${args.serverName}`,+ );+ }++ /** Checks out a connection together with the exact target used to create or reuse it. */+ private async checkoutConnection(+ args: Parameters<MCPManager['getConnection']>[0],+ ): Promise<{ connection: MCPConnection; connectionTarget: t.MCPConnectionTarget }> {+ const connectionTarget = await this.resolveCheckoutTarget(args);+ if (!connectionTarget) {throw new McpError(ErrorCode.InvalidRequest,`No connection found for server ${args.serverName}`,);}+ const connection = await this.getConnection({+ ...args,+ serverConfig: undefined,+ connectionTarget,+ });+ return { connection, connectionTarget };}/**@@ -398,6 +527,7 @@ export class MCPManager extends UserConnectionManager {*/public async discoverServerTools(args: t.ToolDiscoveryOptions): Promise<t.ToolDiscoveryResult> {const { serverName, user } = args;+ const capabilityProfile = args.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;const registry = MCPServersRegistry.getInstance();const serverConfig = await registry.getServerConfig(serverName, user?.id, args.configServers);@@ -408,6 +538,7 @@ export class MCPManager extends UserConnectionManager {try {const useAppConnection =+ capabilityProfile === STANDARD_MCP_CAPABILITY_PROFILE &&canUseAppConnection(serverConfig) &&(await registry.isAppServerConfig(serverName, serverConfig));const existingAppConnection = useAppConnection@@ -486,6 +617,7 @@ export class MCPManager extends UserConnectionManager {useSSRFProtection,allowedDomains,allowedAddresses,+ capabilityProfile,};const finalizeDiscoveryResult = async (@@ -605,7 +737,11 @@ export class MCPManager extends UserConnectionManager {userId: string,serverName: string,serverConfig?: t.ParsedServerConfig,- options?: { deadlineMs?: number; signal?: AbortSignal },+ options?: {+ deadlineMs?: number;+ signal?: AbortSignal;+ capabilityProfile?: MCPClientCapabilityProfile;+ },): Promise<{tools: t.LCAvailableTools | null;publicationGeneration?: string;@@ -613,6 +749,7 @@ export class MCPManager extends UserConnectionManager {}> {try {const signal = createDeadlineAbortSignal(options?.deadlineMs, options?.signal);+ const capabilityProfile = options?.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;const readToolCatalog = (connection: MCPConnection) =>options == null? MCPServerInspector.getToolCatalog(serverName, connection)@@ -620,6 +757,7 @@ export class MCPManager extends UserConnectionManager {const registry = MCPServersRegistry.getInstance();const effectiveConfig = serverConfig ?? (await registry.getServerConfig(serverName, userId));const useAppConnection =+ capabilityProfile === STANDARD_MCP_CAPABILITY_PROFILE &&effectiveConfig != null &&canUseAppConnection(effectiveConfig) &&(await registry.isAppServerConfig(serverName, effectiveConfig));@@ -632,14 +770,16 @@ export class MCPManager extends UserConnectionManager {let awaitedRecovery: Promise<void> | undefined;while (true) {- const userConnections = this.getUserConnections(userId);- const connection = userConnections?.get(serverName);+ const userConnections = this.userConnections.get(userId);+ const connection = userConnections?.get(+ getMCPConnectionPoolKey(serverName, capabilityProfile),+ );if (!connection) {return { tools: null };}if (effectiveConfig == null) {- await this.disconnectUserConnection(userId, serverName);+ await this.disconnectUserConnection(userId, serverName, { capabilityProfile });return { tools: null };}const connectionConfigGeneration = this.getToolConfigGeneration(connection);@@ -649,7 +789,7 @@ export class MCPManager extends UserConnectionManager {effectiveConfigGeneration != null &&connectionConfigGeneration !== effectiveConfigGeneration) {- await this.disconnectUserConnection(userId, serverName);+ await this.disconnectUserConnection(userId, serverName, { capabilityProfile });return { tools: null };}const publicationGeneration = this.getToolPublicationGeneration(connection);@@ -659,7 +799,7 @@ export class MCPManager extends UserConnectionManager {currentGeneration != null &&publicationGeneration !== currentGeneration) {- await this.disconnectUserConnection(userId, serverName);+ await this.disconnectUserConnection(userId, serverName, { capabilityProfile });return { tools: null };}@@ -680,7 +820,7 @@ export class MCPManager extends UserConnectionManager {generationAfterFetch != null &&publicationGeneration !== generationAfterFetch) {- await this.disconnectUserConnection(userId, serverName);+ await this.disconnectUserConnection(userId, serverName, { capabilityProfile });return { tools: null };}return { tools, publicationGeneration };@@ -899,7 +1039,12 @@ Please follow these instructions when using tools from the respective MCP server});}- const mutationFence = this.createConnectionMutationFence(user.id, serverName);+ const capabilityProfile = connection.capabilityProfile;+ const mutationFence = this.createConnectionMutationFence(+ user.id,+ serverName,+ capabilityProfile,+ );const recoveryController = new AbortController();const recoverySignal = recoveryController.signal;const recovery = Promise.resolve().then(async () => {@@ -917,7 +1062,11 @@ Please follow these instructions when using tools from the respective MCP serverconnection.stopReconnecting();await this.waitForConnectionBorrowersToDrain(connection);recoverySignal.throwIfAborted();- const requestConnectionKey = `${user.id}:${serverName}`;+ const requestConnectionKey = getMCPUserConnectionPoolKey(+ user.id,+ serverName,+ capabilityProfile,+ );if (requestScopedConnections?.connections.get(requestConnectionKey) === connection) {requestScopedConnections.connections.delete(requestConnectionKey);await this.disposeEvictedConnection(@@ -950,6 +1099,7 @@ Please follow these instructions when using tools from the respective MCP serverdirectBearerRecoveryState,directBearerResolvedConfig: refreshedConfig,signal: recoverySignal,+ capabilityProfile,});} finally {mutationFence.release();@@ -1090,6 +1240,151 @@ Please follow these instructions when using tools from the respective MCP server});}+ public clearResourceUriCache(serverName?: string, userId?: string): void {+ if (serverName) {+ for (const key of this.resourceUriCache.keys()) {+ const [keyServerName, keyUserId] = JSON.parse(key) as [string, string | null, string];+ if (keyServerName === serverName && (userId == null || keyUserId === userId)) {+ this.resourceUriCache.delete(key);+ this.appHiddenToolCache.delete(key);+ this.knownToolNamesCache.delete(key);+ this.toolCacheConnStamp.delete(key);+ }+ }+ } else {+ this.resourceUriCache.clear();+ this.appHiddenToolCache.clear();+ this.knownToolNamesCache.clear();+ this.toolCacheConnStamp.clear();+ }+ }++ /**+ * App-level connections can be recreated when a server config changes, so cached tool metadata+ * is only valid while it was built from the current connection instance.+ */+ private connStamp(connection: MCPConnection): string {+ return `${connection.createdAt}:${connection.toolListVersion}`;+ }++ /**+ * Scope for the tool-metadata caches. An app-level connection is shared+ * by every user, and nothing clears its entries (`removeUserConnection` only runs for user-scoped+ * connections), so keying it per user would retain one entry set per user for the process lifetime.+ * User-scoped connections (OAuth/OBO/customUserVars/runtime placeholders) are distinct connections+ * that can expose different tools and different visibility per user, so those keep their per-user+ * key. Decided by connection identity rather than by re-deriving the config's connection scope.+ */+ private cacheScope(serverName: string, connection: MCPConnection, userId?: string): string {+ if (this.appConnections?.getPooledConnection(serverName) === connection) {+ return JSON.stringify([serverName, null, STANDARD_MCP_CAPABILITY_PROFILE]);+ }+ return JSON.stringify([serverName, userId ?? null, connection.capabilityProfile]);+ }++ private isToolCacheFresh(cacheKey: string, connection: MCPConnection): boolean {+ return (+ this.knownToolNamesCache.has(cacheKey) &&+ this.toolCacheConnStamp.get(cacheKey) === this.connStamp(connection)+ );+ }++ protected override removeUserConnection(+ userId: string,+ serverName: string,+ capabilityProfile: MCPClientCapabilityProfile,+ ): void {+ this.clearResourceUriCache(serverName, userId);+ super.removeUserConnection(userId, serverName, capabilityProfile);+ }++ private async buildToolCaches(+ connection: MCPConnection,+ signal?: AbortSignal,+ ): Promise<{+ serverMap: Map<string, { uri: string }>;+ appHidden: Set<string>;+ knownNames: Set<string>;+ complete: boolean;+ connectionStamp: string;+ }> {+ const { tools, complete } = await connection.fetchOrderedToolsSnapshot(undefined, signal);+ const connectionStamp = this.connStamp(connection);+ const serverMap = new Map<string, { uri: string }>();+ const appHidden = new Set<string>();+ const knownNames = new Set<string>();+ for (const tool of tools) {+ knownNames.add(tool.name);+ if (isToolHiddenFromApp(tool)) {+ appHidden.add(tool.name);+ }+ // A malformed `_meta.ui.resourceUri` on one tool only disables that tool's UI metadata,+ // never aborting discovery for the whole server.+ try {+ const uri = getToolUiResourceUri(tool);+ if (uri) {+ serverMap.set(tool.name, { uri });+ }+ } catch (error) {+ logger.warn(`[MCP] Ignoring invalid UI resource metadata on tool "${tool.name}":`, error);+ }+ }+ return { serverMap, appHidden, knownNames, complete, connectionStamp };+ }++ private async populateToolCaches(+ connection: MCPConnection,+ cacheKey: string,+ signal?: AbortSignal,+ ): Promise<void> {+ const { serverMap, appHidden, knownNames, complete, connectionStamp } =+ await this.buildToolCaches(connection, signal);+ // These caches validate app tool calls and associate tools with their declared UI resource, so+ // a page missing from a partial `tools/list` is a false denial rather than a missing feature. An incomplete+ // snapshot (and an empty one, which a transient failure and a genuinely tool-less server both+ // produce) is left unpublished so the next call re-fetches instead of denying until reconnect.+ // A snapshot truncated by a tools/list budget cap reports complete and is cached, for the same+ // reason the advertisement snapshot caches its cap-truncated form: it is reproducible, so+ // re-fetching it on every call pays the full listing cost without widening the result.+ if (!complete || knownNames.size === 0 || connectionStamp !== this.connStamp(connection)) {+ return;+ }+ this.resourceUriCache.set(cacheKey, serverMap);+ this.appHiddenToolCache.set(cacheKey, appHidden);+ this.knownToolNamesCache.set(cacheKey, knownNames);+ this.toolCacheConnStamp.set(cacheKey, connectionStamp);+ }++ private async getResourceMeta(+ connection: MCPConnection,+ serverName: string,+ toolName: string,+ userId?: string,+ requestScoped = false,+ signal?: AbortSignal,+ ): Promise<{ uri: string } | undefined> {+ // Request-scoped servers may expose different tool metadata per request, so their+ // resourceUri/visibility must not be reused from the serverName:userId cache.+ if (requestScoped) {+ const { serverMap, complete, connectionStamp } = await this.buildToolCaches(+ connection,+ signal,+ );+ if (!complete || connectionStamp !== this.connStamp(connection)) {+ return undefined;+ }+ return serverMap.get(toolName);+ }+ const cacheKey = this.cacheScope(serverName, connection, userId);+ if (!this.isToolCacheFresh(cacheKey, connection)) {+ await this.populateToolCaches(connection, cacheKey, signal);+ }+ if (!this.isToolCacheFresh(cacheKey, connection)) {+ return undefined;+ }+ return this.resourceUriCache.get(cacheKey)?.get(toolName);+ }+/*** Calls a tool on an MCP server, using either a user-specific connection* (if userId is provided) or an app-level connection. Updates the last activity timestamp@@ -1122,6 +1417,7 @@ Please follow these instructions when using tools from the respective MCP serveroboIdentityContext,onOAuthCredentialsChanged,onOAuthCredentialsChanging,+ mcpApps,}: {user?: IUser;serverName: string;@@ -1146,8 +1442,10 @@ Please follow these instructions when using tools from the respective MCP serveroboIdentityContext?: AuthIdentityContext;onOAuthCredentialsChanged?: t.UserConnectionContext['onOAuthCredentialsChanged'];onOAuthCredentialsChanging?: t.UserConnectionContext['onOAuthCredentialsChanging'];+ mcpApps?: TMCPAppsPolicy;}): Promise<t.FormattedToolResponse> {const userId = user?.id;+ const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);const logPrefix = userId ? `[MCP][User: ${userId}][${serverName}]` : `[MCP][${serverName}]`;this.bindRequestScopedConnectionStore(requestScopedConnections);let recoveryTakeoverConsumed = false;@@ -1155,6 +1453,7 @@ Please follow these instructions when using tools from the respective MCP serverwhile (true) {/** User-specific connection */let connection: MCPConnection | undefined;+ let checkedOutTarget: t.MCPConnectionTarget | undefined;let connectionRetained = false;let deferredDisposalHeld = false;let attachSharedOAuthHandler: ((relay: OAuthLifecycleRelay) => () => void) | undefined;@@ -1197,7 +1496,7 @@ Please follow these instructions when using tools from the respective MCP servertry {let awaitedCheckoutRecovery: Promise<void> | undefined;while (true) {- connection = await this.getConnection({+ ({ connection, connectionTarget: checkedOutTarget } = await this.checkoutConnection({serverName,user,flowManager,@@ -1218,7 +1517,8 @@ Please follow these instructions when using tools from the respective MCP serverrequestScopedConnections,serverConfig: providedConfig,directBearerRecoveryState,- });+ capabilityProfile,+ }));retainConnectionLease();const checkoutRecovery = this.oauthRecoveries.get(connection);if (!checkoutRecovery || checkoutRecovery.promise === awaitedCheckoutRecovery) {@@ -1419,6 +1719,7 @@ Please follow these instructions when using tools from the respective MCP serveruseSSRFProtection,allowedDomains,allowedAddresses,+ capabilityProfile,},{useOAuth: true,@@ -1557,6 +1858,8 @@ Please follow these instructions when using tools from the respective MCP server),);+ // Deliberately use `request`: the typed wrapper also enforces the tool's output schema and+ // rejects task-required tools, which would turn a server response into a host-side failure.const requestedCredentialSetId = connection.getOAuthCredentialSetId?.();let result: Awaited<ReturnType<typeof requestTool>>;try {@@ -1652,7 +1955,98 @@ Please follow these instructions when using tools from the respective MCP serverawait this.updateUserLastActivity(userId);}this.checkIdleConnections();- return formatToolContent(result as t.MCPToolCallResponse, provider);+ const toolResult = result as t.MCPToolCallResponse;+ const admittedMCPApps = mcpApps ?? DEFAULT_MCP_APPS_POLICY;++ // The app routes reject OBO, Graph-token, and runtime body-placeholder configs, so do not+ // advertise an app bridge for a tool whose follow-up requests cannot be served.+ const appCompatible =+ !rawConfig ||+ (!rawConfig.obo &&+ !(!isDbSourced && mcpOptionsContainGraphTokenPlaceholder(rawConfig as t.MCPOptions)) &&+ getMissingRuntimeBodyPlaceholderFields(rawConfig).length === 0);++ let resourceMeta: { uri: string } | undefined;+ if (admittedMCPApps.enabled && appCompatible && !options?.signal?.aborted) {+ try {+ resourceMeta = await this.getResourceMeta(+ connection,+ serverName,+ toolName,+ userId,+ requiresEphemeralUserConnection(rawConfig),+ options?.signal,+ );+ } catch {+ /* empty */+ }+ }+ if (options?.signal?.aborted) {+ resourceMeta = undefined;+ } else if (resourceMeta) {+ logger.debug(`[MCP][${serverName}][${toolName}] Found resourceUri: ${resourceMeta.uri}`);+ }++ let resolvedAppResource: t.ResourceContents | undefined;+ if (resourceMeta && !options?.signal?.aborted) {+ const resourceUri = resourceMeta.uri;+ try {+ const readResult = await connection.client.readResource(+ { uri: resourceUri },+ { timeout: connection.timeout, signal: options?.signal },+ );+ if (!options?.signal?.aborted) {+ resolvedAppResource = selectResolvedAppResource(readResult.contents, resourceUri);+ }+ if (!resolvedAppResource) {+ logger.warn(+ `[MCP][${serverName}][${toolName}] App resource "${resourceUri}" did not return usable App content; preserving tool result`,+ );+ resourceMeta = undefined;+ }+ } catch (error) {+ if (!options?.signal?.aborted) {+ logger.warn(+ `[MCP][${serverName}][${toolName}] Could not resolve App resource "${resourceUri}"; preserving tool result`,+ error,+ );+ }+ resourceMeta = undefined;+ }+ }++ const serverBinding =+ resourceMeta && connection && checkedOutTarget && userId && this.appBindingCodec+ ? this.appBindingCodec.create(+ this.getAppBindingSubject(+ serverName,+ userId,+ user?.tenantId,+ checkedOutTarget,+ connection,+ ),+ )+ : undefined;+ if (resourceMeta && !serverBinding) {+ resourceMeta = undefined;+ resolvedAppResource = undefined;+ }++ return formatToolContent(+ toolResult,+ provider,+ appCompatible+ ? {+ serverName,+ toolName,+ resourceUri: resourceMeta?.uri,+ resolvedAppResource,+ serverBinding,+ toolArgs: toolArguments,+ mcpApps: admittedMCPApps,+ }+ : { mcpApps: admittedMCPApps },+ );} catch (error) {if (error instanceof OAuthRecoveryTakeoverRequired) {recoveryTakeoverConsumed = true;@@ -1684,4 +2078,423 @@ Please follow these instructions when using tools from the respective MCP server}}}++ private getAppServerConfig(context: MCPAppValidationContext): t.ParsedServerConfig {+ const { serverName, user, connectionTarget } = context;+ const { serverConfig: config } = connectionTarget;+ const logPrefix = `[MCP][User: ${user.id}][${serverName}]`;+ if (config.obo) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `${logPrefix} Server "${serverName}" requires per-call OBO token resolution which is not supported for app requests.`,+ );+ }+ if (!isUserSourced(config) && mcpOptionsContainGraphTokenPlaceholder(config as t.MCPOptions)) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `${logPrefix} Server "${serverName}" requires Graph API token resolution which is not supported for app requests.`,+ );+ }+ const missingBodyFields = getMissingRuntimeBodyPlaceholderFields(config);+ if (missingBodyFields.length > 0) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `${logPrefix} Server "${serverName}" requires request body field(s) (${missingBodyFields.join(', ')}) that are not available for app requests.`,+ );+ }+ return config;+ }++ /** Runs every View callback through the existing connection lease and direct-bearer recovery owner. */+ private async runAppOperation<TResult>(+ context: MCPAppOperationContext,+ operation: (connection: MCPConnection, options: RequestOptions) => Promise<TResult>,+ ): Promise<TResult> {+ const {+ serverName,+ user,+ connectionTarget,+ customUserVars,+ flowManager,+ tokenMethods,+ upstreamTokenProvider,+ onOAuthCredentialsChanging,+ allowlists,+ } = context;+ const { signal } = context;+ const logPrefix = `[MCP][User: ${user.id}][${serverName}]`;+ const config = this.getAppServerConfig(context);+ const directBearerRecovery = usesDirectOpenIDBearerRecovery(config);+ const directBearerRecoveryState: t.DirectBearerRecoveryState = { attempted: false };+ let oauthRecoveryAttempted = false;+ let recoveryTakeoverConsumed = false;++ while (true) {+ signal?.throwIfAborted();+ let connection: MCPConnection | undefined;+ let retained = false;+ let deferredDisposalHeld = false;+ const release = async (preserveDisposalHold = false) => {+ if (!connection || !retained) {+ return;+ }+ if (deferredDisposalHeld && !preserveDisposalHold) {+ await this.releaseDeferredConnectionDisposal(connection);+ deferredDisposalHeld = false;+ }+ retained = false;+ await this.releaseConnection(connection);+ };+ const retain = () => {+ if (!connection || retained) {+ return;+ }+ this.retainConnection(connection);+ retained = true;+ };+ const waitForRecoveryWithoutLease = async (startRecovery: () => Promise<void>) => {+ const recovery = startRecovery();+ if (!deferredDisposalHeld) {+ this.holdDeferredConnectionDisposal(connection!);+ deferredDisposalHeld = true;+ }+ await release(true);+ try {+ await recovery;+ } finally {+ retain();+ }+ };++ try {+ ({ connection } = await this.checkoutConnection({+ serverName,+ user,+ connectionTarget,+ customUserVars,+ flowManager,+ tokenMethods,+ upstreamTokenProvider,+ onOAuthCredentialsChanging,+ directBearerRecoveryState,+ signal,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ }));+ retain();++ const activeRecovery = this.oauthRecoveries.get(connection);+ if (activeRecovery) {+ if (activeRecovery.directBearerRecoveryConsumed) {+ directBearerRecoveryState.attempted = true;+ }+ await release();+ await this.waitForConnectionRecovery(activeRecovery.promise, signal);+ if (activeRecovery.directBearerRecoveryState) {+ Object.assign(directBearerRecoveryState, activeRecovery.directBearerRecoveryState);+ }+ continue;+ }++ const bearerConfig = await resolveDirectOpenIDBearerConfig({+ config: config as t.MCPOptions,+ upstreamTokenProvider,+ resolvedConfig: directBearerRecoveryState.resolvedConfig,+ signal,+ });+ const currentOptions = processMCPEnv({+ user,+ dbSourced: isUserSourced(config),+ options: bearerConfig,+ customUserVars,+ });+ const headers: Record<string, string> =+ 'headers' in currentOptions ? { ...(currentOptions.headers || {}) } : {};+ connection.setRequestHeaders(headers);+ this.assertAppServerBinding(+ context,+ connection,+ projectMCPAppRuntimeTarget(currentOptions),+ );+ const standardOAuth = isOAuthServer(currentOptions) || connection.usesOAuth();+ const attachSharedOAuthHandler = standardOAuth+ ? (relay: OAuthLifecycleRelay) =>+ MCPConnectionFactory.attachRequestOAuthHandler(+ {+ serverName,+ serverConfig: currentOptions,+ dbSourced: isUserSourced(config),+ skipEnvProcessing: true,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ ...allowlists,+ },+ {+ useOAuth: true,+ user,+ flowManager,+ tokenMethods,+ oauthStart: relay.start,+ oauthEnd: relay.end,+ customUserVars,+ onOAuthCredentialsChanging,+ },+ connection!,+ )+ : undefined;++ const recover = async (error: unknown): Promise<void> => {+ if (directBearerRecoveryState.attempted) {+ throw new MCPAuthenticationRejectedError(serverName, false, error);+ }+ directBearerRecoveryState.attempted = true;+ const recovery = this.recoverDirectOpenIDBearerConnection({+ connection: connection!,+ serverName,+ serverConfig: config,+ user,+ flowManager,+ tokenMethods,+ customUserVars,+ upstreamTokenProvider,+ onOAuthCredentialsChanging,+ signal,+ directBearerRecoveryState,+ });+ await release();+ await recovery;+ };+ const recoverOAuth = async (error: unknown): Promise<void> => {+ if (!attachSharedOAuthHandler) {+ throw new MCPAuthenticationRejectedError(serverName, false, error);+ }+ if (oauthRecoveryAttempted) {+ throw new MCPAuthenticationRejectedError(serverName, true, error);+ }+ oauthRecoveryAttempted = true;+ try {+ await waitForRecoveryWithoutLease(() =>+ this.recoverOAuthConnection(+ connection!,+ error,+ serverName,+ user.id,+ attachSharedOAuthHandler,+ undefined,+ undefined,+ flowManager,+ signal,+ !recoveryTakeoverConsumed,+ ),+ );+ } catch (recoveryError) {+ if (recoveryError instanceof OAuthRecoveryTakeoverRequired) {+ oauthRecoveryAttempted = false;+ throw recoveryError;+ }+ if (signal?.aborted) {+ throw recoveryError;+ }+ logger.warn(`${logPrefix} OAuth recovery failed`, recoveryError);+ throw new MCPAuthenticationRejectedError(serverName, false, error);+ }+ };++ const connected = await connection.isConnected(signal);+ if (!connected) {+ const connectionError = connection.getLastConnectionCheckError();+ if (directBearerRecovery && isMCPTransportAuthenticationError(connectionError)) {+ await recover(connectionError);+ continue;+ }+ if (standardOAuth && connection.isOAuthAuthenticationError(connectionError)) {+ await recoverOAuth(connectionError);+ continue;+ }+ throw new McpError(ErrorCode.InternalError, `${logPrefix} Connection is not active.`);+ }++ let result: TResult;+ try {+ result = await operation(connection, {+ timeout: connection.timeout,+ ...(signal ? { signal } : {}),+ });+ } catch (error) {+ if (directBearerRecovery && isMCPTransportAuthenticationError(error)) {+ await recover(error);+ continue;+ }+ if (standardOAuth && connection.isOAuthAuthenticationError(error)) {+ await recoverOAuth(error);+ continue;+ }+ throw error;+ }++ if ((this.userConnections.get(user.id)?.size ?? 0) > 0) {+ await this.updateUserLastActivity(user.id);+ }+ this.checkIdleConnections();+ return result;+ } catch (error) {+ if (error instanceof OAuthRecoveryTakeoverRequired) {+ recoveryTakeoverConsumed = true;+ continue;+ }+ throw error;+ } finally {+ await release();+ }+ }+ }++ private getAppBindingSubject(+ serverName: string,+ userId: string,+ tenantId: unknown,+ connectionTarget: t.MCPConnectionTarget,+ connection: MCPConnection,+ ): MCPAppBindingSubject {+ return {+ serverName,+ userId,+ tenantId: typeof tenantId === 'string' ? tenantId : null,+ connectionTarget,+ runtimeTarget: connection.getMCPAppRuntimeTarget(),+ };+ }++ private assertAppServerBinding(+ context: MCPAppOperationContext,+ connection: MCPConnection,+ currentRuntimeTarget: MCPAppRuntimeTarget,+ ): void {+ const currentSubject = this.getAppBindingSubject(+ context.serverName,+ context.user.id,+ context.user.tenantId,+ context.connectionTarget,+ connection,+ );+ const currentTargetMatches = this.appBindingCodec?.verify(context.serverBinding, {+ ...currentSubject,+ runtimeTarget: currentRuntimeTarget,+ });+ const connectionMatches = this.appBindingCodec?.verify(context.serverBinding, currentSubject);+ if (!currentTargetMatches || !connectionMatches) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `MCP App binding for server "${context.serverName}" is no longer valid.`,+ );+ }+ }++ async validateAppBinding(context: MCPAppValidationContext): Promise<{ valid: true }> {+ context.signal?.throwIfAborted();+ const config = this.getAppServerConfig(context);+ const currentOptions = processMCPEnv({+ user: context.user,+ dbSourced: isUserSourced(config),+ options: config,+ customUserVars: context.customUserVars,+ });+ const valid = this.appBindingCodec?.verify(context.serverBinding, {+ serverName: context.serverName,+ userId: context.user.id,+ tenantId: typeof context.user.tenantId === 'string' ? context.user.tenantId : null,+ connectionTarget: context.connectionTarget,+ runtimeTarget: projectMCPAppRuntimeTarget(currentOptions),+ });+ if (!valid) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `MCP App binding for server "${context.serverName}" is no longer valid.`,+ );+ }+ context.signal?.throwIfAborted();+ return { valid: true };+ }++ async readResource({+ uri,+ ...context+ }: MCPAppOperationContext & {+ uri: string;+ }): Promise<unknown> {+ // The authenticated server remains the authority for its opaque resource URI. LibreChat does+ // not try to invert URI templates or infer a broader client-side authorization namespace.+ return this.runAppOperation(context, (connection, options) =>+ connection.client.readResource({ uri }, options),+ );+ }++ async listResources({+ cursor,+ ...context+ }: MCPAppOperationContext & {+ cursor?: string;+ }): Promise<unknown> {+ return this.runAppOperation(context, (connection, options) =>+ connection.client.listResources(cursor != null ? { cursor } : {}, options),+ );+ }++ async listResourceTemplates({+ cursor,+ ...context+ }: MCPAppOperationContext & {+ cursor?: string;+ }): Promise<unknown> {+ return this.runAppOperation(context, (connection, options) =>+ connection.client.listResourceTemplates(cursor != null ? { cursor } : {}, options),+ );+ }++ /**+ * Proxies a tool call from an MCP App iframe to the MCP server.+ * Unlike callTool, this is a lightweight proxy without provider formatting.+ */+ async appToolCall({+ serverName,+ toolName,+ toolArguments,+ ...context+ }: MCPAppOperationContext & {+ toolName: string;+ toolArguments: Record<string, unknown>;+ }): Promise<unknown> {+ const userId = context.user.id;+ const logPrefix = `[MCP][User: ${userId}][${serverName}]`;+ return this.runAppOperation({ serverName, ...context }, async (connection, options) => {+ const cacheKey = this.cacheScope(serverName, connection, userId);+ if (!this.isToolCacheFresh(cacheKey, connection)) {+ await this.populateToolCaches(connection, cacheKey, options.signal);+ }+ if (!this.isToolCacheFresh(cacheKey, connection)) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `${logPrefix} Tool catalog for server "${serverName}" is not currently available.`,+ );+ }+ if (!this.knownToolNamesCache.get(cacheKey)?.has(toolName)) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `${logPrefix} Tool "${toolName}" is not available on server "${serverName}".`,+ );+ }+ if (this.appHiddenToolCache.get(cacheKey)?.has(toolName)) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `${logPrefix} Tool "${toolName}" is not available to apps (visibility excludes "app").`,+ );+ }+ return connection.client.request(+ {+ method: 'tools/call',+ params: { name: toolName, arguments: toolArguments },+ },+ CallToolResultSchema,+ { ...options, resetTimeoutOnProgress: true },+ );+ });+ }}diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.tsindex af17aa34d4..bff5fde455 100644--- a/packages/api/src/mcp/UserConnectionManager.ts+++ b/packages/api/src/mcp/UserConnectionManager.ts@@ -1,5 +1,6 @@import { logger } from '@librechat/data-schemas';import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';+import type { MCPClientCapabilityProfile } from './capabilities';import type * as t from './types';import {applyRequestHeaders,@@ -18,6 +19,13 @@ import {notifyMCPToolsChanged,renewMCPToolsChangedGeneration,} from '~/mcp/toolsChanged';+import {+ getMCPConnectionPoolKey,+ parseMCPConnectionPoolKey,+ getMCPUserConnectionPoolKey,+ MCP_APPS_CAPABILITY_PROFILE,+ STANDARD_MCP_CAPABILITY_PROFILE,+} from './capabilities';import { resolveDirectOpenIDBearerConfig, usesDirectOpenIDBearerRecovery } from '~/mcp/openid';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { ConnectionsRepository } from '~/mcp/ConnectionsRepository';@@ -36,9 +44,17 @@ type PendingConnection = {promise: Promise<MCPConnection>;oauth: OAuthLifecycleRelay;directBearerRecoveryState: t.DirectBearerRecoveryState;+ configGeneration: string;signal?: AbortSignal;};+type ResolvedUserMCPConnectionOptions = Omit<+ t.UserMCPConnectionOptions,+ 'connectionTarget' | 'serverConfig'+> & {+ connectionTarget: t.MCPConnectionTarget;+};+/*** Why a connection is being torn down. A `mutation` teardown follows a committed change to the* server config or its credentials, so whatever an in-flight creation resolved before it may be@@ -52,6 +68,8 @@ type ConnectionTeardownOptions = {/** The creation that requested the teardown; it is fenced by its own replacement. */preservedCreation?: ConnectionCreationGuard;reason?: ConnectionTeardownReason;+ /** Limits an internal lifecycle teardown to one negotiated session. */+ capabilityProfile?: MCPClientCapabilityProfile;};type ConnectionCreationGuard = { cancelledBy: ConnectionTeardownReason | null };@@ -74,6 +92,34 @@ class ConnectionCreationCancelledError extends Error {/** Bounds re-establishment so back-to-back teardowns cannot spin a caller forever. */const MAX_TEARDOWN_RESTARTS = 3;+const MCP_CAPABILITY_PROFILES: readonly MCPClientCapabilityProfile[] = [+ STANDARD_MCP_CAPABILITY_PROFILE,+ MCP_APPS_CAPABILITY_PROFILE,+];++function getUserConnectionKey(+ userId: string,+ serverName: string,+ capabilityProfile: MCPClientCapabilityProfile,+): string {+ return getMCPUserConnectionPoolKey(userId, serverName, capabilityProfile);+}++function isUserConnectionKeyForUser(key: string, userId: string): boolean {+ try {+ const parsed = JSON.parse(key) as unknown;+ return (+ Array.isArray(parsed) &&+ parsed.length === 3 &&+ parsed[0] === userId &&+ typeof parsed[1] === 'string' &&+ (parsed[2] === STANDARD_MCP_CAPABILITY_PROFILE || parsed[2] === MCP_APPS_CAPABILITY_PROFILE)+ );+ } catch {+ return false;+ }+}+/*** Abstract base class for managing user-specific MCP connections with lifecycle management.* Only meant to be extended by MCPManager.@@ -84,11 +130,11 @@ const MAX_TEARDOWN_RESTARTS = 3;export abstract class UserConnectionManager {// Connections shared by all users.public appConnections: ConnectionsRepository | null = null;- // Connections per userId -> serverName -> connection+ // Connections per userId -> serverName/capability profile -> connectionprotected userConnections: Map<string, Map<string, MCPConnection>> = new Map();/** Last activity timestamp for users (not per server) */protected userLastActivity: Map<string, number> = new Map();- /** In-flight connection promises keyed by `userId:serverName` — coalesces concurrent attempts */+ /** In-flight connection promises keyed by user, server, and capability profile. */protected pendingConnections: Map<string, PendingConnection> = new Map();/** Recovery state owned by request-scoped promises, which the public store intentionally keeps opaque. */private readonly requestPendingDirectBearerRecoveryStates = new WeakMap<@@ -127,6 +173,42 @@ export abstract class UserConnectionManager {return this.toolConfigGenerations.get(connection);}+ protected getSuppliedConnectionTarget({+ connectionTarget,+ serverConfig,+ }: {+ connectionTarget?: t.MCPConnectionTarget;+ serverConfig?: t.ParsedServerConfig;+ }): t.MCPConnectionTarget | undefined {+ if (connectionTarget) {+ return connectionTarget;+ }+ if (serverConfig) {+ return {+ serverConfig,+ connectionOwner: 'principal',+ };+ }+ return undefined;+ }++ protected async resolveConnectionTarget({+ serverName,+ user,+ }: {+ serverName: string;+ user?: { id?: string };+ }): Promise<t.MCPConnectionTarget | undefined> {+ const config = await MCPServersRegistry.getInstance().getServerConfig(serverName, user?.id);+ if (!config) {+ return undefined;+ }+ return {+ serverConfig: config,+ connectionOwner: 'principal',+ };+ }+private runWithForceNewConnectionQueue<T>(key: string, operation: () => Promise<T>): Promise<T> {const previous = this.forceNewConnectionQueues.get(key) ?? Promise.resolve();const result = previous.then(operation, operation);@@ -175,8 +257,9 @@ export abstract class UserConnectionManager {protected createConnectionMutationFence(userId: string,serverName: string,+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,): ConnectionMutationFence {- const key = `${userId}:${serverName}`;+ const key = getUserConnectionKey(userId, serverName, capabilityProfile);const guard: ConnectionCreationGuard = { cancelledBy: null };this.registerConnectionCreation(key, guard);return {@@ -215,7 +298,8 @@ export abstract class UserConnectionManager {? Math.max(1_000, configuredIdleTimeout / 2): 15 * 60 * 1000;const renewals: Promise<void>[] = [];- for (const [serverName, connection] of userConnections) {+ for (const [poolKey, connection] of userConnections) {+ const { serverName } = parseMCPConnectionPoolKey(poolKey);const publicationGeneration = this.toolPublicationGenerations.get(connection);if (!publicationGeneration) {continue;@@ -280,7 +364,10 @@ export abstract class UserConnectionManager {if (!this.lostToolPublicationLeases.has(connection)) {return;}- await this.disconnectUserConnection(userId, serverName, { preservedCreation: creationGuard });+ await this.disconnectUserConnection(userId, serverName, {+ preservedCreation: creationGuard,+ capabilityProfile: connection.capabilityProfile,+ });throw new Error(`[MCP][User: ${userId}][${serverName}] Publication lease is no longer current`);}@@ -299,7 +386,7 @@ export abstract class UserConnectionManager {* a newer connection later.*/private async createUserConnectionWithLifecycleRestarts(- options: t.UserMCPConnectionOptions,+ options: ResolvedUserMCPConnectionOptions,userId: string,clearCooldown: boolean,creationGuard: ConnectionCreationGuard,@@ -334,17 +421,46 @@ export abstract class UserConnectionManager {}/** Gets or creates a connection for a specific user, coalescing concurrent attempts */- public async getUserConnection(opts: t.UserMCPConnectionOptions): Promise<MCPConnection> {- const { serverName, forceNew, user } = opts;- const directBearerRecoveryState = opts.directBearerRecoveryState ?? { attempted: false };- const userId = user?.id;+ public getUserConnection(inputOpts: t.UserMCPConnectionOptions): Promise<MCPConnection> {+ const userId = inputOpts.user?.id;if (!userId) {- throw new McpError(ErrorCode.InvalidRequest, `[MCP] User object missing id property`);+ return Promise.reject(+ new McpError(ErrorCode.InvalidRequest, `[MCP] User object missing id property`),+ );}+ const connectionTarget = this.getSuppliedConnectionTarget(inputOpts);+ if (connectionTarget) {+ return this.getUserConnectionForTarget(inputOpts, connectionTarget, userId);+ }+ return this.resolveConnectionTarget(inputOpts).then((resolvedTarget) => {+ inputOpts.signal?.throwIfAborted();+ if (!resolvedTarget) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `[MCP] Configuration for server "${inputOpts.serverName}" not found.`,+ );+ }+ return this.getUserConnectionForTarget(inputOpts, resolvedTarget, userId);+ });+ }- const config =- opts.serverConfig ??- (await MCPServersRegistry.getInstance().getServerConfig(serverName, userId));+ private async getUserConnectionForTarget(+ inputOpts: t.UserMCPConnectionOptions,+ connectionTarget: t.MCPConnectionTarget,+ userId: string,+ ): Promise<MCPConnection> {+ const { serverConfig: _serverConfig, ...targetOptions } = inputOpts;+ const opts = {+ ...targetOptions,+ connectionTarget,+ } as ResolvedUserMCPConnectionOptions;+ const { serverName, forceNew } = opts;+ const capabilityProfile = opts.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;+ opts.capabilityProfile = capabilityProfile;+ const directBearerRecoveryState = opts.directBearerRecoveryState ?? { attempted: false };++ const config = connectionTarget.serverConfig;+ const configGeneration = getMCPAppToolsPublicationGeneration(config);const missingBodyFields = config? getMissingRuntimeBodyPlaceholderFields(config, opts.requestBody): [];@@ -365,7 +481,7 @@ export abstract class UserConnectionManager {throw new Error(`[MCP][User: ${userId}] Request-scoped connection context is closed`);}this.bindRequestScopedConnectionStore(requestScopedConnections);- const requestConnectionKey = `${userId}:${serverName}`;+ const requestConnectionKey = getUserConnectionKey(userId, serverName, capabilityProfile);const existing = requestScopedConnections.connections.get(requestConnectionKey) as| MCPConnection| undefined;@@ -428,7 +544,7 @@ export abstract class UserConnectionManager {...opts,forceNew: true,ephemeralConnection: true,- serverConfig: config,+ connectionTarget,directBearerRecoveryState,oauthStart: pendingOAuth.start,oauthEnd: pendingOAuth.end,@@ -476,13 +592,28 @@ export abstract class UserConnectionManager {const forceNewConnection = forceNew || ephemeralConnection;const clearCooldown = forceNew === true;- const lockKey = `${userId}:${serverName}`;+ const lockKey = getUserConnectionKey(userId, serverName, capabilityProfile);if (!forceNewConnection) {const pending = this.pendingConnections.get(lockKey);if (pending) {+ if (pending.configGeneration !== configGeneration) {+ await this.waitForConnectionRecovery(+ pending.promise.then(+ () => undefined,+ () => undefined,+ ),+ opts.signal,+ );+ opts.signal?.throwIfAborted();+ return this.getUserConnection(opts);+ }logger.debug(`[MCP][User: ${userId}] Joining in-flight connection attempt`);- const mutationFence = this.createConnectionMutationFence(userId, serverName);+ const mutationFence = this.createConnectionMutationFence(+ userId,+ serverName,+ capabilityProfile,+ );try {await pending.oauth.add({oauthStart: opts.oauthStart,@@ -536,7 +667,7 @@ export abstract class UserConnectionManager {...opts,forceNew: forceNewConnection,ephemeralConnection,- serverConfig: config,+ connectionTarget,directBearerRecoveryState,oauthStart: pendingOAuth.start,oauthEnd: pendingOAuth.end,@@ -554,6 +685,7 @@ export abstract class UserConnectionManager {promise: connectionPromise,oauth: pendingOAuth,directBearerRecoveryState,+ configGeneration,signal: opts.signal,});}@@ -594,22 +726,21 @@ export abstract class UserConnectionManager {connectionTimeout,graphTokenResolver,ephemeralConnection = false,- serverConfig: providedConfig,+ capabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,+ connectionTarget,directBearerRecoveryState = { attempted: false },directBearerResolvedConfig,- }: t.UserMCPConnectionOptions,+ }: ResolvedUserMCPConnectionOptions,userId: string,clearCooldown: boolean,creationGuard?: ConnectionCreationGuard,): Promise<MCPConnection> {signal?.throwIfAborted();this.assertCreationNotCancelled(creationGuard, userId, serverName);- const declaredConfig =- providedConfig ??- (await MCPServersRegistry.getInstance().getServerConfig(serverName, userId));if (- (!declaredConfig || canUseAppConnection(declaredConfig)) &&- (await this.appConnections!.has(serverName))+ connectionTarget.connectionOwner === 'operator' &&+ canUseAppConnection(connectionTarget.serverConfig) &&+ capabilityProfile !== MCP_APPS_CAPABILITY_PROFILE) {throw new McpError(ErrorCode.InvalidRequest,@@ -617,8 +748,10 @@ export abstract class UserConnectionManager {);}+ const declaredConfig = connectionTarget.serverConfig;/** Resolution uses effective headers; identity and persistence keep the declaration. */- const config = declaredConfig && applyRequestHeaders(declaredConfig);+ const config = applyRequestHeaders(declaredConfig);+ const poolKey = getMCPConnectionPoolKey(serverName, capabilityProfile);/** Capture before resolving credentials/creating the connection. If another replica rotates* the generation while creation is in flight, this connection's publications are fenced. */@@ -627,7 +760,7 @@ export abstract class UserConnectionManager {: await getMCPToolsChangedGeneration({ userId, serverName });const userServerMap = this.userConnections.get(userId);- let connection = userServerMap?.get(serverName);+ let connection = userServerMap?.get(poolKey);if (forceNew && connection && !ephemeralConnection) {logger.info(`[MCP][User: ${userId}][${serverName}] Disposing existing connection before forced replacement`,@@ -635,6 +768,7 @@ export abstract class UserConnectionManager {await this.disconnectUserConnection(userId, serverName, {preservedCreation: creationGuard,reason: 'lifecycle',+ capabilityProfile,});connection = undefined;} else if (forceNew) {@@ -648,23 +782,17 @@ export abstract class UserConnectionManager {const existingPublicationGeneration = connection? this.toolPublicationGenerations.get(connection): undefined;- const configGeneration = declaredConfig- ? getMCPAppToolsPublicationGeneration(declaredConfig)- : undefined;+ const configGeneration = getMCPAppToolsPublicationGeneration(declaredConfig);const existingConfigGeneration = connection? this.toolConfigGenerations.get(connection): undefined;- if (- connection &&- configGeneration &&- existingConfigGeneration &&- configGeneration !== existingConfigGeneration- ) {+ if (connection && existingConfigGeneration && configGeneration !== existingConfigGeneration) {logger.info(`[MCP][User: ${userId}][${serverName}] Config identity changed, disconnecting stale connection`,);await this.disconnectUserConnection(userId, serverName, {preservedCreation: creationGuard,+ capabilityProfile,});connection = undefined;}@@ -679,6 +807,7 @@ export abstract class UserConnectionManager {);await this.disconnectUserConnection(userId, serverName, {preservedCreation: creationGuard,+ capabilityProfile,});connection = undefined;}@@ -698,14 +827,13 @@ export abstract class UserConnectionManager {}connection = undefined; // Force creation of a new connection} else if (connection) {- if (!config || (config.updatedAt && connection.isStale(config.updatedAt))) {- if (config) {- logger.info(- `[MCP][User: ${userId}] Server configuration updated; disconnecting stale connection`,- );- }+ if (declaredConfig.updatedAt && connection.isStale(declaredConfig.updatedAt)) {+ logger.info(+ `[MCP][User: ${userId}] Server configuration updated; disconnecting stale connection`,+ );await this.disconnectUserConnection(userId, serverName, {preservedCreation: creationGuard,+ capabilityProfile,});connection = undefined;} else {@@ -742,19 +870,12 @@ export abstract class UserConnectionManager {await this.disconnectUserConnection(userId, serverName, {preservedCreation: creationGuard,reason: 'lifecycle',+ capabilityProfile,});connection = undefined;}}- // Now check if config exists for new connection creation- if (!config || !declaredConfig) {- throw new McpError(- ErrorCode.InvalidRequest,- `[MCP][User: ${userId}] Configuration for server "${serverName}" not found.`,- );- }-// If no valid connection exists, create a new onelogger.info(`[MCP][User: ${userId}] Establishing new connection`);@@ -804,6 +925,7 @@ export abstract class UserConnectionManager {allowedDomains,allowedAddresses,ephemeralConnection,+ capabilityProfile,};/**@@ -914,6 +1036,7 @@ export abstract class UserConnectionManager {serverConfig: declaredConfig,...(effectiveGeneration && { publicationGeneration: effectiveGeneration }),...(publicationRevision && { publicationRevision }),+ capabilityProfile,});});@@ -966,7 +1089,8 @@ export abstract class UserConnectionManager {connectionTimeout,graphTokenResolver,ephemeralConnection,- serverConfig: declaredConfig,+ capabilityProfile,+ connectionTarget,directBearerRecoveryState,directBearerResolvedConfig: refreshedConfig,},@@ -982,11 +1106,16 @@ export abstract class UserConnectionManager {if (!this.userConnections.has(userId)) {this.userConnections.set(userId, new Map());}- this.userConnections.get(userId)?.set(serverName, connection);+ this.userConnections.get(userId)?.set(poolKey, connection);}logger.info(`[MCP][User: ${userId}][${serverName}] Connection successfully established`);- await this.backfillResolvedInstructions(serverName, declaredConfig, connection, userId);+ if (+ capabilityProfile === STANDARD_MCP_CAPABILITY_PROFILE ||+ connectionTarget.connectionOwner !== 'operator'+ ) {+ await this.backfillResolvedInstructions(serverName, declaredConfig, connection, userId);+ }signal?.throwIfAborted();if (!ephemeralConnection) {await this.updateUserLastActivity(userId);@@ -1003,8 +1132,8 @@ export abstract class UserConnectionManager {logger.error(`[MCP][User: ${userId}] Error during cleanup after failed connection`);});// Ensure cleanup even if connection attempt fails- if (connection && this.userConnections.get(userId)?.get(serverName) === connection) {- this.removeUserConnection(userId, serverName);+ if (connection && this.userConnections.get(userId)?.get(poolKey) === connection) {+ this.removeUserConnection(userId, serverName, capabilityProfile);}throw error; // Re-throw the error to the caller}@@ -1222,16 +1351,34 @@ export abstract class UserConnectionManager {};}- /** Returns all connections for a specific user */- public getUserConnections(userId: string): Map<string, MCPConnection> | undefined {- return this.userConnections.get(userId);+ /** Returns the logical server map for one immutable capability profile. */+ public getUserConnections(+ userId: string,+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,+ ): Map<string, MCPConnection> | undefined {+ const pooledConnections = this.userConnections.get(userId);+ if (!pooledConnections) {+ return undefined;+ }+ const connections = new Map<string, MCPConnection>();+ for (const [poolKey, connection] of pooledConnections) {+ const identity = parseMCPConnectionPoolKey(poolKey);+ if (identity.capabilityProfile === capabilityProfile) {+ connections.set(identity.serverName, connection);+ }+ }+ return connections;}/** Removes a specific user connection entry */- protected removeUserConnection(userId: string, serverName: string): void {+ protected removeUserConnection(+ userId: string,+ serverName: string,+ capabilityProfile: MCPClientCapabilityProfile,+ ): void {const userMap = this.userConnections.get(userId);if (userMap) {- userMap.delete(serverName);+ userMap.delete(getMCPConnectionPoolKey(serverName, capabilityProfile));if (userMap.size === 0) {this.userConnections.delete(userId);// Only remove user activity timestamp if all connections are gone@@ -1367,28 +1514,44 @@ export abstract class UserConnectionManager {public async disconnectUserConnection(userId: string,serverName: string,- { preservedCreation, reason = 'mutation' }: ConnectionTeardownOptions = {},+ { preservedCreation, reason = 'mutation', capabilityProfile }: ConnectionTeardownOptions = {},): Promise<void> {- const pendingKey = `${userId}:${serverName}`;+ if (capabilityProfile == null) {+ await Promise.all(+ MCP_CAPABILITY_PROFILES.map((profile) =>+ this.disconnectUserConnection(userId, serverName, {+ preservedCreation,+ reason,+ capabilityProfile: profile,+ }),+ ),+ );+ return;+ }+ const pendingKey = getUserConnectionKey(userId, serverName, capabilityProfile);const pending = this.pendingConnections.get(pendingKey);this.cancelConnectionCreations(pendingKey, reason, preservedCreation);if (pending && preservedCreation == null) {this.pendingConnections.delete(pendingKey);}const userMap = this.userConnections.get(userId);- const connection = userMap?.get(serverName);+ const connection = userMap?.get(getMCPConnectionPoolKey(serverName, capabilityProfile));const logPrefix = `[MCP][User: ${userId}]`;if (connection) {logger.info(`${logPrefix} Disconnecting server connection`);connection.removeAllListeners?.('toolsChanged');- this.removeUserConnection(userId, serverName);+ this.removeUserConnection(userId, serverName, capabilityProfile);}/*** Started in the same synchronous stretch as the fence: `cancelMCPToolsChanged` drops the* pending publication before it awaits, so a creation re-established while this teardown* is still disposing cannot have its own publication and retry timer cancelled by it.*/- const publicationCancelled = cancelMCPToolsChanged({ userId, serverName });+ const publicationCancelled = cancelMCPToolsChanged({+ userId,+ serverName,+ capabilityProfile,+ });/** Observed here so a rejection cannot surface as unhandled while disposal is awaited. */publicationCancelled.catch(() => undefined);try {@@ -1406,13 +1569,13 @@ export abstract class UserConnectionManager {{ preservedCreation, reason = 'mutation' }: ConnectionTeardownOptions = {},): Promise<void> {for (const key of this.activeConnectionCreations.keys()) {- if (key.startsWith(`${userId}:`)) {+ if (isUserConnectionKeyForUser(key, userId)) {this.cancelConnectionCreations(key, reason, preservedCreation);}}if (preservedCreation == null) {for (const key of this.pendingConnections.keys()) {- if (key.startsWith(`${userId}:`)) {+ if (isUserConnectionKeyForUser(key, userId)) {this.pendingConnections.delete(key);}}@@ -1421,7 +1584,9 @@ export abstract class UserConnectionManager {const disconnectPromises: Promise<void>[] = [];if (userMap) {logger.info(`[MCP][User: ${userId}] Disconnecting all servers...`);- const userServers = Array.from(userMap.keys());+ const userServers = Array.from(+ new Set(Array.from(userMap.keys(), (key) => parseMCPConnectionPoolKey(key).serverName)),+ );for (const serverName of userServers) {disconnectPromises.push(this.disconnectUserConnection(userId, serverName, { preservedCreation, reason }).catch(diff --git a/packages/api/src/mcp/__tests__/ConnectionsRepository.test.ts b/packages/api/src/mcp/__tests__/ConnectionsRepository.test.tsindex a4dbb5d158..bebcfd704b 100644--- a/packages/api/src/mcp/__tests__/ConnectionsRepository.test.ts+++ b/packages/api/src/mcp/__tests__/ConnectionsRepository.test.ts@@ -3,8 +3,9 @@ import type * as t from '~/mcp/types';import {setMCPToolsChangedHandler,setMCPToolsChangedRevisionHandler,- getMCPAppToolsPublicationGeneration,+ getMCPToolCatalogGeneration,} from '~/mcp/toolsChanged';+import { STANDARD_MCP_CAPABILITY_PROFILE } from '~/mcp/capabilities';import { ConnectionsRepository } from '~/mcp/ConnectionsRepository';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';import { MCPConnection } from '~/mcp/connection';@@ -37,10 +38,12 @@ const mockRegistryInstance = {shouldEnableSSRFProtection: mockShouldEnableSSRFProtection,getAllowedDomains: mockGetAllowedDomains,getAllowedAddresses: mockGetAllowedAddresses,+ getMCPAppsPolicy: jest.fn().mockReturnValue({ enabled: true, legacyHtmlEnabled: true }),resolveAllowlists: jest.fn(async () => ({allowedDomains: mockGetAllowedDomains(),allowedAddresses: mockGetAllowedAddresses(),useSSRFProtection: mockShouldEnableSSRFProtection(),+ mcpApps: { enabled: true, legacyHtmlEnabled: true },})),};@@ -143,6 +146,7 @@ describe('ConnectionsRepository', () => {allowedDomains: null,allowedAddresses: null,dbSourced: false,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,},undefined,);@@ -151,6 +155,54 @@ describe('ConnectionsRepository', () => {expect(mockConnection.refreshToolList).not.toHaveBeenCalled();});+ it('creates an operator connection only for the expected current config', async () => {+ const expectedConfig = mockServerConfigs.server1;++ await expect(repository.get('server1', { expectedConfig })).resolves.toBe(mockConnection);++ expect(MCPConnectionFactory.create).toHaveBeenCalledWith(+ expect.objectContaining({ serverConfig: expectedConfig }),+ undefined,+ );+ });++ it('rejects a stale expected config without evicting the current pooled connection', async () => {+ repository['connections'].set('server1', mockConnection);+ const staleConfig = { ...mockServerConfigs.server1, url: 'http://localhost:3999' };++ await expect(repository.get('server1', { expectedConfig: staleConfig })).rejects.toThrow(+ 'changed during connection checkout',+ );++ expect(repository.getPooledConnection('server1')).toBe(mockConnection);+ expect(mockConnection.dispose).not.toHaveBeenCalled();+ });++ it('disposes a new connection when the current config changes before publication', async () => {+ let releaseCreation!: () => void;+ let markCreationStarted!: () => void;+ const creationHeld = new Promise<void>((resolve) => {+ releaseCreation = resolve;+ });+ const creationStarted = new Promise<void>((resolve) => {+ markCreationStarted = resolve;+ });+ (MCPConnectionFactory.create as jest.Mock).mockImplementationOnce(async () => {+ markCreationStarted();+ await creationHeld;+ return mockConnection;+ });++ const load = repository.get('server1', { expectedConfig: mockServerConfigs.server1 });+ await creationStarted;+ mockServerConfigs.server1 = { ...mockServerConfigs.server1, url: 'http://localhost:3999' };+ releaseCreation();++ await expect(load).rejects.toThrow('changed during connection checkout');+ expect(mockConnection.dispose).toHaveBeenCalledTimes(1);+ expect(repository.getPooledConnection('server1')).toBeUndefined();+ });+it('refuses an app connection for a server declaring chat-only headers', async () => {mockServerConfigs.server1 = {...mockServerConfigs.server1,@@ -209,7 +261,7 @@ describe('ConnectionsRepository', () => {expect.objectContaining({serverName: 'server1',tools: [],- publicationGeneration: getMCPAppToolsPublicationGeneration(mockServerConfigs.server1),+ publicationGeneration: getMCPToolCatalogGeneration(mockServerConfigs.server1),}),);expect(loaded).toBe(false);@@ -367,6 +419,7 @@ describe('ConnectionsRepository', () => {allowedDomains: null,allowedAddresses: null,dbSourced: false,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,},undefined,);@@ -410,6 +463,7 @@ describe('ConnectionsRepository', () => {allowedDomains: null,allowedAddresses: null,dbSourced: false,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,},undefined,);diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.tsindex aa0748c383..fb109abd33 100644--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts@@ -636,6 +636,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (const manager = new MCPManager();jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,@@ -724,6 +725,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (const manager = new MCPManager();jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,@@ -814,6 +816,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (const manager = new MCPManager();jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.tsindex c6369c41e5..5ee264ceea 100644--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts@@ -1,9 +1,22 @@import { EventEmitter } from 'events';import { logger } from '@librechat/data-schemas';-import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';+import {+ CallToolResultSchema,+ ReadResourceResultSchema,+ ListResourcesResultSchema,+ ListResourceTemplatesResultSchema,+ McpError,+ ErrorCode,+} from '@modelcontextprotocol/sdk/types.js';import type { IUser } from '@librechat/data-schemas';import type { GraphTokenResolver } from '~/utils/graph';import type * as t from '~/mcp/types';+import {+ getMCPConnectionPoolKey,+ getMCPUserConnectionPoolKey,+ MCP_APPS_CAPABILITY_PROFILE,+ STANDARD_MCP_CAPABILITY_PROFILE,+} from '~/mcp/capabilities';import { OboTokenResolutionError, detectOAuthRequirement, resolveOboToken } from '~/mcp/oauth';import { createMCPRequestContext, cleanupMCPRequestContext } from '~/mcp/request';import { MCPServersInitializer } from '~/mcp/registry/MCPServersInitializer';@@ -53,6 +66,31 @@ jest.mock('~/auth/domain', () => ({isMCPDomainAllowed: jest.fn().mockResolvedValue(true),}));+const fakeClient = (+ request: jest.Mock,+ capabilities: object | null = { resources: {}, tools: {} },+) =>+ ({+ request,+ getServerCapabilities: () => capabilities ?? undefined,+ readResource: (params: unknown, options?: unknown) =>+ request({ method: 'resources/read', params }, ReadResourceResultSchema, options),+ listResources: (params: unknown, options?: unknown) =>+ request(+ { method: 'resources/list', params: params ?? {} },+ ListResourcesResultSchema,+ options,+ ),+ listResourceTemplates: (params: unknown, options?: unknown) =>+ request(+ { method: 'resources/templates/list', params: params ?? {} },+ ListResourceTemplatesResultSchema,+ options,+ ),+ callTool: (params: unknown, resultSchema?: unknown, options?: unknown) =>+ request({ method: 'tools/call', params }, resultSchema ?? CallToolResultSchema, options),+ }) as unknown as MCPConnection['client'];+const mockShouldEnableSSRFProtection = jest.fn().mockReturnValue(false);const mockGetAllowedDomains = jest.fn().mockReturnValue(null);const mockGetAllowedAddresses = jest.fn().mockReturnValue(null);@@ -64,12 +102,14 @@ const mockRegistryInstance = {shouldEnableSSRFProtection: mockShouldEnableSSRFProtection,getAllowedDomains: mockGetAllowedDomains,getAllowedAddresses: mockGetAllowedAddresses,+ getMCPAppsPolicy: jest.fn().mockReturnValue({ enabled: true, legacyHtmlEnabled: true }),// Mirrors the real per-request resolver by reading the base-allowlist mocks above, so// existing tests that override getAllowedDomains/shouldEnableSSRFProtection still apply.resolveAllowlists: jest.fn(async () => ({allowedDomains: mockGetAllowedDomains(),allowedAddresses: mockGetAllowedAddresses(),useSSRFProtection: mockShouldEnableSSRFProtection(),+ mcpApps: { enabled: true, legacyHtmlEnabled: true },})),};@@ -120,6 +160,7 @@ describe('MCPManager', () => {(mockRegistryInstance.getAllowedDomains as jest.Mock).mockReturnValue(null);(mockRegistryInstance.getAllowedAddresses as jest.Mock).mockReturnValue(null);mockProcessMCPEnv.mockImplementation((params) => params.options);+ jest.mocked(graphUtils.preProcessGraphTokens).mockImplementation(async (config) => config);mockIsMCPDomainAllowed.mockResolvedValue(true);mockDetectOAuthRequirement.mockResolvedValue({requiresOAuth: false,@@ -133,6 +174,7 @@ describe('MCPManager', () => {const mock = {has: jest.fn().mockResolvedValue(false),get: jest.fn().mockResolvedValue({} as unknown as MCPConnection),+ getPooledConnection: jest.fn().mockReturnValue(undefined),getAll: jest.fn().mockResolvedValue(new Map()),getMany: jest.fn().mockResolvedValue(new Map()),...appConnectionsConfig,@@ -153,6 +195,22 @@ describe('MCPManager', () => {}describe('getAppToolFunctions', () => {+ it('exposes shared operator sessions only to the standard profile', async () => {+ const loaded = new Map([['shared', {} as MCPConnection]]);+ const getLoaded = jest.fn().mockResolvedValue(loaded);+ mockAppConnections({ getLoaded });++ const manager = await MCPManager.createInstance(newMCPServersConfig());++ await expect(manager.getLoadedAppConnections(STANDARD_MCP_CAPABILITY_PROFILE)).resolves.toBe(+ loaded,+ );+ await expect(manager.getLoadedAppConnections(MCP_APPS_CAPABILITY_PROFILE)).resolves.toEqual(+ new Map(),+ );+ expect(getLoaded).toHaveBeenCalledTimes(1);+ });+it('should return empty object when no servers have tool functions', async () => {(mockRegistryInstance.getAllServerConfigs as jest.Mock).mockResolvedValue({server1: { type: 'stdio', command: 'test', args: [] },@@ -556,7 +614,7 @@ describe('MCPManager', () => {);});- it('should catch synchronous errors from getUserConnections', async () => {+ it('should catch synchronous errors from the profile pool lookup', async () => {(MCPServerInspector.getToolCatalog as jest.Mock) = jest.fn().mockResolvedValue({ tools: {} });mockAppConnections({@@ -565,7 +623,10 @@ describe('MCPManager', () => {const manager = await MCPManager.createInstance(newMCPServersConfig());- const spy = jest.spyOn(manager, 'getUserConnections').mockImplementation(() => {+ const userConnections = (+ manager as unknown as { userConnections: Map<string, Map<string, MCPConnection>> }+ ).userConnections;+ const spy = jest.spyOn(userConnections, 'get').mockImplementation(() => {throw new Error('Failed to get user connections');});@@ -625,7 +686,12 @@ describe('MCPManager', () => {userConnections: Map<string, Map<string, MCPConnection>>;waitForConnectionBorrowersToDrain: (connection: MCPConnection) => Promise<void>;};- lifecycle.userConnections.set(userId, new Map([[serverName, connection]]));+ lifecycle.userConnections.set(+ userId,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );const toolsPromise = manager.getServerToolFunctions(userId, serverName);await new Promise((resolve) => setImmediate(resolve));@@ -663,7 +729,12 @@ describe('MCPManager', () => {>;userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(userId, new Map([[serverName, staleConnection]]));+ internals.userConnections.set(+ userId,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), staleConnection],+ ]),+ );internals.oauthRecoveries.set(staleConnection, {promise: recovery,allowsTakeover: true,@@ -674,7 +745,15 @@ describe('MCPManager', () => {expect(MCPServerInspector.getToolCatalog).not.toHaveBeenCalled();- internals.userConnections.set(userId, new Map([[serverName, recoveredConnection]]));+ internals.userConnections.set(+ userId,+ new Map([+ [+ getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ recoveredConnection,+ ],+ ]),+ );internals.oauthRecoveries.delete(staleConnection);resolveRecovery?.();@@ -734,7 +813,12 @@ describe('MCPManager', () => {const internals = manager as unknown as {userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(userId, new Map([[serverName, overlayConnection]]));+ internals.userConnections.set(+ userId,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), overlayConnection],+ ]),+ );await expect(manager.getServerToolFunctionsSnapshot(userId, serverName, overlayConfig),@@ -754,6 +838,7 @@ describe('MCPManager', () => {function createConnection(): MCPConnection {return {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,isConnected: jest.fn().mockResolvedValue(true),setRequestHeaders: jest.fn(),timeout: 30000,@@ -787,7 +872,15 @@ describe('MCPManager', () => {const activeConnection = createConnection();const replacementConnection = createConnection();const internals = getManagerInternals(manager);- internals.userConnections.set(mockUser.id, new Map([[serverName, replacementConnection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [+ getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ replacementConnection,+ ],+ ]),+ );jest.spyOn(manager, 'getConnection').mockResolvedValue(activeConnection);const updateActivity = jest.spyOn(internals, 'updateUserLastActivity');@@ -917,6 +1010,278 @@ describe('MCPManager', () => {});});+ describe('callTool - declared App document acquisition', () => {+ const user = { id: 'app-user' } as IUser;+ const flowManager = {} as Parameters<MCPManager['callTool']>[0]['flowManager'];+ const serverConfig: t.SSEOptions = {+ type: 'sse',+ url: 'https://api.example.com',+ };+ const resourceUri = 'ui://app';+ const toolResult = {+ content: [+ { type: 'text' as const, text: 'ordinary output' },+ {+ type: 'resource' as const,+ resource: {+ uri: resourceUri,+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>embedded result</p>',+ },+ },+ ],+ structuredContent: { count: 1 },+ _meta: { result: 'meta' },+ isError: false,+ };++ function connectionFor(request: jest.Mock): MCPConnection {+ return {+ createdAt: 1,+ toolListVersion: 0,+ isConnected: jest.fn().mockResolvedValue(true),+ setRequestHeaders: jest.fn(),+ getMCPAppRuntimeTarget: jest.fn(() => ({ type: 'sse', url: serverConfig.url })),+ timeout: 1234,+ fetchOrderedToolsSnapshot: jest.fn().mockResolvedValue({+ tools: [+ {+ name: 'app_tool',+ inputSchema: { type: 'object' },+ _meta: { ui: { resourceUri } },+ },+ ],+ complete: true,+ }),+ client: fakeClient(request),+ } as unknown as MCPConnection;+ }++ async function callWith(+ connection: MCPConnection,+ signal?: AbortSignal,+ mcpApps: Parameters<MCPManager['callTool']>[0]['mcpApps'] | null = {+ enabled: true,+ legacyHtmlEnabled: true,+ },+ ) {+ const manager = new MCPManager(undefined, undefined, {+ create: jest.fn(() => 'binding'),+ verify: jest.fn(() => true),+ });+ jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);+ return manager.callTool({+ user,+ serverName,+ serverConfig,+ toolName: 'app_tool',+ provider: 'openai',+ flowManager,+ options: { signal },+ ...(mcpApps ? { mcpApps } : {}),+ });+ }++ it('reads the exact declared document once and preserves the original result separately', async () => {+ const request = jest.fn(async ({ method }: { method: string }) => {+ if (method === 'tools/call') {+ return toolResult;+ }+ return {+ contents: [+ { uri: 'ui://other', mimeType: 'text/html;profile=mcp-app', text: '<p>other</p>' },+ { uri: resourceUri, mimeType: 'text/plain', text: 'wrong mime' },+ {+ uri: resourceUri,+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>resources/read document</p>',+ _meta: { ui: { csp: { connectDomains: ['https://content.example'] } } },+ },+ ],+ };+ });++ const [, artifacts] = await callWith(connectionFor(request));+ const app = artifacts?.ui_resources?.data?.[0];+ const calls = request.mock.calls as unknown as Array<+ [{ method: string; params?: unknown }, unknown, { timeout?: number }]+ >;++ expect(calls.map(([request]) => request.method)).toEqual(['tools/call', 'resources/read']);+ expect(calls[1][0].params).toEqual({ uri: resourceUri });+ expect(calls[1][2]).toMatchObject({ timeout: 1234 });+ expect(app).toMatchObject({+ uri: resourceUri,+ text: '<p>resources/read document</p>',+ csp: { connectDomains: ['https://content.example'] },+ structuredContent: { count: 1 },+ resultMeta: { result: 'meta' },+ });+ expect(app?.content).toBe(toolResult.content);+ });++ it('keeps canonical tool output without an App artifact when document reading fails', async () => {+ const request = jest.fn(async ({ method }: { method: string }) => {+ if (method === 'tools/call') {+ return toolResult;+ }+ throw new Error('resource unavailable');+ });++ const [text, artifacts] = await callWith(connectionFor(request));++ expect(text).toContain('ordinary output');+ expect(artifacts?.ui_resources).toBeUndefined();+ expect(+ request.mock.calls.filter(([request]) => request.method === 'tools/call'),+ ).toHaveLength(1);+ });++ it('does not read or attach the App when Apps policy denies it', async () => {+ const request = jest.fn().mockResolvedValue(toolResult);+ const connection = connectionFor(request);+ const [, artifacts] = await callWith(connection, undefined, {+ enabled: false,+ legacyHtmlEnabled: false,+ });++ expect(request).toHaveBeenCalledTimes(1);+ expect(connection.fetchOrderedToolsSnapshot).not.toHaveBeenCalled();+ expect(artifacts?.ui_resources).toBeUndefined();+ });++ it('keeps canonical tool output when no Apps policy was admitted', async () => {+ const request = jest.fn().mockResolvedValue(toolResult);+ const connection = connectionFor(request);++ const [text, artifacts] = await callWith(connection, undefined, null);++ expect(text).toContain('ordinary output');+ expect(request).toHaveBeenCalledTimes(1);+ expect(connection.fetchOrderedToolsSnapshot).not.toHaveBeenCalled();+ expect(artifacts?.ui_resources).toBeUndefined();+ });++ it('keeps canonical tool output when the declared resource read is aborted', async () => {+ let readStarted: (() => void) | undefined;+ const started = new Promise<void>((resolve) => {+ readStarted = resolve;+ });+ const request = jest.fn(+ ({ method }: { method: string }, _schema: unknown, options: { signal?: AbortSignal }) => {+ if (method === 'tools/call') {+ return Promise.resolve(toolResult);+ }+ readStarted?.();+ return new Promise((_resolve, reject) => {+ options.signal?.addEventListener('abort', () => reject(options.signal?.reason), {+ once: true,+ });+ });+ },+ );+ const controller = new AbortController();+ const call = callWith(connectionFor(request), controller.signal);+ await started;+ controller.abort(new DOMException('stopped', 'AbortError'));++ await expect(call).resolves.toEqual(+ expect.arrayContaining([expect.stringContaining('ordinary output')]),+ );+ expect(+ request.mock.calls.filter(([request]) => request.method === 'tools/call'),+ ).toHaveLength(1);+ });++ it('keeps canonical tool output when metadata discovery is aborted', async () => {+ let snapshotStarted: (() => void) | undefined;+ const started = new Promise<void>((resolve) => {+ snapshotStarted = resolve;+ });+ const request = jest.fn().mockResolvedValue(toolResult);+ const connection = connectionFor(request);+ (connection.fetchOrderedToolsSnapshot as jest.Mock).mockImplementation(+ (_deadline: unknown, signal?: AbortSignal) => {+ snapshotStarted?.();+ return new Promise((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ });+ },+ );+ const controller = new AbortController();+ const call = callWith(connection, controller.signal);+ await started;+ controller.abort(new DOMException('stopped', 'AbortError'));++ await expect(call).resolves.toEqual(+ expect.arrayContaining([expect.stringContaining('ordinary output')]),+ );+ expect(request).toHaveBeenCalledTimes(1);+ });++ it('does not reuse declared App metadata after an incomplete catalog refresh', async () => {+ const request = jest.fn(async ({ method }: { method: string }) => {+ if (method === 'tools/call') {+ return toolResult;+ }+ return {+ contents: [+ {+ uri: resourceUri,+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>resources/read document</p>',+ },+ ],+ };+ });+ const connection = connectionFor(request);+ const manager = new MCPManager(undefined, undefined, {+ create: jest.fn(() => 'binding'),+ verify: jest.fn(() => true),+ });+ jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);++ const first = await manager.callTool({+ user,+ serverName,+ serverConfig,+ toolName: 'app_tool',+ provider: 'openai',+ flowManager,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+ });+ connection.toolListVersion += 1;+ (connection.fetchOrderedToolsSnapshot as jest.Mock).mockResolvedValueOnce({+ tools: [],+ complete: false,+ });+ const second = await manager.callTool({+ user,+ serverName,+ serverConfig,+ toolName: 'app_tool',+ provider: 'openai',+ flowManager,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },+ });++ expect(first[1]?.ui_resources?.data).toHaveLength(1);+ expect(second[1]?.ui_resources).toBeUndefined();+ expect(request.mock.calls.map(([request]) => (request as { method: string }).method)).toEqual(+ ['tools/call', 'resources/read', 'tools/call'],+ );+ });++ it('uses the admitted policy without a post-call policy read', async () => {+ const request = jest.fn().mockResolvedValue(toolResult);+ mockRegistryInstance.resolveAllowlists.mockClear();++ await callWith(connectionFor(request));++ expect(mockRegistryInstance.resolveAllowlists).not.toHaveBeenCalled();+ });+ });+describe('callTool - Graph Token Integration', () => {const mockUser: Partial<IUser> = {id: 'user-123',@@ -1459,6 +1824,7 @@ describe('MCPManager', () => {function createConnection(request: jest.Mock) {const emitter = new EventEmitter();return Object.assign(emitter, {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,client: { request },connect: jest.fn().mockResolvedValue(undefined),disconnect: jest.fn().mockResolvedValue(undefined),@@ -2089,7 +2455,10 @@ describe('MCPManager', () => {attachOAuthHandler(() => undefined);const manager = await createManager(connection);const requestContext = createMCPRequestContext();- requestContext.connections.set(`${mockUser.id}:${serverName}`, connection);+ requestContext.connections.set(+ getMCPUserConnectionPoolKey(mockUser.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ connection,+ );const toolPromise = callTool(manager, undefined, jest.fn(), requestContext);await new Promise((resolve) => setImmediate(resolve));@@ -2139,7 +2508,12 @@ describe('MCPManager', () => {const internals = manager as unknown as {userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(mockUser.id, new Map([[serverName, connection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );const toolPromise = callTool(manager);await new Promise((resolve) => setImmediate(resolve));@@ -2470,7 +2844,12 @@ describe('MCPManager', () => {>;userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(mockUser.id, new Map([[serverName, connection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );internals.oauthRecoveries.set(connection, { promise: recovery, allowsTakeover: true });const connectionPromise = manager.getUserConnection({@@ -2517,7 +2896,12 @@ describe('MCPManager', () => {>;userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(mockUser.id, new Map([[serverName, connection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );const connectionPromise = manager.getUserConnection({serverName,@@ -2568,7 +2952,12 @@ describe('MCPManager', () => {releaseConnection: (connection: MCPConnection) => Promise<void>;userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(mockUser.id, new Map([[serverName, staleConnection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), staleConnection],+ ]),+ );internals.retainConnection(staleConnection);internals.oauthRecoveries.set(staleConnection, {promise: recovery,@@ -2608,7 +2997,12 @@ describe('MCPManager', () => {>;userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(mockUser.id, new Map([[serverName, connection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );internals.oauthRecoveries.set(connection, { promise: recovery, allowsTakeover: true });const controller = new AbortController();const abortReason = new Error('request aborted');@@ -2650,7 +3044,15 @@ describe('MCPManager', () => {};(manager as unknown as { userConnections: Map<string, Map<string, MCPConnection>> }- ).userConnections.set(mockUser.id, new Map([[serverName, unusableConnection]]));+ ).userConnections.set(+ mockUser.id,+ new Map([+ [+ getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ unusableConnection,+ ],+ ]),+ );lifecycle.retainConnection(unusableConnection);await expect(@@ -2686,7 +3088,15 @@ describe('MCPManager', () => {const manager = await MCPManager.createInstance(newMCPServersConfig());(manager as unknown as { userConnections: Map<string, Map<string, MCPConnection>> }- ).userConnections.set(mockUser.id, new Map([[serverName, unusableConnection]]));+ ).userConnections.set(+ mockUser.id,+ new Map([+ [+ getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ unusableConnection,+ ],+ ]),+ );await expect(manager.getUserConnection({@@ -2712,7 +3122,12 @@ describe('MCPManager', () => {refreshToolList: jest.fn().mockResolvedValue(undefined),} as unknown as MCPConnection;const requestScopedConnections: t.RequestScopedMCPConnectionStore = {- connections: new Map([[`${mockUser.id}:${serverName}`, requestConnection]]),+ connections: new Map([+ [+ getMCPUserConnectionPoolKey(mockUser.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ requestConnection,+ ],+ ]),pending: new Map(),};const bodyScopedConfig: t.ParsedServerConfig = {@@ -2771,7 +3186,12 @@ describe('MCPManager', () => {>;userConnections: Map<string, Map<string, MCPConnection>>;};- internals.userConnections.set(mockUser.id, new Map([[serverName, connection]]));+ internals.userConnections.set(+ mockUser.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );internals.oauthRecoveries.set(connection, { promise: recovery, allowsTakeover: true });await expect(@@ -2898,7 +3318,7 @@ describe('MCPManager', () => {expect(getUserConnectionSpy).toHaveBeenCalledWith(expect.objectContaining({serverName,- serverConfig,+ connectionTarget: { serverConfig, connectionOwner: 'operator' },user: mockUser,}),);@@ -3567,6 +3987,7 @@ describe('MCPManager', () => {finishConnectionCheck = resolve;});const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,isConnected: jest.fn().mockReturnValueOnce(connectionCheck).mockResolvedValue(true),isStale: jest.fn().mockReturnValue(false),} as unknown as MCPConnection;@@ -3590,7 +4011,12 @@ describe('MCPManager', () => {}>;};- internals.userConnections.set(user.id, new Map([[serverName, connection]]));+ internals.userConnections.set(+ user.id,+ new Map([+ [getMCPConnectionPoolKey(serverName, STANDARD_MCP_CAPABILITY_PROFILE), connection],+ ]),+ );const directBearerRecoveryState: t.DirectBearerRecoveryState = { attempted: false };const sharedState: t.DirectBearerRecoveryState = { attempted: true };@@ -3782,6 +4208,7 @@ describe('MCPManager', () => {},};const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,isConnected: jest.fn().mockResolvedValue(true),setRequestHeaders: jest.fn(),stopReconnecting: jest.fn(),@@ -3793,7 +4220,12 @@ describe('MCPManager', () => {isConnected: jest.fn().mockResolvedValue(true),} as unknown as MCPConnection;const requestScopedConnections = {- connections: new Map([[`${user.id}:${serverName}`, connection]]),+ connections: new Map([+ [+ getMCPUserConnectionPoolKey(user.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ connection,+ ],+ ]),pending: new Map(),};const upstreamTokenProvider = jest@@ -3819,7 +4251,10 @@ describe('MCPManager', () => {.spyOn(manager, 'getUserConnection').mockResolvedValueOnce(connection).mockImplementationOnce(async () => {- requestScopedConnections.connections.set(`${user.id}:${serverName}`, replacement);+ requestScopedConnections.connections.set(+ getMCPUserConnectionPoolKey(user.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ replacement,+ );return replacement;});@@ -3843,9 +4278,11 @@ describe('MCPManager', () => {connection,expect.stringContaining('Request-scoped'),);- expect(requestScopedConnections.connections.get(`${user.id}:${serverName}`)).toBe(- replacement,- );+ expect(+ requestScopedConnections.connections.get(+ getMCPUserConnectionPoolKey(user.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ ),+ ).toBe(replacement);expect(connection.client.request).toHaveBeenCalledTimes(1);});@@ -3854,7 +4291,10 @@ describe('MCPManager', () => {async (abortAt) => {const controller = new AbortController();const cancelled = new Error('request stopped');- const connection = { stopReconnecting: jest.fn() } as unknown as MCPConnection;+ const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ stopReconnecting: jest.fn(),+ } as unknown as MCPConnection;const upstreamTokenProvider = jest.fn(async () => {if (abortAt === 'refresh') {controller.abort(cancelled);@@ -3921,7 +4361,10 @@ describe('MCPManager', () => {entered();await gate;};- const connection = { stopReconnecting: jest.fn() } as unknown as MCPConnection;+ const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ stopReconnecting: jest.fn(),+ } as unknown as MCPConnection;const replacement = {} as MCPConnection;const upstreamTokenProvider = jest.fn(async () => {if (stage === 'refresh') {@@ -3983,7 +4426,10 @@ describe('MCPManager', () => {'accounts for a borrower before it can join recovery (joins=%s)',async (joins) => {const manager = await MCPManager.createInstance(newMCPServersConfig());- const connection = { stopReconnecting: jest.fn() } as unknown as MCPConnection;+ const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ stopReconnecting: jest.fn(),+ } as unknown as MCPConnection;const controller = new AbortController();let finish!: () => void;let entered!: () => void;@@ -4032,6 +4478,7 @@ describe('MCPManager', () => {it('fences a delayed direct-bearer replacement when the server config mutates', async () => {const connection = {+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,stopReconnecting: jest.fn(),} as unknown as MCPConnection;let finishRefresh: ((tokens: { access_token: string }) => void) | undefined;@@ -4076,66 +4523,755 @@ describe('MCPManager', () => {});});- describe('getConnection', () => {- const mockUser: Partial<IUser> = {- id: 'user-123',- provider: 'openid',- openidId: 'oidc-sub-456',+ describe('MCP App operations', () => {+ const user = { id: 'user-123', role: 'ADMIN' } as IUser & { id: string };+ const flowManager = {} as Parameters<MCPManager['readResource']>[0]['flowManager'];+ const appBindingCodec = {+ create: jest.fn(() => 'binding'),+ verify: jest.fn(() => true),};+ const createAppManager = (configs: t.MCPServers) =>+ MCPManager.createInstance(configs, { appBindingCodec });+ const defaultOAuthCredentialsChanging = jest.fn(async () => async () => undefined);++ const context = (+ serverName: string,+ config: t.ParsedServerConfig,+ extra: Partial<Parameters<MCPManager['readResource']>[0]> = {},+ ) => ({+ serverName,+ serverBinding: 'binding',+ user,+ connectionTarget: {+ serverConfig: config,+ connectionOwner: config.requiresOAuth ? ('principal' as const) : ('operator' as const),+ },+ allowlists: {+ allowedDomains: null,+ allowedAddresses: null,+ useSSRFProtection: false,+ },+ flowManager,+ onOAuthCredentialsChanging: defaultOAuthCredentialsChanging,+ ...extra,+ });- it('should continue using shared app connections for non-OBO servers', async () => {- const appConnection = {+ const connection = (request: jest.Mock, tools = [{ name: 'do_thing', _meta: {} }]) =>+ ({+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ createdAt: 1,+ toolListVersion: 1,isConnected: jest.fn().mockResolvedValue(true),- } as unknown as MCPConnection;+ getLastConnectionCheckError: jest.fn(),+ isOAuthAuthenticationError: jest.fn((error: { status?: number }) => error?.status === 401),+ usesOAuth: jest.fn().mockReturnValue(false),+ setRequestHeaders: jest.fn(),+ getMCPAppRuntimeTarget: jest.fn(() => ({+ type: 'sse',+ url: 'https://example.com/mcp',+ })),+ fetchOrderedToolsSnapshot: jest.fn().mockResolvedValue({ tools, complete: true }),+ timeout: 30_000,+ client: fakeClient(request),+ }) as unknown as MCPConnection;- const appConnections = {- get: jest.fn().mockResolvedValue(appConnection),- };+ const newOAuthConnection = (request: jest.Mock) =>+ Object.assign(connection(request), {+ isStale: jest.fn().mockReturnValue(false),+ refreshToolList: jest.fn().mockResolvedValue(undefined),+ on: jest.fn(),+ removeAllListeners: jest.fn(),+ dispose: jest.fn().mockResolvedValue(undefined),+ });- const nonOboConfig: t.SSEOptions = {- type: 'sse',- url: 'https://api.example.com',+ const standardOAuthConfig = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ requiresOAuth: true,+ oauth: { client_id: 'client' },+ } as t.ParsedServerConfig;++ const prepareFreshOAuthAppOperation = ({+ request,+ publish,+ renewalCurrent = true,+ }: {+ request: jest.Mock;+ publish: jest.Mock;+ renewalCurrent?: boolean;+ }) => {+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ const appConnection = newOAuthConnection(request);+ const onOAuthCredentialsChanging = jest.fn().mockResolvedValue(publish);+ const generation = jest+ .spyOn(toolsChanged, 'getMCPToolsChangedGeneration')+ .mockResolvedValue('generation-a');+ const renewal = jest+ .spyOn(toolsChanged, 'renewMCPToolsChangedGeneration')+ .mockResolvedValue(renewalCurrent);+ (MCPConnectionFactory.create as jest.Mock).mockImplementation(+ async (_basic: t.BasicConnectionOptions, options: t.OAuthConnectionOptions) => {+ const publishPrepared = await options.onOAuthCredentialsChanging?.({+ userId: user.id,+ serverName: 'srv',+ });+ await publishPrepared?.();+ return appConnection;+ },+ );+ return {+ appConnection,+ onOAuthCredentialsChanging,+ renewal,+ restore: () => {+ generation.mockRestore();+ renewal.mockRestore();+ },};+ };- mockAppConnections(appConnections);- (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(nonOboConfig);+ it.each([+ {+ name: 'OBO',+ config: {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ obo: { audience: 'api://mcp' },+ },+ message: /OBO token resolution/,+ },+ {+ name: 'Graph',+ config: {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_GRAPH_ACCESS_TOKEN}}' },+ },+ message: /Graph API token resolution/,+ },+ {+ name: 'BODY',+ config: {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/{{LIBRECHAT_BODY_CONVERSATIONID}}/mcp',+ },+ message: /request body field/,+ },+ ])(+ 'rejects unsupported $name configuration before connection checkout',+ async ({ config, message }) => {+ const manager = await createAppManager(newMCPServersConfig());+ const getConnection = jest.spyOn(manager, 'getConnection');- const manager = await MCPManager.createInstance(newMCPServersConfig());- const getUserConnectionSpy = jest.spyOn(manager, 'getUserConnection');+ await expect(+ manager.readResource({+ ...context('srv', config as t.ParsedServerConfig),+ uri: 'data://catalog/42',+ }),+ ).rejects.toThrow(message);+ expect(getConnection).not.toHaveBeenCalled();+ },+ );- const connection = await manager.getConnection({- serverName,- user: mockUser as IUser,+ it('uses the supplied authorized server config without another registry lookup', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ } as t.ParsedServerConfig;+ const request = jest.fn().mockResolvedValue({ resources: [] });+ const appConnection = connection(request);+ const manager = await createAppManager(newMCPServersConfig());+ const getConnection = jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);++ await expect(manager.listResources(context('srv', config))).resolves.toEqual({+ resources: [],});- expect(connection).toBe(appConnection);- expect(appConnections.get).toHaveBeenCalledWith(serverName);- expect(getUserConnectionSpy).not.toHaveBeenCalled();+ expect(mockRegistryInstance.getAllServerConfigs).not.toHaveBeenCalled();+ expect(getConnection).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionTarget: { serverConfig: config, connectionOwner: 'operator' },+ }),+ );});- it('keeps a static request-header overlay off its same-named shared app connection', async () => {- const appConnections = {- get: jest.fn(),- has: jest.fn().mockResolvedValue(true),- };- mockAppConnections(appConnections);- const candidate = {- isConnected: jest.fn().mockResolvedValue(true),- refreshToolList: jest.fn().mockResolvedValue({ tools: [], complete: true }),- on: jest.fn(),- } as unknown as MCPConnection;- (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(candidate);- const declared: t.ParsedServerConfig = {- type: 'streamable-http',- url: 'https://api.example.com/mcp',+ it('validates a binding from the supplied target without checking out a connection', async () => {+ const config = {source: 'yaml',- requestHeaders: { 'X-Workspace': 'chat-only' },- };- const manager = await MCPManager.createInstance(newMCPServersConfig());- await expect(- manager.getConnection({- serverName,- user: mockUser as IUser,+ type: 'sse',+ url: 'https://example.com/mcp',+ } as t.ParsedServerConfig;+ const manager = await createAppManager(newMCPServersConfig());+ const getConnection = jest.spyOn(manager, 'getConnection');++ await expect(manager.validateAppBinding(context('srv', config))).resolves.toEqual({+ valid: true,+ });++ expect(getConnection).not.toHaveBeenCalled();+ expect(appBindingCodec.verify).toHaveBeenCalledWith(+ 'binding',+ expect.objectContaining({+ serverName: 'srv',+ userId: user.id,+ connectionTarget: { serverConfig: config, connectionOwner: 'operator' },+ runtimeTarget: { type: 'sse', url: 'https://example.com/mcp' },+ }),+ );+ });++ it('uses the normal checkout path for an existing standard OAuth connection', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ requiresOAuth: true,+ oauth: { client_id: 'client' },+ } as t.ParsedServerConfig;+ const request = jest.fn().mockResolvedValue({ resources: [] });+ const appConnection = connection(request);+ const manager = await createAppManager(newMCPServersConfig());+ const getConnection = jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);+ const onOAuthCredentialsChanging = jest.fn(async () => async () => 'generation-b');++ await manager.listResources(context('srv', config, { onOAuthCredentialsChanging }));++ expect(getConnection).toHaveBeenCalledWith(+ expect.objectContaining({+ user,+ connectionTarget: { serverConfig: config, connectionOwner: 'principal' },+ flowManager,+ onOAuthCredentialsChanging,+ }),+ );+ expect(request).toHaveBeenCalledWith(+ expect.objectContaining({ method: 'resources/list' }),+ ListResourcesResultSchema,+ expect.any(Object),+ );+ });++ it('uses the shared OAuth recovery owner and retries an App operation once', async () => {+ const unauthorized = Object.assign(new Error('Unauthorized'), { status: 401 });+ const request = jest+ .fn()+ .mockRejectedValueOnce(unauthorized)+ .mockResolvedValueOnce({ resources: [] });+ const appConnection = connection(request);+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);+ const recoverOAuth = jest+ .spyOn(+ manager as unknown as {+ recoverOAuthConnection: (...args: unknown[]) => Promise<void>;+ },+ 'recoverOAuthConnection',+ )+ .mockResolvedValue();++ await expect(manager.listResources(context('srv', standardOAuthConfig))).resolves.toEqual({+ resources: [],+ });++ expect(recoverOAuth).toHaveBeenCalledWith(+ appConnection,+ unauthorized,+ 'srv',+ user.id,+ expect.any(Function),+ undefined,+ undefined,+ flowManager,+ undefined,+ true,+ );+ expect(request).toHaveBeenCalledTimes(2);+ });++ it('adopts the authorization generation published by a fresh App OAuth connection', async () => {+ const request = jest.fn().mockResolvedValue({ resources: [] });+ const publish = jest.fn().mockResolvedValue('generation-b');+ const { onOAuthCredentialsChanging, renewal, restore } = prepareFreshOAuthAppOperation({+ request,+ publish,+ });++ try {+ const manager = await createAppManager(newMCPServersConfig());+ await expect(+ manager.listResources(+ context('srv', standardOAuthConfig, { onOAuthCredentialsChanging }),+ ),+ ).resolves.toEqual({ resources: [] });++ expect(onOAuthCredentialsChanging).toHaveBeenCalledWith({+ userId: user.id,+ serverName: 'srv',+ });+ expect(publish).toHaveBeenCalledTimes(1);+ expect(renewal).toHaveBeenCalledWith({+ userId: user.id,+ serverName: 'srv',+ publicationGeneration: 'generation-b',+ });+ expect(request).toHaveBeenCalledTimes(1);+ } finally {+ restore();+ }+ });++ it('does not run an App operation after a foreign rotation fences its fresh OAuth connection', async () => {+ const request = jest.fn();+ const { appConnection, onOAuthCredentialsChanging, restore } = prepareFreshOAuthAppOperation({+ request,+ publish: jest.fn().mockResolvedValue('generation-b'),+ renewalCurrent: false,+ });++ try {+ const manager = await createAppManager(newMCPServersConfig());+ await expect(+ manager.listResources(+ context('srv', standardOAuthConfig, { onOAuthCredentialsChanging }),+ ),+ ).rejects.toThrow('Publication lease is no longer current');++ expect(appConnection.dispose).toHaveBeenCalled();+ expect(request).not.toHaveBeenCalled();+ } finally {+ restore();+ }+ });++ it('does not run an App operation when OAuth authorization publication fails', async () => {+ const request = jest.fn();+ const publicationError = new Error('authorization publication unavailable');+ const { onOAuthCredentialsChanging, restore } = prepareFreshOAuthAppOperation({+ request,+ publish: jest.fn().mockRejectedValue(publicationError),+ });++ try {+ const manager = await createAppManager(newMCPServersConfig());+ await expect(+ manager.listResources(+ context('srv', standardOAuthConfig, { onOAuthCredentialsChanging }),+ ),+ ).rejects.toBe(publicationError);+ expect(request).not.toHaveBeenCalled();+ } finally {+ restore();+ }+ });++ it('forwards an opaque auxiliary URI to the same authenticated server without local template inference', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ } as t.ParsedServerConfig;+ const request = jest.fn().mockResolvedValue({+ contents: [{ uri: 'data://catalog/part%2Fleaf', text: 'leaf' }],+ });+ const appConnection = connection(request);+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);++ await manager.readResource({+ ...context('srv', config),+ uri: 'data://catalog/part%2Fleaf',+ });++ expect(request).toHaveBeenCalledTimes(1);+ expect(request).toHaveBeenCalledWith(+ {+ method: 'resources/read',+ params: { uri: 'data://catalog/part%2Fleaf' },+ },+ ReadResourceResultSchema,+ expect.objectContaining({ timeout: 30_000 }),+ );+ });++ it('binds the authenticated user and role, forwards cancellation, and awaits activity renewal', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ headers: { 'X-User': '{{LIBRECHAT_USER_ID}}' },+ } as t.ParsedServerConfig;+ const request = jest.fn().mockResolvedValue({ resources: [] });+ const appConnection = connection(request);+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);+ const activity = jest+ .spyOn(+ manager as unknown as { updateUserLastActivity: (userId: string) => Promise<void> },+ 'updateUserLastActivity',+ )+ .mockResolvedValue();+ (+ manager as unknown as {+ userConnections: Map<string, Map<string, MCPConnection>>;+ }+ ).userConnections.set(+ user.id,+ new Map([[getMCPConnectionPoolKey('srv', MCP_APPS_CAPABILITY_PROFILE), appConnection]]),+ );+ const signal = new AbortController().signal;++ await manager.listResources({ ...context('srv', config, { signal }), cursor: 'next' });++ expect(manager.getConnection).toHaveBeenCalledWith(+ expect.objectContaining({+ user,+ connectionTarget: { serverConfig: config, connectionOwner: 'operator' },+ signal,+ }),+ );+ expect(request).toHaveBeenCalledWith(+ expect.objectContaining({ method: 'resources/list', params: { cursor: 'next' } }),+ ListResourcesResultSchema,+ expect.objectContaining({ signal }),+ );+ expect(activity).toHaveBeenCalledWith(user.id);+ });++ it('releases the connection lease when an SDK operation fails', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ } as t.ParsedServerConfig;+ const failure = new Error('provider unavailable');+ const appConnection = connection(jest.fn().mockRejectedValue(failure));+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);+ const retain = jest.spyOn(+ manager as unknown as { retainConnection: (value: MCPConnection) => void },+ 'retainConnection',+ );+ const release = jest.spyOn(+ manager as unknown as { releaseConnection: (value: MCPConnection) => Promise<void> },+ 'releaseConnection',+ );++ await expect(+ manager.readResource({ ...context('srv', config), uri: 'data://catalog/42' }),+ ).rejects.toBe(failure);+ expect(retain).toHaveBeenCalledWith(appConnection);+ expect(release).toHaveBeenCalledWith(appConnection);+ });++ it('uses the existing direct OpenID recovery coordinator and retries once after releasing', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.ParsedServerConfig;+ const request = jest+ .fn()+ .mockRejectedValueOnce(Object.assign(new Error('Unauthorized'), { status: 401 }))+ .mockResolvedValueOnce({ resources: [] });+ const appConnection = connection(request);+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);+ const release = jest.spyOn(+ manager as unknown as { releaseConnection: (value: MCPConnection) => Promise<void> },+ 'releaseConnection',+ );+ const recover = jest+ .spyOn(+ manager as unknown as {+ recoverDirectOpenIDBearerConnection: (args: object) => Promise<void>;+ },+ 'recoverDirectOpenIDBearerConnection',+ )+ .mockResolvedValue();+ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'current-token' });++ await manager.listResources({+ ...context('srv', config, { upstreamTokenProvider }),+ });++ expect(recover).toHaveBeenCalledWith(+ expect.objectContaining({+ connection: appConnection,+ serverName: 'srv',+ serverConfig: config,+ user,+ upstreamTokenProvider,+ }),+ );+ expect(release.mock.invocationCallOrder[0]).toBeLessThan(request.mock.invocationCallOrder[1]);+ expect(request).toHaveBeenCalledTimes(2);+ });++ it('reacquires after lifecycle eviction while direct OpenID refresh is in flight', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}' },+ } as t.ParsedServerConfig;+ const stale = Object.assign(+ connection(+ jest.fn().mockRejectedValue(Object.assign(new Error('Unauthorized'), { status: 401 })),+ ),+ {+ dispose: jest.fn().mockResolvedValue(undefined),+ removeAllListeners: jest.fn(),+ stopReconnecting: jest.fn(),+ },+ );+ const replacementRequest = jest.fn().mockResolvedValue({ resources: [] });+ const replacement = connection(replacementRequest);+ const manager = await createAppManager(newMCPServersConfig());+ jest+ .spyOn(manager, 'getConnection')+ .mockResolvedValueOnce(stale)+ .mockResolvedValueOnce(replacement);+ const createReplacement = jest+ .spyOn(manager, 'getUserConnection')+ .mockResolvedValue(replacement);+ (+ manager as unknown as {+ userConnections: Map<string, Map<string, MCPConnection>>;+ }+ ).userConnections.set(+ user.id,+ new Map([[getMCPConnectionPoolKey('srv', MCP_APPS_CAPABILITY_PROFILE), stale]]),+ );+ let refreshStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ refreshStarted = resolve;+ });+ let finishRefresh!: (tokens: { access_token: string }) => void;+ const refresh = new Promise<{ access_token: string }>((resolve) => {+ finishRefresh = resolve;+ });+ const upstreamTokenProvider = jest+ .fn()+ .mockResolvedValueOnce({ access_token: 'stale-token' })+ .mockImplementationOnce(() => {+ refreshStarted();+ return refresh;+ });++ const result = manager.listResources({+ ...context('srv', config, { upstreamTokenProvider }),+ });+ await started;+ await manager.disconnectUserConnection(user.id, 'srv', { reason: 'lifecycle' });+ expect(stale.dispose).toHaveBeenCalledTimes(1);+ finishRefresh({ access_token: 'fresh-token' });++ await expect(result).resolves.toEqual({ resources: [] });+ expect(createReplacement).toHaveBeenCalledWith(+ expect.objectContaining({ forceNew: true, serverName: 'srv', user }),+ );+ expect(replacementRequest).toHaveBeenCalledTimes(1);+ });++ it('enforces app tool visibility and returns the standard raw call result', async () => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ } as t.ParsedServerConfig;+ const visibleRequest = jest.fn().mockResolvedValue({+ content: [{ type: 'text', text: 'done' }],+ });+ const visibleConnection = connection(visibleRequest);+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(visibleConnection);+ const signal = new AbortController().signal;++ await expect(+ manager.appToolCall({+ ...context('srv', config, { signal }),+ toolName: 'do_thing',+ toolArguments: { value: 1 },+ }),+ ).resolves.toEqual({ content: [{ type: 'text', text: 'done' }] });+ expect(visibleConnection.fetchOrderedToolsSnapshot).toHaveBeenCalledWith(undefined, signal);++ (MCPManager as unknown as { instance: null }).instance = null;+ const hiddenRequest = jest.fn();+ const hiddenManager = await createAppManager(newMCPServersConfig());+ jest+ .spyOn(hiddenManager, 'getConnection')+ .mockResolvedValue(+ connection(hiddenRequest, [+ { name: 'do_thing', _meta: { ui: { visibility: ['model'] } } },+ ]),+ );++ await expect(+ hiddenManager.appToolCall({+ ...context('srv', config),+ toolName: 'do_thing',+ toolArguments: {},+ }),+ ).rejects.toMatchObject({ code: ErrorCode.InvalidRequest });+ expect(hiddenRequest).not.toHaveBeenCalled();+ });++ it.each([+ { name: 'incomplete', snapshot: { tools: [], complete: false } },+ { name: 'empty', snapshot: { tools: [], complete: true } },+ ])(+ 'does not authorize an App tool from stale cache after a $name catalog refresh',+ async ({ snapshot }) => {+ const config = {+ source: 'yaml',+ type: 'sse',+ url: 'https://example.com/mcp',+ } as t.ParsedServerConfig;+ const request = jest.fn().mockResolvedValue({ content: [{ type: 'text', text: 'done' }] });+ const appConnection = connection(request);+ const snapshots = appConnection.fetchOrderedToolsSnapshot as jest.Mock;+ const manager = await createAppManager(newMCPServersConfig());+ jest.spyOn(manager, 'getConnection').mockResolvedValue(appConnection);++ await expect(+ manager.appToolCall({+ ...context('srv', config),+ toolName: 'do_thing',+ toolArguments: {},+ }),+ ).resolves.toEqual({ content: [{ type: 'text', text: 'done' }] });++ appConnection.toolListVersion += 1;+ snapshots.mockResolvedValueOnce(snapshot);+ await expect(+ manager.appToolCall({+ ...context('srv', config),+ toolName: 'do_thing',+ toolArguments: {},+ }),+ ).rejects.toMatchObject({ code: ErrorCode.InvalidRequest });++ snapshots.mockResolvedValueOnce({+ tools: [{ name: 'do_thing', _meta: {} }],+ complete: true,+ });+ await expect(+ manager.appToolCall({+ ...context('srv', config),+ toolName: 'do_thing',+ toolArguments: {},+ }),+ ).resolves.toEqual({ content: [{ type: 'text', text: 'done' }] });+ expect(request).toHaveBeenCalledTimes(2);+ },+ );+ });++ describe('getConnection', () => {+ const mockUser: Partial<IUser> = {+ id: 'user-123',+ provider: 'openid',+ openidId: 'oidc-sub-456',+ };++ it('should continue using shared app connections for non-OBO servers', async () => {+ const appConnection = {+ isConnected: jest.fn().mockResolvedValue(true),+ } as unknown as MCPConnection;++ const appConnections = {+ get: jest.fn().mockResolvedValue(appConnection),+ };++ const nonOboConfig: t.SSEOptions = {+ type: 'sse',+ url: 'https://api.example.com',+ };++ mockAppConnections(appConnections);+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(nonOboConfig);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnectionSpy = jest.spyOn(manager, 'getUserConnection');++ const connection = await manager.getConnection({+ serverName,+ user: mockUser as IUser,+ });++ expect(connection).toBe(appConnection);+ expect(appConnections.get).toHaveBeenCalledWith(serverName, {+ expectedConfig: nonOboConfig,+ });+ expect(getUserConnectionSpy).not.toHaveBeenCalled();+ });++ it('uses a profile-separated user session for Apps on an operator server', async () => {+ const appConnections = {+ get: jest.fn().mockResolvedValue({} as MCPConnection),+ };+ const userConnection = {} as MCPConnection;+ const operatorConfig: t.SSEOptions = {+ type: 'sse',+ url: 'https://api.example.com',+ };+ mockAppConnections(appConnections);+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(operatorConfig);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnectionSpy = jest+ .spyOn(manager, 'getUserConnection')+ .mockResolvedValue(userConnection);++ await expect(+ manager.getConnection({+ serverName,+ user: mockUser as IUser,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ }),+ ).resolves.toBe(userConnection);+ expect(appConnections.get).not.toHaveBeenCalled();+ expect(getUserConnectionSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ connectionTarget: {+ serverConfig: operatorConfig,+ connectionOwner: 'operator',+ },+ }),+ );+ });++ it('keeps a static request-header overlay off its same-named shared app connection', async () => {+ const appConnections = {+ get: jest.fn(),+ has: jest.fn().mockResolvedValue(true),+ };+ mockAppConnections(appConnections);+ const candidate = {+ isConnected: jest.fn().mockResolvedValue(true),+ refreshToolList: jest.fn().mockResolvedValue({ tools: [], complete: true }),+ on: jest.fn(),+ } as unknown as MCPConnection;+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(candidate);+ const declared: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://api.example.com/mcp',+ source: 'yaml',+ requestHeaders: { 'X-Workspace': 'chat-only' },+ };+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ await expect(+ manager.getConnection({+ serverName,+ user: mockUser as IUser,serverConfig: declared,}),).resolves.toBe(candidate);@@ -4187,11 +5323,50 @@ describe('MCPManager', () => {expect(getUserConnectionSpy).toHaveBeenCalledWith(expect.objectContaining({serverName,- serverConfig: runtimeHeaderConfig,+ connectionTarget: {+ serverConfig: runtimeHeaderConfig,+ connectionOwner: 'operator',+ },user: mockUser,}),);});++ it('uses the admitted principal target when it shadows an operator server name', async () => {+ const principalConfig = {+ type: 'sse',+ url: 'https://principal.example.com',+ source: 'config',+ } as t.ParsedServerConfig;+ const userConnection = {} as MCPConnection;+ const appConnections = { get: jest.fn() };+ mockAppConnections(appConnections);+ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const getUserConnection = jest+ .spyOn(manager, 'getUserConnection')+ .mockResolvedValue(userConnection);++ await expect(+ manager.getConnection({+ serverName,+ user: mockUser as IUser,+ connectionTarget: {+ serverConfig: principalConfig,+ connectionOwner: 'principal',+ },+ }),+ ).resolves.toBe(userConnection);++ expect(appConnections.get).not.toHaveBeenCalled();+ expect(getUserConnection).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionTarget: {+ serverConfig: principalConfig,+ connectionOwner: 'principal',+ },+ }),+ );+ });});describe('discoverServerTools', () => {@@ -4657,6 +5832,75 @@ describe('MCPManager', () => {dispose: jest.fn().mockResolvedValue(undefined),}) as unknown as MCPConnection;+ it('keeps concurrent standard and Apps sessions distinct and disconnects both', async () => {+ const serverConfig: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ startup: false,+ };+ const created = new Map<string, MCPConnection>();+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(serverConfig);+ (mockRegistryInstance.isAppServerConfig as jest.Mock).mockResolvedValue(false);+ (MCPConnectionFactory.create as jest.Mock).mockImplementation(+ async (basic: t.BasicConnectionOptions) => {+ const capabilityProfile = basic.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;+ const connection = Object.assign(newUserConnection(), {+ serverName,+ capabilityProfile,+ });+ created.set(capabilityProfile, connection);+ return connection;+ },+ );++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const [standard, apps] = await Promise.all([+ manager.getConnection({+ serverName,+ user: mockUser,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ }),+ manager.getConnection({+ serverName,+ user: mockUser,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ }),+ ]);++ expect(standard).toBe(created.get(STANDARD_MCP_CAPABILITY_PROFILE));+ expect(apps).toBe(created.get(MCP_APPS_CAPABILITY_PROFILE));+ expect(standard).not.toBe(apps);+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(2);+ expect(manager.getUserConnections(userId)?.get(serverName)).toBe(standard);+ expect(manager.getUserConnections(userId, MCP_APPS_CAPABILITY_PROFILE)?.get(serverName)).toBe(+ apps,+ );++ await expect(+ manager.getConnection({+ serverName,+ user: mockUser,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ }),+ ).resolves.toBe(standard);+ await expect(+ manager.getConnection({+ serverName,+ user: mockUser,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ }),+ ).resolves.toBe(apps);+ expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(2);++ await manager.disconnectUserConnection(userId, serverName);++ expect(standard.dispose).toHaveBeenCalledTimes(1);+ expect(apps.dispose).toHaveBeenCalledTimes(1);+ expect(manager.getUserConnections(userId)).toBeUndefined();+ });+/** An OAuth server whose connection build refreshes credentials, fencing the catalog mid-build. */const refreshingOAuthServer = () => {const connection = newUserConnection();@@ -4805,6 +6049,7 @@ describe('MCPManager', () => {userId,serverName,serverConfig,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});} finally {notifySpy.mockRestore();@@ -5137,6 +6382,52 @@ describe('MCPManager', () => {expect(connection.dispose).toHaveBeenCalledTimes(1);});+ it.each(['serverConfig', 'connectionTarget'] as const)(+ 'registers a forced creation synchronously for a supplied %s',+ async (targetKind) => {+ const config: t.ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'user',+ dbId: 'server-1',+ };+ const connection = newUserConnection();+ mockAppConnections({ has: jest.fn().mockResolvedValue(false) });+ (MCPConnectionFactory.create as jest.Mock).mockResolvedValue(connection);++ const manager = await MCPManager.createInstance(newMCPServersConfig());+ const target =+ targetKind === 'serverConfig'+ ? { serverConfig: config }+ : {+ connectionTarget: {+ serverConfig: config,+ connectionOwner: 'principal' as const,+ },+ };+ const creation = manager.getUserConnection({+ serverName,+ user: mockUser,+ forceNew: true,+ ...target,+ });+ const activeCreations = (+ manager as unknown as {+ activeConnectionCreations: Map<string, Set<unknown>>;+ }+ ).activeConnectionCreations;++ const poolKey = getMCPUserConnectionPoolKey(+ userId,+ serverName,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );+ expect(activeCreations.get(poolKey)?.size).toBe(1);+ await expect(creation).resolves.toBe(connection);+ expect(activeCreations.has(poolKey)).toBe(false);+ },+ );+it.each([false, true])('cancels and disposes a pending connection during mutation teardown (forceNew=%s)',async (forceNew) => {@@ -5406,7 +6697,17 @@ describe('MCPManager', () => {/** A creation re-established while disposal is still awaited publishes its own catalog;* a cancellation issued after that point would drop the replacement's pending change. */- expect(cancelSpy).toHaveBeenCalledWith({ userId, serverName });+ expect(cancelSpy).toHaveBeenNthCalledWith(1, {+ userId,+ serverName,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ });+ expect(cancelSpy).toHaveBeenNthCalledWith(2, {+ userId,+ serverName,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ });+ expect(cancelSpy).toHaveBeenCalledTimes(2);expect(cancelSpy.mock.invocationCallOrder[0]).toBeLessThan((connection.dispose as jest.Mock).mock.invocationCallOrder[0],);@@ -5423,7 +6724,28 @@ describe('MCPManager', () => {expect(clearRecoveryState).not.toHaveBeenCalled();await manager.disconnectUserConnection(userId, serverName);- expect(clearRecoveryState).toHaveBeenCalledWith(userId, serverName, undefined);+ expect(clearRecoveryState).toHaveBeenNthCalledWith(+ 1,+ userId,+ serverName,+ undefined,+ undefined,+ );+ expect(clearRecoveryState).toHaveBeenNthCalledWith(+ 2,+ userId,+ serverName,+ undefined,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );+ expect(clearRecoveryState).toHaveBeenNthCalledWith(+ 3,+ userId,+ serverName,+ undefined,+ MCP_APPS_CAPABILITY_PROFILE,+ );+ expect(clearRecoveryState).toHaveBeenCalledTimes(3);});it('fails a creation that a lifecycle teardown keeps cancelling on every attempt', async () => {@@ -5639,6 +6961,7 @@ describe('MCPManager', () => {serverName,serverConfig,publicationGeneration: 'generation-a',+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});} finally {generationSpy.mockRestore();@@ -6366,7 +7689,11 @@ describe('MCPManager', () => {).toBe(probe);expect(await manager.getUserConnection({ serverName, user: mockUser })).toBe(live);expect(live.disconnect).not.toHaveBeenCalled();- expect(requestScopedConnections.connections.get(`${mockUser.id}:${serverName}`)).toBe(probe);+ expect(+ requestScopedConnections.connections.get(+ getMCPUserConnectionPoolKey(mockUser.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ ),+ ).toBe(probe);});it('should reuse BODY-scoped connections within a request-scoped connection store', async () => {@@ -6414,9 +7741,11 @@ describe('MCPManager', () => {expect(first).toBe(requestScopedConnection);expect(second).toBe(requestScopedConnection);expect(MCPConnectionFactory.create).toHaveBeenCalledTimes(1);- expect(requestScopedConnections.connections.get(`${mockUser.id}:${serverName}`)).toBe(- requestScopedConnection,- );+ expect(+ requestScopedConnections.connections.get(+ getMCPUserConnectionPoolKey(mockUser.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ ),+ ).toBe(requestScopedConnection);});it('rechecks the request-scoped owner after a late connection replacement', async () => {@@ -6431,7 +7760,12 @@ describe('MCPManager', () => {} as unknown as MCPConnection;const replacement = newUserConnection();const store = {- connections: new Map([[`${mockUser.id}:${serverName}`, oldConnection]]),+ connections: new Map([+ [+ getMCPUserConnectionPoolKey(mockUser.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ oldConnection,+ ],+ ]),pending: new Map(),};const manager = await MCPManager.createInstance(newMCPServersConfig());@@ -6449,7 +7783,10 @@ describe('MCPManager', () => {});await new Promise((resolve) => setImmediate(resolve));expect(oldConnection.isConnected).toHaveBeenCalledTimes(1);- store.connections.set(`${mockUser.id}:${serverName}`, replacement);+ store.connections.set(+ getMCPUserConnectionPoolKey(mockUser.id, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ replacement,+ );finishProbe?.(true);await expect(checkout).resolves.toBe(replacement);expect(MCPConnectionFactory.create).not.toHaveBeenCalled();diff --git a/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.tsindex 780c99b092..9a5711f1be 100644--- a/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts+++ b/packages/api/src/mcp/__tests__/MCPOAuthRaceCondition.test.ts@@ -134,10 +134,13 @@ describe('MCP OAuth Race Condition Fixes', () => {shouldEnableSSRFProtection: jest.fn().mockReturnValue(false),getAllowedDomains: jest.fn().mockReturnValue(null),getAllowedAddresses: jest.fn().mockReturnValue(null),+ getMCPAppsPolicy: jest.fn().mockReturnValue({ enabled: true, legacyHtmlEnabled: true }),+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,useSSRFProtection: false,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },}),});@@ -177,6 +180,113 @@ describe('MCP OAuth Race Condition Fixes', () => {}});+ it('cancels after asynchronous lookup without starting connection creation', async () => {+ const { UserConnectionManager } = await import('~/mcp/UserConnectionManager');+ const { MCPConnectionFactory } = await import('~/mcp/MCPConnectionFactory');+ const { MCPServersRegistry } = await import('~/mcp/registry/MCPServersRegistry');+ class TestManager extends UserConnectionManager {}+ const manager = new TestManager();+ let resolveConfig!: (config: object) => void;+ const config = new Promise<object>((resolve) => {+ resolveConfig = resolve;+ });+ const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({+ getServerConfig: jest.fn().mockReturnValue(config),+ } as never);+ const createSpy = jest.spyOn(MCPConnectionFactory, 'create');+ const controller = new AbortController();++ const creation = manager.getUserConnection({+ serverName: 'test-server',+ user: { id: 'user-cancelled' } as never,+ signal: controller.signal,+ });+ controller.abort(new Error('request cancelled'));+ resolveConfig({ type: 'sse', url: 'https://mcp.example.com' });++ await expect(creation).rejects.toThrow('request cancelled');+ expect(createSpy).not.toHaveBeenCalled();+ registrySpy.mockRestore();+ createSpy.mockRestore();+ });++ it('waits for a different config generation and then creates its own connection', async () => {+ const { UserConnectionManager } = await import('~/mcp/UserConnectionManager');+ const { MCPConnectionFactory } = await import('~/mcp/MCPConnectionFactory');+ class TestManager extends UserConnectionManager {}+ const manager = new TestManager();+ manager.appConnections = {} as never;+ const connection = (name: string) =>+ ({+ name,+ on: jest.fn(),+ isConnected: jest.fn().mockResolvedValue(true),+ refreshToolList: jest.fn().mockResolvedValue(undefined),+ removeAllListeners: jest.fn(),+ dispose: jest.fn().mockResolvedValue(undefined),+ isStale: jest.fn().mockReturnValue(false),+ }) as never;+ const secondConnection = connection('second');+ const firstFailure = new Error('first target unavailable');+ let releaseFirst!: () => void;+ const firstHeld = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const createSpy = jest+ .spyOn(MCPConnectionFactory, 'create')+ .mockImplementation(async (options) => {+ if (+ 'url' in options.serverConfig &&+ options.serverConfig.url === 'https://first.example.com'+ ) {+ await firstHeld;+ throw firstFailure;+ }+ return secondConnection;+ });+ const registrySpy = jest+ .spyOn(+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ require('~/mcp/registry/MCPServersRegistry').MCPServersRegistry,+ 'getInstance',+ )+ .mockReturnValue({+ resolveAllowlists: jest.fn().mockResolvedValue({+ allowedDomains: null,+ allowedAddresses: null,+ useSSRFProtection: false,+ }),+ });+ const user = { id: 'user-generation' } as never;+ const first = manager.getUserConnection({+ serverName: 'test-server',+ user,+ connectionTarget: {+ connectionOwner: 'principal',+ serverConfig: { type: 'sse', url: 'https://first.example.com' },+ },+ });+ await new Promise((resolve) => setTimeout(resolve, 0));+ const waiterOAuthStart = jest.fn();+ const second = manager.getUserConnection({+ serverName: 'test-server',+ user,+ oauthStart: waiterOAuthStart,+ connectionTarget: {+ connectionOwner: 'principal',+ serverConfig: { type: 'sse', url: 'https://second.example.com' },+ },+ });+ releaseFirst();++ await expect(first).rejects.toBe(firstFailure);+ await expect(second).resolves.toBe(secondConnection);+ expect(createSpy).toHaveBeenCalledTimes(2);+ expect(waiterOAuthStart).not.toHaveBeenCalled();+ registrySpy.mockRestore();+ createSpy.mockRestore();+ });+it('should re-issue the pending OAuth URL when joining an in-flight connection', async () => {const { UserConnectionManager } = await import('~/mcp/UserConnectionManager');@@ -213,10 +323,13 @@ describe('MCP OAuth Race Condition Fixes', () => {shouldEnableSSRFProtection: jest.fn().mockReturnValue(false),getAllowedDomains: jest.fn().mockReturnValue(null),getAllowedAddresses: jest.fn().mockReturnValue(null),+ getMCPAppsPolicy: jest.fn().mockReturnValue({ enabled: true, legacyHtmlEnabled: true }),+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,useSSRFProtection: false,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },}),});@@ -301,10 +414,13 @@ describe('MCP OAuth Race Condition Fixes', () => {shouldEnableSSRFProtection: jest.fn().mockReturnValue(false),getAllowedDomains: jest.fn().mockReturnValue(null),getAllowedAddresses: jest.fn().mockReturnValue(null),+ getMCPAppsPolicy: jest.fn().mockReturnValue({ enabled: true, legacyHtmlEnabled: true }),+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,useSSRFProtection: false,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },}),});@@ -423,10 +539,13 @@ describe('MCP OAuth Race Condition Fixes', () => {shouldEnableSSRFProtection: jest.fn().mockReturnValue(false),getAllowedDomains: jest.fn().mockReturnValue(null),getAllowedAddresses: jest.fn().mockReturnValue(null),+ getMCPAppsPolicy: jest.fn().mockReturnValue({ enabled: true, legacyHtmlEnabled: true }),+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,useSSRFProtection: false,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },}),});@@ -500,6 +619,7 @@ describe('MCP OAuth Race Condition Fixes', () => {type: 'streamable-http',url: 'http://localhost:9999/',}),+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,@@ -581,6 +701,7 @@ describe('MCP OAuth Race Condition Fixes', () => {type: 'streamable-http',url: 'http://localhost:9999/',}),+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn().mockResolvedValue({allowedDomains: null,allowedAddresses: null,diff --git a/packages/api/src/mcp/__tests__/appToolPublication.integration.test.ts b/packages/api/src/mcp/__tests__/appToolPublication.integration.test.tsindex 016d745a2a..ad39ecc7a9 100644--- a/packages/api/src/mcp/__tests__/appToolPublication.integration.test.ts+++ b/packages/api/src/mcp/__tests__/appToolPublication.integration.test.ts@@ -8,9 +8,10 @@ import type { ParsedServerConfig } from '../types';import {notifyMCPToolsChanged,setMCPToolsChangedHandler,- getMCPAppToolsPublicationGeneration,+ getMCPToolCatalogGeneration,setMCPToolsChangedRevisionHandler,} from '../toolsChanged';+import { STANDARD_MCP_CAPABILITY_PROFILE } from '../capabilities';import { createMCPCatalogStore } from '../catalog/store';import { createMCPToolCacheService } from '../tools';import { MCPConnection } from '../connection';@@ -71,6 +72,7 @@ function createHarness() {serverConfig: event.serverConfig as ParsedServerConfig,publicationGeneration: event.publicationGeneration,publicationRevision: event.publicationRevision,+ capabilityProfile: event.capabilityProfile,});});@@ -90,7 +92,11 @@ async function createConnection(tools: Tool[]) {await server.connect(serverTransport);/** No userId: this is an app-shared connection, the scope agents read from. */- const connection = new MCPConnection({ serverName: SERVER_NAME, serverConfig: appConfig });+ const connection = new MCPConnection({+ serverName: SERVER_NAME,+ serverConfig: appConfig,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ });await connection.client.connect(clientTransport);connection.emit('connectionChange', 'connected');@@ -106,7 +112,7 @@ async function createConnection(tools: Tool[]) {}describe('app-level tool publication', () => {- const configGeneration = getMCPAppToolsPublicationGeneration(appConfig);+ const configGeneration = getMCPToolCatalogGeneration(appConfig);let harness: Awaited<ReturnType<typeof createConnection>> | undefined;afterEach(async () => {@@ -131,6 +137,7 @@ describe('app-level tool publication', () => {serverConfig: appConfig,publicationGeneration: configGeneration,publicationRevision: snapshot.publicationRevision,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});const published = await service.getMCPServerTools('user-1', SERVER_NAME, appConfig);@@ -163,6 +170,7 @@ describe('app-level tool publication', () => {serverConfig: appConfig,publicationGeneration: configGeneration,publicationRevision: current.publicationRevision,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});await notifyMCPToolsChanged({tools: stale.tools,@@ -170,6 +178,7 @@ describe('app-level tool publication', () => {serverConfig: appConfig,publicationGeneration: configGeneration,publicationRevision: stale.publicationRevision,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});const published = await service.getMCPServerTools('user-1', SERVER_NAME, appConfig);diff --git a/packages/api/src/mcp/__tests__/apps.test.ts b/packages/api/src/mcp/__tests__/apps.test.tsnew file mode 100644index 0000000000..d24a86d21c--- /dev/null+++ b/packages/api/src/mcp/__tests__/apps.test.ts@@ -0,0 +1,432 @@+import { logger } from '@librechat/data-schemas';+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';+import type { PluginAuthMethods } from '@librechat/data-schemas';+import type { MCPAppRequestContext, MCPAppsProxyManager, ToolWithMeta } from '../apps';+import {+ buildAppProxyErrorResponse,+ callAppTool,+ isDeniedAppRequest,+ isToolHiddenFromApp,+ isToolHiddenFromModel,+ listAppResources,+ listAppResourceTemplates,+ readAppResource,+ resolveAppRequestContext,+ resolveEffectiveAppServerConfig,+} from '../apps';+import { MCPAuthenticationRefreshError, MCPAuthenticationRejectedError } from '../errors';+import { createMCPAppBindingCodec, projectMCPAppRuntimeTarget } from '../apps/binding';+import { OpenIDReauthRequiredError } from '~/utils/oidc';+import { getPluginAuthMap } from '~/agents/auth';++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },+}));++jest.mock('~/agents/auth', () => ({ getPluginAuthMap: jest.fn() }));++const tool = (visibility?: unknown): ToolWithMeta =>+ ({+ name: 'do_thing',+ ...(visibility === undefined ? {} : { _meta: { ui: { visibility } } }),+ }) as ToolWithMeta;++describe('MCP App server bindings', () => {+ const connectionTarget = {+ serverConfig: {+ source: 'yaml' as const,+ type: 'sse' as const,+ url: 'https://mcp.example.com',+ },+ connectionOwner: 'operator' as const,+ };+ const subject = {+ userId: 'user-1',+ tenantId: 'tenant-1',+ serverName: 'srv',+ connectionTarget,+ runtimeTarget: projectMCPAppRuntimeTarget(connectionTarget.serverConfig),+ };++ it('validates only the same opaque user, config, and resolved runtime target', () => {+ const codec = createMCPAppBindingCodec('secret');+ const binding = codec.create(subject);++ expect(binding).toMatch(/^v1\.[A-Za-z0-9_-]+$/);+ expect(codec.verify(binding, subject)).toBe(true);+ expect(codec.verify(binding, { ...subject, userId: 'user-2' })).toBe(false);+ expect(+ codec.verify(binding, {+ ...subject,+ runtimeTarget: { type: 'sse', url: 'https://replacement.example.com' },+ }),+ ).toBe(false);+ });+});++describe('tool visibility', () => {+ describe('isToolHiddenFromApp', () => {+ it('treats an absent visibility field as both scopes (not hidden)', () => {+ expect(isToolHiddenFromApp(tool())).toBe(false);+ });++ it('does not hide tools whose explicit visibility includes app', () => {+ expect(isToolHiddenFromApp(tool(['app']))).toBe(false);+ expect(isToolHiddenFromApp(tool(['model', 'app']))).toBe(false);+ expect(isToolHiddenFromApp(tool(['app', 'internal']))).toBe(false);+ });++ it('hides tools whose explicit visibility omits app, including empty/future arrays', () => {+ expect(isToolHiddenFromApp(tool(['model']))).toBe(true);+ expect(isToolHiddenFromApp(tool([]))).toBe(true);+ expect(isToolHiddenFromApp(tool(['model', 'internal']))).toBe(true);+ });+ });++ describe('isToolHiddenFromModel', () => {+ it('treats an absent visibility field as both scopes (not hidden)', () => {+ expect(isToolHiddenFromModel(tool())).toBe(false);+ });++ it('does not hide tools whose explicit visibility includes model', () => {+ expect(isToolHiddenFromModel(tool(['model']))).toBe(false);+ expect(isToolHiddenFromModel(tool(['model', 'app']))).toBe(false);+ expect(isToolHiddenFromModel(tool(['model', 'internal']))).toBe(false);+ });++ it('hides tools whose explicit visibility omits model, including empty/future arrays', () => {+ expect(isToolHiddenFromModel(tool(['app']))).toBe(true);+ expect(isToolHiddenFromModel(tool([]))).toBe(true);+ expect(isToolHiddenFromModel(tool(['app', 'internal']))).toBe(true);+ });+ });+});++describe('App request config and auth resolution', () => {+ const findPluginAuthsByKeys = jest.fn() as unknown as PluginAuthMethods['findPluginAuthsByKeys'];+ const mockGetPluginAuthMap = getPluginAuthMap as jest.MockedFunction<typeof getPluginAuthMap>;+ const user = { id: 'user-1', role: 'USER' } as Parameters<+ typeof resolveAppRequestContext+ >[0]['user'];+ const flowManager = {} as Parameters<typeof resolveAppRequestContext>[0]['flowManager'];+ const onOAuthCredentialsChanging = jest.fn(async () => async () => undefined);+ const allowlists = {+ allowedDomains: ['a.example.com'],+ allowedAddresses: null,+ useSSRFProtection: false,+ };++ beforeEach(() => jest.clearAllMocks());++ it('resolves the request config and the server customUserVars together', async () => {+ mockGetPluginAuthMap.mockResolvedValue({ mcp_srv: { API_KEY: 'secret' } });++ const ctx = await resolveAppRequestContext({+ user,+ serverName: 'srv',+ serverBinding: 'binding',+ resolveServerConfig: () =>+ Promise.resolve({+ serverConfig: { type: 'sse', url: 'https://a.example.com' },+ connectionOwner: 'principal',+ }),+ findPluginAuthsByKeys,+ flowManager,+ onOAuthCredentialsChanging,+ allowlists,+ });++ expect(ctx.connectionTarget.serverConfig).toEqual({+ type: 'sse',+ url: 'https://a.example.com',+ });+ expect(ctx.customUserVars).toEqual({ API_KEY: 'secret' });+ expect(ctx.user).toBe(user);+ expect(ctx.serverName).toBe('srv');+ expect(ctx.onOAuthCredentialsChanging).toBe(onOAuthCredentialsChanging);+ expect(ctx.allowlists).toBe(allowlists);+ });++ it('fails closed when config resolution fails', async () => {+ await expect(+ resolveAppRequestContext({+ user,+ serverName: 'srv',+ serverBinding: 'binding',+ resolveServerConfig: () => Promise.reject(new Error('config unavailable')),+ findPluginAuthsByKeys,+ flowManager,+ onOAuthCredentialsChanging,+ allowlists,+ }),+ ).rejects.toThrow('config unavailable');+ });++ it('fails closed when auth-value resolution fails rather than proceeding unresolved', async () => {+ mockGetPluginAuthMap.mockRejectedValue(new Error('db down'));++ await expect(+ resolveAppRequestContext({+ user,+ serverName: 'srv',+ serverBinding: 'binding',+ resolveServerConfig: () =>+ Promise.resolve({+ serverConfig: { type: 'sse', url: 'https://a.example.com' },+ connectionOwner: 'principal',+ }),+ findPluginAuthsByKeys,+ flowManager,+ onOAuthCredentialsChanging,+ allowlists,+ }),+ ).rejects.toThrow('db down');+ expect(logger.error).toHaveBeenCalled();+ });++ it('resolves without customUserVars for a user with no stored vars', async () => {+ mockGetPluginAuthMap.mockResolvedValue({});++ const ctx = await resolveAppRequestContext({+ user,+ serverName: 'srv',+ serverBinding: 'binding',+ resolveServerConfig: () =>+ Promise.resolve({+ serverConfig: { type: 'sse', url: 'https://a.example.com' },+ connectionOwner: 'principal',+ }),+ findPluginAuthsByKeys,+ flowManager,+ onOAuthCredentialsChanging,+ allowlists,+ });++ expect(ctx.customUserVars).toBeUndefined();+ expect(ctx.connectionTarget.serverConfig).toEqual({+ type: 'sse',+ url: 'https://a.example.com',+ });+ });++ it('rejects a target omitted by the effective user and role config', async () => {+ mockGetPluginAuthMap.mockResolvedValue({});++ await expect(+ resolveAppRequestContext({+ user,+ serverName: 'srv',+ serverBinding: 'binding',+ resolveServerConfig: () => Promise.resolve(undefined),+ findPluginAuthsByKeys,+ flowManager,+ onOAuthCredentialsChanging,+ allowlists,+ }),+ ).rejects.toMatchObject({ code: ErrorCode.InvalidRequest });+ });++ it('initializes and resolves only the admitted target through the role-aware registry merge', async () => {+ const target = { type: 'sse' as const, url: 'https://raw.example.com' };+ const parsed = { ...target, source: 'yaml' as const };+ const effective = { ...parsed, url: 'https://effective.example.com' };+ const unrelated = new Promise<Record<string, never>>(() => undefined);+ const ensureConfigServers = jest.fn(+ async (config: Record<string, unknown>): Promise<Record<string, typeof parsed>> => {+ if ('unrelated' in config) {+ await unrelated;+ }+ return { srv: parsed };+ },+ );+ const getAllServerConfigs = jest.fn().mockResolvedValue({ srv: effective });+ const recoverServerConfig = jest.fn();++ await expect(+ resolveEffectiveAppServerConfig({+ serverName: 'srv',+ user,+ mcpConfig: {+ srv: target,+ unrelated: { type: 'stdio', command: 'never-initialized', args: [] },+ },+ ensureConfigServers,+ getAllServerConfigs,+ recoverServerConfig,+ isAppServerConfig: jest.fn().mockResolvedValue(false),+ }),+ ).resolves.toEqual({ serverConfig: effective, connectionOwner: 'principal' });++ expect(ensureConfigServers).toHaveBeenCalledWith({ srv: target });+ expect(getAllServerConfigs).toHaveBeenCalledWith(user.id, { srv: parsed }, user.role);+ expect(recoverServerConfig).not.toHaveBeenCalled();+ });++ it('lets the role-aware registry supply an unmodified base target when no raw override exists', async () => {+ const effective = {+ source: 'yaml' as const,+ type: 'sse' as const,+ url: 'https://base.example.com',+ };+ const ensureConfigServers = jest.fn().mockResolvedValue({});+ const getAllServerConfigs = jest.fn().mockResolvedValue({ srv: effective });+ const recoverServerConfig = jest.fn();++ await expect(+ resolveEffectiveAppServerConfig({+ serverName: 'srv',+ user,+ mcpConfig: {},+ ensureConfigServers,+ getAllServerConfigs,+ recoverServerConfig,+ isAppServerConfig: jest.fn().mockResolvedValue(false),+ }),+ ).resolves.toEqual({ serverConfig: effective, connectionOwner: 'principal' });++ expect(ensureConfigServers).toHaveBeenCalledWith({});+ expect(getAllServerConfigs).toHaveBeenCalledWith(user.id, {}, user.role);+ expect(recoverServerConfig).not.toHaveBeenCalled();+ });++ it('resolves an inspection-failed target through the upstream recovery owner', async () => {+ const stub = {+ source: 'yaml' as const,+ type: 'sse' as const,+ url: 'https://unavailable.example.com',+ inspectionFailed: true,+ };+ const recovered = {+ source: 'yaml' as const,+ type: 'sse' as const,+ url: 'https://recovered.example.com',+ };+ const recoverServerConfig = jest.fn().mockResolvedValue(recovered);++ await expect(+ resolveEffectiveAppServerConfig({+ serverName: 'srv',+ user,+ mcpConfig: {},+ ensureConfigServers: jest.fn().mockResolvedValue({}),+ getAllServerConfigs: jest.fn().mockResolvedValue({ srv: stub }),+ recoverServerConfig,+ isAppServerConfig: jest.fn().mockResolvedValue(false),+ }),+ ).resolves.toEqual({ serverConfig: recovered, connectionOwner: 'principal' });++ expect(recoverServerConfig).toHaveBeenCalledWith('srv', stub, user.id);+ });++ it('returns a missing target without invoking recovery', async () => {+ const recoverServerConfig = jest.fn();++ await expect(+ resolveEffectiveAppServerConfig({+ serverName: 'srv',+ user,+ mcpConfig: {},+ ensureConfigServers: jest.fn().mockResolvedValue({}),+ getAllServerConfigs: jest.fn().mockResolvedValue({}),+ recoverServerConfig,+ isAppServerConfig: jest.fn().mockResolvedValue(false),+ }),+ ).resolves.toBeUndefined();++ expect(recoverServerConfig).not.toHaveBeenCalled();+ });+});++describe('app proxy error mapping', () => {+ it('treats an InvalidRequest denial as a client error and surfaces its message', () => {+ const denial = new McpError(ErrorCode.InvalidRequest, 'Resource "x" is not permitted.');+ expect(isDeniedAppRequest(denial)).toBe(true);+ expect(buildAppProxyErrorResponse(denial, 'Failed to read resource')).toEqual({+ status: 400,+ body: { error: denial.message },+ });+ });++ it.each([new McpError(ErrorCode.InternalError, 'boom'), new Error('boom'), null, 'boom'])(+ 'hides an unexpected failure behind the fallback message: %s',+ (error) => {+ expect(isDeniedAppRequest(error)).toBe(false);+ expect(buildAppProxyErrorResponse(error, 'Failed to read resource')).toEqual({+ status: 500,+ body: { error: 'Failed to read resource' },+ });+ },+ );++ it('returns the established actionable response for expired OpenID sessions', () => {+ const error = new OpenIDReauthRequiredError('Please sign in again.');++ expect(buildAppProxyErrorResponse(error, 'Failed to read resource')).toEqual({+ status: 401,+ body: { error: 'invalid_token', message: 'Please sign in again.' },+ });+ expect(isDeniedAppRequest(error)).toBe(true);+ });++ it('returns bounded authentication rejection and refresh responses', () => {+ const rejected = new MCPAuthenticationRejectedError('srv', true);+ const refresh = new MCPAuthenticationRefreshError();++ expect(buildAppProxyErrorResponse(rejected, 'Failed to read resource')).toEqual({+ status: 403,+ body: {+ error: 'invalid_token',+ code: 'MCP_AUTHENTICATION_REJECTED',+ message:+ 'MCP server "srv" rejected the bearer credential. The connection was refreshed; retry the tool deliberately.',+ retryable: true,+ connectionRefreshed: true,+ },+ });+ expect(buildAppProxyErrorResponse(refresh, 'Failed to read resource')).toEqual({+ status: 503,+ body: {+ code: 'MCP_AUTHENTICATION_REFRESH_FAILED',+ message: 'The OpenID session could not refresh the MCP bearer credential temporarily.',+ retryable: true,+ },+ });+ });+});++describe('app proxy input validation', () => {+ const manager = {+ readResource: jest.fn(),+ listResources: jest.fn(),+ listResourceTemplates: jest.fn(),+ validateAppBinding: jest.fn(),+ appToolCall: jest.fn(),+ } as jest.Mocked<MCPAppsProxyManager>;+ const context = { serverName: 'srv' } as MCPAppRequestContext;++ beforeEach(() => jest.clearAllMocks());++ it('rejects malformed values before calling the manager', async () => {+ await expect(readAppResource(manager, context, 42)).rejects.toMatchObject({+ code: ErrorCode.InvalidRequest,+ });+ await expect(listAppResources(manager, context, 42)).rejects.toMatchObject({+ code: ErrorCode.InvalidRequest,+ });+ await expect(listAppResourceTemplates(manager, context, null)).rejects.toMatchObject({+ code: ErrorCode.InvalidRequest,+ });+ await expect(callAppTool(manager, context, 42, {})).rejects.toMatchObject({+ code: ErrorCode.InvalidRequest,+ });+ await expect(callAppTool(manager, context, 'tool', [])).rejects.toMatchObject({+ code: ErrorCode.InvalidRequest,+ });++ expect(manager.readResource).not.toHaveBeenCalled();+ expect(manager.listResources).not.toHaveBeenCalled();+ expect(manager.listResourceTemplates).not.toHaveBeenCalled();+ expect(manager.appToolCall).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/mcp/__tests__/auth.test.ts b/packages/api/src/mcp/__tests__/auth.test.tsindex 7bad722730..00446f7776 100644--- a/packages/api/src/mcp/__tests__/auth.test.ts+++ b/packages/api/src/mcp/__tests__/auth.test.ts@@ -173,6 +173,26 @@ describe('getUserMCPAuthMap', () => {expect(result).toEqual({});});+ it('propagates lookup failures when throwOnError is set, and asks the map to throw too', async () => {+ const toolInstances = [createMockTool('test_mcp_Server1', 'Server1')];+ const dbError = new Error('Database connection failed');++ mockGetPluginAuthMap.mockRejectedValue(dbError);++ await expect(+ getUserMCPAuthMap({+ userId: 'user123',+ toolInstances,+ findPluginAuthsByKeys: mockFindPluginAuthsByKeys,+ throwOnError: true,+ }),+ ).rejects.toThrow('Database connection failed');++ expect(mockGetPluginAuthMap).toHaveBeenCalledWith(+ expect.objectContaining({ throwError: true }),+ );+ });+it('should handle non-Error exceptions gracefully', async () => {const toolInstances = [createMockTool('test_mcp_Server1', 'Server1')];diff --git a/packages/api/src/mcp/__tests__/capabilities.test.ts b/packages/api/src/mcp/__tests__/capabilities.test.tsnew file mode 100644index 0000000000..7a1e732d41--- /dev/null+++ b/packages/api/src/mcp/__tests__/capabilities.test.ts@@ -0,0 +1,105 @@+import { Server } from '@modelcontextprotocol/sdk/server/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import type { ClientCapabilities } from '@modelcontextprotocol/sdk/types.js';+import type { MCPClientCapabilityProfile } from '~/mcp/capabilities';+import {+ getMCPConnectionPoolKey,+ getMCPUserConnectionPoolKey,+ MCP_APPS_CAPABILITY_PROFILE,+ resolveMCPClientCapabilityProfile,+ STANDARD_MCP_CAPABILITY_PROFILE,+} from '~/mcp/capabilities';+import { MCPConnection } from '~/mcp/connection';++jest.mock('@librechat/data-schemas', () => ({+ logger: {+ info: jest.fn(),+ warn: jest.fn(),+ error: jest.fn(),+ debug: jest.fn(),+ },+}));++jest.mock('~/auth', () => ({+ createSSRFSafeUndiciConnect: jest.fn(() => undefined),+ isOAuthUrlAllowed: jest.fn(() => false),+ isSSRFTarget: jest.fn(() => false),+ resolveHostnameSSRF: jest.fn(async () => false),+}));++describe('MCP client capability profiles', () => {+ const clients: MCPConnection[] = [];+ const servers: Server[] = [];++ afterEach(async () => {+ await Promise.all(clients.splice(0).map((connection) => connection.client.close()));+ await Promise.all(servers.splice(0).map((server) => server.close()));+ });++ async function negotiateCapabilities(+ capabilityProfile?: MCPClientCapabilityProfile,+ ): Promise<ClientCapabilities | undefined> {+ const server = new Server(+ { name: 'capability-test-server', version: '1.0.0' },+ { capabilities: {} },+ );+ servers.push(server);++ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);++ const connection = new MCPConnection({+ serverName: 'capability-test-server',+ serverConfig: { type: 'streamable-http', url: 'http://localhost/mcp' },+ useSSRFProtection: false,+ ...(capabilityProfile == null ? {} : { capabilityProfile }),+ });+ clients.push(connection);+ await connection.client.connect(clientTransport);++ return server.getClientCapabilities();+ }++ it.each([+ ['omitted policy', undefined, STANDARD_MCP_CAPABILITY_PROFILE],+ ['disabled policy', { enabled: false }, STANDARD_MCP_CAPABILITY_PROFILE],+ ['enabled policy', { enabled: true }, MCP_APPS_CAPABILITY_PROFILE],+ ] as const)('resolves %s to the immutable session profile', (_label, policy, expected) => {+ expect(resolveMCPClientCapabilityProfile(policy)).toBe(expected);+ });++ it('keeps every server and user profile tuple unambiguous', () => {+ expect(getMCPConnectionPoolKey('server:one', STANDARD_MCP_CAPABILITY_PROFILE)).toBe(+ JSON.stringify(['server:one', STANDARD_MCP_CAPABILITY_PROFILE]),+ );+ expect(getMCPConnectionPoolKey('server:one', MCP_APPS_CAPABILITY_PROFILE)).toBe(+ JSON.stringify(['server:one', MCP_APPS_CAPABILITY_PROFILE]),+ );+ expect(+ getMCPUserConnectionPoolKey('user:one', 'server:one', STANDARD_MCP_CAPABILITY_PROFILE),+ ).toBe(JSON.stringify(['user:one', 'server:one', STANDARD_MCP_CAPABILITY_PROFILE]));+ expect(getMCPUserConnectionPoolKey('user:one', 'server:one', MCP_APPS_CAPABILITY_PROFILE)).toBe(+ JSON.stringify(['user:one', 'server:one', MCP_APPS_CAPABILITY_PROFILE]),+ );+ expect(+ getMCPConnectionPoolKey('["server:one","apps"]', STANDARD_MCP_CAPABILITY_PROFILE),+ ).not.toBe(getMCPConnectionPoolKey('server:one', MCP_APPS_CAPABILITY_PROFILE));+ });++ it.each([+ ['omitted', undefined],+ ['standard', STANDARD_MCP_CAPABILITY_PROFILE],+ ] as const)('advertises no extensions for the %s profile', async (_label, profile) => {+ await expect(negotiateCapabilities(profile)).resolves.toEqual({});+ });++ it('advertises the MCP Apps HTML extension for the apps profile', async () => {+ await expect(negotiateCapabilities(MCP_APPS_CAPABILITY_PROFILE)).resolves.toEqual({+ extensions: {+ 'io.modelcontextprotocol/ui': {+ mimeTypes: ['text/html;profile=mcp-app'],+ },+ },+ });+ });+});diff --git a/packages/api/src/mcp/__tests__/parsers.test.ts b/packages/api/src/mcp/__tests__/parsers.test.tsindex 742cbf8e22..110e126379 100644--- a/packages/api/src/mcp/__tests__/parsers.test.ts+++ b/packages/api/src/mcp/__tests__/parsers.test.ts@@ -1,5 +1,14 @@+import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';+import { isMcpAppMimeType, MCP_APP_MIME_TYPE } from 'librechat-data-provider';import type * as t from '../types';-import { formatToolContent, DEFAULT_MCP_IMAGE_DATA_MAX_BYTES } from '../parsers';+import {+ formatToolContent,+ isRenderableUiResource,+ selectResolvedAppResource,+ DEFAULT_MCP_IMAGE_DATA_MAX_BYTES,+} from '../parsers';++const ENABLED_MCP_APPS_POLICY = { enabled: true, legacyHtmlEnabled: true } as const;describe('formatToolContent', () => {describe('unrecognized providers', () => {@@ -256,8 +265,8 @@ describe('formatToolContent', () => {type: 'resource',resource: {uri: 'ui://carousel',- mimeType: 'application/json',- text: '{"items": []}',+ mimeType: 'text/html',+ text: '<div>carousel</div>',},},],@@ -268,18 +277,392 @@ describe('formatToolContent', () => {expect(content).toContain('UI Resource ID:');expect(content).toContain('UI Resource Marker: \\ui{');expect(content).toContain('Resource URI: ui://carousel');- expect(content).toContain('Resource MIME Type: application/json');+ expect(content).toContain('Resource MIME Type: text/html');const uiResourceArtifact = artifacts?.ui_resources?.data?.[0];expect(uiResourceArtifact).toBeTruthy();expect(uiResourceArtifact).toMatchObject({uri: 'ui://carousel',- mimeType: 'application/json',- text: '{"items": []}',+ mimeType: 'text/html',+ text: '<div>carousel</div>',});expect(uiResourceArtifact?.resourceId).toEqual(expect.any(String));});+ it('transports non-HTML ui:// resources with matching placement markers', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://legacy',+ mimeType: 'application/vnd.example.chart+json',+ text: '{"items": []}',+ },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'openai', {+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ });+ const resource = artifacts?.ui_resources?.data?.[0];++ expect(resource).toMatchObject({+ uri: 'ui://legacy',+ mimeType: 'application/vnd.example.chart+json',+ text: '{"items": []}',+ resourceId: expect.any(String),+ });+ expect(content).toContain(`UI Resource ID: ${resource?.resourceId}`);+ expect(content).toContain(`UI Resource Marker: \\ui{${resource?.resourceId}}`);+ expect(content).toContain('UI Resource Markers Available:');+ expect(content).toContain('Resource URI: ui://legacy');+ expect(content).not.toContain('{"items": []}');+ });++ it('uses the separately resolved document and preserves the canonical tool result', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://app',+ mimeType: 'text/html',+ text: '<p>hi</p>',+ },+ },+ ],+ structuredContent: { count: 3 },+ isError: false,+ };++ const [, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ resolvedAppResource: {+ uri: 'ui://app',+ mimeType: MCP_APP_MIME_TYPE,+ text: '<p>from resources/read</p>',+ },+ });++ const uiResourceArtifact = artifacts?.ui_resources?.data?.[0];+ expect(uiResourceArtifact).toMatchObject({+ uri: 'ui://app',+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ structuredContent: { count: 3 },+ });+ expect(uiResourceArtifact?.content).toBe(result.content);+ expect(CallToolResultSchema.safeParse(result).success).toBe(true);+ expect(uiResourceArtifact?.text).toBe('<p>from resources/read</p>');+ });++ it('falls back to a URI-only App snapshot when the hydrated artifact exceeds its cap', () => {+ const result: t.MCPToolCallResponse = { content: [{ type: 'text', text: 'ordinary' }] };+ const [, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: { ...ENABLED_MCP_APPS_POLICY, maxPersistedAppBytes: 1024 },+ resolvedAppResource: {+ uri: 'ui://app',+ mimeType: MCP_APP_MIME_TYPE,+ text: 'x'.repeat(4096),+ _meta: { ui: { permissions: { camera: {} } } },+ },+ });++ expect(artifacts?.ui_resources?.data?.[0]).toMatchObject({+ uri: 'ui://app',+ serverBinding: 'binding',+ content: result.content,+ });+ expect(artifacts?.ui_resources?.data?.[0]?.text).toBeUndefined();+ expect(artifacts?.ui_resources?.data?.[0]?._meta).toBeUndefined();+ });++ it('omits an oversized URI-only App snapshot while preserving canonical output', () => {+ const result: t.MCPToolCallResponse = { content: [{ type: 'text', text: 'ordinary' }] };+ const [content, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ toolArgs: { input: 'x'.repeat(4096) },+ mcpApps: { ...ENABLED_MCP_APPS_POLICY, maxPersistedAppBytes: 256 },+ });++ expect(content).toContain('ordinary');+ expect(artifacts?.ui_resources).toBeUndefined();+ });++ it('renders a plain text/html ui:// resource statically without app-bridge metadata', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://static', mimeType: 'text/html', text: '<p>hi</p>' },+ },+ ],+ structuredContent: { count: 3 },+ };++ const [content, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ });++ const uiResourceArtifact = artifacts?.ui_resources?.data?.[0];+ expect(content).toContain('UI Resource Marker:');+ expect(uiResourceArtifact).toMatchObject({ uri: 'ui://static' });+ expect(uiResourceArtifact?.serverName).toBeUndefined();+ expect(uiResourceArtifact?.toolName).toBeUndefined();+ expect(uiResourceArtifact?.structuredContent).toBeUndefined();+ expect(uiResourceArtifact?.resultMeta).toBeUndefined();+ });++ it('renders only the exact tool-declared app when the result returns a different profiled resource', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://chart',+ mimeType: 'text/html;profile=mcp-app',+ text: '<p>c</p>',+ },+ },+ ],+ };++ const [, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ });++ const uris = (artifacts?.ui_resources?.data ?? []).map((r) => r.uri);+ expect(uris).toEqual(['ui://app']);+ });++ it('does not double-synthesize when the returned resource is the declared app', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: 'text/html;profile=mcp-app', text: '<p>a</p>' },+ },+ ],+ };++ const [, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ });++ const uris = (artifacts?.ui_resources?.data ?? []).map((r) => r.uri);+ expect(uris).toEqual(['ui://app']);+ });++ it('uses resource-content sandbox metadata and never falls back to tool metadata', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://app',+ mimeType: MCP_APP_MIME_TYPE,+ text: '<p>a</p>',+ _meta: {+ ui: {+ csp: { connectDomains: ['https://content.example'] },+ permissions: { camera: {} },+ },+ },+ },+ },+ ],+ };+ const metadata = {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ resolvedAppResource:+ result.content?.[0]?.type === 'resource' ? result.content[0].resource : undefined,+ csp: { connectDomains: ['https://tool.example'] },+ permissions: { microphone: {} },+ } as Parameters<typeof formatToolContent>[2];++ const [, embedded] = formatToolContent(result, 'openai', metadata);+ expect(embedded?.ui_resources?.data?.[0]).toMatchObject({+ csp: { connectDomains: ['https://content.example'] },+ permissions: { camera: {} },+ });++ const [, synthesized] = formatToolContent({ content: [] }, 'openai', {+ ...metadata,+ resolvedAppResource: undefined,+ });+ expect(synthesized?.ui_resources?.data?.[0]?.csp).toBeUndefined();+ expect(synthesized?.ui_resources?.data?.[0]?.permissions).toBeUndefined();+ });++ it('creates one declared App and preserves every embedded body in its canonical result', () => {+ const bigA = 'A'.repeat(5000);+ const bigB = 'B'.repeat(5000);+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://a', mimeType: 'text/html;profile=mcp-app', text: bigA },+ },+ {+ type: 'resource',+ resource: { uri: 'ui://b', mimeType: 'text/html;profile=mcp-app', text: bigB },+ },+ ],+ };++ const [, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://declared',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ resolvedAppResource: {+ uri: 'ui://declared',+ mimeType: MCP_APP_MIME_TYPE,+ text: '<p>declared</p>',+ },+ });++ const data = artifacts?.ui_resources?.data ?? [];+ expect(data).toHaveLength(1);+ expect(data[0].text).toBe('<p>declared</p>');+ expect(data[0].content).toBe(result.content);+ expect(JSON.stringify(data[0].content)).toContain(bigA);+ expect(JSON.stringify(data[0].content)).toContain(bigB);+ });++ it('suppresses embedded ui:// resources when apps are disabled for the scope', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: 'text/html', text: '<p>hi</p>' },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ });++ expect(artifacts?.ui_resources).toBeUndefined();+ expect(content).toContain('Resource URI: ui://app');+ expect(content).not.toContain('UI Resource Marker:');+ });++ it('does not synthesize the tool-declared app when apps are disabled for the scope', () => {+ const result: t.MCPToolCallResponse = { content: [{ type: 'text', text: 'done' }] };++ const [content, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ });++ expect(artifacts?.ui_resources).toBeUndefined();+ expect(content).toBe('done');+ });++ it('keeps legacy HTML enabled but does not synthesize a declared App when policy is omitted', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://legacy', mimeType: 'text/html', text: '<p>legacy</p>' },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ });++ expect(content).toContain('UI Resource Marker:');+ expect(artifacts?.ui_resources?.data).toMatchObject([{ uri: 'ui://legacy' }]);+ });++ it('does not synthesize an app for an empty declared resourceUri', () => {+ const result: t.MCPToolCallResponse = { content: [{ type: 'text', text: 'done' }] };++ const [, artifacts] = formatToolContent(result, 'openai', {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: '',+ });++ expect(artifacts?.ui_resources).toBeUndefined();+ });++ it('gives embedded ui:// resources distinct ids per tool result payload', () => {+ const resourceIdFor = (sc: Record<string, unknown>) =>+ formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: 'text/html', text: '<p>same</p>' },+ },+ ],+ structuredContent: sc,+ } as t.MCPToolCallResponse,+ 'openai',+ { serverName: 'srv', serverBinding: 'binding', toolName: 'do_thing' },+ )[1]?.ui_resources?.data?.[0]?.resourceId;++ expect(resourceIdFor({ a: 1 })).not.toEqual(resourceIdFor({ a: 2 }));+ });++ it('does not attach an unlinked app-profile resource', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://graph', mimeType: MCP_APP_MIME_TYPE, text: '<p>g</p>' },+ },+ ],+ structuredContent: { a: 1 },+ };++ const [, artifacts] = formatToolContent(result, 'openai', { toolName: 'do_thing' });+ expect(artifacts?.ui_resources).toBeUndefined();+ });it('should handle regular resources', () => {const result: t.MCPToolCallResponse = {content: [@@ -329,8 +712,8 @@ describe('formatToolContent', () => {type: 'resource',resource: {uri: 'ui://button',- mimeType: 'application/json',- text: '{"label": "Click me"}',+ mimeType: 'text/html',+ text: '<button>Click me</button>',},},{@@ -348,14 +731,14 @@ describe('formatToolContent', () => {expect(content).toContain('Some text');expect(content).toContain('UI Resource Marker: \\ui{');expect(content).toContain('Resource URI: ui://button');- expect(content).toContain('Resource MIME Type: application/json');+ expect(content).toContain('Resource MIME Type: text/html');expect(content).toContain('Resource URI: file://data.csv');const uiResource = artifacts?.ui_resources?.data?.[0];expect(uiResource).toMatchObject({uri: 'ui://button',- mimeType: 'application/json',- text: '{"label": "Click me"}',+ mimeType: 'text/html',+ text: '<button>Click me</button>',});expect(uiResource?.resourceId).toEqual(expect.any(String));});@@ -369,8 +752,8 @@ describe('formatToolContent', () => {type: 'resource',resource: {uri: 'ui://graph',- mimeType: 'application/json',- text: '{"type": "line"}',+ mimeType: 'text/html',+ text: '<svg>graph</svg>',},},],@@ -381,7 +764,7 @@ describe('formatToolContent', () => {expect(content).toContain('Content with multimedia');expect(content).toContain('UI Resource Marker: \\ui{');expect(content).toContain('Resource URI: ui://graph');- expect(content).toContain('Resource MIME Type: application/json');+ expect(content).toContain('Resource MIME Type: text/html');expect(artifacts).toEqual({content: [{@@ -393,8 +776,8 @@ describe('formatToolContent', () => {data: [{uri: 'ui://graph',- mimeType: 'application/json',- text: '{"type": "line"}',+ mimeType: 'text/html',+ text: '<svg>graph</svg>',resourceId: expect.any(String),},],@@ -431,8 +814,8 @@ describe('formatToolContent', () => {type: 'resource',resource: {uri: 'ui://chart',- mimeType: 'application/json',- text: '{"type": "bar"}',+ mimeType: 'text/html',+ text: '<svg>chart</svg>',},},{@@ -454,7 +837,7 @@ describe('formatToolContent', () => {expect(content).toContain('UI Resource ID:');expect(content).toContain('UI Resource Marker: \\ui{');expect(content).toContain('Resource URI: ui://chart');- expect(content).toContain('Resource MIME Type: application/json');+ expect(content).toContain('Resource MIME Type: text/html');expect(content).toContain('Resource URI: https://api.example.com/data');expect(content).toContain('Conclusion');expect(content).toContain('UI Resource Markers Available:');@@ -473,8 +856,8 @@ describe('formatToolContent', () => {data: [{uri: 'ui://chart',- mimeType: 'application/json',- text: '{"type": "bar"}',+ mimeType: 'text/html',+ text: '<svg>chart</svg>',resourceId: expect.any(String),},],@@ -867,4 +1250,820 @@ describe('formatToolContent', () => {);});});++ describe('MCP apps on unrecognized providers', () => {+ it('does not promote an unlinked embedded App while keeping its html out of model text', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ { type: 'text', text: 'ok' },+ {+ type: 'resource',+ resource: {+ uri: 'ui://s/app',+ mimeType: 'text/html;profile=mcp-app',+ text: '<html>SECRET_BODY</html>',+ },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'vertexai' as t.Provider, {+ serverName: 's',+ serverBinding: 'binding',+ toolName: 't',+ toolArgs: { a: 1 },+ });++ const data = artifacts?.ui_resources?.data ?? [];+ expect(data).toHaveLength(0);+ expect(content).not.toContain('UI Resource Marker:');+ expect(content).not.toContain('SECRET_BODY');+ });++ it('synthesizes the tool-declared app for an unrecognized provider', () => {+ const [, artifacts] = formatToolContent(+ { content: [{ type: 'text', text: 'done' }] },+ 'vertexai' as t.Provider,+ {+ serverName: 's',+ serverBinding: 'binding',+ toolName: 't',+ resourceUri: 'ui://s/app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ },+ );++ expect(artifacts?.ui_resources?.data).toMatchObject([+ { uri: 'ui://s/app', mimeType: 'text/html;profile=mcp-app' },+ ]);+ });++ it('keeps the plain string output when apps are disabled for the scope', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: 'text/html;profile=mcp-app', text: '<p>hi</p>' },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'vertexai' as t.Provider, {+ serverName: 's',+ serverBinding: 'binding',+ toolName: 't',+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ });++ expect(artifacts).toBeUndefined();+ // Suppressing the app must not paste a whole untrusted HTML document into model context: the+ // pre-apps baseline never carried one, and the document is meant for the sandbox.+ expect(content).toBe('Resource URI: ui://app\nType: text/html;profile=mcp-app');+ expect(content).not.toContain('<p>hi</p>');+ });++ it('preserves ordinary unrecognized-provider image output beside an unlinked App resource', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ { type: 'image', data: 'base64data', mimeType: 'image/png' },+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: 'text/html;profile=mcp-app', text: '<p>a</p>' },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'vertexai' as t.Provider, {+ serverName: 's',+ serverBinding: 'binding',+ toolName: 't',+ });++ expect(artifacts?.ui_resources).toBeUndefined();+ expect(artifacts?.content).toBeUndefined();+ expect(content).toContain('base64data');+ });++ it('keeps bounded standalone images in model output beside a legacy UI attachment', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ { type: 'image', data: 'base64data', mimeType: 'image/png' },+ {+ type: 'resource',+ resource: { uri: 'ui://legacy', mimeType: 'text/html', text: '<p>view</p>' },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'vertexai' as t.Provider);++ const resource = artifacts?.ui_resources?.data?.[0];+ expect(content).toContain('base64data');+ expect(content).toContain(`UI Resource Marker: \\ui{${resource?.resourceId}}`);+ expect(content.split(`UI Resource Marker: \\ui{${resource?.resourceId}}`)).toHaveLength(2);+ expect(artifacts?.content).toBeUndefined();+ expect(resource).toMatchObject({ uri: 'ui://legacy', mimeType: 'text/html' });+ });++ it('keeps bounded embedded image blobs in model output beside a legacy UI attachment', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'file:///chart.png', mimeType: 'image/png', blob: 'aW1hZ2U=' },+ },+ {+ type: 'resource',+ resource: { uri: 'ui://legacy', mimeType: 'text/html', text: '<p>view</p>' },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'vertexai' as t.Provider);++ expect(content).toContain('data:image/png;base64,aW1hZ2U=');+ expect(artifacts?.content).toBeUndefined();+ expect(artifacts?.ui_resources?.data).toHaveLength(1);+ });++ it.each([+ {+ name: 'standalone image',+ part: { type: 'image', data: 'QUJDRA==', mimeType: 'image/png' },+ },+ {+ name: 'embedded image resource',+ part: {+ type: 'resource',+ resource: { uri: 'file:///chart.png', mimeType: 'image/png', blob: 'QUJDRA==' },+ },+ },+ ])('enforces the image cap for a mixed $name result', ({ part }) => {+ const originalMaxImageBytes = process.env.MCP_IMAGE_DATA_MAX_BYTES;+ try {+ process.env.MCP_IMAGE_DATA_MAX_BYTES = '3';+ const result: t.MCPToolCallResponse = {+ content: [+ part as t.ToolContentPart,+ {+ type: 'resource',+ resource: { uri: 'ui://legacy', mimeType: 'text/html', text: '<p>view</p>' },+ },+ ],+ };++ expect(() => formatToolContent(result, 'vertexai' as t.Provider)).toThrow(+ 'MCP image result exceeds maximum size of 3 bytes',+ );+ } finally {+ if (originalMaxImageBytes === undefined) {+ delete process.env.MCP_IMAGE_DATA_MAX_BYTES;+ } else {+ process.env.MCP_IMAGE_DATA_MAX_BYTES = originalMaxImageBytes;+ }+ }+ });++ it('transports custom UI data when Apps and legacy HTML are disabled', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://custom/chart',+ mimeType: 'application/vnd.example.chart+json',+ text: '{"series":[1,2]}',+ },+ },+ ],+ };++ const [content, artifacts] = formatToolContent(result, 'vertexai' as t.Provider, {+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ });++ const resource = artifacts?.ui_resources?.data?.[0];+ expect(resource).toMatchObject({+ uri: 'ui://custom/chart',+ mimeType: 'application/vnd.example.chart+json',+ text: '{"series":[1,2]}',+ resourceId: expect.any(String),+ });+ expect(content).toContain('{"series":[1,2]}');+ expect(content).toContain(`UI Resource ID: ${resource?.resourceId}`);+ expect(content).toContain(`UI Resource Marker: \\ui{${resource?.resourceId}}`);+ expect(content).toContain('UI Resource Markers Available:');+ expect(artifacts?.content).toBeUndefined();+ });++ it('extracts a non-app ui:// resource without app-bridge metadata', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://s/doc', mimeType: 'text/html', text: '<p>doc</p>' },+ },+ ],+ };++ const [, artifacts] = formatToolContent(result, 'vertexai' as t.Provider, {+ serverName: 's',+ serverBinding: 'binding',+ toolName: 't',+ });++ const resource = artifacts?.ui_resources?.data?.[0];+ expect(resource).toMatchObject({ uri: 'ui://s/doc', mimeType: 'text/html' });+ expect(resource?.serverName).toBeUndefined();+ expect(resource?.toolName).toBeUndefined();+ expect(resource?.content).toBeUndefined();+ });++ it('records the effective HTML MIME for a legacy ui:// resource that omits it', () => {+ const [content, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://s/legacy', text: '<p>legacy</p>' },+ },+ ],+ },+ 'openai',+ );++ expect(content).toContain('UI Resource Marker:');+ expect(content).not.toContain('<p>legacy</p>');+ expect(artifacts?.ui_resources?.data).toMatchObject([+ { uri: 'ui://s/legacy', mimeType: 'text/html' },+ ]);+ });++ it('transports explicit XHTML without making it HTML-renderable', () => {+ const [content, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://s/xhtml',+ mimeType: 'application/xhtml+xml',+ text: '<p>xhtml</p>',+ },+ },+ ],+ },+ 'openai',+ );++ const resource = artifacts?.ui_resources?.data?.[0];+ expect(content).not.toContain('<p>xhtml</p>');+ expect(content).toContain(`UI Resource Marker: \\ui{${resource?.resourceId}}`);+ expect(resource).toMatchObject({+ uri: 'ui://s/xhtml',+ mimeType: 'application/xhtml+xml',+ text: '<p>xhtml</p>',+ });+ });+ });++ describe('un-profiled echo of the tool-declared app uri', () => {+ const echoResult = (resource: Record<string, unknown>): t.MCPToolCallResponse => ({+ content: [{ type: 'resource', resource } as t.ToolContentPart],+ });++ const appMetadata = {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ };++ it('drops the static echo and renders only the declared app', () => {+ const [content, artifacts] = formatToolContent(+ echoResult({ uri: 'ui://app', mimeType: 'text/html', text: '<p>static</p>' }),+ 'openai',+ appMetadata,+ );++ const data = artifacts?.ui_resources?.data ?? [];+ expect(data).toHaveLength(1);+ expect(data[0]).toMatchObject({+ uri: 'ui://app',+ mimeType: 'text/html;profile=mcp-app',+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ });+ expect(content).not.toContain('UI Resource Marker:');+ expect(content).toContain('Resource URI: ui://app');+ expect(content).not.toContain('Resource Text:');+ expect(content).not.toContain('<p>static</p>');+ });++ it('drops the echo when its mime type is omitted entirely', () => {+ const [content, artifacts] = formatToolContent(+ echoResult({ uri: 'ui://app', text: '<p>static</p>' }),+ 'openai',+ appMetadata,+ );++ const data = artifacts?.ui_resources?.data ?? [];+ expect(data).toHaveLength(1);+ expect(data[0]).toMatchObject({ uri: 'ui://app', mimeType: 'text/html;profile=mcp-app' });+ expect(content).not.toContain('<p>static</p>');+ });++ it('renders the declared app when the echo carries no body at all', () => {+ const [, artifacts] = formatToolContent(+ echoResult({ uri: 'ui://app', mimeType: 'text/html' }),+ 'openai',+ appMetadata,+ );++ const data = artifacts?.ui_resources?.data ?? [];+ expect(data).toHaveLength(1);+ expect(data[0]).toMatchObject({+ uri: 'ui://app',+ mimeType: 'text/html;profile=mcp-app',+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ });+ });++ it('produces the same artifact on an unrecognized provider', () => {+ const resource = { uri: 'ui://app', mimeType: 'text/html', text: '<p>static</p>' };+ const [, recognized] = formatToolContent(echoResult(resource), 'openai', appMetadata);+ const [, unrecognized] = formatToolContent(+ echoResult(resource),+ 'vertexai' as t.Provider,+ appMetadata,+ );++ expect(unrecognized?.ui_resources).toEqual(recognized?.ui_resources);+ });++ it('keeps a different un-profiled ui:// resource alongside the declared app', () => {+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://chart', mimeType: 'text/html', text: '<p>chart</p>' },+ },+ ],+ };++ const [, artifacts] = formatToolContent(result, 'openai', appMetadata);++ const data = artifacts?.ui_resources?.data ?? [];+ expect(data).toHaveLength(2);+ const chart = data.find((resource) => resource.uri === 'ui://chart');+ expect(chart).toMatchObject({ mimeType: 'text/html' });+ expect(chart?.serverName).toBeUndefined();+ expect(chart?.toolName).toBeUndefined();+ expect(data.some((resource) => resource.uri === 'ui://app')).toBe(true);+ });++ it('preserves a declared-URI legacy echo body in the canonical App result', () => {+ const body = 'A'.repeat(5000);+ const [, artifacts] = formatToolContent(+ echoResult({ uri: 'ui://app', mimeType: 'text/html', text: body }),+ 'openai',+ appMetadata,+ );++ const snapshot = JSON.stringify(artifacts?.ui_resources?.data?.[0]?.content ?? []);+ expect(snapshot).toContain(body);+ expect(snapshot).toContain('ui://app');+ });++ it('preserves a sibling App body in the canonical declared-App result', () => {+ const body = 'B'.repeat(5000);+ const result: t.MCPToolCallResponse = {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://chart', mimeType: 'text/html;profile=mcp-app', text: body },+ },+ ],+ };++ const [, artifacts] = formatToolContent(result, 'openai', appMetadata);++ const synthetic = artifacts?.ui_resources?.data?.find(+ (resource) => resource.uri === 'ui://app',+ );+ const snapshot = JSON.stringify(synthetic?.content ?? []);+ expect(snapshot).toContain(body);+ expect(snapshot).toContain('ui://chart');+ });+ });++ describe('ordinary resources beside a declared App', () => {+ const metadata = {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ };++ it('preserves text and JSON bodies for an ordinary resource', () => {+ const [text] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'db://other', mimeType: 'application/json', text: '{"ok":true}' },+ },+ ],+ },+ 'openai',+ metadata,+ );++ expect(text).toContain('Resource Text: {"ok":true}');+ });++ it('preserves binary summaries for an ordinary resource', () => {+ const [text] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'file://other',+ mimeType: 'application/octet-stream',+ blob: Buffer.from([0xff, 0x00]).toString('base64'),+ },+ },+ ],+ },+ 'openai',+ metadata,+ );++ expect(text).toContain('Resource Content: 2 bytes of binary data');+ });++ it('preserves an image resource at the declared URI as image and UI transport', () => {+ const [content, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: 'image/png', blob: 'aW1hZ2U=' },+ },+ ],+ },+ 'openai',+ metadata,+ );++ expect(artifacts?.content).toEqual([+ { type: 'image_url', image_url: { url: 'data:image/png;base64,aW1hZ2U=' } },+ ]);+ const imageResource = artifacts?.ui_resources?.data?.find(+ (resource) => resource.mimeType === 'image/png',+ );+ expect(imageResource).toMatchObject({ uri: 'ui://app', blob: 'aW1hZ2U=' });+ expect(content).toContain(`UI Resource Marker: \\ui{${imageResource?.resourceId}}`);+ });+ });+});++describe('shared result snapshot', () => {+ const appMeta = {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ resolvedAppResource: {+ uri: 'ui://app',+ mimeType: MCP_APP_MIME_TYPE,+ text: '<p>resolved</p>',+ },+ };++ const snapshotOf = (+ result: t.MCPToolCallResponse,+ metadata: Parameters<typeof formatToolContent>[2] = appMeta,+ ) => {+ const [, artifacts] = formatToolContent(result, 'openai', metadata);+ return artifacts?.ui_resources?.data?.[0]?.content;+ };++ const appView = (text: string) => ({+ type: 'resource' as const,+ resource: { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, text },+ });++ const schemaCases: Array<{ name: string; result: t.MCPToolCallResponse; metadata?: object }> = [+ { name: 'app view with text', result: { content: [appView('<p>hi</p>')] } },+ {+ name: 'app view with blob',+ result: {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, blob: 'YmluYXJ5' },+ },+ ],+ },+ },+ {+ name: 'app view plus a file resource',+ result: {+ content: [+ appView('<p>hi</p>'),+ {+ type: 'resource',+ resource: { uri: 'file://report', mimeType: 'text/plain', text: 'row,1' },+ },+ ],+ },+ },+ {+ name: 'synthesized declared app',+ result: { content: [{ type: 'text', text: 'done' }] },+ metadata: { ...appMeta, resourceUri: 'ui://app' },+ },+ ];++ it.each(schemaCases)('stays a valid CallToolResult: $name', ({ result, metadata }) => {+ const content = snapshotOf(+ result,+ (metadata ?? appMeta) as Parameters<typeof formatToolContent>[2],+ );+ expect(CallToolResultSchema.safeParse({ content }).success).toBe(true);+ });++ it('preserves the ui:// carrier body in the canonical result', () => {+ const [, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, blob: 'YmluYXJ5' },+ },+ ],+ },+ 'openai',+ appMeta,+ );++ const uiResource = artifacts?.ui_resources?.data?.[0];+ expect(uiResource?.content).toEqual([+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, blob: 'YmluYXJ5' },+ },+ ]);+ });++ it.each([+ { uri: 'file://report', mimeType: 'text/plain', text: 'row,1' },+ { uri: 'db://items/1', mimeType: 'application/json', text: '{"a":1}' },+ { uri: 'custom://thing', mimeType: 'text/plain', text: 'payload' },+ ])('preserves a non-UI body in the snapshot: $uri', (resource) => {+ const content = snapshotOf({ content: [appView('<p>hi</p>'), { type: 'resource', resource }] });+ expect(content?.[1]).toEqual({ type: 'resource', resource });+ });++ it('preserves a non-UI blob body in the snapshot', () => {+ const resource = {+ uri: 'file://report.bin',+ mimeType: 'application/octet-stream',+ blob: 'YQ==',+ };+ const content = snapshotOf({ content: [appView('<p>hi</p>'), { type: 'resource', resource }] });+ expect(content?.[1]).toEqual({ type: 'resource', resource });+ });+});++describe('ui:// resource identity and rendering', () => {+ const appMeta = { serverName: 'srv', serverBinding: 'binding', toolName: 'do_thing' };++ it('gives two legacy ui:// resources with identical html distinct ids', () => {+ const html = '<p>same</p>';+ const [, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://a', mimeType: 'text/html', text: html },+ },+ {+ type: 'resource',+ resource: { uri: 'ui://b', mimeType: 'text/html', text: html },+ },+ ],+ },+ 'openai',+ appMeta,+ );++ const ids = (artifacts?.ui_resources?.data ?? []).map((resource) => resource.resourceId);+ expect(ids).toHaveLength(2);+ expect(new Set(ids).size).toBe(2);+ });++ it('does not emit a marker for a static ui:// view with no body', () => {+ const [content, artifacts] = formatToolContent(+ {+ content: [+ { type: 'resource', resource: { uri: 'ui://static', mimeType: 'text/html', text: '' } },+ ],+ },+ 'openai',+ );++ expect(artifacts).toBeUndefined();+ expect(content).not.toContain('\\ui{');+ expect(content).toContain('Resource URI: ui://static');+ });++ it('suppresses the ui:// document body when apps are disabled for the scope', () => {+ const [content, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, text: '<html>doc</html>' },+ },+ ],+ },+ 'openai',+ { ...appMeta, mcpApps: { enabled: false, legacyHtmlEnabled: false } },+ );++ expect(artifacts).toBeUndefined();+ expect(content).toContain('Resource URI: ui://app');+ expect(content).not.toContain('<html>doc</html>');+ expect(content).not.toContain('Resource Text:');+ expect(content).not.toContain('\\ui{');+ });++ it('still surfaces a non-ui:// html resource body', () => {+ const [content] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: { uri: 'file://page.html', mimeType: 'text/html', text: '<p>page</p>' },+ },+ ],+ },+ 'openai',+ );++ expect(content).toContain('Resource Text: <p>page</p>');+ });+});++describe('isMcpAppMimeType', () => {+ const accepted = [+ MCP_APP_MIME_TYPE,+ 'text/html; profile=mcp-app',+ 'text/html;charset=utf-8;profile=mcp-app',+ 'text/html;profile=mcp-app;charset=utf-8',+ 'text/html;profile="mcp-app"',+ 'TEXT/HTML; PROFILE=mcp-app',+ ];+ const rejected = [+ 'application/xhtml+xml;profile=mcp-app',+ 'text/htmlx;profile=mcp-app',+ 'image/svg+xml;profile=mcp-app',+ 'text/html',+ 'text/html;xprofile=mcp-app',+ 'text/html;profile=mcp-app-evil',+ undefined,+ null,+ 42 as unknown as string,+ ];++ it.each(accepted)('accepts %s', (mimeType) => {+ expect(isMcpAppMimeType(mimeType)).toBe(true);+ });++ it.each(rejected)('rejects %s', (mimeType) => {+ expect(isMcpAppMimeType(mimeType as string | undefined)).toBe(false);+ });++ it.each([...accepted, 'text/html', 'text/html;xprofile=mcp-app'])(+ 'selects a resolved document exactly when the App profile matches: %s',+ (mimeType) => {+ const selected = selectResolvedAppResource(+ [{ uri: 'ui://app', mimeType, text: '<p>a</p>' } as t.ResourceContents],+ 'ui://app',+ );+ expect(!!selected).toBe(isMcpAppMimeType(mimeType));+ },+ );+});++describe('selectResolvedAppResource', () => {+ it('selects only the first usable exact-URI App item', () => {+ const selected = selectResolvedAppResource(+ [+ { uri: 'ui://other', mimeType: MCP_APP_MIME_TYPE, text: '<p>other</p>' },+ { uri: 'ui://app', mimeType: 'text/plain', text: 'wrong mime' },+ { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, text: '<p>exact</p>' },+ { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, text: '<p>later</p>' },+ ],+ 'ui://app',+ );++ expect(selected).toMatchObject({ text: '<p>exact</p>' });+ });++ it('accepts a nonempty UTF-8 blob and rejects empty, malformed, binary, and wrong-URI blobs', () => {+ const blob = Buffer.from('<p>blob</p>', 'utf8').toString('base64');+ expect(+ selectResolvedAppResource(+ [{ uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, blob }],+ 'ui://app',+ ),+ ).toMatchObject({ blob });++ for (const resource of [+ { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, blob: '' },+ { uri: 'ui://app', mimeType: MCP_APP_MIME_TYPE, blob: '***' },+ {+ uri: 'ui://app',+ mimeType: MCP_APP_MIME_TYPE,+ blob: Buffer.from([0xff, 0x00]).toString('base64'),+ },+ { uri: 'ui://other', mimeType: MCP_APP_MIME_TYPE, blob },+ ] as t.ResourceContents[]) {+ expect(selectResolvedAppResource([resource], 'ui://app')).toBeUndefined();+ }+ });+});++describe('isRenderableUiResource media types', () => {+ const uiResource = (mimeType?: string): t.ToolContentPart =>+ ({+ type: 'resource',+ resource: { uri: 'ui://app', mimeType, text: '<p>hi</p>' },+ }) as t.ToolContentPart;++ it.each([+ ['text/html', true],+ ['Text/HTML', true],+ ['TEXT/HTML;profile=mcp-app', true],+ ['Text/HTML;profile=mcp-app', true],+ ['text/html; charset=UTF-8', true],+ [' Text/HTML ', true],+ ['application/xhtml+xml', false],+ ['Application/XHTML+XML', false],+ [undefined, true],+ ['application/json', false],+ ['text/plain', false],+ ['text/plain;x=html', false],+ ['image/png', false],+ ])('classifies %j renderable=%s', (mimeType, expected) => {+ expect(isRenderableUiResource(uiResource(mimeType as string | undefined))).toBe(expected);+ });++ it('keeps a differently-cased app body out of the model-visible text', () => {+ const [content, artifacts] = formatToolContent(+ {+ content: [+ {+ type: 'resource',+ resource: {+ uri: 'ui://app',+ mimeType: 'Text/HTML;profile=mcp-app',+ text: '<p>secret markup</p>',+ },+ },+ ],+ },+ 'openai',+ {+ serverName: 'srv',+ serverBinding: 'binding',+ toolName: 'do_thing',+ resourceUri: 'ui://app',+ mcpApps: ENABLED_MCP_APPS_POLICY,+ resolvedAppResource: {+ uri: 'ui://app',+ mimeType: 'Text/HTML;profile=mcp-app',+ text: '<p>read document</p>',+ },+ },+ );++ expect(content).not.toContain('secret markup');+ expect(artifacts?.ui_resources?.data?.[0]).toMatchObject({+ uri: 'ui://app',+ serverName: 'srv',+ serverBinding: 'binding',+ text: '<p>read document</p>',+ });+ });});diff --git a/packages/api/src/mcp/__tests__/sandbox.test.ts b/packages/api/src/mcp/__tests__/sandbox.test.tsnew file mode 100644index 0000000000..cfed339cd8--- /dev/null+++ b/packages/api/src/mcp/__tests__/sandbox.test.ts@@ -0,0 +1,227 @@+import fs from 'fs';+import path from 'path';+import { MCP_APP_CSP_MAX_LENGTH } from 'librechat-data-provider';+import { buildSandboxResponse } from '../sandbox';++const SANDBOX_PATH = path.resolve(__dirname, '../../../../../client/public/mcp-sandbox.html');+const SANDBOX_HTML = fs.readFileSync(SANDBOX_PATH, 'utf8');++const serve = (+ query: {+ csp?: string | string[];+ frameAncestors?: string;+ limits?: { maxSourcesPerDirective: number; maxSerializedLength: number };+ } = {},+) => buildSandboxResponse({ sandboxHtml: SANDBOX_HTML, ...query });++const policies = (query?: Parameters<typeof serve>[0]): string[] =>+ serve(query).headers['Content-Security-Policy'] as string[];+const resourcePolicy = (query?: Parameters<typeof serve>[0]): string => policies(query)[1];+const viewPolicy = (query?: Parameters<typeof serve>[0]): string => {+ const match = serve(query).body.match(/window\.__MCP_VIEW_CSP = ("(?:[^"\\]|\\.)*");/);+ if (!match) {+ throw new Error('View CSP was not embedded');+ }+ return JSON.parse(match[1]) as string;+};++describe('buildSandboxResponse frame-ancestors', () => {+ it('keeps frame-ancestors as its own policy, first, so the resource policy cannot loosen it', () => {+ const emitted = policies({ csp: JSON.stringify({ frameDomains: ['https://a.example.com'] }) });+ expect(emitted).toHaveLength(2);+ expect(emitted[0]).toBe("frame-ancestors 'none'");+ expect(emitted[1]).not.toContain('frame-ancestors');+ });++ it('uses only the supplied configured ancestors', () => {+ expect(policies({ frameAncestors: 'https://host.example.com' })[0]).toBe(+ 'frame-ancestors https://host.example.com',+ );+ expect(+ policies({+ frameAncestors: 'https://one.example.com, https://two.example.com:8443',+ })[0],+ ).toBe('frame-ancestors https://one.example.com https://two.example.com:8443');+ expect(policies({ frameAncestors: undefined })[0]).toBe("frame-ancestors 'none'");+ });++ it('omits X-Frame-Options only when a cross-origin ancestor is configured', () => {+ const crossOrigin = serve({ frameAncestors: 'https://host.example.com' }).headers;+ expect(crossOrigin['Cross-Origin-Resource-Policy']).toBe('cross-origin');+ expect('X-Frame-Options' in crossOrigin).toBe(false);++ const sameOrigin = serve().headers;+ expect(sameOrigin['Cross-Origin-Resource-Policy']).toBe('same-origin');+ expect(sameOrigin['X-Frame-Options']).toBe('DENY');+ });++ it('drops a token that tries to inject an extra directive', () => {+ expect(policies({ frameAncestors: 'https://ok.com; script-src *' })[0]).toBe(+ "frame-ancestors 'none'",+ );+ });+});++describe('buildSandboxResponse resource policy', () => {+ it('allows the proxy blob install while the View gets the restrictive frame default', () => {+ const policy = resourcePolicy();+ expect(policy).toContain('frame-src blob:');+ expect(policy).not.toContain("frame-src 'none'");+ expect(viewPolicy()).toContain("frame-src 'none'");+ expect(viewPolicy()).not.toContain('frame-src blob:');+ expect(policy).toContain("default-src 'none'");+ expect(policy).toContain("connect-src 'none'");+ expect(policy).toContain("form-action 'none'");+ expect(policy).toContain("worker-src 'self'");+ expect(policy).toContain("base-uri 'self'");+ });++ it('widens frame-src to declared frameDomains only', () => {+ const query = { csp: JSON.stringify({ frameDomains: ['https://embed.example.com'] }) };+ expect(resourcePolicy(query)).toContain('frame-src blob: https://embed.example.com');+ expect(viewPolicy(query)).toContain('frame-src https://embed.example.com');+ expect(viewPolicy(query)).not.toContain('blob:');+ });++ it('bounds form-action and connect-src to the declared egress allowlist', () => {+ const policy = resourcePolicy({+ csp: JSON.stringify({ connectDomains: ['https://api.example.com'] }),+ });+ expect(policy).toContain('connect-src https://api.example.com');+ expect(policy).toContain('form-action https://api.example.com');+ });++ it('keeps the proxy script and styles running under the stable policy', () => {+ expect(resourcePolicy()).toContain("script-src 'self' 'unsafe-inline'");+ expect(resourcePolicy()).toContain("style-src 'self' 'unsafe-inline'");+ });++ it('uses the stable restrictive default without undeclared script capabilities', () => {+ const policy = resourcePolicy();+ expect(policy).toContain("script-src 'self' 'unsafe-inline'");+ expect(policy).toContain("style-src 'self' 'unsafe-inline'");+ expect(policy).toContain("img-src 'self' data:");+ expect(policy).toContain("media-src 'self' data:");+ expect(policy).not.toContain("'unsafe-eval'");+ expect(policy).not.toContain('wasm-unsafe-eval');+ });++ it.each([+ 'javascript:alert(1)',+ 'data:',+ 'blob:',+ '*',+ 'http://*',+ 'https://*',+ 'evil.com; script-src *',+ "'self'",+ "'unsafe-eval'",+ "'nonce-abc123'",+ 'a\nb.com',+ 'a\rb.com',+ 'under_score.com',+ '[::1]',+ 'https://a.com?x=1',+ 'https://a.com#f',+ ])('drops the illegal declared domain %j', (domain) => {+ expect(resourcePolicy({ csp: JSON.stringify({ connectDomains: [domain] }) })).toContain(+ "connect-src 'none'",+ );+ });++ it.each([+ 'https://api.example.com',+ 'https://*.example.com',+ 'https://a.example.com:8443',+ 'https://a.example.com:*',+ 'HTTPS://API.EXAMPLE.COM',+ 'wss://socket.example.com',+ 'api.example.com',+ 'https://api.example.com/path',+ ])('emits the legal declared domain %j', (domain) => {+ expect(resourcePolicy({ csp: JSON.stringify({ connectDomains: [domain] }) })).toContain(+ `connect-src ${domain}`,+ );+ });++ it('emits declared domains trimmed', () => {+ expect(+ resourcePolicy({ csp: JSON.stringify({ connectDomains: ['\n https://a.com '] }) }),+ ).toContain('connect-src https://a.com;');+ });++ it('caps the number of declared domains', () => {+ const domains = Array.from({ length: 40 }, (_, i) => `https://d${i}.example.com`);+ const emitted = resourcePolicy({ csp: JSON.stringify({ connectDomains: domains }) })+ .split('; ')+ .find((directive) => directive.startsWith('connect-src '));+ expect(emitted?.split(' ')).toHaveLength(33);+ expect(emitted).not.toContain('d32.example.com');+ });++ it('honors deployment-provided source and serialized-length limits', () => {+ const domains = Array.from({ length: 40 }, (_, i) => `https://d${i}.example.com`);+ const csp = JSON.stringify({ connectDomains: domains });+ const emitted = resourcePolicy({+ csp,+ limits: { maxSourcesPerDirective: 40, maxSerializedLength: csp.length },+ })+ .split('; ')+ .find((directive) => directive.startsWith('connect-src '));++ expect(emitted?.split(' ')).toHaveLength(41);+ expect(emitted).toContain('d39.example.com');+ expect(+ resourcePolicy({+ csp,+ limits: { maxSourcesPerDirective: 40, maxSerializedLength: csp.length - 1 },+ }),+ ).toContain("connect-src 'none'");+ });++ it.each([+ ['oversized', `{"connectDomains":["https://a.com"],"pad":"${'x'.repeat(4200)}"}`],+ ['unparseable', '{not json'],+ ['an array', '["https://a.com"]'],+ ['null', 'null'],+ ['repeated', ['{"connectDomains":["https://a.com"]}', '{"connectDomains":["https://b.com"]}']],+ ])('falls back to the restrictive default for %s csp', (_name, csp) => {+ const policy = resourcePolicy({ csp });+ expect(policy).toContain("connect-src 'none'");+ expect(policy).toContain('frame-src blob:');+ });++ it('accepts a declaration exactly at the length the client mirrors', () => {+ const pad = 'a'.repeat(+ MCP_APP_CSP_MAX_LENGTH - '{"connectDomains":["https://a.com"],"pad":""}'.length,+ );+ const csp = `{"connectDomains":["https://a.com"],"pad":"${pad}"}`;+ expect(csp).toHaveLength(MCP_APP_CSP_MAX_LENGTH);+ expect(resourcePolicy({ csp })).toContain('connect-src https://a.com');+ });+});++describe('buildSandboxResponse document', () => {+ it('substitutes both trusted policy markers in the supplied document', () => {+ expect(SANDBOX_HTML).toContain('/*__CSP_APPLIED__*/');+ expect(SANDBOX_HTML).toContain('/*__VIEW_CSP__*/');++ const { headers, body } = serve();+ expect(body).not.toContain('/*__CSP_APPLIED__*/');+ expect(body).not.toContain('/*__VIEW_CSP__*/');+ expect(body).toContain('window.__MCP_SANDBOX_CSP_APPLIED = true;');+ expect(body).toContain('window.__MCP_VIEW_CSP = ');+ expect(headers['Cache-Control']).toContain('no-store');+ expect(headers['Content-Type']).toBe('text/html; charset=utf-8');+ expect(headers['X-Content-Type-Options']).toBe('nosniff');+ expect(headers['Referrer-Policy']).toBe('same-origin');+ });++ it('serializes the trusted View policy without creating an inline script boundary', () => {+ const { body } = serve({ csp: JSON.stringify({ resourceDomains: ['https://x.test/path'] }) });+ expect(body).not.toContain('</script><script-src');+ expect(+ viewPolicy({ csp: JSON.stringify({ resourceDomains: ['https://x.test/path'] }) }),+ ).toContain('https://x.test/path');+ });+});diff --git a/packages/api/src/mcp/__tests__/scope.integration.test.ts b/packages/api/src/mcp/__tests__/scope.integration.test.tsindex 84a5f2d1fd..1ffec3e56a 100644--- a/packages/api/src/mcp/__tests__/scope.integration.test.ts+++ b/packages/api/src/mcp/__tests__/scope.integration.test.ts@@ -223,6 +223,7 @@ describe('request-scoped MCP lifecycle integration', () => {server = await createRequestScopedTestServer();manager = createManager();jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({+ isAppServerConfig: jest.fn().mockResolvedValue(false),resolveAllowlists: jest.fn(async () => ({allowedDomains: null,allowedAddresses: null,diff --git a/packages/api/src/mcp/apps.ts b/packages/api/src/mcp/apps.tsnew file mode 100644index 0000000000..78a4a03499--- /dev/null+++ b/packages/api/src/mcp/apps.ts@@ -0,0 +1,382 @@+/**+ * Reimplemented here so `@librechat/api` (emitted as CommonJS) never statically+ * imports the ESM-only `@modelcontextprotocol/ext-apps` package.+ */++import { logger } from '@librechat/data-schemas';+import { MCP_APP_MIME_TYPE } from 'librechat-data-provider';+import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';+import type { PluginAuthMethods, TokenMethods, IUser } from '@librechat/data-schemas';+import type { UpstreamTokenProvider } from './oauth/obo';+import type { FlowStateManager } from '~/flow/manager';+import type { MCPOAuthTokens } from './oauth';+import type * as t from './types';+import { MCPAuthenticationRefreshError, MCPAuthenticationRejectedError } from './errors';+import { getServerCustomUserVars, getUserMCPAuthMap } from './auth';+import { OpenIDReauthRequiredError } from '~/utils/oidc';++export interface ToolWithMeta {+ _meta?: Record<string, unknown> | null;+}++type McpUiToolVisibility = 'model' | 'app';++interface McpUiToolMeta {+ resourceUri?: string;+ visibility?: McpUiToolVisibility[];+}++export const RESOURCE_URI_META_KEY = 'ui/resourceUri';++export const RESOURCE_MIME_TYPE: string = MCP_APP_MIME_TYPE;++export type AuthenticatedMCPAppUser = IUser & { id: string };++export interface MCPAppValidationContext {+ serverName: string;+ serverBinding: string;+ user: AuthenticatedMCPAppUser;+ connectionTarget: t.MCPConnectionTarget;+ customUserVars?: Record<string, string>;+ signal?: AbortSignal;+}++export interface MCPAppAllowlists {+ allowedDomains?: string[] | null;+ allowedAddresses?: string[] | null;+ useSSRFProtection: boolean;+}++export interface MCPAppOperationContext extends MCPAppValidationContext {+ allowlists: MCPAppAllowlists;+ flowManager: FlowStateManager<MCPOAuthTokens | null>;+ tokenMethods?: TokenMethods;+ upstreamTokenProvider?: UpstreamTokenProvider;+ onOAuthCredentialsChanging: NonNullable<t.UserConnectionContext['onOAuthCredentialsChanging']>;+}++export function getToolUiResourceUri(tool: ToolWithMeta): string | undefined {+ const uiMeta = tool._meta?.ui as McpUiToolMeta | undefined;+ let uri: unknown = uiMeta?.resourceUri;++ if (uri === undefined) {+ uri = tool._meta?.[RESOURCE_URI_META_KEY];+ }++ if (typeof uri === 'string' && uri.startsWith('ui://')) {+ return uri;+ } else if (uri !== undefined) {+ throw new Error(`Invalid UI resource URI: ${JSON.stringify(uri)}`);+ }+ return undefined;+}++/**+ * Visibility defaults to both scopes only when the field is absent. Once a server sends an explicit+ * array, a scope is granted only if the array includes it, so an empty or future-scoped array (e.g.+ * `[]`, `['model','internal']`) hides the tool from whichever scope it omits.+ */+export function isToolHiddenFromApp(tool: ToolWithMeta): boolean {+ const visibility = (tool._meta?.ui as McpUiToolMeta | undefined)?.visibility;+ return Array.isArray(visibility) && !visibility.includes('app');+}++export function isToolHiddenFromModel(tool: ToolWithMeta): boolean {+ const visibility = (tool._meta?.ui as McpUiToolMeta | undefined)?.visibility;+ return Array.isArray(visibility) && !visibility.includes('model');+}++/** Declared here rather than importing MCPManager to avoid a circular import. */+export interface MCPAppsProxyManager {+ validateAppBinding(args: MCPAppValidationContext): Promise<{ valid: true }>;+ readResource(args: MCPAppOperationContext & { uri: string }): Promise<unknown>;+ listResources(args: MCPAppOperationContext & { cursor?: string }): Promise<unknown>;+ listResourceTemplates(args: MCPAppOperationContext & { cursor?: string }): Promise<unknown>;+ appToolCall(+ args: MCPAppOperationContext & {+ toolName: string;+ toolArguments: Record<string, unknown>;+ },+ ): Promise<unknown>;+}++export type MCPAppRequestContext = MCPAppOperationContext;++export async function resolveAppValidationContext({+ serverName,+ serverBinding,+ user,+ resolveServerConfig,+ findPluginAuthsByKeys,+ signal,+}: {+ user: AuthenticatedMCPAppUser;+ serverName: string;+ serverBinding: unknown;+ resolveServerConfig: () => Promise<t.MCPConnectionTarget | undefined>;+ findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];+ signal?: AbortSignal;+}): Promise<MCPAppValidationContext> {+ const userId = user.id;+ if (typeof serverBinding !== 'string' || serverBinding.length === 0) {+ throw new McpError(ErrorCode.InvalidRequest, 'serverBinding must be a non-empty string');+ }+ const [connectionTarget, userMCPAuthMap] = await Promise.all([+ resolveServerConfig(),+ getUserMCPAuthMap({+ userId,+ servers: [serverName],+ findPluginAuthsByKeys,+ throwOnError: true,+ }).catch((error) => {+ logger.error(+ `[resolveAppValidationContext] Failed to resolve MCP auth values for user ${userId}, server ${serverName}; failing closed`,+ error,+ );+ throw error;+ }),+ ]);+ if (!connectionTarget) {+ throw new McpError(+ ErrorCode.InvalidRequest,+ `Configuration for MCP server "${serverName}" is not available to this user.`,+ );+ }+ signal?.throwIfAborted();+ return {+ serverName,+ serverBinding,+ user,+ connectionTarget,+ customUserVars: getServerCustomUserVars(userMCPAuthMap, serverName),+ signal,+ };+}++export async function resolveEffectiveAppServerConfig({+ serverName,+ user,+ mcpConfig,+ ensureConfigServers,+ getAllServerConfigs,+ recoverServerConfig,+ isAppServerConfig,+}: {+ serverName: string;+ user: AuthenticatedMCPAppUser;+ mcpConfig: Record<string, t.MCPOptions>;+ ensureConfigServers: (+ config: Record<string, t.MCPOptions>,+ ) => Promise<Record<string, t.ParsedServerConfig>>;+ getAllServerConfigs: (+ userId: string,+ configServers: Record<string, t.ParsedServerConfig>,+ role?: string,+ ) => Promise<Record<string, t.ParsedServerConfig>>;+ recoverServerConfig: (+ serverName: string,+ config: t.ParsedServerConfig,+ userId?: string,+ ) => Promise<t.ParsedServerConfig | undefined>;+ isAppServerConfig: (serverName: string, config: t.ParsedServerConfig) => Promise<boolean>;+}): Promise<t.MCPConnectionTarget | undefined> {+ const rawConfig = mcpConfig[serverName];+ const configServers = await ensureConfigServers(rawConfig ? { [serverName]: rawConfig } : {});+ const effectiveConfigs = await getAllServerConfigs(user.id, configServers, user.role);+ const selectedConfig = effectiveConfigs[serverName];+ const serverConfig = selectedConfig?.inspectionFailed+ ? await recoverServerConfig(serverName, selectedConfig, user.id)+ : selectedConfig;+ if (!serverConfig) {+ return undefined;+ }+ return {+ serverConfig,+ connectionOwner: (await isAppServerConfig(serverName, serverConfig)) ? 'operator' : 'principal',+ };+}++/**+ * Resolves the request-scoped config and auth context so app follow-up requests can reconnect to+ * config-sourced servers even when the original tool-call connection is gone.+ *+ * Fails closed on both config and auth resolution: a transient lookup failure must reject rather+ * than fall back to the base config (wrong server) or to unresolved/stale credentials. A user who+ * genuinely has no vars still resolves to an empty map without throwing, so that path proceeds.+ * `resolveServerConfig` is supplied by the typed controller from the already admitted request+ * config, so policy admission and operation routing use one snapshot and one effective target.+ */+export async function resolveAppRequestContext({+ serverName,+ serverBinding,+ user,+ resolveServerConfig,+ findPluginAuthsByKeys,+ flowManager,+ tokenMethods,+ upstreamTokenProvider,+ onOAuthCredentialsChanging,+ allowlists,+ signal,+}: {+ user: AuthenticatedMCPAppUser;+ serverName: string;+ serverBinding: unknown;+ resolveServerConfig: () => Promise<t.MCPConnectionTarget | undefined>;+ findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];+ flowManager: FlowStateManager<MCPOAuthTokens | null>;+ tokenMethods?: TokenMethods;+ upstreamTokenProvider?: UpstreamTokenProvider;+ onOAuthCredentialsChanging: NonNullable<t.UserConnectionContext['onOAuthCredentialsChanging']>;+ allowlists: MCPAppAllowlists;+ signal?: AbortSignal;+}): Promise<MCPAppRequestContext> {+ const validationContext = await resolveAppValidationContext({+ serverName,+ serverBinding,+ user,+ resolveServerConfig,+ findPluginAuthsByKeys,+ signal,+ });+ return {+ ...validationContext,+ allowlists,+ flowManager,+ tokenMethods,+ upstreamTokenProvider,+ onOAuthCredentialsChanging,+ signal,+ };+}++export async function validateAppServerBinding(+ manager: MCPAppsProxyManager,+ ctx: MCPAppValidationContext,+): Promise<{ valid: true }> {+ return manager.validateAppBinding(ctx);+}++/** A denied app request is an expected client error, not a host fault. */+export function isDeniedAppRequest(error: unknown): boolean {+ return (+ error instanceof OpenIDReauthRequiredError ||+ error instanceof MCPAuthenticationRejectedError ||+ error instanceof MCPAuthenticationRefreshError ||+ (error != null &&+ typeof error === 'object' &&+ (error as { code?: unknown }).code === ErrorCode.InvalidRequest)+ );+}++export function buildAppProxyErrorResponse(+ error: unknown,+ fallbackMessage: string,+): { status: number; body: Record<string, unknown> } {+ if (+ error != null &&+ typeof error === 'object' &&+ (error as { code?: unknown }).code === ErrorCode.InvalidRequest+ ) {+ return { status: 400, body: { error: (error as Error).message } };+ }+ if (error instanceof OpenIDReauthRequiredError) {+ return {+ status: error.statusCode,+ body: { error: 'invalid_token', message: error.message },+ };+ }+ if (error instanceof MCPAuthenticationRejectedError) {+ return {+ status: error.statusCode,+ body: {+ error: 'invalid_token',+ code: error.code,+ message: error.message,+ retryable: error.retryable,+ connectionRefreshed: error.connectionRefreshed,+ },+ };+ }+ if (error instanceof MCPAuthenticationRefreshError) {+ return {+ status: error.statusCode,+ body: { code: error.code, message: error.message, retryable: error.retryable },+ };+ }+ return { status: 500, body: { error: fallbackMessage } };+}++export async function readAppResource(+ manager: MCPAppsProxyManager,+ ctx: MCPAppRequestContext,+ uri: unknown,+): Promise<unknown> {+ if (!ctx.serverName) {+ throw new McpError(ErrorCode.InvalidRequest, 'serverName and uri are required');+ }+ if (typeof uri !== 'string' || uri.length === 0) {+ throw new McpError(ErrorCode.InvalidRequest, 'uri must be a non-empty string');+ }+ return manager.readResource({+ ...ctx,+ uri,+ });+}++export async function listAppResources(+ manager: MCPAppsProxyManager,+ ctx: MCPAppRequestContext,+ cursor: unknown,+): Promise<unknown> {+ if (!ctx.serverName) {+ throw new McpError(ErrorCode.InvalidRequest, 'serverName is required');+ }+ if (cursor !== undefined && typeof cursor !== 'string') {+ throw new McpError(ErrorCode.InvalidRequest, 'cursor must be a string');+ }+ return manager.listResources({+ ...ctx,+ cursor,+ });+}++export async function listAppResourceTemplates(+ manager: MCPAppsProxyManager,+ ctx: MCPAppRequestContext,+ cursor: unknown,+): Promise<unknown> {+ if (!ctx.serverName) {+ throw new McpError(ErrorCode.InvalidRequest, 'serverName is required');+ }+ if (cursor !== undefined && typeof cursor !== 'string') {+ throw new McpError(ErrorCode.InvalidRequest, 'cursor must be a string');+ }+ return manager.listResourceTemplates({+ ...ctx,+ cursor,+ });+}++export async function callAppTool(+ manager: MCPAppsProxyManager,+ ctx: MCPAppRequestContext,+ toolName: unknown,+ toolArguments: unknown,+): Promise<unknown> {+ if (!ctx.serverName || typeof toolName !== 'string' || toolName.length === 0) {+ throw new McpError(ErrorCode.InvalidRequest, 'serverName and toolName are required');+ }+ if (+ toolArguments !== undefined &&+ toolArguments !== null &&+ (typeof toolArguments !== 'object' || Array.isArray(toolArguments))+ ) {+ throw new McpError(ErrorCode.InvalidRequest, 'arguments must be an object');+ }+ return manager.appToolCall({+ ...ctx,+ toolName,+ toolArguments: (toolArguments as Record<string, unknown>) || {},+ });+}diff --git a/packages/api/src/mcp/apps/binding.ts b/packages/api/src/mcp/apps/binding.tsnew file mode 100644index 0000000000..632fb43f64--- /dev/null+++ b/packages/api/src/mcp/apps/binding.ts@@ -0,0 +1,68 @@+import { createHmac, timingSafeEqual } from 'crypto';+import type { MCPConnectionTarget, MCPOptions } from '../types';+import { getMCPAppToolsPublicationGeneration } from '../toolsChanged';++const BINDING_VERSION = 'v1';+const BINDING_KEY_DOMAIN = 'librechat:mcp-app:server-binding:v1';++export type MCPAppRuntimeTarget =+ | { type: 'stdio'; command: string; args: string[]; cwd: string | null; env: [string, string][] }+ | { type: string; url: string };++export interface MCPAppBindingSubject {+ userId: string;+ tenantId?: string | null;+ serverName: string;+ connectionTarget: MCPConnectionTarget;+ runtimeTarget: MCPAppRuntimeTarget;+}++export interface MCPAppBindingCodec {+ create(subject: MCPAppBindingSubject): string;+ verify(binding: string, subject: MCPAppBindingSubject): boolean;+}++/** Keeps routing identity while excluding live request headers and refreshable credentials. */+export function projectMCPAppRuntimeTarget(config: MCPOptions): MCPAppRuntimeTarget {+ if (config.type === 'stdio') {+ return {+ type: 'stdio',+ command: config.command,+ args: [...config.args],+ cwd: config.cwd ?? null,+ env: Object.entries(config.env ?? {}).sort(([left], [right]) => left.localeCompare(right)),+ };+ }+ return { type: config.type, url: config.url };+}++export function createMCPAppBindingCodec(secret: string): MCPAppBindingCodec {+ if (!secret) {+ throw new Error('JWT_SECRET is required to bind persisted MCP Apps');+ }+ const key = createHmac('sha256', secret).update(BINDING_KEY_DOMAIN).digest();+ const digest = (subject: MCPAppBindingSubject): string => {+ const payload = JSON.stringify({+ userId: subject.userId,+ tenantId: subject.tenantId ?? null,+ serverName: subject.serverName,+ connectionOwner: subject.connectionTarget.connectionOwner,+ configGeneration: getMCPAppToolsPublicationGeneration(subject.connectionTarget.serverConfig),+ runtimeTarget: subject.runtimeTarget,+ });+ return createHmac('sha256', key).update(payload).digest('base64url');+ };+ const create = (subject: MCPAppBindingSubject): string => `${BINDING_VERSION}.${digest(subject)}`;++ return {+ create,+ verify(binding, subject) {+ if (!binding.startsWith(`${BINDING_VERSION}.`)) {+ return false;+ }+ const actual = Buffer.from(binding);+ const expected = Buffer.from(create(subject));+ return actual.length === expected.length && timingSafeEqual(actual, expected);+ },+ };+}diff --git a/packages/api/src/mcp/apps/controller.spec.ts b/packages/api/src/mcp/apps/controller.spec.tsnew file mode 100644index 0000000000..bd2a4079b0--- /dev/null+++ b/packages/api/src/mcp/apps/controller.spec.ts@@ -0,0 +1,811 @@+import { EventEmitter } from 'events';+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';+import type { MCPOptions } from 'librechat-data-provider';+import type { RequestHandler, Response } from 'express';+import type { MCPAppsControllerDependencies } from './controller';+import type { MCPAppsProxyManager } from '../apps';+import { createMCPAppsController } from './controller';+import { getPluginAuthMap } from '~/agents/auth';++jest.mock('~/agents/auth', () => ({ getPluginAuthMap: jest.fn() }));++const mockGetPluginAuthMap = getPluginAuthMap as jest.MockedFunction<typeof getPluginAuthMap>;++type MockRequest = EventEmitter & {+ aborted: boolean;+ complete: boolean;+ destroyed: boolean;+ body: Record<string, unknown>;+ query: Record<string, unknown>;+ user?: { id: string; role?: string };+ config?: {+ mcpSettings?: {+ apps?: boolean;+ allowedDomains?: string[] | null;+ allowedAddresses?: string[] | null;+ };+ mcpConfig?: Record<string, { type?: string; command?: string; args?: string[] }>;+ };+};++type MockResponse = EventEmitter & {+ headersSent: boolean;+ writableEnded: boolean;+ destroyed: boolean;+ status: jest.Mock;+ json: jest.Mock;+ send: jest.Mock;+ setHeader: jest.Mock;+ end: jest.Mock;+};++const makeRequest = (overrides: Partial<MockRequest> = {}): MockRequest =>+ Object.assign(new EventEmitter(), {+ aborted: false,+ complete: true,+ destroyed: false,+ body: { serverName: 'srv', serverBinding: 'binding', uri: 'ui://view' },+ query: {},+ user: { id: 'user-1', role: 'USER' },+ ...overrides,+ });++const makeResponse = (): MockResponse => {+ const response = Object.assign(new EventEmitter(), {+ headersSent: false,+ writableEnded: false,+ destroyed: false,+ status: jest.fn(),+ json: jest.fn(),+ send: jest.fn(),+ setHeader: jest.fn(),+ end: jest.fn(),+ });+ response.status.mockReturnValue(response);+ response.json.mockReturnValue(response);+ response.send.mockReturnValue(response);+ response.end.mockReturnValue(response);+ return response;+};++const asHandlerRequest = (request: MockRequest): Parameters<RequestHandler>[0] =>+ request as unknown as Parameters<RequestHandler>[0];+const asHandlerResponse = (response: MockResponse): Response => response as unknown as Response;++function makeDependencies(manager: MCPAppsProxyManager) {+ const provider = jest.fn();+ const onOAuthCredentialsChanging = jest.fn(async () => async () => undefined);+ const dependencies: MCPAppsControllerDependencies = {+ logger: { error: jest.fn() },+ sandboxPath: '/tmp/mcp-sandbox.html',+ sandboxFrameAncestors: 'https://host.example.com',+ readSandboxFile: jest.fn(() => '<script>/*__CSP_APPLIED__*/ /*__VIEW_CSP__*/</script>'),+ getManager: jest.fn(() => manager),+ getFlowManager: jest.fn(+ () => ({}) as ReturnType<MCPAppsControllerDependencies['getFlowManager']>,+ ),+ getAppConfig: jest.fn(async () => ({+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ })),+ getSandboxCspLimits: jest.fn(async () => ({+ maxSourcesPerDirective: 32,+ maxSerializedLength: 4096,+ })),+ ensureConfigServers: jest.fn(async () => ({+ srv: { type: 'stdio', command: 'test', args: [] },+ })),+ getAllServerConfigs: jest.fn(async () => ({+ srv: { type: 'stdio', command: 'effective', args: [] },+ })),+ recoverServerConfig: jest.fn(async (_serverName, config) => config),+ isAppServerConfig: jest.fn(async () => false),+ resolveCachedAppServerConfig: jest.fn(async () => ({+ serverConfig: { type: 'stdio', command: 'cached', args: [] },+ connectionOwner: 'principal',+ })),+ findPluginAuthsByKeys: jest.fn(),+ tokenMethods: {+ findToken: jest.fn(),+ createToken: jest.fn(),+ updateToken: jest.fn(),+ deleteTokens: jest.fn(),+ },+ createOAuthCredentialsChanging: jest.fn(() => onOAuthCredentialsChanging),+ createUpstreamTokenProvider: jest.fn(() => provider),+ } as unknown as MCPAppsControllerDependencies;+ return { dependencies, provider, onOAuthCredentialsChanging };+}++const makeManager = (): jest.Mocked<MCPAppsProxyManager> => ({+ validateAppBinding: jest.fn(),+ readResource: jest.fn(),+ listResources: jest.fn(),+ listResourceTemplates: jest.fn(),+ appToolCall: jest.fn(),+});++describe('createMCPAppsController', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockGetPluginAuthMap.mockResolvedValue({ mcp_srv: { API_KEY: 'secret' } });+ });++ it('validates a persisted binding through the admitted target context', async () => {+ const manager = makeManager();+ manager.validateAppBinding.mockResolvedValue({ valid: true });+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: {+ mcpSettings: {+ apps: true,+ allowedDomains: ['mcp.example.com'],+ allowedAddresses: null,+ },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ });+ const response = makeResponse();++ await controller.validateMCPApp(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(manager.validateAppBinding).toHaveBeenCalledWith(+ expect.objectContaining({+ serverName: 'srv',+ serverBinding: 'binding',+ connectionTarget: {+ serverConfig: { type: 'stdio', command: 'cached', args: [] },+ connectionOwner: 'principal',+ },+ customUserVars: { API_KEY: 'secret' },+ }),+ );+ expect(dependencies.resolveCachedAppServerConfig).toHaveBeenCalledWith({+ serverName: 'srv',+ userId: 'user-1',+ role: 'USER',+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ allowedDomains: ['mcp.example.com'],+ allowedAddresses: null,+ });+ expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.recoverServerConfig).not.toHaveBeenCalled();+ expect(dependencies.getFlowManager).not.toHaveBeenCalled();+ expect(dependencies.createOAuthCredentialsChanging).not.toHaveBeenCalled();+ expect(dependencies.createUpstreamTokenProvider).not.toHaveBeenCalled();+ expect(response.json).toHaveBeenCalledWith({ valid: true });+ });++ it('reuses the admitted config snapshot for manager resolution', async () => {+ const manager = makeManager();+ manager.readResource.mockResolvedValue({ contents: [] });+ const { dependencies, provider, onOAuthCredentialsChanging } = makeDependencies(manager);+ dependencies.getAppConfig = jest.fn(async () => ({+ mcpSettings: {+ apps: true,+ allowedDomains: ['mcp.example.com'],+ allowedAddresses: ['10.0.0.0/8'],+ },+ mcpConfig: {+ srv: { type: 'stdio', command: 'test', args: [] },+ } satisfies Record<string, MCPOptions>,+ }));+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest();+ const response = makeResponse();+ const next = jest.fn();++ await controller.requireMCPAppsEnabled(+ asHandlerRequest(request),+ asHandlerResponse(response),+ next,+ );++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(next).toHaveBeenCalledTimes(1);+ expect(dependencies.getAppConfig).toHaveBeenCalledTimes(1);+ expect(dependencies.ensureConfigServers).toHaveBeenCalledWith({+ srv: { type: 'stdio', command: 'test', args: [] },+ });+ expect(dependencies.getAllServerConfigs).toHaveBeenCalledWith(+ 'user-1',+ { srv: { type: 'stdio', command: 'test', args: [] } },+ 'USER',+ );+ expect(dependencies.recoverServerConfig).not.toHaveBeenCalled();+ expect(manager.readResource).toHaveBeenCalledWith(+ expect.objectContaining({+ serverName: 'srv',+ serverBinding: 'binding',+ uri: 'ui://view',+ user: request.user,+ connectionTarget: {+ serverConfig: { type: 'stdio', command: 'effective', args: [] },+ connectionOwner: 'principal',+ },+ customUserVars: { API_KEY: 'secret' },+ upstreamTokenProvider: provider,+ onOAuthCredentialsChanging,+ allowlists: {+ allowedDomains: ['mcp.example.com'],+ allowedAddresses: ['10.0.0.0/8'],+ useSSRFProtection: false,+ },+ signal: expect.any(AbortSignal),+ }),+ );+ expect(dependencies.createOAuthCredentialsChanging).toHaveBeenCalledWith(request);+ expect(response.json).toHaveBeenCalledWith({ contents: [] });+ expect(request.listenerCount('aborted')).toBe(0);+ expect(response.listenerCount('close')).toBe(0);+ });++ it('aborts the manager operation when the HTTP request closes and does not write afterward', async () => {+ const manager = makeManager();+ let operationStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ operationStarted = resolve;+ });+ let operationSignal: AbortSignal | undefined;+ manager.readResource.mockImplementation(async ({ signal }) => {+ operationSignal = signal;+ operationStarted();+ await new Promise<void>((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ });+ });+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ });+ const response = makeResponse();++ const handled = controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );+ await started;+ request.emit('aborted');+ await handled;++ expect(operationSignal?.aborted).toBe(true);+ expect(response.json).not.toHaveBeenCalled();+ expect(dependencies.logger.error).not.toHaveBeenCalled();+ expect(request.listenerCount('aborted')).toBe(0);+ expect(response.listenerCount('close')).toBe(0);+ });++ it('does not mistake a fully consumed request for a lost response transport', async () => {+ const manager = makeManager();+ manager.readResource.mockResolvedValue({ contents: [] });+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ destroyed: true,+ complete: true,+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ });+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(manager.readResource).toHaveBeenCalledTimes(1);+ expect(response.json).toHaveBeenCalledWith({ contents: [] });+ });++ it.each([{ aborted: true }, { destroyed: true, complete: false }])(+ 'stops before context work for an already terminated request: %p',+ async (terminal) => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ ...terminal,+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ });+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getManager).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ expect(response.json).not.toHaveBeenCalled();+ expect(request.listenerCount('aborted')).toBe(0);+ expect(response.listenerCount('close')).toBe(0);+ },+ );++ it('stops before context work when the request terminates during admission', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ let finishAdmission!: (value: {+ mcpSettings: { apps: true };+ mcpConfig: { srv: { type: 'stdio'; command: string; args: string[] } };+ }) => void;+ dependencies.getAppConfig = jest.fn(+ () =>+ new Promise((resolve) => {+ finishAdmission = resolve;+ }),+ );+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest();+ const response = makeResponse();+ const next = jest.fn();++ const admission = controller.requireMCPAppsEnabled(+ asHandlerRequest(request),+ asHandlerResponse(response),+ next,+ );+ request.aborted = true;+ finishAdmission({+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ });+ await admission;+ expect(next).toHaveBeenCalledTimes(1);++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getManager).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ expect(response.json).not.toHaveBeenCalled();+ });++ it('stops after cancellation during effective config resolution without manager lookup', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ let finishResolution!: (+ value: Record<string, { type: 'stdio'; command: string; args: string[] }>,+ ) => void;+ dependencies.getAllServerConfigs = jest.fn(+ () =>+ new Promise((resolve) => {+ finishResolution = resolve;+ }),+ );+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ });+ const response = makeResponse();++ const handled = controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );+ await Promise.resolve();+ await Promise.resolve();+ request.aborted = true;+ request.emit('aborted');+ finishResolution({ srv: { type: 'stdio', command: 'effective', args: [] } });+ await handled;++ expect(dependencies.getManager).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ expect(response.json).not.toHaveBeenCalled();+ expect(request.listenerCount('aborted')).toBe(0);+ expect(response.listenerCount('close')).toBe(0);+ });++ it('rejects unauthenticated requests before resolving config or auth', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(makeRequest({ user: undefined })),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(response.status).toHaveBeenCalledWith(401);+ expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ });++ it('fails closed when a proxy handler is invoked without admitted request config', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(response.status).toHaveBeenCalledWith(500);+ expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ });++ it('returns an ordinary 400 response for a manager authorization rejection', async () => {+ const manager = makeManager();+ manager.readResource.mockRejectedValue(+ new McpError(ErrorCode.InvalidRequest, 'Server "srv" is not available to this user.'),+ );+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(+ makeRequest({+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ }),+ ),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(response.status).toHaveBeenCalledWith(400);+ expect(response.json).toHaveBeenCalledWith({+ error: 'MCP error -32600: Server "srv" is not available to this user.',+ });+ expect(dependencies.logger.error).not.toHaveBeenCalled();+ });++ it('stops before registry and manager work when strict admission config fails', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ dependencies.getAppConfig = jest.fn().mockRejectedValue(new Error('config unavailable'));+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();+ const next = jest.fn();++ await controller.requireMCPAppsEnabled(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(response),+ next,+ );++ expect(response.status).toHaveBeenCalledWith(500);+ expect(next).not.toHaveBeenCalled();+ expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ });++ it('fails closed before manager use when admitted config initialization fails', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ dependencies.ensureConfigServers = jest+ .fn()+ .mockRejectedValue(new Error('registry unavailable'));+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'scoped' } },+ },+ });+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(dependencies.ensureConfigServers).toHaveBeenCalledWith({+ srv: { type: 'stdio', command: 'scoped' },+ });+ expect(response.status).toHaveBeenCalledWith(500);+ expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ });++ it('rejects an unavailable config-tier stub before manager lookup', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const stub = {+ type: 'stdio' as const,+ command: 'test',+ source: 'config' as const,+ inspectionFailed: true,+ };+ dependencies.ensureConfigServers = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.recoverServerConfig = jest.fn().mockResolvedValue(undefined);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: {+ mcpSettings: { apps: true },+ mcpConfig: { srv: { type: 'stdio', command: 'test', args: [] } },+ },+ });+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(dependencies.recoverServerConfig).toHaveBeenCalledWith('srv', stub, 'user-1');+ expect(dependencies.getManager).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ expect(response.status).toHaveBeenCalledWith(400);+ });++ it('passes the recovered YAML target to the manager instead of its failed stub', async () => {+ const manager = makeManager();+ manager.readResource.mockResolvedValue({ contents: [] });+ const { dependencies } = makeDependencies(manager);+ const stub = {+ type: 'sse' as const,+ url: 'https://unavailable.example.com',+ source: 'yaml' as const,+ inspectionFailed: true,+ };+ const recovered = {+ type: 'sse' as const,+ url: 'https://recovered.example.com',+ source: 'yaml' as const,+ };+ dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.recoverServerConfig = jest.fn().mockResolvedValue(recovered);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: { mcpSettings: { apps: true }, mcpConfig: {} },+ });+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(dependencies.recoverServerConfig).toHaveBeenCalledWith('srv', stub, 'user-1');+ expect(manager.readResource).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionTarget: { serverConfig: recovered, connectionOwner: 'principal' },+ }),+ );+ expect(response.json).toHaveBeenCalledWith({ contents: [] });+ });++ it('fails closed when failed-target recovery rejects', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const stub = {+ type: 'sse' as const,+ url: 'https://unavailable.example.com',+ source: 'yaml' as const,+ inspectionFailed: true,+ };+ dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.recoverServerConfig = jest.fn().mockRejectedValue(new Error('recovery failed'));+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: { mcpSettings: { apps: true }, mcpConfig: {} },+ });+ const response = makeResponse();++ await controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(dependencies.getManager).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ expect(response.status).toHaveBeenCalledWith(500);+ });++ it('finishes shared failed-target recovery but stops before manager lookup after cancellation', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const stub = {+ type: 'sse' as const,+ url: 'https://unavailable.example.com',+ source: 'yaml' as const,+ inspectionFailed: true,+ };+ const recovered = {+ type: 'sse' as const,+ url: 'https://recovered.example.com',+ source: 'yaml' as const,+ };+ dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ let recoveryStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ recoveryStarted = resolve;+ });+ let finishRecovery!: (value: typeof recovered) => void;+ dependencies.recoverServerConfig = jest.fn(+ () =>+ new Promise((resolve) => {+ finishRecovery = resolve;+ recoveryStarted();+ }),+ );+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({+ config: { mcpSettings: { apps: true }, mcpConfig: {} },+ });+ const response = makeResponse();++ const handled = controller.readMCPResource(+ asHandlerRequest(request),+ asHandlerResponse(response),+ jest.fn(),+ );+ await started;+ request.aborted = true;+ request.emit('aborted');+ finishRecovery(recovered);+ await handled;++ expect(dependencies.recoverServerConfig).toHaveBeenCalledWith('srv', stub, 'user-1');+ expect(dependencies.getManager).not.toHaveBeenCalled();+ expect(manager.readResource).not.toHaveBeenCalled();+ expect(response.json).not.toHaveBeenCalled();+ expect(request.listenerCount('aborted')).toBe(0);+ expect(response.listenerCount('close')).toBe(0);+ });++ it('loads the sandbox document lazily and caches only a successful read', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ expect(dependencies.readSandboxFile).not.toHaveBeenCalled();++ for (let index = 0; index < 2; index++) {+ await controller.serveMCPSandbox(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(makeResponse()),+ jest.fn(),+ );+ }++ expect(dependencies.readSandboxFile).toHaveBeenCalledTimes(1);+ expect(dependencies.readSandboxFile).toHaveBeenCalledWith('/tmp/mcp-sandbox.html', 'utf8');+ expect(dependencies.getSandboxCspLimits).toHaveBeenCalledTimes(2);+ });++ it('fails closed when trusted sandbox limits cannot be resolved', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ dependencies.getSandboxCspLimits = jest.fn(async () => {+ throw new Error('config unavailable');+ });+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();++ await controller.serveMCPSandbox(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(response.status).toHaveBeenCalledWith(500);+ expect(response.send).not.toHaveBeenCalled();+ });++ it('retries a sandbox document read after a request-time failure', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const readSandboxFile = dependencies.readSandboxFile as jest.Mock;+ readSandboxFile+ .mockImplementationOnce(() => {+ throw new Error('file unavailable');+ })+ .mockReturnValueOnce('<script>/*__CSP_APPLIED__*/ /*__VIEW_CSP__*/</script>');+ const controller = createMCPAppsController(dependencies);+ const failedResponse = makeResponse();+ const recoveredResponse = makeResponse();++ await controller.serveMCPSandbox(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(failedResponse),+ jest.fn(),+ );+ await controller.serveMCPSandbox(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(recoveredResponse),+ jest.fn(),+ );++ expect(failedResponse.status).toHaveBeenCalledWith(500);+ expect(recoveredResponse.send).toHaveBeenCalledWith(+ expect.stringContaining('window.__MCP_SANDBOX_CSP_APPLIED = true;'),+ );+ expect(recoveredResponse.setHeader).toHaveBeenCalledWith(+ 'Content-Security-Policy',+ expect.arrayContaining(['frame-ancestors https://host.example.com']),+ );+ expect(readSandboxFile).toHaveBeenCalledTimes(2);+ });++ it('reuses request config and rejects requests when MCP Apps are disabled', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest({ config: { mcpSettings: { apps: false } } });+ const response = makeResponse();+ const next = jest.fn();++ await controller.requireMCPAppsEnabled(+ asHandlerRequest(request),+ asHandlerResponse(response),+ next,+ );++ expect(dependencies.getAppConfig).not.toHaveBeenCalled();+ expect(response.status).toHaveBeenCalledWith(403);+ expect(next).not.toHaveBeenCalled();+ });++ it('rejects requests when MCP Apps are omitted from the effective config', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ dependencies.getAppConfig = jest.fn(async () => ({ mcpSettings: {} }));+ const controller = createMCPAppsController(dependencies);+ const request = makeRequest();+ const response = makeResponse();+ const next = jest.fn();++ await controller.requireMCPAppsEnabled(+ asHandlerRequest(request),+ asHandlerResponse(response),+ next,+ );++ expect(request.config).toEqual({ mcpSettings: {} });+ expect(response.status).toHaveBeenCalledWith(403);+ expect(next).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/mcp/apps/controller.ts b/packages/api/src/mcp/apps/controller.tsnew file mode 100644index 0000000000..bebe5ef1e4--- /dev/null+++ b/packages/api/src/mcp/apps/controller.ts@@ -0,0 +1,368 @@+import { resolveMCPAppsPolicy } from 'librechat-data-provider';+import type { PluginAuthMethods, TokenMethods } from '@librechat/data-schemas';+import type { Request, RequestHandler, Response } from 'express';+import type { MCPAppCspLimits } from 'librechat-data-provider';+import type { MCPAppAllowlists, MCPAppsProxyManager, AuthenticatedMCPAppUser } from '../apps';+import type { UpstreamTokenProvider } from '../oauth/obo';+import type { FlowStateManager } from '~/flow/manager';+import type { MCPOAuthTokens } from '../oauth';+import type * as t from '../types';+import {+ readAppResource,+ listAppResources,+ listAppResourceTemplates,+ callAppTool,+ validateAppServerBinding,+ buildAppProxyErrorResponse,+ isDeniedAppRequest,+ resolveAppRequestContext,+ resolveAppValidationContext,+ resolveEffectiveAppServerConfig,+} from '../apps';+import { buildSandboxResponse } from '../sandbox';++interface MCPAppsBody {+ serverName?: unknown;+ serverBinding?: unknown;+ uri?: unknown;+ cursor?: unknown;+ toolName?: unknown;+ arguments?: unknown;+}++interface MCPAppsConfig {+ mcpSettings?: {+ apps?: boolean;+ allowedDomains?: string[] | null;+ allowedAddresses?: string[] | null;+ };+ mcpConfig?: Record<string, t.MCPOptions>;+}++type MCPAppsRequest = Request<object, object, MCPAppsBody> & {+ user?: AuthenticatedMCPAppUser;+ config?: MCPAppsConfig;+};++interface Logger {+ error(message: string, error?: unknown): void;+}++export interface MCPAppsControllerDependencies {+ logger: Logger;+ sandboxPath: string;+ sandboxFrameAncestors?: string;+ readSandboxFile: (path: string, encoding: 'utf8') => string;+ getManager: () => MCPAppsProxyManager;+ getFlowManager: () => FlowStateManager<MCPOAuthTokens | null>;+ getAppConfig: (request: MCPAppsRequest) => Promise<MCPAppsConfig | undefined>;+ getSandboxCspLimits: () => Promise<MCPAppCspLimits>;+ ensureConfigServers: (+ mcpConfig: Record<string, t.MCPOptions>,+ ) => Promise<Record<string, t.ParsedServerConfig>>;+ getAllServerConfigs: (+ userId: string,+ configServers: Record<string, t.ParsedServerConfig>,+ role?: string,+ ) => Promise<Record<string, t.ParsedServerConfig>>;+ recoverServerConfig: (+ serverName: string,+ config: t.ParsedServerConfig,+ userId?: string,+ ) => Promise<t.ParsedServerConfig | undefined>;+ isAppServerConfig: (serverName: string, config: t.ParsedServerConfig) => Promise<boolean>;+ resolveCachedAppServerConfig: (args: {+ serverName: string;+ userId: string;+ role?: string;+ mcpConfig: Record<string, t.MCPOptions>;+ allowedDomains?: string[] | null;+ allowedAddresses?: string[] | null;+ }) => Promise<t.MCPConnectionTarget | undefined>;+ findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];+ tokenMethods: TokenMethods;+ createOAuthCredentialsChanging: (+ request: MCPAppsRequest,+ ) => NonNullable<t.UserConnectionContext['onOAuthCredentialsChanging']>;+ createUpstreamTokenProvider: (+ request: MCPAppsRequest,+ response: Response,+ user: AuthenticatedMCPAppUser,+ ) => UpstreamTokenProvider;+}++type AppProxy = (+ manager: MCPAppsProxyManager,+ context: Awaited<ReturnType<typeof resolveAppRequestContext>>,+ body: MCPAppsBody,+) => Promise<unknown>;++interface AppProxyOptions {+ label: string;+ fallback: string;+ proxy: AppProxy;+ logExpectedErrors?: boolean;+}++function getServerName(body: MCPAppsBody): string {+ if (typeof body.serverName !== 'string' || body.serverName.length === 0) {+ return '';+ }+ return body.serverName;+}++function attachCancellation(+ request: MCPAppsRequest,+ response: Response,+): {+ signal: AbortSignal;+ dispose: () => void;+} {+ const controller = new AbortController();+ const abort = () => {+ if (!controller.signal.aborted) {+ controller.abort(new Error('MCP App request cancelled'));+ }+ };+ request.once('aborted', abort);+ response.once('close', abort);+ if (+ request.aborted ||+ (request.destroyed && !request.complete) ||+ response.destroyed ||+ response.writableEnded+ ) {+ abort();+ }+ return {+ signal: controller.signal,+ dispose: () => {+ request.off('aborted', abort);+ response.off('close', abort);+ },+ };+}++function canWriteResponse(response: Response): boolean {+ return !response.headersSent && !response.writableEnded && !response.destroyed;+}++function getAdmittedMCPConfig(request: MCPAppsRequest): Record<string, t.MCPOptions> {+ if (request.config == null) {+ throw new Error('MCP App request configuration was not admitted');+ }+ return request.config.mcpConfig ?? {};+}++function getAdmittedMCPAllowlists(request: MCPAppsRequest): MCPAppAllowlists {+ if (request.config == null) {+ throw new Error('MCP App request configuration was not admitted');+ }+ const { allowedDomains, allowedAddresses } = request.config.mcpSettings ?? {};+ return {+ allowedDomains,+ allowedAddresses,+ useSSRFProtection: !Array.isArray(allowedDomains) || allowedDomains.length === 0,+ };+}++export function createMCPAppsController(dependencies: MCPAppsControllerDependencies): {+ readMCPResource: RequestHandler;+ listMCPResources: RequestHandler;+ listMCPResourceTemplates: RequestHandler;+ appToolCall: RequestHandler;+ validateMCPApp: RequestHandler;+ serveMCPSandbox: RequestHandler;+ requireMCPAppsEnabled: RequestHandler;+} {+ let sandboxHtml: string | undefined;+ const loadSandboxHtml = (): string => {+ sandboxHtml ??= dependencies.readSandboxFile(dependencies.sandboxPath, 'utf8');+ return sandboxHtml;+ };++ const sendError = (+ response: Response,+ error: unknown,+ options: Omit<AppProxyOptions, 'proxy'>,+ ) => {+ if (options.logExpectedErrors || !isDeniedAppRequest(error)) {+ dependencies.logger.error(`[${options.label}] Error:`, error);+ }+ if (!canWriteResponse(response)) {+ return;+ }+ const { status, body } = buildAppProxyErrorResponse(error, options.fallback);+ response.status(status).json(body);+ };++ const createProxyHandler =+ (options: AppProxyOptions): RequestHandler =>+ async (baseRequest, response): Promise<void> => {+ const request = baseRequest as MCPAppsRequest;+ const user = request.user;+ if (!user?.id) {+ response.status(401).json({ error: 'Unauthorized' });+ return;+ }+ const cancellation = attachCancellation(request, response);+ try {+ cancellation.signal.throwIfAborted();+ const body = request.body ?? {};+ const serverName = getServerName(body);+ const context = await resolveAppRequestContext({+ user,+ serverName,+ serverBinding: body.serverBinding,+ resolveServerConfig: () =>+ resolveEffectiveAppServerConfig({+ serverName,+ user,+ mcpConfig: getAdmittedMCPConfig(request),+ ensureConfigServers: dependencies.ensureConfigServers,+ getAllServerConfigs: dependencies.getAllServerConfigs,+ recoverServerConfig: dependencies.recoverServerConfig,+ isAppServerConfig: dependencies.isAppServerConfig,+ }),+ findPluginAuthsByKeys: dependencies.findPluginAuthsByKeys,+ flowManager: dependencies.getFlowManager(),+ tokenMethods: dependencies.tokenMethods,+ onOAuthCredentialsChanging: dependencies.createOAuthCredentialsChanging(request),+ upstreamTokenProvider: dependencies.createUpstreamTokenProvider(request, response, user),+ allowlists: getAdmittedMCPAllowlists(request),+ signal: cancellation.signal,+ });+ cancellation.signal.throwIfAborted();+ const result = await options.proxy(dependencies.getManager(), context, body);+ if (canWriteResponse(response)) {+ response.json(result);+ }+ } catch (error) {+ if (!cancellation.signal.aborted) {+ sendError(response, error, options);+ }+ } finally {+ cancellation.dispose();+ }+ };++ const readMCPResource = createProxyHandler({+ label: 'readMCPResource',+ fallback: 'Failed to read resource',+ proxy: (manager, context, body) => readAppResource(manager, context, body.uri),+ });+ const validateMCPApp: RequestHandler = async (baseRequest, response): Promise<void> => {+ const request = baseRequest as MCPAppsRequest;+ const user = request.user;+ if (!user?.id) {+ response.status(401).json({ error: 'Unauthorized' });+ return;+ }+ const cancellation = attachCancellation(request, response);+ try {+ cancellation.signal.throwIfAborted();+ const body = request.body ?? {};+ const serverName = getServerName(body);+ const allowlists = getAdmittedMCPAllowlists(request);+ const context = await resolveAppValidationContext({+ user,+ serverName,+ serverBinding: body.serverBinding,+ resolveServerConfig: () =>+ dependencies.resolveCachedAppServerConfig({+ serverName,+ userId: user.id,+ role: user.role,+ mcpConfig: getAdmittedMCPConfig(request),+ allowedDomains: allowlists.allowedDomains,+ allowedAddresses: allowlists.allowedAddresses,+ }),+ findPluginAuthsByKeys: dependencies.findPluginAuthsByKeys,+ signal: cancellation.signal,+ });+ cancellation.signal.throwIfAborted();+ const result = await validateAppServerBinding(dependencies.getManager(), context);+ if (canWriteResponse(response)) {+ response.json(result);+ }+ } catch (error) {+ if (!cancellation.signal.aborted) {+ sendError(response, error, {+ label: 'validateMCPApp',+ fallback: 'Failed to validate MCP App',+ });+ }+ } finally {+ cancellation.dispose();+ }+ };+ const listMCPResources = createProxyHandler({+ label: 'listMCPResources',+ fallback: 'Failed to list resources',+ proxy: (manager, context, body) => listAppResources(manager, context, body.cursor),+ });+ const listMCPResourceTemplates = createProxyHandler({+ label: 'listMCPResourceTemplates',+ fallback: 'Failed to list resource templates',+ proxy: (manager, context, body) => listAppResourceTemplates(manager, context, body.cursor),+ });+ const appToolCall = createProxyHandler({+ label: 'appToolCall',+ fallback: 'Failed to execute tool',+ logExpectedErrors: true,+ proxy: (manager, context, body) => callAppTool(manager, context, body.toolName, body.arguments),+ });++ const serveMCPSandbox: RequestHandler = async (request, response): Promise<void> => {+ try {+ const limits = await dependencies.getSandboxCspLimits();+ const { headers, body } = buildSandboxResponse({+ sandboxHtml: loadSandboxHtml(),+ frameAncestors: dependencies.sandboxFrameAncestors,+ csp: typeof request.query.csp === 'string' ? request.query.csp : undefined,+ limits,+ });+ for (const [name, value] of Object.entries(headers)) {+ response.setHeader(name, value);+ }+ response.send(body);+ } catch (error) {+ dependencies.logger.error('[serveMCPSandbox] Error:', error);+ if (response.headersSent) {+ response.end();+ return;+ }+ response.status(500).json({ error: 'Failed to load MCP sandbox' });+ }+ };++ const requireMCPAppsEnabled: RequestHandler = async (+ baseRequest,+ response,+ next,+ ): Promise<void> => {+ const request = baseRequest as MCPAppsRequest;+ try {+ const appConfig = request.config ?? (await dependencies.getAppConfig(request));+ request.config = appConfig;+ if (!resolveMCPAppsPolicy(appConfig?.mcpSettings?.apps).enabled) {+ response.status(403).json({ error: 'MCP Apps are disabled' });+ return;+ }+ next();+ } catch (error) {+ dependencies.logger.error('[requireMCPAppsEnabled] Error:', error);+ response.status(500).json({ error: 'Failed to resolve MCP Apps configuration' });+ }+ };++ return {+ readMCPResource,+ listMCPResources,+ listMCPResourceTemplates,+ appToolCall,+ validateMCPApp,+ serveMCPSandbox,+ requireMCPAppsEnabled,+ };+}diff --git a/packages/api/src/mcp/apps/limits.spec.ts b/packages/api/src/mcp/apps/limits.spec.tsnew file mode 100644index 0000000000..8e87d3bdc1--- /dev/null+++ b/packages/api/src/mcp/apps/limits.spec.ts@@ -0,0 +1,187 @@+import { MemoryStore } from 'express-rate-limit';+import type { NextFunction, Request, Response } from 'express';+import { createMCPAppAdmissionRateLimiter, createMCPAppRateLimiter } from './limits';++type LimitOverrides = {+ resourcesPerMinute?: number;+ toolCallsPerMinute?: number;+};++type Invocation = {+ status: number;+ body?: unknown;+ headers: Record<string, string>;+};++function createHarness(kind: 'resource' | 'toolCall', limits?: LimitOverrides) {+ const logViolation = jest.fn().mockResolvedValue(undefined);+ const middleware = createMCPAppRateLimiter(kind, {+ store: new MemoryStore(),+ logViolation,+ score: 3,+ });++ const invoke = (): Promise<Invocation> =>+ new Promise((resolve, reject) => {+ const headers: Record<string, string> = {};+ const request = {+ user: { id: 'user-1' },+ config: limits ? { config: { rateLimits: { mcpApps: limits } } } : { config: {} },+ } as unknown as Request;+ const response = {+ headersSent: false,+ setHeader(name: string, value: string | number) {+ headers[name.toLowerCase()] = String(value);+ return response;+ },+ status(code: number) {+ response.statusCode = code;+ return response;+ },+ json(body: unknown) {+ resolve({ status: response.statusCode, body, headers });+ return response;+ },+ statusCode: 200,+ } as unknown as Response;+ const next: NextFunction = (error?: unknown) => {+ if (error) {+ reject(error);+ return;+ }+ resolve({ status: 200, headers });+ };++ middleware(request, response, next);+ });++ return { invoke, logViolation };+}++describe('createMCPAppRateLimiter', () => {+ it.each([+ ['resource' as const, '120'],+ ['toolCall' as const, '60'],+ ])('uses the schema default for %s requests', async (kind, expected) => {+ const { invoke } = createHarness(kind);++ const response = await invoke();++ expect(response.status).toBe(200);+ expect(response.headers['x-ratelimit-limit']).toBe(expected);+ });++ it.each([+ ['resource' as const, { resourcesPerMinute: 2 }, 'resource'],+ ['toolCall' as const, { toolCallsPerMinute: 2 }, 'tool call'],+ ])(+ 'applies the request-scoped %s limit and reports its effective value',+ async (kind, limits, label) => {+ const { invoke, logViolation } = createHarness(kind, limits);++ expect((await invoke()).status).toBe(200);+ expect((await invoke()).status).toBe(200);+ const limited = await invoke();++ expect(limited.status).toBe(429);+ expect(limited.body).toEqual({+ message: `Too many app ${label} requests. Try again later`,+ });+ expect(logViolation).toHaveBeenCalledWith(+ expect.objectContaining({ user: { id: 'user-1' } }),+ expect.anything(),+ 'tool_call_limit',+ {+ type: 'tool_call_limit',+ max: 2,+ limiter: 'user',+ windowInMinutes: 1,+ },+ 3,+ );+ },+ );+});++describe('createMCPAppAdmissionRateLimiter', () => {+ it('shares the base-policy limit across App operation kinds for one user', async () => {+ const logViolation = jest.fn().mockResolvedValue(undefined);+ const middleware = createMCPAppAdmissionRateLimiter({+ store: new MemoryStore(),+ getLimit: () => 2,+ logViolation,+ });+ const invoke = (): Promise<Invocation> =>+ new Promise((resolve, reject) => {+ const headers: Record<string, string> = {};+ const request = { user: { id: 'user-1' } } as unknown as Request;+ const response = {+ headersSent: false,+ setHeader(name: string, value: string | number) {+ headers[name.toLowerCase()] = String(value);+ return response;+ },+ status(code: number) {+ response.statusCode = code;+ return response;+ },+ json(body: unknown) {+ resolve({ status: response.statusCode, body, headers });+ return response;+ },+ statusCode: 200,+ } as unknown as Response;+ middleware(request, response, (error?: unknown) => {+ if (error) {+ reject(error);+ } else {+ resolve({ status: 200, headers });+ }+ });+ });++ expect((await invoke()).status).toBe(200);+ expect((await invoke()).status).toBe(200);+ const limited = await invoke();++ expect(limited.status).toBe(429);+ expect(limited.body).toEqual({ message: 'Too many app requests. Try again later' });+ expect(logViolation).toHaveBeenCalledWith(+ expect.objectContaining({ user: { id: 'user-1' } }),+ expect.anything(),+ 'tool_call_limit',+ expect.objectContaining({ max: 2, limiter: 'user' }),+ undefined,+ );+ });++ it('uses the shared default when registry policy resolution fails', async () => {+ const middleware = createMCPAppAdmissionRateLimiter({+ store: new MemoryStore(),+ getLimit: () => {+ throw new Error('registry unavailable');+ },+ logViolation: jest.fn().mockResolvedValue(undefined),+ });+ const headers: Record<string, string> = {};+ const request = { user: { id: 'user-2' } } as unknown as Request;+ const response = {+ setHeader(name: string, value: string | number) {+ headers[name.toLowerCase()] = String(value);+ return response;+ },+ } as unknown as Response;++ await new Promise<void>((resolve, reject) => {+ middleware(request, response, (error?: unknown) => {+ if (error) {+ reject(error);+ } else {+ resolve();+ }+ });+ });++ expect(headers['x-ratelimit-limit']).toBe('240');+ });+});diff --git a/packages/api/src/mcp/apps/limits.ts b/packages/api/src/mcp/apps/limits.tsnew file mode 100644index 0000000000..31677b14fa--- /dev/null+++ b/packages/api/src/mcp/apps/limits.ts@@ -0,0 +1,119 @@+import { rateLimit } from 'express-rate-limit';+import {+ ViolationTypes,+ resolveMCPAppRateLimits,+ DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+} from 'librechat-data-provider';+import type { AugmentedRequest, Store } from 'express-rate-limit';+import type { Request, RequestHandler, Response } from 'express';+import type { TCustomConfig } from 'librechat-data-provider';++type MCPAppRateLimitKind = 'resource' | 'toolCall';++type MCPAppRateLimitRequest = Request & {+ user?: { id?: string };+ config?: {+ config?: {+ rateLimits?: TCustomConfig['rateLimits'];+ };+ };+};++type ViolationDetails = {+ type: ViolationTypes;+ max: number;+ limiter: 'user';+ windowInMinutes: 1;+};++export interface MCPAppRateLimiterDependencies {+ store: Store;+ score?: number | string;+ logViolation: (+ request: Request,+ response: Response,+ type: ViolationTypes,+ details: ViolationDetails,+ score?: number | string,+ ) => Promise<void>;+}++export interface MCPAppAdmissionRateLimiterDependencies extends MCPAppRateLimiterDependencies {+ getLimit: () => number | undefined;+}++const limiters: Record<+ MCPAppRateLimitKind,+ {+ key: keyof ReturnType<typeof resolveMCPAppRateLimits>;+ message: string;+ }+> = {+ resource: {+ key: 'resourcesPerMinute',+ message: 'Too many app resource requests. Try again later',+ },+ toolCall: {+ key: 'toolCallsPerMinute',+ message: 'Too many app tool call requests. Try again later',+ },+};++export function createMCPAppRateLimiter(+ kind: MCPAppRateLimitKind,+ dependencies: MCPAppRateLimiterDependencies,+): RequestHandler {+ const definition = limiters[kind];+ return rateLimit({+ windowMs: 60_000,+ limit: (request) => {+ const config = (request as MCPAppRateLimitRequest).config?.config;+ return resolveMCPAppRateLimits(config?.rateLimits)[definition.key];+ },+ handler: async (request, response) => {+ const type = ViolationTypes.TOOL_CALL_LIMIT;+ const details: ViolationDetails = {+ type,+ max: (request as AugmentedRequest).rateLimit.limit,+ limiter: 'user',+ windowInMinutes: 1,+ };+ await dependencies.logViolation(request, response, type, details, dependencies.score);+ response.status(429).json({ message: definition.message });+ },+ keyGenerator: (request) => String((request as MCPAppRateLimitRequest).user?.id ?? ''),+ store: dependencies.store,+ });+}++/** Shared inexpensive admission bucket evaluated before request-scoped MCP policy/config work. */+export function createMCPAppAdmissionRateLimiter(+ dependencies: MCPAppAdmissionRateLimiterDependencies,+): RequestHandler {+ return rateLimit({+ windowMs: 60_000,+ limit: () => {+ try {+ const configured = dependencies.getLimit();+ return typeof configured === 'number' && Number.isSafeInteger(configured) && configured > 0+ ? configured+ : DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE;+ } catch {+ return DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE;+ }+ },+ handler: async (request, response) => {+ const type = ViolationTypes.TOOL_CALL_LIMIT;+ const details: ViolationDetails = {+ type,+ max: (request as AugmentedRequest).rateLimit.limit,+ limiter: 'user',+ windowInMinutes: 1,+ };+ await dependencies.logViolation(request, response, type, details, dependencies.score);+ response.status(429).json({ message: 'Too many app requests. Try again later' });+ },+ keyGenerator: (request) => String((request as MCPAppRateLimitRequest).user?.id ?? ''),+ store: dependencies.store,+ });+}diff --git a/packages/api/src/mcp/assistants.ts b/packages/api/src/mcp/assistants.tsindex 78906210b4..7cf303e623 100644--- a/packages/api/src/mcp/assistants.ts+++ b/packages/api/src/mcp/assistants.ts@@ -1,17 +1,87 @@import { logger } from '@librechat/data-schemas';import {Constants,+ Tools,buildServerNameAliases,normalizeServerName,splitMCPToolKey,} from 'librechat-data-provider';-import type { MCPOptions } from 'librechat-data-provider';-import type { LCAvailableTools, LCFunctionTool, ParsedServerConfig } from '~/mcp/types';+import type { MCPOptions, UIResource } from 'librechat-data-provider';+import type { Artifacts, LCAvailableTools, LCFunctionTool, ParsedServerConfig } from '~/mcp/types';import { createConcurrencyLimiter } from '~/utils/promise';import { findShadowedServerNames } from '~/mcp/utils';const RECOVERY_CONCURRENCY = 3;+interface AssistantMCPMessage {+ messageId?: string;+ conversationId?: string | null;+ attachments?: unknown[];+}++interface AssistantMCPArtifactHost {+ responseMessage?: AssistantMCPMessage;+ finalMessage?: AssistantMCPMessage;+ res?: {+ destroyed?: boolean;+ writableEnded?: boolean;+ write(chunk: string): unknown;+ };+}++export interface AssistantMCPToolResult {+ output: unknown;+ uiResources?: UIResource[];+}++/** Separates host-only App data from an MCP result before Assistants submits model-bound output. */+export function splitAssistantMCPToolResult(+ rawOutput: unknown,+ isMCPTool: boolean,+): AssistantMCPToolResult {+ if (!isMCPTool || !Array.isArray(rawOutput) || rawOutput.length !== 2) {+ return { output: rawOutput };+ }+ const [output, candidateArtifact] = rawOutput as [unknown, Artifacts];+ const uiResources = candidateArtifact?.[Tools.ui_resources]?.data;+ return {+ output,+ ...(Array.isArray(uiResources) && uiResources.length > 0 ? { uiResources } : {}),+ };+}++/** Persists and streams an App attachment through either Assistants runtime's message owner. */+export function appendAssistantMCPAppArtifact({+ host,+ toolCallId,+ uiResources,+}: {+ host: AssistantMCPArtifactHost;+ toolCallId: string;+ uiResources: UIResource[];+}): void {+ const message = host.responseMessage ?? host.finalMessage;+ if (+ !message ||+ typeof message.messageId !== 'string' ||+ typeof message.conversationId !== 'string'+ ) {+ return;+ }+ const attachment = {+ type: Tools.ui_resources,+ messageId: message.messageId,+ toolCallId,+ conversationId: message.conversationId,+ [Tools.ui_resources]: uiResources,+ };+ message.attachments ??= [];+ message.attachments.push(attachment);+ if (host.res && !host.res.destroyed && !host.res.writableEnded) {+ host.res.write(`event: attachment\ndata: ${JSON.stringify(attachment)}\n\n`);+ }+}+export interface AssistantMCPUser {id?: string;role?: string;diff --git a/packages/api/src/mcp/auth.ts b/packages/api/src/mcp/auth.tsindex c374f75019..33f12cbd21 100644--- a/packages/api/src/mcp/auth.ts+++ b/packages/api/src/mcp/auth.ts@@ -20,6 +20,7 @@ export async function getUserMCPAuthMap({toolInstances,serverNames,findPluginAuthsByKeys,+ throwOnError = false,}: {userId: string;tools?: (string | undefined)[];@@ -33,6 +34,12 @@ export async function getUserMCPAuthMap({*/serverNames?: readonly string[];findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];+ /**+ * Propagate lookup/decryption failures instead of degrading to an empty map. Callers that must+ * distinguish "this user has no vars" from "we could not read them" (and fail closed rather than+ * proceed with unresolved credentials) opt in; every other caller keeps the swallowing default.+ */+ throwOnError?: boolean;}): Promise<Record<string, Record<string, string>>> {let allMcpCustomUserVars: Record<string, Record<string, string>> = {};let mcpPluginKeysToFetch: string[] = [];@@ -86,7 +93,7 @@ export async function getUserMCPAuthMap({allMcpCustomUserVars = await getPluginAuthMap({userId,pluginKeys: mcpPluginKeysToFetch,- throwError: false,+ throwError: throwOnError,findPluginAuthsByKeys,});} catch (err) {@@ -96,6 +103,9 @@ export async function getUserMCPAuthMap({)}), user ${userId}: ${err instanceof Error ? err.message : 'Unknown error'}`,err,);+ if (throwOnError) {+ throw err;+ }}return allMcpCustomUserVars;diff --git a/packages/api/src/mcp/capabilities.ts b/packages/api/src/mcp/capabilities.tsnew file mode 100644index 0000000000..dc3d93db39--- /dev/null+++ b/packages/api/src/mcp/capabilities.ts@@ -0,0 +1,47 @@+import type { TMCPAppsPolicy } from 'librechat-data-provider';++export type MCPClientCapabilityProfile = 'standard' | 'apps';++export const STANDARD_MCP_CAPABILITY_PROFILE: MCPClientCapabilityProfile = 'standard';+export const MCP_APPS_CAPABILITY_PROFILE: MCPClientCapabilityProfile = 'apps';++/** Resolves the immutable capabilities negotiated by one MCP client session. */+export function resolveMCPClientCapabilityProfile(+ mcpApps?: Pick<TMCPAppsPolicy, 'enabled'>,+): MCPClientCapabilityProfile {+ return mcpApps?.enabled === true ? MCP_APPS_CAPABILITY_PROFILE : STANDARD_MCP_CAPABILITY_PROFILE;+}++/** Keeps internal pool keys distinct without changing the server's logical identity. */+export function getMCPConnectionPoolKey(+ serverName: string,+ capabilityProfile: MCPClientCapabilityProfile,+): string {+ return JSON.stringify([serverName, capabilityProfile]);+}++/** Decodes the private, profile-aware connection-pool identity. */+export function parseMCPConnectionPoolKey(poolKey: string): {+ serverName: string;+ capabilityProfile: MCPClientCapabilityProfile;+} {+ const parsed = JSON.parse(poolKey) as unknown;+ if (+ !Array.isArray(parsed) ||+ parsed.length !== 2 ||+ typeof parsed[0] !== 'string' ||+ (parsed[1] !== STANDARD_MCP_CAPABILITY_PROFILE && parsed[1] !== MCP_APPS_CAPABILITY_PROFILE)+ ) {+ throw new Error('Invalid MCP connection pool key');+ }+ return { serverName: parsed[0], capabilityProfile: parsed[1] };+}++/** Keeps per-user work distinct by logical server and immutable capability profile. */+export function getMCPUserConnectionPoolKey(+ userId: string,+ serverName: string,+ capabilityProfile: MCPClientCapabilityProfile,+): string {+ return JSON.stringify([userId, serverName, capabilityProfile]);+}diff --git a/packages/api/src/mcp/catalog/recovery.spec.ts b/packages/api/src/mcp/catalog/recovery.spec.tsindex f5f75a308d..f372bf78b4 100644--- a/packages/api/src/mcp/catalog/recovery.spec.ts+++ b/packages/api/src/mcp/catalog/recovery.spec.ts@@ -17,6 +17,7 @@ import {readMCPRecoveryGenerationAround,recoverMCPServerCatalogs,} from './recovery';+import { MCP_APPS_CAPABILITY_PROFILE, STANDARD_MCP_CAPABILITY_PROFILE } from '../capabilities';import { prepareMCPAuthorizationMutation } from '../authorization';import { MCPTokenRefreshUnavailableError } from '../oauth';@@ -781,6 +782,54 @@ describe('recoverMCPServerCatalogs', () => {]);});+ it('does not coalesce recovery across capability profiles', async () => {+ const discoverServerTools = jest.fn().mockResolvedValue({ tools: [] });+ const deps = {+ loadUserMCPAuthMap: jest.fn().mockResolvedValue({}),+ discoverServerTools,+ formatServerTools: jest.fn().mockReturnValue({}),+ recoveryTracker,+ };+ const config = serverConfig('profiled');++ await Promise.all([+ recoverMCPServerCatalogs(+ {+ user,+ servers: [+ {+ serverName: 'profiled',+ serverConfig: config,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ },+ ],+ },+ deps,+ ),+ recoverMCPServerCatalogs(+ {+ user,+ servers: [+ {+ serverName: 'profiled',+ serverConfig: config,+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ },+ ],+ },+ deps,+ ),+ ]);++ expect(discoverServerTools).toHaveBeenCalledTimes(2);+ expect(discoverServerTools).toHaveBeenCalledWith(+ expect.objectContaining({ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE }),+ );+ expect(discoverServerTools).toHaveBeenCalledWith(+ expect.objectContaining({ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE }),+ );+ });+it('retains reauthorization state and recovered public tools during the retry window', async () => {let recoveryGeneration = 'generation-1';const discoverServerTools = jest.fn().mockResolvedValue({diff --git a/packages/api/src/mcp/catalog/recovery.ts b/packages/api/src/mcp/catalog/recovery.tsindex 8e542575a4..6c3bbcd51c 100644--- a/packages/api/src/mcp/catalog/recovery.ts+++ b/packages/api/src/mcp/catalog/recovery.ts@@ -3,6 +3,8 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';import type { Tool } from '@modelcontextprotocol/sdk/types.js';import type { IUser } from '@librechat/data-schemas';import type { LCAvailableTools, ParsedServerConfig, ToolDiscoveryOptions } from '../types';+import type { MCPClientCapabilityProfile } from '../capabilities';+import { MCP_APPS_CAPABILITY_PROFILE, STANDARD_MCP_CAPABILITY_PROFILE } from '../capabilities';import { hasCustomUserVars, waitUntilDeadline, getMissingCustomUserVars } from '../utils';import { usesDirectOpenIDBearerRecovery } from '../openid';import { getServerCustomUserVars } from '../auth';@@ -39,6 +41,7 @@ const DEFAULT_RECOVERY_POLICY: MCPServerCatalogRecoveryPolicy = {export interface MCPServerCatalogRecoveryInput {serverName: string;serverConfig: ParsedServerConfig;+ capabilityProfile?: MCPClientCapabilityProfile;}export interface MCPServerCatalogRecoveryDeps {@@ -178,12 +181,17 @@ export interface MCPServerCatalogLoaderDeps extends MCPServerCatalogRecoveryDepsuserId: string,serverName: string,serverConfig: ParsedServerConfig,+ capabilityProfile?: MCPClientCapabilityProfile,) => Promise<LCAvailableTools | null>;getServerToolFunctionsSnapshot: (userId: string,serverName: string,serverConfig: ParsedServerConfig,- options?: { deadlineMs?: number; signal?: AbortSignal },+ options?: {+ deadlineMs?: number;+ signal?: AbortSignal;+ capabilityProfile?: MCPClientCapabilityProfile;+ },) => Promise<MCPServerCatalogSnapshot>;cacheServerTools: (params: {userId: string;@@ -192,6 +200,7 @@ export interface MCPServerCatalogLoaderDeps extends MCPServerCatalogRecoveryDepsserverConfig: ParsedServerConfig;publicationGeneration?: string;publicationRevision?: string;+ capabilityProfile?: MCPClientCapabilityProfile;}) => Promise<void>;}@@ -211,6 +220,7 @@ interface MCPServerCatalogRecoveryResult {interface MCPServerCatalogEntry extends MCPServerCatalogSnapshot {serverName: string;serverConfig: ParsedServerConfig;+ capabilityProfile?: MCPClientCapabilityProfile;source: 'cache' | 'snapshot';}@@ -342,15 +352,20 @@ function resolveBudget(return policy.discoveryTimeoutMs;}-function getRecoveryKey(userId: string, serverName: string): string {- return `${userId}\u0000${serverName}`;+function getRecoveryKey(+ userId: string,+ serverName: string,+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,+): string {+ return JSON.stringify([userId, serverName, capabilityProfile]);}function getRecoveryFingerprint(serverConfig: ParsedServerConfig,policy: MCPServerCatalogRecoveryPolicy,+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,): string {- return JSON.stringify([serverConfig, policy]);+ return JSON.stringify([serverConfig, policy, capabilityProfile]);}export class MCPServerCatalogRecoveryTracker {@@ -371,8 +386,8 @@ export class MCPServerCatalogRecoveryTracker {policy: MCPServerCatalogRecoveryPolicy,): boolean {return !this.isDiscoveryHeld(- getRecoveryKey(user.id, candidate.serverName),- getRecoveryFingerprint(candidate.serverConfig, policy),+ getRecoveryKey(user.id, candidate.serverName, candidate.capabilityProfile),+ getRecoveryFingerprint(candidate.serverConfig, policy, candidate.capabilityProfile),undefined,);}@@ -385,8 +400,14 @@ export class MCPServerCatalogRecoveryTracker {discovery: Promise<unknown>,): void {this.detach(- getRecoveryKey(user.id, candidate.serverName),- { configFingerprint: getRecoveryFingerprint(candidate.serverConfig, policy) },+ getRecoveryKey(user.id, candidate.serverName, candidate.capabilityProfile),+ {+ configFingerprint: getRecoveryFingerprint(+ candidate.serverConfig,+ policy,+ candidate.capabilityProfile,+ ),+ },discovery,);}@@ -458,14 +479,26 @@ export class MCPServerCatalogRecoveryTracker {* Clears suppression after a credential/config mutation commits. A clear from a publication* carries the generation it wrote; see `clearState` for the state it spares.*/- public clear(userId: string, serverName?: string, generation?: string): void {+ public clear(+ userId: string,+ serverName?: string,+ generation?: string,+ capabilityProfile?: MCPClientCapabilityProfile,+ ): void {if (serverName != null) {- this.clearState(getRecoveryKey(userId, serverName), generation);+ if (capabilityProfile != null) {+ this.clearState(getRecoveryKey(userId, serverName, capabilityProfile), generation);+ return;+ }+ this.clearState(+ getRecoveryKey(userId, serverName, STANDARD_MCP_CAPABILITY_PROFILE),+ generation,+ );+ this.clearState(getRecoveryKey(userId, serverName, MCP_APPS_CAPABILITY_PROFILE), generation);return;}- const prefix = `${userId}\u0000`;for (const key of this.states.keys()) {- if (key.startsWith(prefix)) {+ if ((JSON.parse(key) as unknown[])[0] === userId) {this.clearState(key, generation);}}@@ -504,8 +537,12 @@ export class MCPServerCatalogRecoveryTracker {detach: DiscoveryDetacher,) => Promise<RecoveryOutcome>,): Promise<RecoveryOutcome> {- const key = getRecoveryKey(user.id, candidate.serverName);- const configFingerprint = getRecoveryFingerprint(candidate.serverConfig, policy);+ const key = getRecoveryKey(user.id, candidate.serverName, candidate.capabilityProfile);+ const configFingerprint = getRecoveryFingerprint(+ candidate.serverConfig,+ policy,+ candidate.capabilityProfile,+ );const now = Date.now();const existing = this.states.get(key);const held = this.isDiscoveryHeld(key, configFingerprint, recoveryGeneration);@@ -656,7 +693,7 @@ function trackPublications(async function discoverCandidate(user: IUser,- { serverName, serverConfig, customUserVars }: RecoveryCandidate,+ { serverName, serverConfig, customUserVars, capabilityProfile }: RecoveryCandidate,deps: MCPServerCatalogRecoveryDeps,policy: MCPServerCatalogRecoveryPolicy,{@@ -687,6 +724,7 @@ async function discoverCandidate(await trackPublication?.(async () => generation);},onDiscoveryDetached: onDetached,+ capabilityProfile,});/** Discovery can await work that ignores its budget — a token refresh persisting behind a* stalled write — and a shared flight has no request signal to end that wait, so it would hold@@ -931,7 +969,7 @@ async function recoverMCPServerCatalogsWithState(observedGeneration == null ||snapshotGeneration !== observedGeneration)) {- tracker.clear(user.id, candidate.serverName);+ tracker.clear(user.id, candidate.serverName, undefined, candidate.capabilityProfile);results[index] = { serverName: candidate.serverName, tools: null };return;}@@ -968,7 +1006,7 @@ async function recoverMCPServerCatalogsWithState(? finalGeneration !== outcomeGeneration: finalGeneration != null && finalGeneration !== outcomeGeneration);if (superseded) {- tracker.clear(user.id, candidate.serverName);+ tracker.clear(user.id, candidate.serverName, undefined, candidate.capabilityProfile);results[index] = { serverName: candidate.serverName, tools: null };return;}@@ -1020,13 +1058,24 @@ export async function loadMCPServerCatalogs(): Promise<MCPServerCatalogLoaderResult> {const { user, servers, signal } = params;const cached: MCPServerCatalogEntry[] = await Promise.all(- servers.map(async ({ serverName, serverConfig }) => {+ servers.map(async ({ serverName, serverConfig, capabilityProfile }) => {try {- const tools = await deps.getCachedServerTools(user.id, serverName, serverConfig);- return { serverName, serverConfig, tools, source: 'cache' as const };+ const tools = await deps.getCachedServerTools(+ user.id,+ serverName,+ serverConfig,+ capabilityProfile,+ );+ return { serverName, serverConfig, capabilityProfile, tools, source: 'cache' as const };} catch (error) {logger.error(`[MCP catalog loader] Failed to read cached tools for ${serverName}:`, error);- return { serverName, serverConfig, tools: null, source: 'cache' as const };+ return {+ serverName,+ serverConfig,+ capabilityProfile,+ tools: null,+ source: 'cache' as const,+ };}}),);@@ -1043,7 +1092,11 @@ export async function loadMCPServerCatalogs(user.id,entry.serverName,entry.serverConfig,- { deadlineMs: Date.now() + mcpConfig.TOOLS_LIST_TIMEOUT_MS, signal },+ {+ deadlineMs: Date.now() + mcpConfig.TOOLS_LIST_TIMEOUT_MS,+ signal,+ capabilityProfile: entry.capabilityProfile,+ },);snapshots[index] = { ...entry, ...snapshot, source: 'snapshot' as const };} catch (error) {@@ -1064,7 +1117,11 @@ export async function loadMCPServerCatalogs(const coldServers = snapshots.filter(({ tools }) => tools == null)- .map(({ serverName, serverConfig }) => ({ serverName, serverConfig }));+ .map(({ serverName, serverConfig, capabilityProfile }) => ({+ serverName,+ serverConfig,+ capabilityProfile,+ }));let recovered: MCPServerCatalogRecoveryResult = {serverTools: new Map(),reauthRequiredServers: new Set(),@@ -1094,7 +1151,12 @@ export async function loadMCPServerCatalogs(}serverTools.set(snapshot.serverName, tools);if (snapshot.tools != null) {- deps.recoveryTracker?.clear(user.id, snapshot.serverName);+ deps.recoveryTracker?.clear(+ user.id,+ snapshot.serverName,+ undefined,+ snapshot.capabilityProfile,+ );}if (snapshot.source !== 'snapshot' || snapshot.tools == null) {@@ -1108,6 +1170,7 @@ export async function loadMCPServerCatalogs(serverConfig: snapshot.serverConfig,publicationGeneration: snapshot.publicationGeneration,publicationRevision: snapshot.publicationRevision,+ capabilityProfile: snapshot.capabilityProfile,}).catch((error) =>logger.error(diff --git a/packages/api/src/mcp/catalog/store.ts b/packages/api/src/mcp/catalog/store.tsindex 21a6063367..80492245ff 100644--- a/packages/api/src/mcp/catalog/store.ts+++ b/packages/api/src/mcp/catalog/store.ts@@ -171,6 +171,7 @@ export interface CachedToolsOptions {userId?: string;serverName?: string;configGeneration?: string;+ allowLegacyMigration?: boolean;ttl?: number;}@@ -541,7 +542,7 @@ export function createMCPCatalogStore(deps: CatalogStoreDeps): MCPCatalogStore {}const toolsKey = ToolCacheKeys.MCP_SERVER(userId, serverName, configGeneration);let cached = await cache.get(toolsKey);- if (cached == null && configGeneration) {+ if (cached == null && configGeneration && options.allowLegacyMigration !== false) {cached = await withUserQueue(userId,serverName,diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.tsindex 818b6c17a1..c8ccfc776d 100644--- a/packages/api/src/mcp/connection.ts+++ b/packages/api/src/mcp/connection.ts@@ -1,6 +1,7 @@import { isIP } from 'node:net';import { EventEmitter } from 'events';import { logger } from '@librechat/data-schemas';+import { MCP_UI_EXTENSION_ID } from 'librechat-data-provider';import { fetch as undiciFetch, Agent, ProxyAgent } from 'undici';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';@@ -21,6 +22,8 @@ import type {Dispatcher,} from 'undici';import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';+import type { ClientCapabilities } from '@modelcontextprotocol/sdk/types.js';+import type { MCPClientCapabilityProfile } from './capabilities';import type { MCPOAuthTokens } from './oauth/types';import type * as t from './types';import {@@ -30,13 +33,16 @@ import {MCPTransportAuthenticationError,isStandaloneSseConflict,} from './errors';+import { MCP_APPS_CAPABILITY_PROFILE, STANDARD_MCP_CAPABILITY_PROFILE } from './capabilities';import { createSSRFSafeUndiciConnect, isSSRFTarget, resolveHostnameSSRF } from '~/auth';+import { projectMCPAppRuntimeTarget, type MCPAppRuntimeTarget } from './apps/binding';import { reserveMCPToolsChangedRevision } from './toolsChanged';import { runOutsideTracing } from '~/utils/tracing';import { mediaTypeEssence } from '~/utils/headers';import { isAddressAllowed } from '~/auth/domain';import { withMCPRequestSignal } from './signal';import { withTimeout } from '~/utils/promise';+import { RESOURCE_MIME_TYPE } from './apps';import { isOAuthServer } from './utils';import { mcpConfig } from './mcpConfig';@@ -997,6 +1003,7 @@ interface MCPConnectionParams {ephemeralConnection?: boolean;/** The owner will replace this connection after a tools/list authentication rejection. */directBearerRecoveryEnabled?: boolean;+ capabilityProfile?: MCPClientCapabilityProfile;}/** Result of an MCP `tools/list` request: one page of tools plus an optional pagination cursor. */@@ -1022,6 +1029,7 @@ export class MCPConnection extends EventEmitter {private connectPromise: Promise<void> | null = null;private readonly MAX_RECONNECT_ATTEMPTS = 3;public readonly serverName: string;+ public readonly capabilityProfile: MCPClientCapabilityProfile;private shouldStopReconnecting = false;private isReconnecting = false;private isInitializing = false;@@ -1072,6 +1080,13 @@ export class MCPConnection extends EventEmitter {*/public readonly createdAt: number;+ /**+ * Bumped on every tools/list_changed notification. Consumers that cache tool metadata can fold+ * this into their freshness check to detect tool changes that happen on a live connection, which+ * createdAt alone (stable until reconnect) cannot.+ */+ public toolListVersion = 0;+private static circuitBreakers: Map<string, CircuitBreakerState> = new Map();public static clearCooldown(serverName: string): void {@@ -1165,6 +1180,11 @@ export class MCPConnection extends EventEmitter {this.requestHeaders = normalizedHeaders;}+ /** Stable routing identity captured by this connection, without live authorization headers. */+ getMCPAppRuntimeTarget(): MCPAppRuntimeTarget {+ return projectMCPAppRuntimeTarget(this.options);+ }+getRequestHeaders(): Record<string, string> | null | undefined {return this.requestHeaders;}@@ -1197,6 +1217,7 @@ export class MCPConnection extends EventEmitter {super();this.options = params.serverConfig;this.serverName = params.serverName;+ this.capabilityProfile = params.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;this.userId = params.userId;this.useSSRFProtection = params.useSSRFProtection === true;this.allowedAddresses = params.allowedAddresses ?? null;@@ -1211,14 +1232,16 @@ export class MCPConnection extends EventEmitter {if (params.oauthTokens) {this.oauthTokens = params.oauthTokens;}+ const capabilities: ClientCapabilities =+ this.capabilityProfile === MCP_APPS_CAPABILITY_PROFILE+ ? { extensions: { [MCP_UI_EXTENSION_ID]: { mimeTypes: [RESOURCE_MIME_TYPE] } } }+ : {};this.client = new Client({name: '@librechat/api-client',version: '1.2.3',},- {- capabilities: {},- },+ { capabilities },);this.setupEventListeners();@@ -1846,6 +1869,9 @@ export class MCPConnection extends EventEmitter {private subscribeToToolListChanges(): void {this.client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {logger.debug(`${this.getLogPrefix()} Server reported a changed tool list`);+ // Stamps the MCP Apps per-tool metadata caches (resourceUri, visibility) as stale; createdAt+ // alone cannot see a list change on a still-live connection.+ this.toolListVersion += 1;await this.refreshToolList();});}@@ -2610,6 +2636,7 @@ export class MCPConnection extends EventEmitter {serverName: this.serverName,serverConfig: this.options,userId: this.userId,+ capabilityProfile: this.capabilityProfile,}),};} catch (error) {diff --git a/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts b/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.tsindex fd8ecb110a..d46c6db311 100644--- a/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts+++ b/packages/api/src/mcp/oauth/OAuthReconnectionManager.test.ts@@ -4,6 +4,7 @@ import type { ParsedServerConfig } from '../..';import { OAuthReconnectionManager } from './OAuthReconnectionManager';import { OAuthReconnectionTracker } from './OAuthReconnectionTracker';import { FlowStateManager, MCPConnection, MCPOptions } from '../..';+import { STANDARD_MCP_CAPABILITY_PROFILE } from '../capabilities';import { MCPManager } from '../MCPManager';jest.mock('@librechat/data-schemas', () => ({@@ -216,6 +217,7 @@ describe('OAuthReconnectionManager', () => {expect(mockMCPManager.getUserConnection).toHaveBeenCalledWith({serverName: 'server3',user: { id: userId },+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,serverConfig: { initTimeout: 5000 },flowManager,tokenMethods,@@ -257,6 +259,7 @@ describe('OAuthReconnectionManager', () => {expect(reconnectionTracker.isActive(userId, 'server1')).toBe(false);expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1', {reason: 'lifecycle',+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});});@@ -398,6 +401,7 @@ describe('OAuthReconnectionManager', () => {expect(reconnectionTracker.isActive(userId, 'server1')).toBe(false);expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1', {reason: 'lifecycle',+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});});@@ -667,6 +671,7 @@ describe('OAuthReconnectionManager', () => {expect(reconnectionTracker.isFailed(userId, 'server1')).toBe(true);expect(mockMCPManager.disconnectUserConnection).toHaveBeenCalledWith(userId, 'server1', {reason: 'lifecycle',+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,});});});diff --git a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts b/packages/api/src/mcp/oauth/OAuthReconnectionManager.tsindex 1e831cffc6..b853a9aba8 100644--- a/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts+++ b/packages/api/src/mcp/oauth/OAuthReconnectionManager.ts@@ -4,6 +4,7 @@ import type { ParsedServerConfig, UserConnectionContext } from '~/mcp/types';import type { MCPOAuthTokens } from './types';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { OAuthReconnectionTracker } from './OAuthReconnectionTracker';+import { STANDARD_MCP_CAPABILITY_PROFILE } from '~/mcp/capabilities';import { requiresEphemeralUserConnection } from '~/mcp/utils';import { FlowStateManager } from '~/flow/manager';import { MCPManager } from '~/mcp/MCPManager';@@ -152,7 +153,10 @@ export class OAuthReconnectionManager {private cleanupOnFailedReconnect(userId: string, serverName: string): void {this.reconnectionsTracker.setFailed(userId, serverName);this.reconnectionsTracker.removeActive(userId, serverName);- this.mcpManager?.disconnectUserConnection(userId, serverName, { reason: 'lifecycle' });+ this.mcpManager?.disconnectUserConnection(userId, serverName, {+ reason: 'lifecycle',+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,+ });}/**@@ -211,6 +215,7 @@ export class OAuthReconnectionManager {const connection = await this.mcpManager.getUserConnection({serverName,user: { id: userId } as IUser,+ capabilityProfile: STANDARD_MCP_CAPABILITY_PROFILE,serverConfig: config,flowManager: this.flowManager,tokenMethods: this.tokenMethods,@@ -268,7 +273,10 @@ export class OAuthReconnectionManager {}// if the server is already connected, don't attempt to reconnect- const existingConnections = this.mcpManager.getUserConnections(userId);+ const existingConnections = this.mcpManager.getUserConnections(+ userId,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );if (existingConnections?.has(serverName)) {const isConnected = await existingConnections.get(serverName)?.isConnected();if (isConnected) {diff --git a/packages/api/src/mcp/parsers.ts b/packages/api/src/mcp/parsers.tsindex a30ecdacb3..14c8cc295b 100644--- a/packages/api/src/mcp/parsers.ts+++ b/packages/api/src/mcp/parsers.ts@@ -1,6 +1,14 @@import crypto from 'node:crypto';-import { Tools } from 'librechat-data-provider';-import type { UIResource } from 'librechat-data-provider';+import {+ Tools,+ DEFAULT_MCP_APP_PERSISTED_BYTES,+ MCP_APP_MIME_TYPE,+ isHtmlMediaType,+ isMcpAppMimeType,+ resolveMCPAppsPolicy,+ resolveMCPUIResourceMimeType,+} from 'librechat-data-provider';+import type { UIResource, TMCPAppsPolicy } from 'librechat-data-provider';import type * as t from './types';export const DEFAULT_MCP_IMAGE_DATA_MAX_BYTES: number = 10 * 1024 * 1024;@@ -9,6 +17,43 @@ function generateResourceId(text: string): string {return crypto.createHash('sha256').update(text).digest('hex').substring(0, 10);}+/**+ * Derives a UI resource ID that is unique per result snapshot. The frontend indexes conversation+ * resources by ID, so two calls that share a base (resourceUri/text) and args but differ in+ * structuredContent, text content, _meta, or error state must not collide and overwrite each other.+ */+function deriveResourceId(+ base: string,+ result: t.MCPToolCallResponse,+ toolArgs: unknown,+ serverName?: string,+ toolName?: string,+): string {+ const meta = (result as { _meta?: unknown } | undefined)?._meta;+ const parts = [+ serverName ?? '',+ toolName ?? '',+ base,+ result?.structuredContent != null ? JSON.stringify(result.structuredContent) : '',+ result?.content != null ? JSON.stringify(result.content) : '',+ meta != null ? JSON.stringify(meta) : '',+ result?.isError === true ? '1' : '',+ toolArgs != null ? JSON.stringify(toolArgs) : '',+ ];+ return generateResourceId(parts.join('\x00'));+}++function fitsPersistedAppLimit(resource: UIResource, maxBytes: number): boolean {+ try {+ return (+ Buffer.byteLength(JSON.stringify({ [Tools.ui_resources]: { data: [resource] } }), 'utf8') <=+ maxBytes+ );+ } catch {+ return false;+ }+}+function getMCPImageDataMaxBytes(): number {const raw = process.env.MCP_IMAGE_DATA_MAX_BYTES;if (!raw) {@@ -131,6 +176,38 @@ function readResourceBody(resource: t.ResourceContents): t.ResourceBody {}}+function hasUsableAppBody(resource: t.ResourceContents): boolean {+ if ('text' in resource && typeof resource.text === 'string' && resource.text.length > 0) {+ return true;+ }+ if (!('blob' in resource) || typeof resource.blob !== 'string' || !resource.blob) {+ return false;+ }++ const encoded = resource.blob.replace(/[\t\n\f\r ]/g, '');+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {+ return false;+ }+ try {+ const decoded = utf8Decoder.decode(Buffer.from(encoded, 'base64'));+ return decoded.length > 0 && !decoded.includes('\0');+ } catch {+ return false;+ }+}++export function selectResolvedAppResource(+ contents: t.ResourceContents[] | undefined,+ resourceUri: string,+): t.ResourceContents | undefined {+ return contents?.find(+ (resource) =>+ resource.uri === resourceUri &&+ isMcpAppMimeType(resource.mimeType) &&+ hasUsableAppBody(resource),+ );+}+const LINE_BREAKS = /[\r\n\u2028\u2029]+/g;/**@@ -186,14 +263,17 @@ function parseAsString(result: t.MCPToolCallResponse): string {}if (item.type === 'resource') {const resourceText = [];- const body = readResourceBody(item.resource);- if (body.text) {- resourceText.push(body.text);- } else if (body.image) {- assertImageDataWithinLimit(body.image);- resourceText.push(`data:${body.image.mimeType};base64,${body.image.data}`);- } else if (body.binaryBytes != null) {- resourceText.push(describeBinaryResource(body.binaryBytes));+ // A ui:// HTML body is a whole document meant for the sandbox, never model context.+ if (!isRenderableUiResource(item)) {+ const body = readResourceBody(item.resource);+ if (body.text) {+ resourceText.push(body.text);+ } else if (body.image) {+ assertImageDataWithinLimit(body.image);+ resourceText.push(`data:${body.image.mimeType};base64,${body.image.data}`);+ } else if (body.binaryBytes != null) {+ resourceText.push(describeBinaryResource(body.binaryBytes));+ }}if (item.resource.uri) {resourceText.push(`Resource URI: ${flattenMetadata(item.resource.uri)}`);@@ -214,6 +294,28 @@ function parseAsString(result: t.MCPToolCallResponse): string {return text;}+function isUiResource(+ item: t.ToolContentPart,+): item is Extract<t.ToolContentPart, { type: 'resource' }> {+ const uri = item.type === 'resource' ? item.resource?.uri : undefined;+ return typeof uri === 'string' && uri.startsWith('ui://');+}++/**+ * MCP Apps renders only `ui://` resources whose mime type is HTML (mime omitted defaults to HTML),+ * the single renderable resource type the spec defines.+ *+ * Deliberately wider than `isMcpAppMimeType`: a plain `text/html` `ui://` resource still renders+ * through the legacy HTML renderer. Both tiers parse the media type through the same shared helpers, so a+ * differently-cased `Text/HTML;profile=mcp-app` cannot be renderable to one and not the other.+ */+export function isRenderableUiResource(item: t.ToolContentPart): boolean {+ if (!isUiResource(item)) {+ return false;+ }+ return isHtmlMediaType(resolveMCPUIResourceMimeType(item.resource.mimeType));+}+/*** Converts MCPToolCallResponse content into a plain-text string plus optional artifacts* (images, UI resources). All providers receive string content; images are separated into@@ -226,22 +328,48 @@ function parseAsString(result: t.MCPToolCallResponse): string {export function formatToolContent(result: t.MCPToolCallResponse,provider: t.Provider,+ metadata?: {+ serverName?: string;+ toolName?: string;+ resourceUri?: string;+ resolvedAppResource?: t.ResourceContents;+ serverBinding?: string;+ toolArgs?: Record<string, unknown>;+ mcpApps?: TMCPAppsPolicy;+ },): t.FormattedContentResult {- if (!RECOGNIZED_PROVIDERS.has(provider)) {+ const mcpApps = metadata?.mcpApps ?? resolveMCPAppsPolicy();+ const isRecognizedProvider = RECOGNIZED_PROVIDERS.has(provider);+ // Truthiness, not != null: an empty resourceUri/serverName/toolName cannot address an app, and a+ // single predicate keeps this gate and the synthesis below from drifting apart.+ const hasSyntheticApp = !!(+ metadata?.resourceUri &&+ metadata.serverName &&+ metadata.toolName &&+ metadata.serverBinding+ );+ const hasUiResource = result?.content?.some((item) => isUiResource(item));+ if (!isRecognizedProvider && !hasSyntheticApp && !hasUiResource) {return [parseAsString(result), undefined];}const content = result?.content ?? [];- if (!content.length) {+ if (!content.length && !hasSyntheticApp) {return ['(No response)', undefined];}const imageUrls: t.FormattedContent[] = [];const uiResources: UIResource[] = [];- let currentTextBlock = '';+ let placementMarkerCount = 0;+ // Assistants submits only this string; keep its bounded conversion independent from host UI data.+ let currentTextBlock = isRecognizedProvider ? '' : parseAsString(result);type ContentHandler = undefined | ((item: t.ToolContentPart) => void);+ const appendTextBlock = (text: string): void => {+ currentTextBlock += (currentTextBlock ? '\n\n' : '') + text;+ };+const collectImage = (item: t.ImageContent): void => {assertImageDataWithinLimit(item);const formatter = imageFormatters.default as t.ImageFormatter;@@ -258,34 +386,75 @@ export function formatToolContent(resource_link: (item: t.ResourceLink) => void;} = {text: (item) => {- currentTextBlock += (currentTextBlock ? '\n\n' : '') + item.text;+ if (isRecognizedProvider) {+ appendTextBlock(item.text);+ }},image: (item) => {- if (!isImageContent(item)) {+ if (!isRecognizedProvider || !isImageContent(item)) {return;}collectImage(item);},resource: (item) => {- const isUiResource = item.resource.uri.startsWith('ui://');+ const isDeclaredEcho = hasSyntheticApp && item.resource.uri === metadata?.resourceUri;const resourceText: string[] = [];-- if (isUiResource) {- const contentToHash =- 'text' in item.resource && item.resource.text && typeof item.resource.text === 'string'- ? item.resource.text- : item.resource.uri;- const resourceId = generateResourceId(contentToHash);+ const inlineText =+ 'text' in item.resource && typeof item.resource.text === 'string' ? item.resource.text : '';+ // App-profile documents are resolved separately from the tool result. Plain HTML remains on+ // the legacy renderer, except for an echo of the declared App URI which would duplicate it.+ const isRenderableResource = isRenderableUiResource(item);+ const isLegacyResource =+ mcpApps.legacyHtmlEnabled &&+ isRenderableResource &&+ !isMcpAppMimeType(item.resource.mimeType);+ // Custom clients consume non-HTML UI attachments by marker; MIME/policy still own rendering.+ const isCoreUiResource =+ isUiResource(item) && !isRenderableResource && !isMcpAppMimeType(item.resource.mimeType);+ const hasInlineBody =+ !!inlineText ||+ ('blob' in item.resource && typeof item.resource.blob === 'string' && !!item.resource.blob);+ const shouldTransportUiResource =+ hasInlineBody && (isCoreUiResource || (isLegacyResource && !isDeclaredEcho));++ if (shouldTransportUiResource) {+ // Distinct URIs must not collide into one resourceId even when their markup is identical:+ // the client indexes conversation resources by id, so the second would overwrite the first.+ const baseHash = `${item.resource.uri}\x00${inlineText}`;+ const resourceId = deriveResourceId(+ baseHash,+ result,+ metadata?.toolArgs,+ undefined,+ undefined,+ );const uiResource: UIResource = {...item.resource,+ ...(isLegacyResource+ ? { mimeType: resolveMCPUIResourceMimeType(item.resource.mimeType) }+ : {}),resourceId,};uiResources.push(uiResource);- resourceText.push(`UI Resource ID: ${resourceId}`);- resourceText.push(`UI Resource Marker: \\ui{${resourceId}}`);- } else {+ placementMarkerCount += 1;+ const placementReference =+ `UI Resource ID: ${resourceId}\n` + `UI Resource Marker: \\ui{${resourceId}}`;+ if (isRecognizedProvider) {+ resourceText.push(placementReference);+ } else {+ appendTextBlock(placementReference);+ }++ // A non-HTML ui:// image remains an ordinary image result as well as core UI transport.+ if (isRecognizedProvider && isCoreUiResource) {+ const body = readResourceBody(item.resource);+ if (body.image) {+ collectImage(body.image);+ }+ }+ } else if (isRecognizedProvider && !isRenderableResource) {const body = readResourceBody(item.resource);if (body.text) {resourceText.push(`Resource Text: ${body.text}`);@@ -296,22 +465,25 @@ export function formatToolContent(}}- if (item.resource.uri.length) {+ if (isRecognizedProvider && item.resource.uri.length) {resourceText.push(`Resource URI: ${flattenMetadata(item.resource.uri)}`);}- if (item.resource.mimeType != null && item.resource.mimeType) {+ if (isRecognizedProvider && item.resource.mimeType != null && item.resource.mimeType) {resourceText.push(`Resource MIME Type: ${flattenMetadata(item.resource.mimeType)}`);}if (resourceText.length) {- currentTextBlock += (currentTextBlock ? '\n\n' : '') + resourceText.join('\n');+ appendTextBlock(resourceText.join('\n'));}},resource_link: (item) => {+ if (!isRecognizedProvider) {+ return;+ }const lines = describeResourceLink(item);if (lines.length) {- currentTextBlock += (currentTextBlock ? '\n\n' : '') + lines.join('\n');+ appendTextBlock(lines.join('\n'));}},};@@ -320,13 +492,83 @@ export function formatToolContent(const handler = contentHandlers[item.type as keyof typeof contentHandlers] as ContentHandler;if (handler) {handler(item as never);- } else {+ } else if (isRecognizedProvider) {const stringified = JSON.stringify(item, null, 2);- currentTextBlock += (currentTextBlock ? '\n\n' : '') + stringified;+ appendTextBlock(stringified);}}- if (uiResources.length > 0) {+ // The declared App document is acquired through resources/read and passed separately. Persistence+ // admission can discard its body while retaining the bound URI descriptor for a later read.+ if (+ hasSyntheticApp &&+ mcpApps.enabled &&+ metadata?.resourceUri &&+ metadata.serverName &&+ metadata.toolName &&+ metadata.serverBinding+ ) {+ const resolvedResource =+ metadata.resolvedAppResource?.uri === metadata.resourceUri &&+ isMcpAppMimeType(metadata.resolvedAppResource.mimeType) &&+ hasUsableAppBody(metadata.resolvedAppResource)+ ? metadata.resolvedAppResource+ : undefined;+ let resolvedBody = '';+ if (resolvedResource && 'text' in resolvedResource) {+ resolvedBody = resolvedResource.text;+ } else if (resolvedResource && 'blob' in resolvedResource) {+ resolvedBody = resolvedResource.blob;+ }+ const itemUi = (resolvedResource?._meta as { ui?: Record<string, unknown> } | undefined)?.ui as+ | { csp?: UIResource['csp']; permissions?: UIResource['permissions'] }+ | undefined;+ const snapshot = {+ uri: metadata.resourceUri,+ mimeType: resolvedResource?.mimeType ?? MCP_APP_MIME_TYPE,+ serverName: metadata.serverName,+ serverBinding: metadata.serverBinding,+ toolName: metadata.toolName,+ structuredContent: result?.structuredContent,+ content: result?.content,+ toolArgs: metadata.toolArgs,+ isError: result?.isError,+ resultMeta: (result as { _meta?: Record<string, unknown> })?._meta,+ };+ const fullResource: UIResource = {+ ...resolvedResource,+ ...snapshot,+ resourceId: deriveResourceId(+ `${metadata.resourceUri}\x00${resolvedBody}`,+ result,+ metadata.toolArgs,+ metadata.serverName,+ metadata.toolName,+ ),+ csp: itemUi?.csp,+ permissions: itemUi?.permissions,+ };+ const maxBytes = mcpApps.maxPersistedAppBytes ?? DEFAULT_MCP_APP_PERSISTED_BYTES;+ if (fitsPersistedAppLimit(fullResource, maxBytes)) {+ uiResources.push(fullResource);+ } else {+ const uriResource: UIResource = {+ ...snapshot,+ resourceId: deriveResourceId(+ `${metadata.resourceUri}\x00`,+ result,+ metadata.toolArgs,+ metadata.serverName,+ metadata.toolName,+ ),+ };+ if (fitsPersistedAppLimit(uriResource, maxBytes)) {+ uiResources.push(uriResource);+ }+ }+ }++ if (placementMarkerCount > 0) {const uiInstructions = `UI Resource Markers Available:diff --git a/packages/api/src/mcp/registry/MCPServerInspector.ts b/packages/api/src/mcp/registry/MCPServerInspector.tsindex 6cb0c05dcf..b890b79e4c 100644--- a/packages/api/src/mcp/registry/MCPServerInspector.ts+++ b/packages/api/src/mcp/registry/MCPServerInspector.ts@@ -17,6 +17,7 @@ import { isDirectOpenIDBearerRecoveryEnabled } from '~/mcp/openid';import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory';import { MCPDomainNotAllowedError } from '~/mcp/errors';import { detectOAuthRequirement } from '~/mcp/oauth';+import { isToolHiddenFromModel } from '~/mcp/apps';import { isEnabled } from '~/utils';/**@@ -210,6 +211,9 @@ export class MCPServerInspector {keyServerName,);tools.forEach((tool) => {+ if (isToolHiddenFromModel(tool)) {+ return;+ }const keyToolName = keyToolNames.get(tool.name) ?? tool.name;const name = `${keyToolName}${Constants.mcp_delimiter}${keyServerName}`;toolFunctions[name] = {diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.tsindex 6d4a0a9717..9893f5cafe 100644--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts@@ -1,6 +1,11 @@import { createHash } from 'crypto';-import { isProcessMCPServerConfig } from 'librechat-data-provider';import { logger, encryptV2, decryptV2, scopedCacheKey } from '@librechat/data-schemas';+import {+ DEFAULT_MCP_APPS_POLICY,+ isProcessMCPServerConfig,+ resolveMCPAppsPolicy,+} from 'librechat-data-provider';+import type { TMCPAppsPolicy } from 'librechat-data-provider';import type { IServerConfigsRepositoryInterface } from './ServerConfigsRepositoryInterface';import type { ReadThroughTransforms, FillToken } from './cache/ReadThroughAllCache';import type * as t from '~/mcp/types';@@ -201,9 +206,11 @@ export interface MCPAllowlistContext {* dependency. Reads the ALS tenant context internally; pass the acting user to also pick up* user/role-scoped overrides.*/-export type MCPAllowlistResolver = (- ctx?: MCPAllowlistContext,-) => Promise<{ allowedDomains?: string[] | null; allowedAddresses?: string[] | null }>;+export type MCPAllowlistResolver = (ctx?: MCPAllowlistContext) => Promise<{+ allowedDomains?: string[] | null;+ allowedAddresses?: string[] | null;+ mcpApps: TMCPAppsPolicy;+}>;/** Effective allowlists resolved for a request. */interface ResolvedMCPAllowlists {@@ -239,6 +246,7 @@ export class MCPServersRegistry {/** YAML-derived base allowlists; used at boot and as the fallback when no resolver is set. */private readonly allowedDomains?: string[] | null;private readonly allowedAddresses?: string[] | null;+ private readonly mcpApps: TMCPAppsPolicy;/** Resolves the per-request (tenant-scoped) merged allowlists; falls back to the base above. */private readonly allowlistResolver?: MCPAllowlistResolver;private readonly readThroughCache: ReadThroughCache<t.ParsedServerConfig | undefined>;@@ -273,6 +281,7 @@ export class MCPServersRegistry {allowedDomains?: string[] | null,allowedAddresses?: string[] | null,allowlistResolver?: MCPAllowlistResolver,+ mcpApps: TMCPAppsPolicy = resolveMCPAppsPolicy(),) {this.dbConfigsRepo = new ServerConfigsDB(mongoose);this.cacheConfigsRepo = ServerConfigsCacheFactory.create(APP_CACHE_NAMESPACE, false);@@ -280,6 +289,7 @@ export class MCPServersRegistry {this.allowedDomains = allowedDomains;this.allowedAddresses = allowedAddresses;this.allowlistResolver = allowlistResolver;+ this.mcpApps = mcpApps;const ttl = cacheConfig.MCP_REGISTRY_CACHE_TTL;@@ -303,6 +313,7 @@ export class MCPServersRegistry {allowedDomains?: string[] | null,allowedAddresses?: string[] | null,allowlistResolver?: MCPAllowlistResolver,+ mcpApps?: TMCPAppsPolicy,): MCPServersRegistry {if (!mongoose) {throw new Error(@@ -320,6 +331,7 @@ export class MCPServersRegistry {allowedDomains,allowedAddresses,allowlistResolver,+ mcpApps,);return MCPServersRegistry.instance;}@@ -342,6 +354,11 @@ export class MCPServersRegistry {return this.allowedAddresses;}+ /** YAML base executable-UI policy used when no request resolver is available. */+ public getMCPAppsPolicy(): TMCPAppsPolicy {+ return this.mcpApps;+ }+/** Returns true when no explicit allowedDomains allowlist is configured, enabling SSRF TOCTOU protection */public shouldEnableSSRFProtection(): boolean {return !Array.isArray(this.allowedDomains) || this.allowedDomains.length === 0;@@ -362,24 +379,82 @@ export class MCPServersRegistry {allowedDomains?: string[] | null;allowedAddresses?: string[] | null;useSSRFProtection: boolean;+ mcpApps: TMCPAppsPolicy;}> {let allowedDomains = this.allowedDomains;let allowedAddresses = this.allowedAddresses;+ let mcpApps = this.getMCPAppsPolicy();if (this.allowlistResolver) {try {const resolved = await this.allowlistResolver(ctx);allowedDomains = resolved.allowedDomains;allowedAddresses = resolved.allowedAddresses;+ mcpApps = resolved.mcpApps;} catch {logger.warn(- '[MCPServersRegistry] Allowlist resolver failed; falling back to YAML base allowlists',+ '[MCPServersRegistry] Allowlist resolver failed; falling back to YAML base allowlists and disabling apps',);+ // Allowlists fall back to the operator baseline, but apps fail CLOSED: a scope that disabled+ // them would otherwise get inline app HTML persisted and rendered, and the gated endpoints+ // cannot retract HTML that already reached the transcript.+ mcpApps = DEFAULT_MCP_APPS_POLICY;}}return {allowedDomains,allowedAddresses,useSSRFProtection: !Array.isArray(allowedDomains) || allowedDomains.length === 0,+ mcpApps,+ };+ }++ /**+ * Resolves an App validation target from configuration already admitted and cached by the host.+ * This path never initializes, reinspects, recovers, or connects to an MCP server. A config-tier+ * entry that is absent or failed therefore stays unavailable instead of silently rebinding a+ * persisted App to a same-name base server.+ */+ public async resolveCachedAppServerConfig({+ serverName,+ userId,+ role,+ mcpConfig,+ allowedDomains,+ allowedAddresses,+ }: {+ serverName: string;+ userId: string;+ role?: string;+ mcpConfig: Record<string, t.MCPOptions>;+ allowedDomains?: string[] | null;+ allowedAddresses?: string[] | null;+ }): Promise<t.MCPConnectionTarget | undefined> {+ const baseConfigs = await this.getBaseServerConfigs(userId, role);+ const base = baseConfigs[serverName];+ const rawConfig = mcpConfig[serverName];+ let selectedConfig = base;++ if (rawConfig && base?.source !== 'user' && !isProcessMCPServerConfig(base)) {+ const yamlSnapshot = await this.cacheConfigsRepo.getAll();+ if (!this.isUnmodifiedYamlServer(yamlSnapshot, serverName, rawConfig)) {+ const cached = await this.configCacheRepo.get(+ this.configCacheKey(serverName, rawConfig, { allowedDomains, allowedAddresses }),+ );+ if (!cached || cached.inspectionFailed) {+ return undefined;+ }+ selectedConfig = base ? { ...cached, source: overlaySource(base, cached) } : cached;+ }+ }++ if (!selectedConfig || selectedConfig.inspectionFailed) {+ return undefined;+ }+ return {+ serverConfig: selectedConfig,+ connectionOwner: (await this.isAppServerConfig(serverName, selectedConfig))+ ? 'operator'+ : 'principal',};}diff --git a/packages/api/src/mcp/registry/__tests__/MCPReinitRecovery.integration.test.ts b/packages/api/src/mcp/registry/__tests__/MCPReinitRecovery.integration.test.tsindex c248b7f25e..69460642f5 100644--- a/packages/api/src/mcp/registry/__tests__/MCPReinitRecovery.integration.test.ts+++ b/packages/api/src/mcp/registry/__tests__/MCPReinitRecovery.integration.test.ts@@ -561,6 +561,7 @@ describe('MCP reinitialize recovery – integration (issue #12143)', () => {async (ctx) => ({allowedDomains: ctx?.userId === 'user-b' ? ['127.0.0.1', 'localhost'] : ['127.0.0.1'],allowedAddresses: null,+ mcpApps: { enabled: false, legacyHtmlEnabled: false },}),);server = await createMCPServerOnPort(await getFreePort());diff --git a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.tsindex d746d50f0d..1de7296a93 100644--- a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts+++ b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts@@ -1,6 +1,11 @@import './helpers/setupCredsEnv';import { logger } from '@librechat/data-schemas';import { setImmediate as realSetImmediate } from 'timers';+import {+ DEFAULT_MCP_APPS_POLICY,+ DEFAULT_MCP_APP_PERSISTED_BYTES,+ DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+} from 'librechat-data-provider';import type * as t from '~/mcp/types';import {MCPServersRegistry,@@ -517,10 +522,18 @@ describe('MCPServersRegistry', () => {resolver?: (ctx?: { userId?: string; role?: string }) => Promise<{allowedDomains?: string[] | null;allowedAddresses?: string[] | null;+ mcpApps: { enabled: boolean; legacyHtmlEnabled: boolean };}>,+ mcpApps?: { enabled: boolean; legacyHtmlEnabled: boolean },): MCPServersRegistry => {(MCPServersRegistry as unknown as { instance: undefined }).instance = undefined;- MCPServersRegistry.createInstance(mockMongoose, allowedDomains, allowedAddresses, resolver);+ MCPServersRegistry.createInstance(+ mockMongoose,+ allowedDomains,+ allowedAddresses,+ resolver,+ mcpApps,+ );return MCPServersRegistry.getInstance();};@@ -530,6 +543,12 @@ describe('MCPServersRegistry', () => {allowedDomains: ['yaml.com'],allowedAddresses: ['10.0.0.0/8'],useSSRFProtection: false,+ mcpApps: {+ enabled: false,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ },});});@@ -539,6 +558,12 @@ describe('MCPServersRegistry', () => {allowedDomains: undefined,allowedAddresses: undefined,useSSRFProtection: true,+ mcpApps: {+ enabled: false,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ },});});@@ -546,6 +571,7 @@ describe('MCPServersRegistry', () => {const resolver = jest.fn().mockResolvedValue({allowedDomains: ['admin-added.com'],allowedAddresses: ['172.16.0.0/12'],+ mcpApps: { enabled: true, legacyHtmlEnabled: true },});const reg = createWith(['yaml.com'], null, resolver);@@ -556,17 +582,21 @@ describe('MCPServersRegistry', () => {allowedDomains: ['admin-added.com'],allowedAddresses: ['172.16.0.0/12'],useSSRFProtection: false,+ mcpApps: { enabled: true, legacyHtmlEnabled: true },});});- it('falls back to the YAML base allowlists when the resolver throws', async () => {+ it('falls back to the YAML base allowlists but disables apps when the resolver throws', async () => {const resolver = jest.fn().mockRejectedValue(new Error('DB down'));const reg = createWith(['yaml.com'], null, resolver);+ // Allowlists fall back to the operator baseline; apps fail closed because inline app HTML+ // cannot be retracted once it reaches the transcript.await expect(reg.resolveAllowlists()).resolves.toEqual({allowedDomains: ['yaml.com'],allowedAddresses: null,useSSRFProtection: false,+ mcpApps: DEFAULT_MCP_APPS_POLICY,});});@@ -574,6 +604,7 @@ describe('MCPServersRegistry', () => {const resolver = jest.fn().mockResolvedValue({allowedDomains: ['admin-added.com'],allowedAddresses: ['10.0.0.0/8'],+ mcpApps: { enabled: true, legacyHtmlEnabled: true },});const reg = createWith(['yaml-only.com'], null, resolver);const inspectSpy = jest.spyOn(MCPServerInspector, 'inspect');@@ -618,6 +649,103 @@ describe('MCPServersRegistry', () => {});});+ describe('resolveCachedAppServerConfig', () => {+ const rawConfig: t.MCPOptions = {+ type: 'streamable-http',+ url: 'https://config.example.com/mcp',+ };+ const allowlists = {+ allowedDomains: ['config.example.com'],+ allowedAddresses: null,+ };++ it('returns an exact healthy config-cache target without inspecting or connecting', async () => {+ const cachedConfig = {+ ...rawConfig,+ source: 'config' as const,+ requiresOAuth: false,+ } as t.ParsedServerConfig;+ const key = registry['configCacheKey']('srv', rawConfig, allowlists);+ const { config: storedCachedConfig } = await registry['configCacheRepo'].add(+ key,+ cachedConfig,+ );+ const inspectSpy = jest.spyOn(MCPServerInspector, 'inspect');+ inspectSpy.mockClear();++ await expect(+ registry.resolveCachedAppServerConfig({+ serverName: 'srv',+ userId: 'user-1',+ role: 'USER',+ mcpConfig: { srv: rawConfig },+ ...allowlists,+ }),+ ).resolves.toEqual({+ serverConfig: storedCachedConfig,+ connectionOwner: 'principal',+ });+ expect(inspectSpy).not.toHaveBeenCalled();+ });++ it('keeps an absent or failed config-cache target unavailable instead of using a same-name base', async () => {+ await registry['cacheConfigsRepo'].add('srv', {+ type: 'streamable-http',+ url: 'https://base.example.com/mcp',+ requiresOAuth: false,+ source: 'yaml',+ });++ await expect(+ registry.resolveCachedAppServerConfig({+ serverName: 'srv',+ userId: 'user-1',+ role: 'USER',+ mcpConfig: { srv: rawConfig },+ ...allowlists,+ }),+ ).resolves.toBeUndefined();++ const key = registry['configCacheKey']('srv', rawConfig, allowlists);+ await registry['configCacheRepo'].add(key, {+ ...rawConfig,+ source: 'config',+ inspectionFailed: true,+ } as t.ParsedServerConfig);+ await expect(+ registry.resolveCachedAppServerConfig({+ serverName: 'srv',+ userId: 'user-1',+ role: 'USER',+ mcpConfig: { srv: rawConfig },+ ...allowlists,+ }),+ ).resolves.toBeUndefined();+ });++ it('uses the operator target for an admitted unmodified YAML config', async () => {+ const yamlConfig = {+ ...rawConfig,+ source: 'yaml' as const,+ requiresOAuth: false,+ } as t.ParsedServerConfig;+ const { config: storedYamlConfig } = await registry['cacheConfigsRepo'].add(+ 'srv',+ yamlConfig,+ );++ await expect(+ registry.resolveCachedAppServerConfig({+ serverName: 'srv',+ userId: 'user-1',+ role: 'USER',+ mcpConfig: { srv: rawConfig },+ ...allowlists,+ }),+ ).resolves.toEqual({ serverConfig: storedYamlConfig, connectionOwner: 'operator' });+ });+ });+describe('reset', () => {it('should clear all servers from cache repository', async () => {// Add servers to cache using the new API@@ -924,7 +1052,11 @@ describe('MCPServersRegistry', () => {mockMongoose,null,null,- async (ctx) => ({ allowedDomains: [`${ctx?.userId}.example.com`], allowedAddresses: null }),+ async (ctx) => ({+ allowedDomains: [`${ctx?.userId}.example.com`],+ allowedAddresses: null,+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ }),);await tenantRegistry.reset();await tenantRegistry.addServerStub('stub_server', stubOptions, 'CACHE');@@ -1057,7 +1189,11 @@ describe('MCPServersRegistry', () => {markResolving();await resolverHeld;}- return { allowedDomains: null, allowedAddresses: null };+ return {+ allowedDomains: null,+ allowedAddresses: null,+ mcpApps: { enabled: false, legacyHtmlEnabled: false },+ };},);await slowRegistry.reset();diff --git a/packages/api/src/mcp/sandbox.ts b/packages/api/src/mcp/sandbox.tsnew file mode 100644index 0000000000..2f000d2de3--- /dev/null+++ b/packages/api/src/mcp/sandbox.ts@@ -0,0 +1,127 @@+import { normalizeMCPAppCspDeclaration, resolveMCPAppCspLimits } from 'librechat-data-provider';+import type { MCPAppCspDeclaration, MCPAppCspLimits } from 'librechat-data-provider';++/** Replaced on the way out so the proxy can refuse to build a frame it has no response policy for. */+const CSP_APPLIED_PLACEHOLDER = '/*__CSP_APPLIED__*/';+const CSP_APPLIED_MARKER = 'window.__MCP_SANDBOX_CSP_APPLIED = true;';+const VIEW_CSP_PLACEHOLDER = '/*__VIEW_CSP__*/';++/** The operator setting accepts only explicit HTTP(S) origins, never raw CSP syntax. */+const FRAME_ANCESTOR_RE = /^https?:\/\/[a-zA-Z0-9][a-zA-Z0-9.-]*(?::\d{1,5})?$/;++export interface SandboxResponse {+ headers: Record<string, string | string[]>;+ body: string;+}++const toDomainList = (value?: string[]): string => value?.join(' ') ?? '';++const buildCspPolicy = (csp: MCPAppCspDeclaration, proxyLoader: boolean): string => {+ const resourceDomains = toDomainList(csp.resourceDomains);+ const connectDomains = toDomainList(csp.connectDomains) || "'none'";+ const frameDomains = toDomainList(csp.frameDomains);++ const scriptSrc = "script-src 'self' 'unsafe-inline' " + resourceDomains;++ return [+ "default-src 'none'",+ scriptSrc.trim(),+ ("style-src 'self' 'unsafe-inline' " + resourceDomains).trim(),+ 'connect-src ' + connectDomains,+ // form-action does not fall back to default-src, so with allow-forms a form could post to+ // any origin; bound it to the declared egress allowlist ('none' when none is declared).+ 'form-action ' + connectDomains,+ ("img-src 'self' data: " + resourceDomains).trim(),+ ("media-src 'self' data: " + resourceDomains).trim(),+ ("font-src 'self' " + resourceDomains).trim(),+ proxyLoader+ ? ('frame-src blob: ' + frameDomains).trim()+ : 'frame-src ' + (frameDomains || "'none'"),+ ("worker-src 'self' " + resourceDomains).trim(),+ "object-src 'none'",+ 'base-uri ' + (toDomainList(csp.baseUriDomains) || "'self'"),+ ].join('; ');+};++const serializeInlineScriptString = (value: string): string =>+ JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (character) => {+ const code = character.charCodeAt(0).toString(16).padStart(4, '0');+ return `\\u${code}`;+ });++/** An unparseable, oversized, or repeated `csp` param yields the restrictive default policy. */+const parseCspParam = (+ raw: string | string[] | undefined,+ limits: MCPAppCspLimits,+): MCPAppCspDeclaration => {+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > limits.maxSerializedLength) {+ return {};+ }+ try {+ const parsed: unknown = JSON.parse(raw);+ return normalizeMCPAppCspDeclaration(parsed, limits);+ } catch {+ return {};+ }+};++/**+ * The MCP Apps spec requires the Host and Sandbox to have different origins for web hosts. The+ * dedicated sandbox origin is unusable until the operator lists its allowed host origin(s).+ */+const buildFrameAncestors = (raw?: string): string => {+ // Only accept scheme://host[:port] tokens. A raw value is interpolated into the CSP header, so+ // an unvalidated token containing ";" would inject an unrelated directive.+ return (raw ?? '')+ .trim()+ .split(/[\s,]+/)+ .filter((token) => FRAME_ANCESTOR_RE.test(token))+ .join(' ');+};++/**+ * Builds the proxy response policy and the separate View policy from one normalized declaration.+ * The proxy refuses to build an app frame unless this route substituted both trusted markers.+ */+export function buildSandboxResponse({+ sandboxHtml,+ frameAncestors,+ csp,+ limits: rawLimits,+}: {+ sandboxHtml: string;+ frameAncestors?: string;+ csp?: string | string[];+ limits?: Partial<MCPAppCspLimits>;+}): SandboxResponse {+ const ancestors = buildFrameAncestors(frameAncestors);+ const limits = resolveMCPAppCspLimits(rawLimits);+ const declaration = parseCspParam(csp, limits);+ const proxyPolicy = buildCspPolicy(declaration, true);+ const viewPolicy = buildCspPolicy(declaration, false);+ const headers: Record<string, string | string[]> = {+ 'Content-Type': 'text/html; charset=utf-8',+ // Required, not merely hygienic: the per-resource policy below varies per request.+ 'Cache-Control': 'no-store, no-cache, must-revalidate',+ 'X-Content-Type-Options': 'nosniff',+ 'Referrer-Policy': 'same-origin',+ 'Cross-Origin-Resource-Policy': ancestors ? 'cross-origin' : 'same-origin',+ };+ if (!ancestors) {+ headers['X-Frame-Options'] = 'DENY';+ }+ const ancestorsPolicy = ancestors ? `frame-ancestors ${ancestors}` : "frame-ancestors 'none'";+ // frame-ancestors stays its own policy: CSP3 excludes it from the meta-element path, and+ // multiple policies intersect, so the resource policy cannot loosen it.+ headers['Content-Security-Policy'] = [ancestorsPolicy, proxyPolicy];++ return {+ headers,+ body: sandboxHtml+ .replace(CSP_APPLIED_PLACEHOLDER, CSP_APPLIED_MARKER)+ .replace(+ VIEW_CSP_PLACEHOLDER,+ `window.__MCP_VIEW_CSP = ${serializeInlineScriptString(viewPolicy)};`,+ ),+ };+}diff --git a/packages/api/src/mcp/tools.spec.ts b/packages/api/src/mcp/tools.spec.tsindex 56fad5f666..6c11a54a25 100644--- a/packages/api/src/mcp/tools.spec.ts+++ b/packages/api/src/mcp/tools.spec.ts@@ -2,7 +2,8 @@ import { logger } from '@librechat/data-schemas';import { Constants, normalizeServerName } from 'librechat-data-provider';import type { LCAvailableTools, ParsedServerConfig } from './types';import type { MCPToolCacheDeps, MCPToolInput } from './tools';-import { getMCPAppToolsPublicationGeneration } from './toolsChanged';+import { getMCPToolCatalogGeneration } from './toolsChanged';+import { MCP_APPS_CAPABILITY_PROFILE } from './capabilities';import { createMCPToolCacheService } from './tools';const requestScopedConfig: ParsedServerConfig = {@@ -87,6 +88,46 @@ function createSharedCacheDeps(params: {describe('createMCPToolCacheService', () => {describe('configuration-addressed app catalogs', () => {+ it('keeps standard operator catalogs global and Apps catalogs user-scoped', async () => {+ const appCache = new Map<string, LCAvailableTools>();+ const userCache = new Map<string, LCAvailableTools>();+ const deps = createSharedCacheDeps({ config: cacheableConfig, appCache, userCache });+ const service = createMCPToolCacheService(deps);+ const standardTools = {+ [toolName('standard', 'dynamic')]: makeTool(toolName('standard', 'dynamic')),+ };+ const appsTools = {+ [toolName('apps', 'dynamic')]: makeTool(toolName('apps', 'dynamic')),+ };++ await service.cacheMCPServerTools({+ userId: 'u1',+ serverName: 'dynamic',+ serverTools: standardTools,+ publicationRevision: '1',+ });+ await service.cacheMCPServerTools({+ userId: 'u1',+ serverName: 'dynamic',+ serverTools: appsTools,+ publicationGeneration: 'apps-lease',+ capabilityProfile: MCP_APPS_CAPABILITY_PROFILE,+ });++ await expect(service.getMCPServerTools('u1', 'dynamic')).resolves.toEqual(standardTools);+ await expect(+ service.getMCPServerTools('u1', 'dynamic', undefined, MCP_APPS_CAPABILITY_PROFILE),+ ).resolves.toEqual(appsTools);+ expect(appCache).toHaveProperty('size', 1);+ expect(userCache).toHaveProperty('size', 1);+ expect(deps.getCachedTools).toHaveBeenLastCalledWith({+ userId: 'u1',+ serverName: 'dynamic',+ configGeneration: getMCPToolCatalogGeneration(cacheableConfig, MCP_APPS_CAPABILITY_PROFILE),+ allowLegacyMigration: false,+ });+ });+it('restores the static catalog without discovering app server configs', async () => {const staticTools = { builtin: makeTool('builtin') };const updateCachedGlobalTools = jest.fn(async (update) => update({}));@@ -128,7 +169,7 @@ describe('createMCPToolCacheService', () => {const setCachedAppServerTools = jest.fn().mockResolvedValue(true);const deps = createMockDeps({ setCachedAppServerTools });const service = createMCPToolCacheService(deps);- const generation = getMCPAppToolsPublicationGeneration(cacheableConfig);+ const generation = getMCPToolCatalogGeneration(cacheableConfig);await expect(service.replaceAppServerTools({@@ -278,13 +319,13 @@ describe('createMCPToolCacheService', () => {await newService.replaceAppServerTools({serverName: 'dynamic',serverTools: newTools,- publicationGeneration: getMCPAppToolsPublicationGeneration(newConfig),+ publicationGeneration: getMCPToolCatalogGeneration(newConfig),publicationRevision: '1',});await oldService.replaceAppServerTools({serverName: 'dynamic',serverTools: oldTools,- publicationGeneration: getMCPAppToolsPublicationGeneration(oldConfig),+ publicationGeneration: getMCPToolCatalogGeneration(oldConfig),publicationRevision: '1',});@@ -312,7 +353,7 @@ describe('createMCPToolCacheService', () => {await oldService.replaceAppServerTools({serverName: 'dynamic',serverTools: stale,- publicationGeneration: getMCPAppToolsPublicationGeneration(oldConfig),+ publicationGeneration: getMCPToolCatalogGeneration(oldConfig),publicationRevision: '1',});await expect(newService.getMCPServerTools('user', 'dynamic')).resolves.toBeNull();@@ -320,7 +361,7 @@ describe('createMCPToolCacheService', () => {await newService.replaceAppServerTools({serverName: 'dynamic',serverTools: current,- publicationGeneration: getMCPAppToolsPublicationGeneration(newConfig),+ publicationGeneration: getMCPToolCatalogGeneration(newConfig),publicationRevision: '1',});await expect(newService.getMCPServerTools('user', 'dynamic')).resolves.toEqual(current);@@ -347,12 +388,12 @@ describe('createMCPToolCacheService', () => {expect(setCachedAppServerTools).toHaveBeenCalledWith('alpha',- getMCPAppToolsPublicationGeneration(alphaConfig),+ getMCPToolCatalogGeneration(alphaConfig),{ [alpha]: makeTool(alpha) },);expect(setCachedAppServerTools).toHaveBeenCalledWith('beta',- getMCPAppToolsPublicationGeneration(betaConfig),+ getMCPToolCatalogGeneration(betaConfig),{ [beta]: makeTool(beta) },);expect(deps.setCachedTools).not.toHaveBeenCalled();@@ -394,7 +435,7 @@ describe('createMCPToolCacheService', () => {expect(setCachedToolsIfCurrent).toHaveBeenCalledWith(expect.any(Object), {userId: 'u1',serverName: 'tenant',- configGeneration: getMCPAppToolsPublicationGeneration(tenantConfig),+ configGeneration: getMCPToolCatalogGeneration(tenantConfig),publicationGeneration: 'connection-generation',});});diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.tsindex cc68e53ba8..70d324c832 100644--- a/packages/api/src/mcp/tools.ts+++ b/packages/api/src/mcp/tools.ts@@ -1,4 +1,7 @@import { logger } from '@librechat/data-schemas';+import { DynamicStructuredTool } from '@librechat/agents/langchain/tools';+import { patchConfig, pickRunnableConfigKeys } from '@langchain/core/runnables';+import { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';import {Constants,buildServerNameAliases,@@ -8,17 +11,45 @@ import {import type { Tool } from '@modelcontextprotocol/sdk/types.js';import type { JsonSchemaType } from '@librechat/agents';import type { LCAvailableTools, LCFunctionTool, ParsedServerConfig } from './types';+import type { MCPClientCapabilityProfile } from './capabilities';import { canUseAppConnection, requiresEphemeralUserConnection } from './utils';-import { getMCPAppToolsPublicationGeneration } from './toolsChanged';import { normalizeJsonSchema, resolveJsonSchemaRefs } from './zod';+import { STANDARD_MCP_CAPABILITY_PROFILE } from './capabilities';+import { getMCPToolCatalogGeneration } from './toolsChanged';+import { isToolHiddenFromModel } from './apps';-export type MCPToolInput = Pick<Tool, 'name' | 'description'> & Partial<Pick<Tool, 'inputSchema'>>;+type DynamicStructuredToolFields = ConstructorParameters<typeof DynamicStructuredTool>[0];+type DynamicStructuredToolFunction = DynamicStructuredToolFields['func'];++export function createMCPStructuredTool(+ func: (+ input: Parameters<DynamicStructuredToolFunction>[0],+ config?: Parameters<DynamicStructuredToolFunction>[2],+ ) => ReturnType<DynamicStructuredToolFunction>,+ fields: Omit<DynamicStructuredToolFields, 'func'>,+): DynamicStructuredTool<unknown> {+ return new DynamicStructuredTool({+ ...fields,+ func: (input, runManager, config) => {+ const childConfig = patchConfig(config, { callbacks: runManager?.getChild() });+ return AsyncLocalStorageProviderSingleton.runWithConfig(+ pickRunnableConfigKeys(childConfig),+ () => func(input, childConfig),+ );+ },+ });+}++/** `_meta` carries the MCP Apps `ui.visibility` used to hide app-only tools from the model. */+export type MCPToolInput = Pick<Tool, 'name' | 'description'> &+ Partial<Pick<Tool, 'inputSchema' | '_meta'>>;export interface MCPToolCacheDeps {getCachedTools: (options?: {userId?: string;serverName?: string;configGeneration?: string;+ allowLegacyMigration?: boolean;}) => Promise<LCAvailableTools | null>;updateCachedGlobalTools?: (update: (tools: LCAvailableTools) => LCAvailableTools,@@ -59,6 +90,7 @@ export interface MCPToolCacheService {serverConfig?: ParsedServerConfig;publicationGeneration?: string;publicationRevision?: string;+ capabilityProfile?: MCPClientCapabilityProfile;}) => Promise<LCAvailableTools | null>;syncStaticTools: (staticTools: LCAvailableTools) => Promise<void>;mergeAppTools: (appTools: LCAvailableTools, staticTools: LCAvailableTools) => Promise<void>;@@ -75,11 +107,13 @@ export interface MCPToolCacheService {serverConfig?: ParsedServerConfig;publicationGeneration?: string;publicationRevision?: string;+ capabilityProfile?: MCPClientCapabilityProfile;}) => Promise<void>;getMCPServerTools: (userId: string,serverName: string,serverConfig?: ParsedServerConfig,+ capabilityProfile?: MCPClientCapabilityProfile,) => Promise<LCAvailableTools | null>;}@@ -92,6 +126,9 @@ export function formatMCPServerTools(serverName: string, tools: MCPToolInput[]):keyServerName,);for (const tool of tools) {+ if (isToolHiddenFromModel(tool)) {+ continue;+ }const keyToolName = keyToolNames.get(tool.name) ?? tool.name;const name = `${keyToolName}${Constants.mcp_delimiter}${keyServerName}`;const entry: LCFunctionTool = {@@ -247,9 +284,11 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSserverConfig?: ParsedServerConfig;publicationGeneration?: string;publicationRevision?: string;+ capabilityProfile?: MCPClientCapabilityProfile;}): Promise<LCAvailableTools | null> {const { userId, serverName, tools, serverConfig, publicationGeneration, publicationRevision } =params;+ const capabilityProfile = params.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;try {if (tools == null) {logger.debug('[MCP Cache] No tools to update');@@ -260,14 +299,18 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSconst resolvedConfig = await resolveCacheConfig(userId, serverName, serverConfig);const configGeneration = resolvedConfig- ? getMCPAppToolsPublicationGeneration(resolvedConfig)+ ? getMCPToolCatalogGeneration(resolvedConfig, capabilityProfile): undefined;if (resolvedConfig && requiresEphemeralUserConnection(resolvedConfig)) {logger.debug(`[MCP Cache] Built ${tools.length} request-scoped tool(s) without caching`);return serverTools;}- if (userId && !(await isAppSharedConfig(serverName, resolvedConfig))) {+ if (+ userId &&+ (capabilityProfile !== STANDARD_MCP_CAPABILITY_PROFILE ||+ !(await isAppSharedConfig(serverName, resolvedConfig)))+ ) {if (setCachedToolsIfCurrent) {if (!publicationGeneration || !configGeneration) {logger.debug('[MCP Cache] Skipped unfenced or unaddressed tool publication');@@ -338,7 +381,10 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheS.filter(([, config]) => config.toolFunctions != null).map(async ([serverName, config]) => {const serverTools = getAppServerSlice(appTools, serverName, boundaries);- const configGeneration = getMCPAppToolsPublicationGeneration(config);+ const configGeneration = getMCPToolCatalogGeneration(+ config,+ STANDARD_MCP_CAPABILITY_PROFILE,+ );await setCachedAppServerTools(serverName, configGeneration, serverTools);}),);@@ -375,7 +421,9 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSlet configGeneration = publicationGeneration;if (!configGeneration) {const config = await resolveCacheConfig(undefined, serverName);- configGeneration = config ? getMCPAppToolsPublicationGeneration(config) : undefined;+ configGeneration = config+ ? getMCPToolCatalogGeneration(config, STANDARD_MCP_CAPABILITY_PROFILE)+ : undefined;}/** Discarding a publication is warned, not debugged: #14857 was invisible for a release* because the only trace of a dropped app catalog was a debug line no deployment runs.@@ -426,6 +474,7 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSserverConfig?: ParsedServerConfig;publicationGeneration?: string;publicationRevision?: string;+ capabilityProfile?: MCPClientCapabilityProfile;}): Promise<void> {const {userId,@@ -434,18 +483,22 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSserverConfig,publicationGeneration,publicationRevision,+ capabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,} = params;try {const count = Object.keys(serverTools).length;const resolvedConfig = await resolveCacheConfig(userId, serverName, serverConfig);const configGeneration = resolvedConfig- ? getMCPAppToolsPublicationGeneration(resolvedConfig)+ ? getMCPToolCatalogGeneration(resolvedConfig, capabilityProfile): undefined;if (resolvedConfig && requiresEphemeralUserConnection(resolvedConfig)) {logger.debug(`[MCP Cache] Skipped caching ${count} request-scoped tool(s)`);return;}- if (await isAppSharedConfig(serverName, resolvedConfig)) {+ if (+ capabilityProfile === STANDARD_MCP_CAPABILITY_PROFILE &&+ (await isAppSharedConfig(serverName, resolvedConfig))+ ) {const appConfigGeneration =userId == null? (publicationGeneration ?? configGeneration)@@ -529,17 +582,21 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSuserId: string,serverName: string,serverConfig?: ParsedServerConfig,+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,): Promise<LCAvailableTools | null> {const resolvedConfig = await resolveCacheConfig(userId, serverName, serverConfig);if (resolvedConfig && requiresEphemeralUserConnection(resolvedConfig)) {return null;}try {- if (await isAppSharedConfig(serverName, resolvedConfig)) {+ if (+ capabilityProfile === STANDARD_MCP_CAPABILITY_PROFILE &&+ (await isAppSharedConfig(serverName, resolvedConfig))+ ) {if (!resolvedConfig) {return null;}- const configGeneration = getMCPAppToolsPublicationGeneration(resolvedConfig);+ const configGeneration = getMCPToolCatalogGeneration(resolvedConfig, capabilityProfile);const serverTools = await getCachedAppServerTools(serverName, configGeneration);if (serverTools == null) {return null;@@ -547,9 +604,15 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSreturn normalizeCachedToolKeys(serverTools, serverName);}const configGeneration = resolvedConfig- ? getMCPAppToolsPublicationGeneration(resolvedConfig)+ ? getMCPToolCatalogGeneration(resolvedConfig, capabilityProfile): undefined;- const cached = (await getCachedTools({ userId, serverName, configGeneration })) ?? null;+ const cached =+ (await getCachedTools({+ userId,+ serverName,+ configGeneration,+ allowLegacyMigration: false,+ })) ?? null;if (!cached) {return null;}diff --git a/packages/api/src/mcp/toolsChanged.spec.ts b/packages/api/src/mcp/toolsChanged.spec.tsindex 2932a7a2ea..5c7cefd9ad 100644--- a/packages/api/src/mcp/toolsChanged.spec.ts+++ b/packages/api/src/mcp/toolsChanged.spec.ts@@ -12,6 +12,7 @@ import {cancelMCPToolsChanged,notifyMCPToolsChanged,getMCPAppToolsPublicationGeneration,+ getMCPToolCatalogGeneration,} from './toolsChanged';const createEvent = (name = 'one'): MCPToolsChangedEvent => ({@@ -201,7 +202,7 @@ describe('MCP tools-changed dispatch', () => {expect(revisionHandler).toHaveBeenCalledTimes(1);expect(revisionHandler).toHaveBeenCalledWith({serverName: 'dynamic',- configGeneration: getMCPAppToolsPublicationGeneration(serverConfig),+ configGeneration: getMCPToolCatalogGeneration(serverConfig),});});diff --git a/packages/api/src/mcp/toolsChanged.ts b/packages/api/src/mcp/toolsChanged.tsindex 6c8854783d..3f55072d2e 100644--- a/packages/api/src/mcp/toolsChanged.ts+++ b/packages/api/src/mcp/toolsChanged.ts@@ -2,7 +2,9 @@ import { createHash } from 'crypto';import { logger } from '@librechat/data-schemas';import { MCPOptionsSchema } from 'librechat-data-provider';import type { Tool } from '@modelcontextprotocol/sdk/types.js';+import type { MCPClientCapabilityProfile } from './capabilities';import type { MCPOptions, ParsedServerConfig } from './types';+import { STANDARD_MCP_CAPABILITY_PROFILE } from './capabilities';import { processMCPEnv } from '../utils/env';const RETRY_BASE_DELAY_MS = 250;@@ -52,12 +54,23 @@ export function getMCPAppToolsPublicationGeneration(config: ParsedServerConfig):.digest('hex');}+/** Addresses catalogs by both configuration and the capabilities that produced them. */+export function getMCPToolCatalogGeneration(+ config: ParsedServerConfig,+ capabilityProfile: MCPClientCapabilityProfile = STANDARD_MCP_CAPABILITY_PROFILE,+): string {+ return createHash('sha256')+ .update(JSON.stringify([getMCPAppToolsPublicationGeneration(config), capabilityProfile]))+ .digest('hex');+}+/** A complete tool-list snapshot and the cache scope it belongs to. */export interface MCPToolsChangedEvent {serverName: string;tools: Tool[];serverConfig: MCPOptions;userId?: string;+ capabilityProfile?: MCPClientCapabilityProfile;/** Connection-bound token used to fence stale cross-replica cache publications. */publicationGeneration?: string;/** Monotonic ticket assigned before an app-level tools/list request begins. */@@ -79,6 +92,9 @@ let handler: MCPToolsChangedHandler | null = null;const pendingChanges = new Map<string, PendingToolsChange>();type MCPToolsChangedScope = Pick<MCPToolsChangedEvent, 'serverName' | 'userId'>;+type MCPToolsChangedPublicationScope = MCPToolsChangedScope & {+ capabilityProfile?: MCPClientCapabilityProfile;+};export type MCPToolsChangedGenerationHandler = (scope: MCPToolsChangedScope,@@ -99,8 +115,12 @@ export type MCPToolsChangedRevisionHandler = (scope: {let revisionHandler: MCPToolsChangedRevisionHandler | null = null;-function getChangeKey(event: MCPToolsChangedScope): string {- return JSON.stringify([event.userId ?? null, event.serverName]);+function getChangeKey(event: MCPToolsChangedPublicationScope): string {+ return JSON.stringify([+ event.userId ?? null,+ event.serverName,+ event.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE,+ ]);}function clearRetryTimer(change: PendingToolsChange): void {@@ -218,13 +238,14 @@ export async function reserveMCPToolsChangedRevision(scope: {serverName: string;serverConfig: ParsedServerConfig;userId?: string;+ capabilityProfile?: MCPClientCapabilityProfile;}): Promise<string | undefined> {if (scope.userId || !revisionHandler) {return undefined;}return revisionHandler({serverName: scope.serverName,- configGeneration: getMCPAppToolsPublicationGeneration(scope.serverConfig),+ configGeneration: getMCPToolCatalogGeneration(scope.serverConfig, scope.capabilityProfile),});}@@ -261,7 +282,7 @@ export async function notifyMCPToolsChanged(event: MCPToolsChangedEvent): Promis}/** Cancels queued retries and drains an in-flight publication before cache invalidation. */-export async function cancelMCPToolsChanged(scope: MCPToolsChangedScope): Promise<void> {+export async function cancelMCPToolsChanged(scope: MCPToolsChangedPublicationScope): Promise<void> {const key = getChangeKey(scope);const change = pendingChanges.get(key);if (!change) {diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex c029753f00..fc03055bbb 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -98,6 +98,7 @@ export type MCPToolCallResponse =_meta?: Record<string, unknown>;content?: Array<ToolContentPart>;isError?: boolean;+ structuredContent?: Record<string, unknown>;};export type Provider =@@ -247,6 +248,8 @@ export interface BasicConnectionOptions {skipEnvProcessing?: boolean;/** When true, the connection is intentionally short-lived for a single request/tool call */ephemeralConnection?: boolean;+ /** Immutable client capabilities negotiated for this connection. */+ capabilityProfile?: import('../capabilities').MCPClientCapabilityProfile;}/** User context for placeholder resolution in MCP connections (non-OAuth and OAuth alike) */@@ -264,6 +267,8 @@ export interface UserConnectionContext {/** Cancels the connection's SDK requests when the caller itself is cancelled; previously only* OAuth connections could carry a signal, leaving non-OAuth discovery uncancellable. */signal?: AbortSignal;+ /** Immutable client capabilities requested by this caller. */+ capabilityProfile?: import('../capabilities').MCPClientCapabilityProfile;/** Absolute epoch-ms bound on the whole connect-and-list operation. `connectionTimeout` bounds* only a single `connect()`, so a caller that must return within a fixed budget sets this to* cap every segment, including `tools/list` pagination and the unauthenticated fallback. */@@ -327,27 +332,36 @@ export interface OAuthConnectionOptions extends UserConnectionContext {oboIdentityContext?: AuthIdentityContext;}-/** Options accepted by UserConnectionManager.getUserConnection. OAuth fields are optional. */-export interface UserMCPConnectionOptions extends UserConnectionContext {- serverName: string;- forceNew?: boolean;- ephemeralConnection?: boolean;- serverConfig?: ParsedServerConfig;- /** Internal one-shot fence shared across connection initialization and initial tools/list. */- directBearerRecoveryState?: DirectBearerRecoveryState;- flowManager?: FlowStateManager<o.MCPOAuthTokens | null>;- /** Request-local resolved credentials; serverConfig remains the authoritative definition. */- directBearerResolvedConfig?: MCPOptions;- tokenMethods?: TokenMethods;- signal?: AbortSignal;- oauthStart?: OAuthStartHandler;- oauthEnd?: () => Promise<void>;- returnOnOAuth?: boolean;- oboTokenResolver?: OboTokenResolver;- oboTrustChecker?: OboTrustChecker;- oboIdentityContext?: AuthIdentityContext;+export interface MCPConnectionTarget {+ serverConfig: ParsedServerConfig;+ connectionOwner: 'operator' | 'principal';}+type MCPConnectionTargetInput =+ | { connectionTarget: MCPConnectionTarget; serverConfig?: never }+ | { connectionTarget?: never; serverConfig?: ParsedServerConfig };++/** Options accepted by UserConnectionManager.getUserConnection. OAuth fields are optional. */+export type UserMCPConnectionOptions = UserConnectionContext &+ MCPConnectionTargetInput & {+ serverName: string;+ forceNew?: boolean;+ ephemeralConnection?: boolean;+ /** Internal one-shot fence shared across connection initialization and initial tools/list. */+ directBearerRecoveryState?: DirectBearerRecoveryState;+ flowManager?: FlowStateManager<o.MCPOAuthTokens | null>;+ /** Request-local resolved credentials; serverConfig remains the authoritative definition. */+ directBearerResolvedConfig?: MCPOptions;+ tokenMethods?: TokenMethods;+ signal?: AbortSignal;+ oauthStart?: OAuthStartHandler;+ oauthEnd?: () => Promise<void>;+ returnOnOAuth?: boolean;+ oboTokenResolver?: OboTokenResolver;+ oboTrustChecker?: OboTrustChecker;+ oboIdentityContext?: AuthIdentityContext;+ };+export interface ToolDiscoveryOptions {serverName: string;user?: IUser;@@ -373,6 +387,8 @@ export interface ToolDiscoveryOptions {upstreamTokenProvider?: UpstreamTokenProvider;upstreamTokenProviderResolver?: UpstreamTokenProviderResolver;oboIdentityContext?: AuthIdentityContext;+ /** Immutable client capabilities used for this discovery session. */+ capabilityProfile?: import('../capabilities').MCPClientCapabilityProfile;}export interface ToolDiscoveryResult {diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex c6c0cbd262..5825e23a78 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -9,12 +9,17 @@ import {codeEnvironmentUserConfigSchema,CODE_ENVIRONMENT_ADMISSION_MAX_MS,excludedKeys,- endpointSchema,+ DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ DEFAULT_MCP_APP_PERSISTED_BYTES,+ MAX_MCP_APP_PERSISTED_BYTES,+ resolveMCPAppRateLimits,+ resolveMCPAppsPolicy,resolveEndpointType,webSearchSchema,} from './config';import { EModelEndpoint, isDocumentSupportedProvider } from './schemas';import { getEndpointFileConfig, mergeFileConfig } from './file-config';+import { DEFAULT_MCP_APP_CSP_LIMITS } from './mcp/csp';import { modelSpecSubagentsSchema } from './models';const endpointsConfig: TEndpointsConfig = {@@ -1970,6 +1975,134 @@ describe('bedrockModels defaults', () => {});});+describe('MCP Apps configuration', () => {+ it.each([+ [+ undefined,+ {+ enabled: false,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ },+ ],+ [+ true,+ {+ enabled: true,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ },+ ],+ [+ false,+ {+ enabled: false,+ legacyHtmlEnabled: false,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ },+ ],+ ])('resolves raw apps value %s to the effective policy', (value, expected) => {+ expect(resolveMCPAppsPolicy(value)).toEqual(expected);+ });++ it('defaults and validates deployment-owned sandbox limits', () => {+ expect(configSchema.parse({ version: '1.2.1' }).mcpAppSandbox).toEqual({+ ...DEFAULT_MCP_APP_CSP_LIMITS,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ });+ expect(+ configSchema.parse({+ version: '1.2.1',+ mcpAppSandbox: {+ maxSourcesPerDirective: 64,+ maxSerializedLength: 8192,+ maxPersistedAppBytes: 2048,+ maxAdmissionRequestsPerMinute: 480,+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ },+ }).mcpAppSandbox,+ ).toEqual({+ maxSourcesPerDirective: 64,+ maxSerializedLength: 8192,+ maxPersistedAppBytes: 2048,+ maxAdmissionRequestsPerMinute: 480,+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ });+ for (const mcpAppSandbox of [+ { maxSourcesPerDirective: 0 },+ { maxSourcesPerDirective: 1.5 },+ { maxSerializedLength: -1 },+ { maxSerializedLength: 1.5 },+ { maxSerializedLength: Number.MAX_SAFE_INTEGER + 1 },+ { maxPersistedAppBytes: 0 },+ { maxPersistedAppBytes: 1.5 },+ { maxPersistedAppBytes: MAX_MCP_APP_PERSISTED_BYTES + 1 },+ { maxAdmissionRequestsPerMinute: 0 },+ { maxAdmissionRequestsPerMinute: 1.5 },+ { maxAdmissionRequestsPerMinute: Number.MAX_SAFE_INTEGER + 1 },+ { url: '/api/mcp/sandbox' },+ { url: 'ftp://mcp-sandbox.example.com/api/mcp/sandbox' },+ ]) {+ expect(configSchema.safeParse({ version: '1.2.1', mcpAppSandbox }).success).toBe(false);+ }+ });++ it('publishes optional runtime sandbox fields in the effective policy', () => {+ expect(+ resolveMCPAppsPolicy(+ true,+ undefined,+ 2048,+ 480,+ 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ ),+ ).toEqual({+ enabled: true,+ legacyHtmlEnabled: true,+ maxPersistedAppBytes: 2048,+ maxAdmissionRequestsPerMinute: 480,+ sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ });+ });++ it('defaults App request limits without requiring the parent rateLimits section', () => {+ expect(resolveMCPAppRateLimits()).toEqual({+ resourcesPerMinute: 120,+ toolCallsPerMinute: 60,+ });+ });++ it('resolves configured App request limits', () => {+ expect(+ resolveMCPAppRateLimits({+ mcpApps: { resourcesPerMinute: 2, toolCallsPerMinute: 3 },+ }),+ ).toEqual({ resourcesPerMinute: 2, toolCallsPerMinute: 3 });+ });++ it.each([0, -1, 1.5])('rejects invalid App resource request limits: %s', (value) => {+ expect(+ configSchema.safeParse({+ version: '1.3.5',+ rateLimits: { mcpApps: { resourcesPerMinute: value } },+ }).success,+ ).toBe(false);+ });++ it.each([0, -1, 1.5])('rejects invalid App tool-call limits: %s', (value) => {+ expect(+ configSchema.safeParse({+ version: '1.3.5',+ rateLimits: { mcpApps: { toolCallsPerMinute: value } },+ }).success,+ ).toBe(false);+ });+});+describe('MCP UI refresh configuration', () => {it('preserves configured intervals, including zero to disable polling', () => {const result = configSchema.parse({diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 61b529dc7c..8f1216d905 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -32,11 +32,11 @@ import {DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,} from './limits';import {- CODE_ENVIRONMENT_DECISION_VERSION,- CODE_ENVIRONMENT_MOVE_VERSION,- CODE_ENVIRONMENT_TRANSITION_VERSION,- CODE_WORKSPACE_RECOVERY_VERSION,-} from './code/workspace';+ DEFAULT_MCP_APP_CSP_LIMITS,+ resolveMCPAppCspLimits,+ type MCPAppCspLimits,+} from './mcp/csp';+import { CODE_ENVIRONMENT_DECISION_VERSION, CODE_ENVIRONMENT_MOVE_VERSION } from './code/workspace';import { ComponentTypes, SettingTypes, OptionTypes } from './generate';import { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code';import { specsConfigSchema, TSpecsConfig } from './models';@@ -62,7 +62,7 @@ export const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'd/** How long a started social login may take to return to its callback before its `state` expires. */export const DEFAULT_OAUTH_STATE_TTL_MS = 10 * 60 * 1000;-export const BASE_ONLY_CONFIG_SECTIONS = ['filters'] as const;+export const BASE_ONLY_CONFIG_SECTIONS = ['filters', 'mcpAppSandbox'] as const;/** Sections that may be stored in the tenant's base config document but must* not be overridden or tombstoned by role, group, or user config documents. */export const BASE_PRINCIPAL_CONFIG_SECTIONS = ['langfuse'] as const;@@ -2077,6 +2077,15 @@ export enum RateLimitPrefix {EMAIL_CHANGE_CONFIRM = 'EMAIL_CHANGE_CONFIRM',}+export const mcpAppRateLimitSchema = z+ .object({+ resourcesPerMinute: z.number().int().positive().default(120),+ toolCallsPerMinute: z.number().int().positive().default(60),+ })+ .default({});++export type TMCPAppRateLimits = z.infer<typeof mcpAppRateLimitSchema>;+export const rateLimitSchema = z.object({twoFactorManagement: z.object({@@ -2122,6 +2131,7 @@ export const rateLimitSchema = z.object({userWindowInMinutes: z.number().optional(),}).optional(),+ mcpApps: mcpAppRateLimitSchema.optional(),/** Requesting a change of the registered email; keyed by the authenticated user. */emailChange: z.object({@@ -2140,6 +2150,12 @@ export const rateLimitSchema = z.object({.optional(),});+export function resolveMCPAppRateLimits(+ rateLimits?: z.input<typeof rateLimitSchema>,+): TMCPAppRateLimits {+ return mcpAppRateLimitSchema.parse(rateLimits?.mcpApps);+}+export enum EImageOutputType {PNG = 'png',WEBP = 'webp',@@ -2608,6 +2624,46 @@ export type StartupConfigContext = 'share';*/export type EndpointsDropParamsMap = Record<string, string[] | Record<string, string[]>>;+export type TMCPAppsPolicy = {+ enabled: boolean;+ legacyHtmlEnabled: boolean;+ cspLimits?: MCPAppCspLimits;+ /** Server-enforced UTF-8 JSON byte cap for one persisted MCP App artifact. */+ maxPersistedAppBytes?: number;+ /** Shared per-user ceiling applied before principal-scoped MCP App admission. */+ maxAdmissionRequestsPerMinute?: number;+ /** Deployment-owned dedicated Sandbox Proxy URL published to authenticated clients. */+ sandboxUrl?: string;+};++export const DEFAULT_MCP_APP_PERSISTED_BYTES = 1024 * 1024;+export const MAX_MCP_APP_PERSISTED_BYTES = 4 * 1024 * 1024;+export const DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE = 240;++export const DEFAULT_MCP_APPS_POLICY: TMCPAppsPolicy = {+ enabled: false,+ legacyHtmlEnabled: false,+ maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+};++export function resolveMCPAppsPolicy(+ value?: boolean,+ cspLimits?: Partial<MCPAppCspLimits>,+ maxPersistedAppBytes = DEFAULT_MCP_APP_PERSISTED_BYTES,+ maxAdmissionRequestsPerMinute = DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,+ sandboxUrl?: string,+): TMCPAppsPolicy {+ return {+ enabled: value === true,+ legacyHtmlEnabled: value !== false,+ ...(cspLimits != null ? { cspLimits: resolveMCPAppCspLimits(cspLimits) } : {}),+ maxPersistedAppBytes,+ maxAdmissionRequestsPerMinute,+ ...(sandboxUrl !== undefined ? { sandboxUrl } : {}),+ };+}+export type TStartupConfig = {appTitle: string;socialLogins?: string[];@@ -2714,6 +2770,7 @@ export type TStartupConfig = {}>;mcpPlaceholder?: string;+ mcpApps?: TMCPAppsPolicy;conversationImportMaxFileSize?: number;buildInfo?: {commit?: string | null;@@ -3237,6 +3294,49 @@ export const configSchema = z.object({includedTools: z.array(z.string()).optional(),filteredTools: z.array(z.string()).optional(),mcpServers: MCPServersSchema.optional(),+ mcpAppSandbox: z+ .object({+ url: z+ .string()+ .trim()+ .url()+ .refine(+ (value) => {+ try {+ return ['http:', 'https:'].includes(new URL(value).protocol);+ } catch {+ return false;+ }+ },+ { message: 'MCP App sandbox URL must use http:// or https://' },+ )+ .optional(),+ maxSourcesPerDirective: z+ .number()+ .int()+ .positive()+ .max(Number.MAX_SAFE_INTEGER)+ .default(DEFAULT_MCP_APP_CSP_LIMITS.maxSourcesPerDirective),+ maxSerializedLength: z+ .number()+ .int()+ .positive()+ .max(Number.MAX_SAFE_INTEGER)+ .default(DEFAULT_MCP_APP_CSP_LIMITS.maxSerializedLength),+ maxPersistedAppBytes: z+ .number()+ .int()+ .positive()+ .max(MAX_MCP_APP_PERSISTED_BYTES)+ .default(DEFAULT_MCP_APP_PERSISTED_BYTES),+ maxAdmissionRequestsPerMinute: z+ .number()+ .int()+ .positive()+ .max(Number.MAX_SAFE_INTEGER)+ .default(DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE),+ })+ .default({}),mcpSettings: z.object({allowedDomains: z.array(z.string()).optional(),@@ -3296,6 +3396,7 @@ export const configSchema = z.object({authorizationFenceRetryBatchSize: z.number().int().positive().max(10_000).default(100),}).default({}),+ apps: z.boolean().optional(),}).optional(),interface: interfaceSchema,diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex ea5a39f43c..6244001881 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -24,6 +24,8 @@ export * from './models';export * from './families';/* mcp */export * from './mcp';+export * from './mcp/appMime';+export * from './mcp/csp';/* RBAC */export * from './permissions';export * from './roles';diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex 6856c060bf..d86428222f 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -40,6 +40,7 @@ export enum QueryKeys {mcpTools = 'mcpTools',mcpConnectionStatus = 'mcpConnectionStatus',mcpAuthValues = 'mcpAuthValues',+ mcpAppResourceHtml = 'mcpAppResourceHtml',agentTools = 'agentTools',actions = 'actions',assistantDocs = 'assistantDocs',diff --git a/packages/data-provider/src/mcp/appMime.spec.ts b/packages/data-provider/src/mcp/appMime.spec.tsnew file mode 100644index 0000000000..8434ce1087--- /dev/null+++ b/packages/data-provider/src/mcp/appMime.spec.ts@@ -0,0 +1,29 @@+import { isHtmlMediaType, isMcpAppMimeType, resolveMCPUIResourceMimeType } from './appMime';++describe('MCP UI media types', () => {+ it.each([+ [undefined, 'text/html'],+ [null, 'text/html'],+ ['', ''],+ ['application/xhtml+xml', 'application/xhtml+xml'],+ ])('normalizes %j to %j', (mimeType, expected) => {+ expect(resolveMCPUIResourceMimeType(mimeType)).toBe(expected);+ });++ it.each([+ ['text/html', true],+ ['Text/HTML', true],+ [' text/html ; charset=utf-8', true],+ ['application/xhtml+xml', false],+ ['', false],+ [undefined, false],+ ])('classifies legacy MIME %j as HTML=%s', (mimeType, expected) => {+ expect(isHtmlMediaType(mimeType)).toBe(expected);+ });++ it('keeps the App profile strict to text/html', () => {+ expect(isMcpAppMimeType('text/html;profile=mcp-app')).toBe(true);+ expect(isMcpAppMimeType('application/xhtml+xml;profile=mcp-app')).toBe(false);+ expect(isMcpAppMimeType(resolveMCPUIResourceMimeType(undefined))).toBe(false);+ });+});diff --git a/packages/data-provider/src/mcp/appMime.ts b/packages/data-provider/src/mcp/appMime.tsnew file mode 100644index 0000000000..865237baf4--- /dev/null+++ b/packages/data-provider/src/mcp/appMime.ts@@ -0,0 +1,73 @@+/**+ * The MCP Apps profile media type. Only `text/html` carrying `profile=mcp-app` runs the App Bridge,+ * so the server (which attaches the bridge payload) and the client (which renders it) must classify+ * a resource identically; a substring test on either side can admit unsupported HTML-like media+ * types.+ */+export const MCP_APP_MIME_TYPE = 'text/html;profile=mcp-app';++/** Spec identifier for the MCP Apps extension, advertised as a per-session host capability. */+export const MCP_UI_EXTENSION_ID = 'io.modelcontextprotocol/ui';++const MCP_APP_PROFILE = 'mcp-app';+const LEGACY_MCP_UI_MIME_TYPE = 'text/html';++function unquote(value: string): string {+ if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) {+ return value.slice(1, -1);+ }+ return value;+}++/** RFC 9110 media types are case-insensitive, and parameters are not part of the type. */+function mediaTypeOf(mimeType: string): string {+ return mimeType.split(';')[0].trim().toLowerCase();+}++/**+ * Resolves the legacy MCP-UI convention that an omitted MIME type means inline HTML. Explicit+ * values are preserved so unsupported types never gain HTML behavior by normalization.+ */+export function resolveMCPUIResourceMimeType(mimeType?: string | null): string {+ return mimeType == null ? LEGACY_MCP_UI_MIME_TYPE : mimeType;+}++/**+ * True only for the inline HTML media type supported by the legacy MCP-UI renderer. Media types are+ * case-insensitive and parameters do not change the underlying type.+ */+export function isHtmlMediaType(mimeType?: string | null): boolean {+ if (typeof mimeType !== 'string') {+ return false;+ }+ return mediaTypeOf(mimeType) === LEGACY_MCP_UI_MIME_TYPE;+}++/**+ * True only for the MCP Apps profile: media type exactly `text/html` plus a `profile` parameter+ * whose value is `mcp-app`. Other parameters (`charset`) may precede or follow it, and the value may+ * be quoted. The media type and parameter names are matched case-insensitively per RFC 9110; the+ * profile value is the spec's literal token.+ */+export function isMcpAppMimeType(mimeType?: string | null): boolean {+ if (typeof mimeType !== 'string') {+ return false;+ }+ const parts = mimeType.split(';');+ if (mediaTypeOf(parts[0]) !== 'text/html') {+ return false;+ }+ for (let i = 1; i < parts.length; i++) {+ const separator = parts[i].indexOf('=');+ if (separator === -1) {+ continue;+ }+ if (parts[i].slice(0, separator).trim().toLowerCase() !== 'profile') {+ continue;+ }+ if (unquote(parts[i].slice(separator + 1).trim()) === MCP_APP_PROFILE) {+ return true;+ }+ }+ return false;+}diff --git a/packages/data-provider/src/mcp/csp.spec.ts b/packages/data-provider/src/mcp/csp.spec.tsnew file mode 100644index 0000000000..3c75063a8a--- /dev/null+++ b/packages/data-provider/src/mcp/csp.spec.ts@@ -0,0 +1,74 @@+import {+ DEFAULT_MCP_APP_CSP_LIMITS,+ MCP_APP_CSP_MAX_DOMAINS,+ normalizeMCPAppCspDeclaration,+ resolveMCPAppCspLimits,+} from './csp';++describe('normalizeMCPAppCspDeclaration', () => {+ it('normalizes every supported directive through one source grammar', () => {+ const declaration = normalizeMCPAppCspDeclaration({+ resourceDomains: [' https://cdn.example.com '],+ connectDomains: ['wss://events.example.com', '*'],+ frameDomains: ['https://embed.example.com'],+ baseUriDomains: ['https://base.example.com/path'],+ ignored: ['https://ignored.example.com'],+ });++ expect(declaration).toEqual({+ resourceDomains: ['https://cdn.example.com'],+ connectDomains: ['wss://events.example.com'],+ frameDomains: ['https://embed.example.com'],+ baseUriDomains: ['https://base.example.com/path'],+ });+ });++ it('returns the restrictive empty declaration for invalid input', () => {+ expect(normalizeMCPAppCspDeclaration(null)).toEqual({});+ expect(normalizeMCPAppCspDeclaration([])).toEqual({});+ expect(normalizeMCPAppCspDeclaration({ connectDomains: ['javascript:alert(1)'] })).toEqual({});+ });++ it('caps each directive independently', () => {+ const domains = Array.from(+ { length: MCP_APP_CSP_MAX_DOMAINS + 4 },+ (_unused, index) => `https://host${index}.example.com`,+ );+ const declaration = normalizeMCPAppCspDeclaration({+ connectDomains: domains,+ frameDomains: domains,+ });++ expect(declaration.connectDomains).toHaveLength(MCP_APP_CSP_MAX_DOMAINS);+ expect(declaration.frameDomains).toHaveLength(MCP_APP_CSP_MAX_DOMAINS);+ });++ it('uses one injected source limit for every directive', () => {+ const domains = Array.from({ length: 5 }, (_, index) => `https://host${index}.example.com`);+ const declaration = normalizeMCPAppCspDeclaration(+ { connectDomains: domains, frameDomains: domains },+ { maxSourcesPerDirective: 3 },+ );++ expect(declaration.connectDomains).toHaveLength(3);+ expect(declaration.frameDomains).toHaveLength(3);+ });++ it('falls back per field when published limits are missing or malformed', () => {+ expect(resolveMCPAppCspLimits()).toEqual(DEFAULT_MCP_APP_CSP_LIMITS);+ expect(+ resolveMCPAppCspLimits({+ maxSourcesPerDirective: 0,+ maxSerializedLength: 8192,+ }),+ ).toEqual({ maxSourcesPerDirective: 32, maxSerializedLength: 8192 });+ });++ it('is idempotent', () => {+ const once = normalizeMCPAppCspDeclaration({+ connectDomains: [' https://api.example.com ', '*'],+ frameDomains: ['https://embed.example.com'],+ });+ expect(normalizeMCPAppCspDeclaration(once)).toEqual(once);+ });+});diff --git a/packages/data-provider/src/mcp/csp.ts b/packages/data-provider/src/mcp/csp.tsnew file mode 100644index 0000000000..0ba2cbdc87--- /dev/null+++ b/packages/data-provider/src/mcp/csp.ts@@ -0,0 +1,86 @@+export type MCPAppCspLimits = {+ maxSourcesPerDirective: number;+ maxSerializedLength: number;+};++export const DEFAULT_MCP_APP_CSP_LIMITS: Readonly<MCPAppCspLimits> = Object.freeze({+ maxSourcesPerDirective: 32,+ maxSerializedLength: 4096,+});++/** Default serialized resource CSP limit retained for mixed-version consumers. */+export const MCP_APP_CSP_MAX_LENGTH = DEFAULT_MCP_APP_CSP_LIMITS.maxSerializedLength;++/** Default source count retained for mixed-version consumers. */+export const MCP_APP_CSP_MAX_DOMAINS = DEFAULT_MCP_APP_CSP_LIMITS.maxSourcesPerDirective;++export type MCPAppCspDeclaration = {+ resourceDomains?: string[];+ connectDomains?: string[];+ frameDomains?: string[];+ baseUriDomains?: string[];+};++const MCP_APP_CSP_SOURCE_PATTERN =+ /^(?:(?:https?|wss?):\/\/)?(?:\*\.)?[a-zA-Z0-9][a-zA-Z0-9\-.]*(?::(?:\d{1,5}|\*))?(?:\/[^\s;,'"?#]*)?$/i;++const validLimit = (value: unknown, fallback: number): number =>+ typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : fallback;++export function resolveMCPAppCspLimits(value?: Partial<MCPAppCspLimits>): MCPAppCspLimits {+ return {+ maxSourcesPerDirective: validLimit(+ value?.maxSourcesPerDirective,+ DEFAULT_MCP_APP_CSP_LIMITS.maxSourcesPerDirective,+ ),+ maxSerializedLength: validLimit(+ value?.maxSerializedLength,+ DEFAULT_MCP_APP_CSP_LIMITS.maxSerializedLength,+ ),+ };+}++const normalizeCspSources = (value: unknown, maxSources: number): string[] | undefined => {+ if (!Array.isArray(value)) {+ return undefined;+ }+ const sources: string[] = [];+ for (const entry of value) {+ const source = typeof entry === 'string' ? entry.trim() : '';+ if (source.length > 0 && MCP_APP_CSP_SOURCE_PATTERN.test(source)) {+ sources.push(source);+ if (sources.length === maxSources) {+ break;+ }+ }+ }+ return sources.length > 0 ? sources : undefined;+};++/**+ * Canonical declaration used for sandbox serialization, response policies, and host link checks.+ * Host link matching remains intentionally narrower than this CSP source grammar.+ */+export function normalizeMCPAppCspDeclaration(+ value: unknown,+ limits?: Partial<MCPAppCspLimits>,+): MCPAppCspDeclaration {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return {};+ }+ const { maxSourcesPerDirective } = resolveMCPAppCspLimits(limits);+ const input = value as Record<keyof MCPAppCspDeclaration, unknown>;+ const normalized: MCPAppCspDeclaration = {};+ for (const key of [+ 'resourceDomains',+ 'connectDomains',+ 'frameDomains',+ 'baseUriDomains',+ ] as const) {+ const sources = normalizeCspSources(input[key], maxSourcesPerDirective);+ if (sources) {+ normalized[key] = sources;+ }+ }+ return normalized;+}diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.tsindex d6d6ea7017..9e692a7621 100644--- a/packages/data-provider/src/schemas.ts+++ b/packages/data-provider/src/schemas.ts@@ -1034,8 +1034,30 @@ export type MemoryArtifact = {export type UIResource = {resourceId: string;uri: string;+ name?: string;mimeType?: string;text?: string;+ serverName?: string;+ toolName?: string;+ /** Opaque server-issued binding required for executable MCP App callbacks. */+ serverBinding?: string;+ structuredContent?: Record<string, unknown>;+ content?: unknown[];+ csp?: {+ connectDomains?: string[];+ resourceDomains?: string[];+ frameDomains?: string[];+ baseUriDomains?: string[];+ };+ permissions?: {+ camera?: Record<string, never>;+ microphone?: Record<string, never>;+ geolocation?: Record<string, never>;+ clipboardWrite?: Record<string, never>;+ };+ toolArgs?: Record<string, unknown>;+ isError?: boolean;+ resultMeta?: Record<string, unknown>;[key: string]: unknown;};diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.tsindex 533ff4b12f..a41ff0718a 100644--- a/packages/data-schemas/src/app/resolution.spec.ts+++ b/packages/data-schemas/src/app/resolution.spec.ts@@ -75,6 +75,33 @@ describe('mergeConfigOverrides', () => {expect(mergeConfigOverrides(base, configs).filters).toEqual(base.filters);});+ it('keeps MCP App sandbox limits at deployment scope', () => {+ const base = {+ mcpAppSandbox: {+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ maxSourcesPerDirective: 64,+ maxSerializedLength: 8192,+ maxAdmissionRequestsPerMinute: 480,+ },+ } as unknown as AppConfig;+ const configs = [+ fakeConfig(+ {+ mcpAppSandbox: {+ url: 'https://user-sandbox.example.com/api/mcp/sandbox',+ maxSourcesPerDirective: 128,+ maxSerializedLength: 16384,+ maxAdmissionRequestsPerMinute: 960,+ },+ },+ 10,+ ['mcpAppSandbox.url', 'mcpAppSandbox.maxAdmissionRequestsPerMinute'],+ ),+ ];++ expect(mergeConfigOverrides(base, configs).mcpAppSandbox).toEqual(base.mcpAppSandbox);+ });+it('applies tenant-wide Langfuse settings only from the base principal', () => {const configs = [fakeConfig(diff --git a/packages/data-schemas/src/app/service.spec.ts b/packages/data-schemas/src/app/service.spec.tsindex 820335f4b5..906f7978d3 100644--- a/packages/data-schemas/src/app/service.spec.ts+++ b/packages/data-schemas/src/app/service.spec.ts@@ -287,6 +287,28 @@ describe('AppService assistants config', () => {});});+describe('AppService MCP App sandbox configuration', () => {+ it('preserves deployment-owned MCP App sandbox limits', async () => {+ const result = await AppService({+ config: {+ mcpAppSandbox: {+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ maxSourcesPerDirective: 64,+ maxSerializedLength: 8192,+ maxAdmissionRequestsPerMinute: 480,+ },+ } as DeepPartial<TCustomConfig>,+ });++ expect(result.mcpAppSandbox).toEqual({+ url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',+ maxSourcesPerDirective: 64,+ maxSerializedLength: 8192,+ maxAdmissionRequestsPerMinute: 480,+ });+ });+});+describe('AppService memory capability', () => {it('strips the memory capability when no memory config is present', async () => {const result = await AppService({ config: {} as DeepPartial<TCustomConfig> });diff --git a/packages/data-schemas/src/app/service.ts b/packages/data-schemas/src/app/service.tsindex 63c7b15850..78016b670b 100644--- a/packages/data-schemas/src/app/service.ts+++ b/packages/data-schemas/src/app/service.ts@@ -161,6 +161,7 @@ export const AppService = async (params?: {const mcpServersConfig = config.mcpServers || null;const mcpSettings = config.mcpSettings || null;+ const mcpAppSandbox = config.mcpAppSandbox ?? configDefaults.mcpAppSandbox;const actions = config.actions;const registration = config.registration ?? configDefaults.registration;const emailChange = config.emailChange;@@ -182,6 +183,7 @@ export const AppService = async (params?: {skillSync,webSearch,mcpSettings,+ mcpAppSandbox,fileStrategy,registration,emailChange,diff --git a/packages/data-schemas/src/types/app.ts b/packages/data-schemas/src/types/app.tsindex 95770d4fcb..7d6d673ab1 100644--- a/packages/data-schemas/src/types/app.ts+++ b/packages/data-schemas/src/types/app.ts@@ -104,6 +104,8 @@ export interface AppConfig {mcpConfig?: TCustomConfig['mcpServers'] | null;/** MCP settings (domain allowlist, etc.) */mcpSettings?: TCustomConfig['mcpSettings'] | null;+ /** Deployment-owned MCP App sandbox transport limits. */+ mcpAppSandbox?: TCustomConfig['mcpAppSandbox'];/** File configuration */fileConfig?: TFileConfig;/** Secure image links configuration, enabled unless explicitly disabled */