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
🐛 fix: Restore MCP App Rendering and Actions (#16382)
Dustin Healyf757a673aaa8
diff --git a/api/server/controllers/mcpApps.js b/api/server/controllers/mcpApps.jsindex 73cf11c6bf..8ed848381e 100644--- a/api/server/controllers/mcpApps.js+++ b/api/server/controllers/mcpApps.js@@ -43,8 +43,8 @@ module.exports = createMCPAppsController({return resolveMCPAppCspLimits(appConfig?.mcpAppSandbox);},ensureConfigServers: (mcpConfig) => getMCPServersRegistry().ensureConfigServers(mcpConfig),- getAllServerConfigs: (userId, configServers, role) =>- getMCPServersRegistry().getAllServerConfigs(userId, configServers, role),+ getServerConfig: (serverName, userId, configServers, role) =>+ getMCPServersRegistry().getServerConfig(serverName, userId, configServers, role),recoverServerConfig: (serverName, config, userId) =>getMCPServersRegistry().recoverServerConfig(serverName, config, userId),isAppServerConfig: (serverName, config) =>diff --git a/api/server/controllers/mcpApps.test.js b/api/server/controllers/mcpApps.test.jsindex ef66938c8a..eb1e8c27ad 100644--- a/api/server/controllers/mcpApps.test.js+++ b/api/server/controllers/mcpApps.test.js@@ -75,7 +75,7 @@ describe('MCP Apps controller wiring', () => {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 getServerConfig = jest.fn().mockResolvedValue({ type: 'sse' });const recoverServerConfig = jest.fn().mockResolvedValue({ type: 'sse' });const isAppServerConfig = jest.fn().mockResolvedValue(true);const resolveCachedAppServerConfig = jest.fn().mockResolvedValue({@@ -86,7 +86,7 @@ describe('MCP Apps controller wiring', () => {getFlowStateManager.mockReturnValue('flow-manager');getMCPServersRegistry.mockReturnValue({ensureConfigServers,- getAllServerConfigs,+ getServerConfig,recoverServerConfig,isAppServerConfig,resolveCachedAppServerConfig,@@ -142,9 +142,9 @@ describe('MCP Apps controller wiring', () => {});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');+ dependencies.getServerConfig('srv', 'user-1', { srv: { type: 'sse' } }, 'USER'),+ ).resolves.toEqual({ type: 'sse' });+ expect(getServerConfig).toHaveBeenCalledWith('srv', 'user-1', { srv: { type: 'sse' } }, 'USER');await expect(dependencies.recoverServerConfig('srv', { type: 'sse', inspectionFailed: true }, 'user-1'),).resolves.toEqual({ type: 'sse' });diff --git a/client/public/mcp-sandbox.html b/client/public/mcp-sandbox.htmlindex e026148e68..25a5467ee1 100644--- a/client/public/mcp-sandbox.html+++ b/client/public/mcp-sandbox.html@@ -38,6 +38,7 @@const SANDBOX_PREFIX = 'ui/notifications/sandbox-';const ATTEST_METHOD = 'ui/notifications/sandbox-frame-attest';+ const CHALLENGE_METHOD = 'ui/notifications/sandbox-frame-challenge';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';@@ -50,13 +51,11 @@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 pendingChallenge = null;let attestedAt = 0;let pendingToInner = [];let pendingToParent = [];@@ -93,9 +92,7 @@// 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- );+ return !!innerFrame && !!innerFrame.contentWindow;}function attestFresh() {@@ -140,10 +137,6 @@function releaseInnerFrame() {discardPending();- if (innerFrameBlobUrl) {- URL.revokeObjectURL(innerFrameBlobUrl);- innerFrameBlobUrl = null;- }if (innerFrame) {innerFrame.remove();innerFrame = null;@@ -201,7 +194,12 @@const attested = !!attestNonce && !!msg.params && msg.params.nonce === attestNonce;if (msg.method === ATTEST_METHOD) {- if (attested && frameUsable()) {+ if (+ attested &&+ frameUsable() &&+ (pendingChallenge === null || msg.params.challenge === pendingChallenge)+ ) {+ pendingChallenge = null;attestedAt = Date.now();flushPending();}@@ -232,6 +230,11 @@'<script>(function(){var N=' +JSON.stringify(nonce) +';var post=function(m){parent.postMessage({jsonrpc:"2.0",method:m,params:{nonce:N}},"*")};' ++ 'addEventListener("message",function(e){if(e.source===parent&&e.data&&e.data.method===' ++ JSON.stringify(CHALLENGE_METHOD) ++ '){parent.postMessage({jsonrpc:"2.0",method:' ++ JSON.stringify(ATTEST_METHOD) ++ ',params:{nonce:N,challenge:e.data.params.challenge}},"*")}});' +'post(' +JSON.stringify(ATTEST_METHOD) +');setInterval(function(){post(' +@@ -262,7 +265,7 @@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.+ // document's pending messages and load events racing the new one.if (resourceApplied || !trustedOrigin) {return;}@@ -274,19 +277,6 @@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.@@ -312,22 +302,28 @@// 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;+ // srcdoc gives the opaque View a stable document URL. A blob URL makes some otherwise+ // conforming bundled apps fail during startup when their dependencies resolve the current+ // location (Blob URL pathnames are not hierarchical URLs).+ innerFrame.srcdoc = injectIntoHead(html, buildViewInjection(attestNonce));innerFrame.style.cssText = 'width:100%;height:100%;border:none;display:block';+ // WindowProxy identity survives navigation. Every document load invalidates liveness;+ // only the injected bootstrap in the loaded realm can answer this fresh challenge.+ // Unlike load counting, this also tolerates an initial about:blank or duplicate load.+ frame.addEventListener('load', () => {+ if (innerFrame !== frame) return;+ attestedAt = 0;+ discardPending();+ pendingChallenge = mintNonce();+ frame.contentWindow.postMessage(+ { jsonrpc: '2.0', method: CHALLENGE_METHOD, params: { challenge: pendingChallenge } },+ '*',+ );+ });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) {@@ -414,7 +410,7 @@}function injectIntoHead(html, injection) {- // The bootstrap must run before any app script, and the app's bytes must reach the blob+ // The bootstrap must run before any app script, and the app's bytes must reach the View// 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);diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsxindex ebdcdcc4bf..90e27340e1 100644--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx@@ -11,6 +11,7 @@ import type { ReactNode, ReactElement } from 'react';import type { ReasoningDisclosures, ToolDisclosures } from './disclosure';import type { ToolCallGroupExpansionState } from './ToolCallGroup';import type { ActivityPhaseSegment } from '~/utils/activityLabels';+import type { MCPAppResourceOccurrence } from '~/utils/mcpApps';import {mapAttachments,getPartKeyIndex,@@ -38,6 +39,8 @@ import { isPreviewedToolCallPart, PreviewedToolCallPart } from './hydration';import { MediaContext, MessageContext, SearchContext } from '~/Providers';import MemoryArtifacts, { hasMemoryArtifacts } from './MemoryArtifacts';import { hasParallelLanes, parallelLaneGroups } from '~/utils/lanes';+import { useMCPAppsPolicy } from '~/Providers/MCPAppsPolicyContext';+import { selectToolCallUIResources } from '~/utils/mcpApps';import PendingSkillCall from './Parts/PendingSkillCall';import ActivityPhaseGroup from './ActivityPhaseGroup';import { hasPendingApprovalInPart } from '~/utils';@@ -123,17 +126,33 @@ const buildToolCallStepOwners = (return owners;};-const collectMessageAppAttachments = (+const collectMessageContent = (content: Array<TMessageContentParts | undefined> | undefined,attachments: TAttachment[] | undefined,-): TAttachment[] => {+ contentIndexOffset = 0,+ contentIndices?: ReadonlyArray<number>,+): {+ attachments: TAttachment[];+ atIndex: Map<number, TAttachment[]>;+ resumeAuthors: ReadonlyMap<number, string | undefined>;+} => {+ const resumeAuthors = new Map<number, string | undefined>();+ let prevType: string | undefined;+ let activeAgentId: string | undefined;+ const atIndex = new Map<number, TAttachment[]>();const attachmentMap = mapAttachments(attachments ?? []);const ownersByToolCallId = buildToolCallStepOwners(content);const collected = new Set<TAttachment>();- for (const part of content ?? []) {- if (part == null) {- continue;+ (content ?? []).forEach((part, index) => {+ if (part == null) return;+ // Attribute the resume point before applying a handoff on that same part.+ if (prevType === ContentTypes.STEER && part.type !== ContentTypes.STEER) {+ resumeAuthors.set(contentIndices?.[index] ?? index + contentIndexOffset, activeAgentId);}+ if (part.type === ContentTypes.AGENT_UPDATE) {+ activeAgentId = part[ContentTypes.AGENT_UPDATE]?.agentId || undefined;+ }+ prevType = part.type;const routed = filterAttachmentsForPart(attachmentMap[getToolCallId(part)],getPartAgentId(part),@@ -141,12 +160,19 @@ const collectMessageAppAttachments = (getSiblingStepIds(part, ownersByToolCallId),);for (const attachment of routed ?? []) {- if (attachment.type === Tools.ui_resources) {+ if (+ attachment.type === Tools.ui_resources &&+ !collected.has(attachment) &&+ selectToolCallUIResources([attachment]).length > 0+ ) {collected.add(attachment);+ const entries = atIndex.get(index) ?? [];+ entries.push(attachment);+ atIndex.set(index, entries);}}- }- return Array.from(collected);+ });+ return { attachments: Array.from(collected), atIndex, resumeAuthors };};const getToolGroupId = (parts: PartWithIndex[], fallbackScope: number): string => {@@ -311,6 +337,8 @@ type ContentPartsProps = {foldLiveActivity?: boolean;/** Internal recursion guard for nested phase segments. */nestedActivityPhase?: boolean;+ /** Subsequent slices around stable App outputs must not repeat message decorations. */+ continuation?: boolean;/** Internal signal that the parent phase card lifted this segment's* attachments into its own media row — the parts below must not render* them a second time inside the fold. */@@ -369,6 +397,7 @@ const ContentPartsBody = memo(function ContentPartsBody({createdAt,foldLiveActivity = true,nestedActivityPhase = false,+ continuation = false,withinActivityPhase = false,parentPhaseOwnsFailurePill = false,cursorOwnedElsewhere = false,@@ -381,7 +410,7 @@ const ContentPartsBody = memo(function ContentPartsBody({toolGroupExpansionState,toolGroupOccurrenceByIndex,toolCallStepOwnersById,-}: ContentPartsProps) {+}: ContentPartsProps & { resumeAuthors: ReadonlyMap<number, string | undefined> }) {const { inlineAttachments, workspaceChanges } = useMemo(() =>workspaceAttachmentsPartitioned@@ -704,38 +733,15 @@ const ContentPartsBody = memo(function ContentPartsBody({],);- /** `postSteerAuthors` marks each part that resumes the response after a- * steer block — where attribution is re-rendered. The value is the ACTIVE- * agent id when a preceding AGENT_UPDATE handed the run off (the resumed- * content belongs to that agent, not the message-level author), undefined- * for the top-level `authorHeader`. Read BEFORE applying the current- * part's own handoff, so a resume point that IS an agent update keeps the- * pre-handoff author and lets the real marker announce the transition. */- const { sequentialParts, detectedResumeAuthors } = useMemo(() => {+ const sequentialParts = useMemo(() => {const parts: PartWithIndex[] = [];- const authors = new Map<number, string | undefined>();- if (!content) {- return { sequentialParts: parts, detectedResumeAuthors: authors };- }- let prevType: string | undefined;- let activeAgentId: string | undefined;- content.forEach((part, localIdx) => {- if (!part) {- return;- }- const idx = absoluteIndexAt(localIdx);- if (prevType === ContentTypes.STEER && part.type !== ContentTypes.STEER) {- authors.set(idx, activeAgentId);+ content?.forEach((part, localIdx) => {+ if (part != null) {+ parts.push({ part, idx: absoluteIndexAt(localIdx) });}- if (part.type === ContentTypes.AGENT_UPDATE) {- activeAgentId = part[ContentTypes.AGENT_UPDATE]?.agentId || undefined;- }- prevType = part.type;- parts.push({ part, idx });});- return { sequentialParts: parts, detectedResumeAuthors: authors };+ return parts;}, [absoluteIndexAt, content]);- const postSteerAuthors = resumeAuthors ?? detectedResumeAuthors;const resolvedToolGroupOccurrences = useMemo(() => {if (toolGroupOccurrenceByIndex != null) {@@ -793,16 +799,16 @@ const ContentPartsBody = memo(function ContentPartsBody({* by the sequential path and the parallel renderer's sequential stretches. */const renderResumeAttribution = useCallback((idx: number, keyIdx: number = idx): ReactElement | null => {- if (authorHeader == null || !postSteerAuthors.has(idx)) {+ if (authorHeader == null || !resumeAuthors.has(idx)) {return null;}- const activeAgentId = postSteerAuthors.get(idx);+ const activeAgentId = resumeAuthors.get(idx);if (activeAgentId != null) {return <AgentUpdate key={`author-${messageId}-${keyIdx}`} currentAgentId={activeAgentId} />;}return <Fragment key={`author-${messageId}-${keyIdx}`}>{authorHeader}</Fragment>;},- [authorHeader, postSteerAuthors, messageId],+ [authorHeader, resumeAuthors, messageId],);// Early return: no content to render AND no pending skill cards@@ -1008,7 +1014,7 @@ const ContentPartsBody = memo(function ContentPartsBody({contentIndexOffset={segmentStartIndex}contentIndices={segmentIndices}laneGroups={messageLaneGroups}- resumeAuthors={postSteerAuthors}+ resumeAuthors={resumeAuthors}toolGroupExpansionState={expansionState}toolGroupOccurrenceByIndex={resolvedToolGroupOccurrences}toolCallStepOwnersById={resolvedToolCallStepOwners}@@ -1188,7 +1194,7 @@ const ContentPartsBody = memo(function ContentPartsBody({if (hasParallelContent && phaseContent == null) {const parallelContent = (<>- {renderPendingSkills()}+ {!continuation && renderPendingSkills()}<ParallelContentRenderercontent={content}messageId={messageId}@@ -1199,7 +1205,7 @@ const ContentPartsBody = memo(function ContentPartsBody({isSubmitting={effectiveIsSubmitting}renderPart={renderPart}renderResumeAttribution={renderResumeAttribution}- showDecorations={!nestedActivityPhase}+ showDecorations={!nestedActivityPhase && !continuation}contentIndexOffset={contentIndexOffset}contentIndices={contentIndices}laneGroups={messageLaneGroups}@@ -1217,11 +1223,8 @@ const ContentPartsBody = memo(function ContentPartsBody({// Sequential content: render parts in order (90% of cases)const sequentialContent = (<SearchContext.Provider value={{ searchResults }}>- {!nestedActivityPhase && <MemoryArtifacts attachments={attachments} />}- {phaseContent != null && hasParallelContent && (- <Sources messageId={messageId} conversationId={conversationId || undefined} />- )}- {!nestedActivityPhase && renderPendingSkills()}+ {!nestedActivityPhase && !continuation && <MemoryArtifacts attachments={attachments} />}+ {!nestedActivityPhase && !continuation && renderPendingSkills()}{showEmptyCursor && (<Container>{/** Nudge only when the dot is truly first under the header — leading@@ -1244,6 +1247,7 @@ const ContentPartsBody = memo(function ContentPartsBody({});const ContentParts = memo(function ContentParts(props: ContentPartsProps) {+ const { enabled: appsEnabled } = useMCPAppsPolicy();const {attachments,messageId,@@ -1326,13 +1330,19 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {previousIdentity.isSubmitting = isSubmitting;}const appRenderScope = appRenderIdentity.current!.scope;- const messageAppAttachments = useMemo(- () => collectMessageAppAttachments(props.content, attachments),- [props.content, attachments],+ const messageContent = useMemo(+ () =>+ collectMessageContent(+ props.content,+ attachments,+ props.contentIndexOffset,+ props.contentIndices,+ ),+ [props.content, attachments, props.contentIndexOffset, props.contentIndices],);const suppressedAppAttachments = useMemo<ReadonlySet<TAttachment>>(- () => new Set(messageAppAttachments),- [messageAppAttachments],+ () => new Set(messageContent.attachments),+ [messageContent.attachments],);const messageContext = useMemo(() => ({@@ -1374,6 +1384,68 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {reasoningState.current = { messageId, disclosures: new Map() };}const reasoningDisclosures = reasoningState.current.disclosures;+ const appContent = useMemo(() => {+ if (!appsEnabled || messageContent.atIndex.size === 0 || props.edit) return null;+ const owners = buildToolCallStepOwners(props.content);+ const lanes = parallelLaneGroups(props.content);+ const { inlineAttachments, workspaceChanges } = partitionWorkspaceChanges(attachments);+ const resourcesByAttachment = new Map<+ TAttachment,+ Array<{ resource: MCPAppResourceOccurrence; ordinal: number }>+ >();+ selectToolCallUIResources(messageContent.attachments).forEach((resource, index) => {+ const entries = resourcesByAttachment.get(resource.attachment) ?? [];+ entries.push({ resource, ordinal: index + 1 });+ resourcesByAttachment.set(resource.attachment, entries);+ });+ const rows: ReactNode[] = [];+ let start = 0;+ const renderSlice = (end: number) => {+ if (end <= start) return;+ // Sparse slices preserve provider/phase indices. App siblings never belong to a fold,+ // parallel column, or tool card that can change parents while the response streams.+ const slice: Array<TMessageContentParts | undefined> = [];+ for (let index = start; index < end; index++) {+ const part = props.content?.[index];+ if (part != null) slice[index] = part;+ }+ rows.push(+ <MCPAppSuppressionContext.Provider key={`body-${start}`} value={suppressedAppAttachments}>+ <SoleToolContext.Provider value={undefined}>+ <ContentPartsBody+ {...props}+ content={slice}+ attachments={inlineAttachments}+ workspaceAttachmentsPartitioned+ continuation={start > 0}+ isLast={props.isLast && end === props.content?.length}+ laneGroups={lanes}+ resumeAuthors={props.resumeAuthors ?? messageContent.resumeAuthors}+ toolCallStepOwnersById={owners}+ />+ </SoleToolContext.Provider>+ </MCPAppSuppressionContext.Provider>,+ );+ };+ for (const [index, appAttachments] of messageContent.atIndex) {+ renderSlice(index + 1);+ for (const attachment of appAttachments) {+ for (const { resource, ordinal } of resourcesByAttachment.get(attachment) ?? []) {+ rows.push(+ <MCPAppViews+ key={`app-${appRenderScope}-${resource.key}`}+ resources={[resource]}+ ordinalStart={ordinal}+ />,+ );+ }+ }+ start = index + 1;+ }+ renderSlice(props.content?.length ?? 0);+ rows.push(<WorkspaceChanges key="workspace" attachments={workspaceChanges} />);+ return rows;+ }, [props, attachments, messageContent, suppressedAppAttachments, appRenderScope, appsEnabled]);/** Published once for the whole message so every markdown block below —* including the ones nested inside phase cards — resolves a bare* `` against the files this turn actually produced.@@ -1394,16 +1466,21 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {<MediaContext.Provider value={media}><ReasoningDisclosureContext.Provider value={reasoningDisclosures}><ToolDisclosureContext.Provider value={toolDisclosures}>- <MCPAppSuppressionContext.Provider value={suppressedAppAttachments}>- {/* A nested message (a subagent's) is not the sole call of the group around it. */}- <SoleToolContext.Provider value={undefined}>- <ContentPartsBody {...props} />- </SoleToolContext.Provider>- </MCPAppSuppressionContext.Provider>- <MCPAppViews- key={`message-apps-${appRenderScope}`}- attachments={messageAppAttachments}- />+ {!props.edit && hasParallelLanes(props.content, props.laneGroups) && (+ <SearchContext.Provider value={{ searchResults: props.searchResults }}>+ <Sources messageId={messageId} conversationId={conversationId || undefined} />+ </SearchContext.Provider>+ )}+ {appContent ?? (+ <MCPAppSuppressionContext.Provider value={suppressedAppAttachments}>+ <SoleToolContext.Provider value={undefined}>+ <ContentPartsBody+ {...props}+ resumeAuthors={props.resumeAuthors ?? messageContent.resumeAuthors}+ />+ </SoleToolContext.Provider>+ </MCPAppSuppressionContext.Provider>+ )}</ToolDisclosureContext.Provider></ReasoningDisclosureContext.Provider></MediaContext.Provider>diff --git a/client/src/components/Chat/Messages/Content/ParallelContent.tsx b/client/src/components/Chat/Messages/Content/ParallelContent.tsxindex f438b72850..b07f851f74 100644--- a/client/src/components/Chat/Messages/Content/ParallelContent.tsx+++ b/client/src/components/Chat/Messages/Content/ParallelContent.tsx@@ -8,7 +8,6 @@ import {} from '~/utils/activityLabels';import { MIN_PARALLEL_LANES, UNATTRIBUTED_LANE, isLaneMarkerPart } from '~/utils/lanes';import MemoryArtifacts from './MemoryArtifacts';-import Sources from '~/components/Web/Sources';import { cn, getPartKeyIndex } from '~/utils';import { SearchContext } from '~/Providers';import SiblingHeader from './SiblingHeader';@@ -344,9 +343,6 @@ export const ParallelContentRenderer = memo(function ParallelContentRenderer({return (<SearchContext.Provider value={{ searchResults }}>{showDecorations && <MemoryArtifacts attachments={attachments} />}- {showDecorations && (- <Sources messageId={messageId} conversationId={conversationId || undefined} />- )}{/* Each section preceded by the sequential content that runs up to it */}{blocks.map(({ leading, section: { groupId, columns } }) => (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 a146e7bd59..d3568986b6 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@@ -3,6 +3,7 @@ import { RecoilRoot } from 'recoil';import { Constants, ContentTypes, Tools } from 'librechat-data-provider';import { act, fireEvent, render, screen, within } from '@testing-library/react';import type { EventSubmission, TAttachment, TMessageContentParts } from 'librechat-data-provider';+import type { MCPAppResourceOccurrence } from '~/utils/mcpApps';import useAttachmentHandler from '~/hooks/SSE/useAttachmentHandler';import useAttachments from '~/hooks/Messages/useAttachments';import { ParallelColumns } from '../ParallelContent';@@ -41,14 +42,31 @@ jest.mock('~/hooks/MCP', () => {};});+jest.mock('~/Providers/MCPAppsPolicyContext', () => ({+ useMCPAppsPolicy: () => ({ enabled: true }),+}));+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[] }) => {+ MCPAppViews: ({+ attachments,+ resources,+ }: {+ attachments?: TAttachment[];+ resources?: MCPAppResourceOccurrence[];+ }) => {const suppressed = ReactActual.useContext(MCPAppSuppressionContext);- const visible = (attachments ?? []).filter((attachment) => !suppressed?.has(attachment));+ const selectedAttachments =+ resources?.map(({ attachment, resource }) => ({+ ...attachment,+ ui_resources: [resource],+ })) ?? attachments;+ const visible = (selectedAttachments ?? []).filter(+ (attachment) => !suppressed?.has(attachment),+ );if (visible.length === 0) {return null;}@@ -135,17 +153,37 @@ jest.mock('../Parts', () => ({},ExecuteCode: () => <div data-testid="execute-code" />,ImageGen: () => <div data-testid="image-gen" />,- AgentUpdate: () => <div data-testid="agent-update" />,+ AgentUpdate: ({ currentAgentId }: { currentAgentId?: string }) => (+ <div data-testid="agent-update" data-agent-id={currentAgentId} />+ ),EmptyText: () => <div data-testid="empty-text" />,Reasoning: () => <div data-testid="reasoning" />,ReasoningCompact: () => <div data-testid="compact-reasoning" />,Summary: () => <div data-testid="summary" />,+ SteerPart: () => <div data-testid="steer" />,Text: jest.fn(({ text }: { text?: string }) => <div data-testid="text">{text}</div>),MemoryCall: ({ attachments }: { attachments?: TAttachment[] }) => (<div data-testid="memory-call" data-count={attachments?.length ?? 0} />),}));+jest.mock('~/components/Web/Sources', () => ({+ __esModule: true,+ default: ({ messageId, conversationId }: { messageId?: string; conversationId?: string }) => {+ const { searchResults } = jest+ .requireActual<typeof import('~/Providers/SearchContext')>('~/Providers/SearchContext')+ .useSearchContext();+ return (+ <div+ data-testid="sources"+ data-message-id={messageId}+ data-conversation-id={conversationId}+ data-search-keys={Object.keys(searchResults ?? {}).join(',')}+ />+ );+ },+}));+jest.mock('../MemoryArtifacts', () => ({__esModule: true,default: () => <div data-testid="memory-artifacts" />,@@ -540,6 +578,132 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {]);});+ const appAttachment = (toolCallId: string): TAttachment =>+ ({+ type: Tools.ui_resources,+ toolCallId,+ ui_resources: [+ {+ resourceId: toolCallId,+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ },+ ],+ }) as TAttachment;++ it.each([false, true])(+ 'retains the handed-off author after an App with phase %s',+ (withPhase) => {+ const handoff: TMessageContentParts = {+ type: ContentTypes.AGENT_UPDATE,+ agent_update: { agentId: 'agent_b', index: 1, runId: 'run' },+ };+ renderContentParts({+ ...baseProps,+ authorHeader: <div data-testid="top-level-author" />,+ content: [+ handoff,+ makeMcpToolCall('app'),+ undefined,+ { type: ContentTypes.STEER, steer: 'continue' },+ undefined,+ makeTextPart('resumed answer'),+ ...(withPhase ? [makePhasePart(3, 6, 'Resumed work')] : []),+ ],+ attachments: [appAttachment('app')],+ });+ if (withPhase) fireEvent.click(screen.getByRole('button', { name: /Resumed work/ }));+ const markers = screen.getAllByTestId('agent-update');+ expect(markers).toHaveLength(2);+ expect(markers[1]).toHaveAttribute('data-agent-id', 'agent_b');+ expect(screen.queryByTestId('top-level-author')).toBeNull();+ expect(markers[1].compareDocumentPosition(screen.getByText('resumed answer'))).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ },+ );++ it.each(['before', 'after', 'between', 'phase', 'none'])(+ 'renders Sources once with Apps %s parallel content',+ (layout) => {+ const lanes: TMessageContentParts[] = [+ { ...makeTextPart('lane A'), agentId: 'agent_a', groupId: 1 },+ { ...makeTextPart('lane B'), agentId: 'agent_b', groupId: 1 },+ ];+ const app = makeMcpToolCall('app');+ const layouts: Record<string, TMessageContentParts[]> = {+ before: [app, ...lanes],+ after: [...lanes, app],+ between: [app, ...lanes, makeMcpToolCall('second-app')],+ phase: [app, ...lanes, makePhasePart(1, 3, 'Parallel research')],+ none: lanes,+ };+ renderContentParts({+ ...baseProps,+ conversationId: 'conversation',+ content: layouts[layout],+ attachments: [appAttachment('app'), appAttachment('second-app')],+ searchResults: { search: { organic: [] } },+ });+ expect(screen.getAllByTestId('sources')).toHaveLength(1);+ expect(screen.getByTestId('sources')).toHaveAttribute('data-message-id', 'msg1');+ expect(screen.getByTestId('sources')).toHaveAttribute('data-conversation-id', 'conversation');+ expect(screen.getByTestId('sources')).toHaveAttribute('data-search-keys', 'search');+ },+ );++ it('updates Sources as parallel content streams after an App', () => {+ const frame = (content: TMessageContentParts[]) => (+ <RecoilRoot>+ <ContentParts {...baseProps} content={content} attachments={[appAttachment('app')]} />+ </RecoilRoot>+ );+ const app = makeMcpToolCall('app');+ const { rerender } = render(frame([app]));+ expect(screen.queryByTestId('sources')).toBeNull();+ const lanes: TMessageContentParts[] = [+ { ...makeTextPart('lane A'), agentId: 'agent_a', groupId: 1 },+ { ...makeTextPart('lane B'), agentId: 'agent_b', groupId: 1 },+ ];+ rerender(frame([app, ...lanes]));+ const sources = screen.getByTestId('sources');+ rerender(frame([app, ...lanes, makeTextPart('answer')]));+ expect(screen.getAllByTestId('sources')).toEqual([sources]);+ });++ it('uses the latest handoff across multiple Apps and a subsequent handoff to the top-level author', () => {+ const handoff = (agentId: string): TMessageContentParts => ({+ type: ContentTypes.AGENT_UPDATE,+ agent_update: { agentId, index: 1, runId: 'run' },+ });+ const steer: TMessageContentParts = { type: ContentTypes.STEER, steer: 'continue' };+ renderContentParts({+ ...baseProps,+ authorHeader: <div data-testid="top-level-author" />,+ content: [+ handoff('agent_a'),+ makeMcpToolCall('app'),+ handoff('agent_b'),+ makeMcpToolCall('second-app'),+ steer,+ makeTextPart('agent answer'),+ handoff(''),+ steer,+ makeTextPart('top-level answer'),+ ],+ attachments: [appAttachment('app'), appAttachment('second-app')],+ });+ expect(screen.getAllByTestId('agent-update').map((marker) => marker.dataset.agentId)).toEqual([+ 'agent_a',+ 'agent_b',+ 'agent_b',+ '',+ ]);+ expect(screen.getAllByTestId('top-level-author')).toHaveLength(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'),@@ -582,7 +746,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {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'],+ ['agent-a/step-1/alpha', 'agent-a/step-2/beta', 'agent-b/step-1/gamma'],);});@@ -620,12 +784,18 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {/></RecoilRoot>);- const { rerender } = render(frame({}));+ const { rerender } = render(frame({ content: [undefined, ...content] }));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' }));+ rerender(+ frame({+ messageId: 'server-user_',+ conversationId: 'conversation-1',+ content: [undefined, ...content],+ }),+ );expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);/** `finalHandler` installs the durable response and drops the client-only owner anchor. */@@ -674,6 +844,14 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {);const { rerender } = render(frame([appCall]));const appView = screen.getByTestId('mcp-app-attachments');+ rerender(frame([makeTextPart('inserted preface'), appCall]));+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);+ rerender(frame([appCall, makeTextPart('after the app')]));+ expect(+ appView.compareDocumentPosition(screen.getByText('after the app')) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);/** A second adjacent call changes the sequential card presentation. */rerender(frame([appCall, otherCall]));@@ -692,6 +870,47 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);});+ it('retains an existing resource when another App is inserted into its tool result', () => {+ const call = makeMcpToolCall('call_app', true, 'step-1', 'agent-a');+ const resource = (resourceId: string) => ({+ resourceId,+ uri: 'ui://demo/view',+ mimeType: 'text/html;profile=mcp-app',+ toolName: 'show_app',+ serverName: 'demo',+ });+ const alpha = resource('alpha');+ const beta = resource('beta');+ const frame = (resources: (typeof alpha)[]) => (+ <RecoilRoot>+ <ContentParts+ {...baseProps}+ content={[call]}+ attachments={[+ {+ type: Tools.ui_resources,+ toolCallId: 'call_app',+ agentId: 'agent-a',+ stepId: 'step-1',+ [Tools.ui_resources]: resources,+ } as unknown as TAttachment,+ ]}+ />+ </RecoilRoot>+ );+ const { rerender } = render(frame([alpha]));+ const original = screen.getByTestId('mcp-app-attachments');+ rerender(frame([beta, alpha]));+ const views = screen.getAllByTestId('mcp-app-attachments');+ expect(views.map((view) => view.dataset.owners)).toEqual([+ 'agent-a/step-1/beta',+ 'agent-a/step-1/alpha',+ ]);+ expect(views[1]).toBe(original);+ rerender(frame([alpha]));+ expect(screen.getByTestId('mcp-app-attachments')).toBe(original);+ });+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 = [@@ -865,7 +1084,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {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'],+ ['agent-a/step-1/alpha', 'agent-a/step-2/beta'],);});diff --git a/client/src/components/MCPUIResource/MCPAppViews.tsx b/client/src/components/MCPUIResource/MCPAppViews.tsxindex fcc37396c5..ccd355dcce 100644--- a/client/src/components/MCPUIResource/MCPAppViews.tsx+++ b/client/src/components/MCPUIResource/MCPAppViews.tsx@@ -9,6 +9,7 @@ import React, {} from 'react';import { Button } from '@librechat/client';import type { TAttachment, UIResource } from 'librechat-data-provider';+import type { MCPAppResourceOccurrence } from '~/utils/mcpApps';import { useMCPAppsHost, useMCPAppViewAtCapacity } from '~/Providers/MCPAppsPolicyContext';import { selectToolCallUIResources, getInlineResourceHtml } from '~/utils/mcpApps';import { useIsMessagesViewReadOnly } from '~/Providers/MessagesViewContext';@@ -49,7 +50,9 @@ function ActiveMCPAppView({ordinal: number;}) {const localize = useLocalize();- const approval = useMCPAppApproval();+ const { policy } = useMCPAppsHost();+ // Reuse the deployment operation limit to bound requests awaiting consent in this View.+ const approval = useMCPAppApproval(policy.operationLimits?.maxActive);const frame = useMCPAppFrame(app, {defaultHeight: DEFAULT_APP_VIEW_HEIGHT,toolArgs: app.toolArgs,@@ -89,7 +92,10 @@ function ActiveMCPAppView({);} else if (frame.status !== 'tornDown') {body = (- <div className="relative my-2 overflow-hidden" style={{ height: frame.height }}>+ <div+ className="relative my-2 overflow-hidden"+ style={{ height: frame.height, width: frame.width, maxWidth: '100%' }}+ ><MCPAppFrame frame={frame} resource={app} spinner /></div>);@@ -229,7 +235,15 @@ const MCPAppView = React.memo(function MCPAppView({);});-export function MCPAppViews({ attachments }: { attachments?: TAttachment[] }) {+export function MCPAppViews({+ attachments,+ resources,+ ordinalStart = 1,+}: {+ attachments?: TAttachment[];+ resources?: MCPAppResourceOccurrence[];+ ordinalStart?: number;+}) {const suppressedAttachments = React.useContext(MCPAppSuppressionContext);const { policy, userId } = useMCPAppsHost();const visibleAttachments = useMemo(@@ -239,7 +253,12 @@ export function MCPAppViews({ attachments }: { attachments?: TAttachment[] }) {: attachments?.filter((attachment) => !suppressedAttachments.has(attachment)),[attachments, suppressedAttachments],);- const apps = useMemo(() => selectToolCallUIResources(visibleAttachments), [visibleAttachments]);+ const apps = useMemo(+ () =>+ resources?.filter(({ attachment }) => !suppressedAttachments?.has(attachment)) ??+ selectToolCallUIResources(visibleAttachments),+ [resources, suppressedAttachments, visibleAttachments],+ );if (!policy.enabled || !userId || apps.length === 0) {return null;@@ -252,7 +271,7 @@ export function MCPAppViews({ attachments }: { attachments?: TAttachment[] }) {key={JSON.stringify([userId, key])}app={resource}userId={userId}- ordinal={index + 1}+ ordinal={ordinalStart + index}/>))}</>diff --git a/client/src/hooks/MCP/__tests__/approval.spec.tsx b/client/src/hooks/MCP/__tests__/approval.spec.tsxindex 2546f9779a..c18c6f1542 100644--- a/client/src/hooks/MCP/__tests__/approval.spec.tsx+++ b/client/src/hooks/MCP/__tests__/approval.spec.tsx@@ -1,5 +1,5 @@import React from 'react';-import { act, fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, renderHook, screen } from '@testing-library/react';import { MCPAppApproval, useMCPAppApproval } from '../approval';jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));@@ -73,24 +73,67 @@ test('discloses conversation tool context before an App-authored chat turn is apview.unmount();});-test('rejects simultaneous App requests and lets the user deny the first', async () => {+test('queues simultaneous App requests and requires separate host approval for each', async () => {let approval!: ReturnType<typeof useMCPAppApproval>;const view = render(<Harness onReady={(value) => (approval = value)} />);let first!: Promise<boolean>;+ let second!: Promise<boolean>;act(() => {first = approval.request(action, new AbortController().signal);- });- await expect(- approval.request(+ second = approval.request({ kind: 'message', serverName: 'fixture', text: 'next' },new AbortController().signal,- ),- ).resolves.toBe(false);- await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'com_ui_cancel' }));+ );+ });+ expect(screen.getByRole('alertdialog')).toHaveTextContent('fixture / remove');+ await act(async () =>+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_mcp_app_run_tool' })),+ );+ await expect(first).resolves.toBe(true);+ expect(screen.getByRole('alertdialog')).toHaveTextContent('next');+ await act(async () =>+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_mcp_app_send_message' })),+ );+ await expect(second).resolves.toBe(true);+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();+ view.unmount();+});++test('cancel settles the entire queue and a queued abort leaves the displayed request intact', async () => {+ let approval!: ReturnType<typeof useMCPAppApproval>;+ const view = render(<Harness onReady={(value) => (approval = value)} />);+ const queuedAbort = new AbortController();+ let first!: Promise<boolean>;+ let second!: Promise<boolean>;+ let third!: Promise<boolean>;+ act(() => {+ first = approval.request(action, new AbortController().signal);+ second = approval.request(action, queuedAbort.signal);+ third = approval.request(action, new AbortController().signal);+ queuedAbort.abort();});+ await expect(second).resolves.toBe(false);+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();+ act(() => approval.cancel());await expect(first).resolves.toBe(false);+ await expect(third).resolves.toBe(false);+ view.unmount();+});++test('bounds queued approvals and settles them all on unmount', async () => {+ const view = renderHook(() => useMCPAppApproval(2));+ let first!: Promise<boolean>;+ let second!: Promise<boolean>;+ act(() => {+ first = view.result.current.request(action, new AbortController().signal);+ second = view.result.current.request(action, new AbortController().signal);+ });+ await expect(view.result.current.request(action, new AbortController().signal)).resolves.toBe(+ false,+ );view.unmount();+ await expect(first).resolves.toBe(false);+ await expect(second).resolves.toBe(false);});test('denying once suppresses repeated prompts until the View is reopened', async () => {@@ -183,3 +226,16 @@ test('an already aborted request does not suspend a fresh View', async () => {view.unmount();await expect(pending).resolves.toBe(false);});++test('an idle bridge cleanup does not suspend later approvals', async () => {+ const view = renderHook(() => useMCPAppApproval());+ act(() => view.result.current.cancel());+ let pending!: Promise<boolean>;+ act(() => {+ pending = view.result.current.request(action, new AbortController().signal);+ });+ expect(view.result.current.pending).toEqual(action);+ act(() => view.result.current.approve());+ await expect(pending).resolves.toBe(true);+ view.unmount();+});diff --git a/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx b/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsxindex 93785848e0..f9309ef759 100644--- a/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx+++ b/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx@@ -92,7 +92,7 @@ class FakeAppBridge {this.toolResults.push(params);}- async sendHostContextChange(params: unknown) {+ setHostContext(params: unknown) {this.hostContextChanges.push(params);}@@ -249,6 +249,11 @@ const flush = async () => {});};+const loadSandbox = async (iframe: HTMLIFrameElement) => {+ fireEvent.load(iframe);+ await flush();+};+const latest = () => FakeAppBridge.instances[FakeAppBridge.instances.length - 1];describe('useAppBridge', () => {@@ -272,6 +277,57 @@ describe('useAppBridge', () => {});describe('ordering', () => {+ it('survives the initial StrictMode effect replay without requiring Retry', async () => {+ let resolveValidation: () => void = () => {};+ let validationSignal: AbortSignal | undefined;+ mockValidateBinding.mockImplementation(+ (_server, _binding, signal) =>+ new Promise<void>((resolve, reject) => {+ resolveValidation = resolve;+ validationSignal = signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ );+ const resource = makeResource({ text: '<p>persisted</p>' });++ render(+ <React.StrictMode>+ <RecoilRoot>+ <QueryClientProvider client={client}>+ <MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">+ <BridgeFrameHarness resource={resource} userId="user-1" />+ </MCPAppsPolicyProvider>+ </QueryClientProvider>+ </RecoilRoot>+ </React.StrictMode>,+ );+ await flush();++ expect(FakeAppBridge.instances).toHaveLength(2);+ expect(FakeAppBridge.instances[0].closed).toBe(true);+ expect(mockValidateBinding).toHaveBeenCalledTimes(1);+ expect(validationSignal?.aborted).toBe(false);++ await act(async () => {+ resolveValidation();+ await Promise.resolve();+ });+ await flush();++ const iframe = screen.getByTitle('MCP App: render') as HTMLIFrameElement;+ const liveBridge = latest();+ expect(iframe.src).toContain('/api/mcp/sandbox');+ expect(liveBridge.connected).not.toBeNull();+ await act(async () => liveBridge.emit('sandboxready'));+ await act(async () => liveBridge.oninitialized?.());+ await flush();++ expect(liveBridge.resourceReady).toEqual([+ expect.objectContaining({ html: '<p>persisted</p>' }),+ ]);+ expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();+ });+it('retries one failed View through a fresh bridge without replacing its iframe or sibling', async () => {const target = makeResource({resourceId: 'target',@@ -334,6 +390,7 @@ describe('useAppBridge', () => {const siblingBridge = FakeAppBridge.instances[1];const targetFrame = screen.getByTitle('MCP App: target');const siblingFrame = screen.getByTitle('MCP App: sibling');+ await loadSandbox(siblingFrame as HTMLIFrameElement);expect(targetFrame).toHaveAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms');targetFrame.dataset.retryAnchor = 'target';siblingFrame.dataset.retryAnchor = 'sibling';@@ -341,6 +398,7 @@ describe('useAppBridge', () => {fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));await flush();+ await loadSandbox(targetFrame as HTMLIFrameElement);const replacement = FakeAppBridge.instances[2];expect(lifecycle).toEqual(['old-close', 'new-connect']);@@ -401,6 +459,7 @@ describe('useAppBridge', () => {{ wrapper, initialProps: { userId: 'user-alpha' } },);await flush();+ await loadSandbox(iframe);const first = latest();await act(async () => first.oninitialized?.());const lifecycle: string[] = [];@@ -423,6 +482,7 @@ describe('useAppBridge', () => {view.rerender({ userId: 'user-beta' });await flush();+ await loadSandbox(iframe);expect(first.teardowns).toBe(1);expect(first.closed).toBe(true);@@ -439,7 +499,7 @@ describe('useAppBridge', () => {).toEqual(['user-alpha', 'user-beta']);});- it('connects the transport before the sandbox document is requested', async () => {+ it('connects the live-window transport before navigating the sandbox document', async () => {let resolveHtml: (value: { html: string }) => void = () => {};mockFetchHtml.mockReturnValue(new Promise((resolve) => {@@ -449,7 +509,7 @@ describe('useAppBridge', () => {const { iframe } = mountBridge(makeResource(), client);await flush();- expect(latest().connected).not.toBeNull();+ expect(latest().connected).toBeNull();expect(iframe.getAttribute('src')).toBeNull();await act(async () => {@@ -458,6 +518,55 @@ describe('useAppBridge', () => {});await flush();expect(iframe.src).toContain('/api/mcp/sandbox');+ expect(latest().connected).not.toBeNull();++ await loadSandbox(iframe);+ expect(latest().connected).not.toBeNull();+ });++ it('accepts bridge messages only from the live iframe and exact sandbox origin', async () => {+ const { iframe } = mountBridge(makeResource(), client);+ await flush();+ const transport = latest().connected as {+ start: () => Promise<void>;+ close: () => Promise<void>;+ onmessage?: (message: unknown) => void;+ onerror?: (error: Error) => void;+ };+ const onmessage = jest.fn();+ const onerror = jest.fn();+ transport.onmessage = onmessage;+ transport.onerror = onerror;+ await transport.start();++ const notification = { jsonrpc: '2.0', method: 'notifications/test' };+ window.dispatchEvent(+ new MessageEvent('message', {+ data: notification,+ origin: 'https://attacker.example',+ source: iframe.contentWindow,+ }),+ );+ window.dispatchEvent(+ new MessageEvent('message', {+ data: notification,+ origin: new URL(iframe.src).origin,+ source: window,+ }),+ );+ expect(onmessage).not.toHaveBeenCalled();++ window.dispatchEvent(+ new MessageEvent('message', {+ data: notification,+ origin: new URL(iframe.src).origin,+ source: iframe.contentWindow,+ }),+ );+ expect(onmessage).toHaveBeenCalledWith(notification);+ expect(onerror).not.toHaveBeenCalled();++ await transport.close();});it('validates persisted inline html before assigning or sending it', async () => {@@ -470,7 +579,7 @@ describe('useAppBridge', () => {const { iframe } = mountBridge(makeResource({ text: '<p>persisted</p>' }), client);await flush();- expect(latest().connected).not.toBeNull();+ expect(latest().connected).toBeNull();expect(iframe.getAttribute('src')).toBeNull();expect(latest().resourceReady).toHaveLength(0);expect(mockValidateBinding).toHaveBeenCalledWith(@@ -485,6 +594,10 @@ describe('useAppBridge', () => {});await flush();expect(iframe.src).toContain('/api/mcp/sandbox');+ expect(latest().connected).not.toBeNull();++ await loadSandbox(iframe);+ expect(latest().connected).not.toBeNull();await act(async () => latest().emit('sandboxready'));await flush();@@ -1329,6 +1442,28 @@ describe('useAppBridge', () => {expect(bridge.hostContextChanges).toHaveLength(0);});+ it('publishes width changes without feeding content height changes back into the App', async () => {+ const measure = jest.spyOn(HTMLIFrameElement.prototype, 'getBoundingClientRect');+ measure.mockReturnValue(new DOMRect(0, 0, 600, 320));+ const mounted = mountBridge(makeResource(), client);+ await flush();+ const observers = window.ResizeObserver as jest.MockedClass<typeof ResizeObserver>;+ const callback = observers.mock.calls.at(-1)![0];+ const observer = observers.mock.results.at(-1)!.value as ResizeObserver;+ measure.mockReturnValue(new DOMRect(0, 0, 600, 1000));+ act(() => callback([], observer));+ expect(latest().hostContextChanges).toHaveLength(0);+ measure.mockReturnValue(new DOMRect(0, 0, 400, 1000));+ act(() => callback([], observer));+ expect(latest().hostContextChanges).toEqual([+ expect.objectContaining({ containerDimensions: { width: 400, maxHeight: 4000 } }),+ ]);+ mounted.view.unmount();+ act(() => callback([], observer));+ expect(latest().hostContextChanges).toHaveLength(1);+ measure.mockRestore();+ });+it('pushes theme changes to a live bridge', async () => {mountBridge(makeResource(), client);await flush();diff --git a/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.ts b/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.tsindex d6a3538091..33894b713e 100644--- a/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.ts+++ b/client/src/hooks/MCP/__tests__/useMCPAppFrame.spec.ts@@ -152,6 +152,18 @@ describe('useMCPAppFrame', () => {});});+ it('accepts finite positive width-only reports and ignores invalid widths', () => {+ const { result } = renderHook(() => useMCPAppFrame(appResource(), { defaultHeight: 100 }));+ act(() => result.current.onSizeChanged({ width: 400 }));+ expect(result.current.width).toBe(400);+ expect(result.current.height).toBe(100);+ expect(result.current.status).toBe('ready');+ for (const width of [0, -1, Infinity, NaN]) {+ act(() => result.current.onSizeChanged({ width }));+ expect(result.current.width).toBe(400);+ }+ });+describe('reveal budget', () => {beforeEach(() => jest.useFakeTimers());afterEach(() => jest.useRealTimers());diff --git a/client/src/hooks/MCP/approval.tsx b/client/src/hooks/MCP/approval.tsxindex 1507d32100..a98bd4989f 100644--- a/client/src/hooks/MCP/approval.tsx+++ b/client/src/hooks/MCP/approval.tsx@@ -1,7 +1,8 @@import { useCallback, useEffect, useRef, useState } from 'react';+import { DEFAULT_MCP_APP_OPERATION_LIMITS } from 'librechat-data-provider';import {AlertDialog,- AlertDialogAction,+ Button,AlertDialogCancel,AlertDialogContent,AlertDialogDescription,@@ -22,53 +23,56 @@ type Pending = {};/** An App can request an action but only a host-controlled button can grant it. */-export function useMCPAppApproval() {+export function useMCPAppApproval(maxPending = DEFAULT_MCP_APP_OPERATION_LIMITS.maxActive) {const [pending, setPending] = useState<Pending | null>(null);- const pendingRef = useRef<Pending | null>(null);+ const queueRef = useRef<Pending[]>([]);const suspendedRef = useRef(false);- const request = useCallback((action: MCPAppAction, signal: AbortSignal): Promise<boolean> => {- if (signal.aborted || pendingRef.current || suspendedRef.current) return Promise.resolve(false);- return new Promise<boolean>((resolve) => {- const settle = (allowed: boolean, notify = true) => {- if (pendingRef.current !== entry) return;- pendingRef.current = null;- signal.removeEventListener('abort', abort);- if (notify) setPending(null);- resolve(allowed && !signal.aborted);- };- // An App can abort its own SDK request while the host dialog is visible. Treat that- // just like a denial, rather than letting it reopen the dialog in a tight loop.- const abort = () => {- if (pendingRef.current === entry) suspendedRef.current = true;- settle(false);- };- const entry: Pending = { action, settle };- pendingRef.current = entry;- signal.addEventListener('abort', abort, { once: true });- if (signal.aborted) abort();- else setPending(entry);- });+ const pause = useCallback((notify = true) => {+ suspendedRef.current = true;+ for (const entry of [...queueRef.current]) entry.settle(false, false);+ if (notify) setPending(null);}, []);- // Escape, backdrop and Cancel all pause further App-requested actions for this View.- // Only closing and reopening its View restores the ability to ask.- const cancel = useCallback(() => {- if (pendingRef.current) {- suspendedRef.current = true;- pendingRef.current.settle(false);- }- }, []);- // Resolve an outstanding SDK request when the owning View disappears.- useEffect(- () => () => {- pendingRef.current?.settle(false, false);+ const request = useCallback(+ (action: MCPAppAction, signal: AbortSignal): Promise<boolean> => {+ if (signal.aborted || suspendedRef.current || queueRef.current.length >= maxPending) {+ return Promise.resolve(false);+ }+ return new Promise<boolean>((resolve) => {+ const settle = (allowed: boolean, notify = true) => {+ const index = queueRef.current.indexOf(entry);+ if (index < 0) return;+ queueRef.current.splice(index, 1);+ signal.removeEventListener('abort', abort);+ if (notify) setPending(queueRef.current[0] ?? null);+ resolve(allowed && !signal.aborted);+ };+ const abort = () => {+ // A cancelled queued request is removed without disrupting the visible approval.+ // Cancelling the displayed request pauses the View to prevent prompt storms.+ if (queueRef.current[0] === entry) pause();+ else settle(false);+ };+ const entry: Pending = { action, settle };+ queueRef.current.push(entry);+ signal.addEventListener('abort', abort, { once: true });+ if (signal.aborted) abort();+ else setPending(queueRef.current[0]);+ });},- [],+ [maxPending, pause],);+ const cancel = useCallback(() => {+ if (queueRef.current.length > 0) pause();+ }, [pause]);+ useEffect(() => {+ suspendedRef.current = false;+ return () => pause(false);+ }, [pause]);return {pending: pending?.action ?? null,request,cancel,- approve: () => pendingRef.current?.settle(true),+ approve: () => pending?.settle(true),};}@@ -124,11 +128,11 @@ export function MCPAppApproval({{close && (<AlertDialogCancel onClick={close}>{localize('com_ui_mcp_app_stop')}</AlertDialogCancel>)}- <AlertDialogAction onClick={approve}>+ <Button onClick={approve}>{localize(action?.kind === 'tool' ? 'com_ui_mcp_app_run_tool' : 'com_ui_mcp_app_send_message',)}- </AlertDialogAction>+ </Button></AlertDialogFooter></AlertDialogContent></AlertDialog>diff --git a/client/src/hooks/MCP/useAppBridge.ts b/client/src/hooks/MCP/useAppBridge.tsindex 0dc82a7225..4ec76a8ce9 100644--- a/client/src/hooks/MCP/useAppBridge.ts+++ b/client/src/hooks/MCP/useAppBridge.ts@@ -1,12 +1,14 @@import { useEffect, useId, useRef } from 'react';import { useQueryClient } from '@tanstack/react-query';+import { JSONRPCMessageSchema } from '@modelcontextprotocol/sdk/types.js';import { QueryKeys, DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS } from 'librechat-data-provider';-import {- AppBridge,- PostMessageTransport,- buildAllowAttribute,-} from '@modelcontextprotocol/ext-apps/app-bridge';+import { AppBridge, buildAllowAttribute } from '@modelcontextprotocol/ext-apps/app-bridge';+import type {+ Transport,+ TransportSendOptions,+} from '@modelcontextprotocol/sdk/shared/transport.js';import type { McpUiStyles, McpUiStyleVariableKey } from '@modelcontextprotocol/ext-apps/app-bridge';+import type { JSONRPCMessage, MessageExtraInfo } from '@modelcontextprotocol/sdk/types.js';import type { UIResource } from 'librechat-data-provider';import type { AppToolResult } from '~/utils/mcpApps';import type { MCPAppAction } from './approval';@@ -21,6 +23,7 @@ import {getInlineResourceHtml,isAllowedAppLink,withSandboxCsp,+ MAX_APP_VIEW_HEIGHT,} from '~/utils/mcpApps';import {useOptionalMessagesOperations,@@ -39,6 +42,61 @@ type ResolvedResource = {permissions: UIResource['permissions'];};+/** A source- and origin-validated transport that resolves the live iframe WindowProxy per event. */+class IframePostMessageTransport implements Transport {+ onclose?: () => void;+ onerror?: (error: Error) => void;+ onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void;+ sessionId?: string;+ setProtocolVersion?: (version: string) => void;++ constructor(private readonly getIframe: () => HTMLIFrameElement | null) {}++ private getTarget(): { window: Window; origin: string } | null {+ const iframe = this.getIframe();+ const target = iframe?.contentWindow;+ const src = iframe?.getAttribute('src');+ if (!target || !src) {+ return null;+ }+ try {+ return { window: target, origin: new URL(src, window.location.href).origin };+ } catch {+ return null;+ }+ }++ private readonly messageListener = (event: MessageEvent) => {+ const target = this.getTarget();+ if (!target || event.source !== target.window || event.origin !== target.origin) {+ return;+ }+ const parsed = JSONRPCMessageSchema.safeParse(event.data);+ if (parsed.success) {+ this.onmessage?.(parsed.data);+ } else if (event.data?.jsonrpc === '2.0') {+ this.onerror?.(new Error(`Invalid JSON-RPC message received: ${parsed.error.message}`));+ }+ };++ async start(): Promise<void> {+ window.addEventListener('message', this.messageListener);+ }++ async send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void> {+ const target = this.getTarget();+ if (!target) {+ throw new Error('MCP App iframe is unavailable');+ }+ target.window.postMessage(message, target.origin);+ }++ async close(): Promise<void> {+ window.removeEventListener('message', this.messageListener);+ this.onclose?.();+ }+}+export type UseAppBridgeParams = {iframeRef: React.RefObject<HTMLIFrameElement | null>;resource: UIResource;@@ -115,6 +173,8 @@ export function useAppBridge({const { cspLimits, maxActionPreviewChars } = useMCPAppsPolicy();const queryClient = useQueryClient();const viewId = useId();+ const effectGenerationRef = useRef(0);+ const activeEffectRef = useRef<{ generation: number; queryKey: string } | null>(null);// 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.@@ -149,12 +209,13 @@ export function useAppBridge({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');+ // Do not remove a missing src from a freshly mounted iframe: Chromium may emit a synthetic+ // about:blank load for that mutation. On fast inline resources, that load can consume the+ // one-shot sandbox listener before the cross-origin sandbox document finishes navigating.+ if (iframe.hasAttribute('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@@ -176,6 +237,12 @@ export function useAppBridge({viewId,attempt,] as const;+ const effectGeneration = ++effectGenerationRef.current;+ const resourceQueryKeyIdentity = JSON.stringify(resourceQueryKey);+ activeEffectRef.current = {+ generation: effectGeneration,+ queryKey: resourceQueryKeyIdentity,+ };const assignSandboxSrc = (csp: UIResource['csp']) => {const { url, applied } = withSandboxCsp(@@ -204,11 +271,18 @@ export function useAppBridge({}};- // 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 bounds = iframe.getBoundingClientRect();+ let hostContext = {+ theme: readHostTheme(),+ platform: 'web' as const,+ locale,+ timeZone,+ displayMode: 'inline' as const,+ availableDisplayModes: ['inline' as const],+ containerDimensions: { width: Math.round(bounds.width), maxHeight: MAX_APP_VIEW_HEIGHT },+ styles: { variables: buildHostStyleVariables() },+ };const bridge = new AppBridge(null,{ name: 'LibreChat', version: '1.0.0' },@@ -217,21 +291,30 @@ export function useAppBridge({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: {} } } : {}),+ ...(!readOnly+ ? {+ serverTools: {},+ serverResources: {},+ message: { text: {} },+ }+ : {}),},{- hostContext: {- theme: readHostTheme(),- platform: 'web',- locale,- timeZone,- displayMode: 'inline',- availableDisplayModes: ['inline'],- styles: { variables: buildHostStyleVariables() },- },+ hostContext,},);+ const resizeObserver = new ResizeObserver(() => {+ if (cancelled) return;+ const width = Math.round(iframe.getBoundingClientRect().width);+ if (width === hostContext.containerDimensions.width) return;+ hostContext = {+ ...hostContext,+ containerDimensions: { width, maxHeight: MAX_APP_VIEW_HEIGHT },+ };+ bridge.setHostContext(hostContext);+ });+ resizeObserver.observe(iframe);let lastTheme = readHostTheme();const themeObserver = new MutationObserver(() => {if (cancelled) {@@ -242,12 +325,12 @@ export function useAppBridge({return;}lastTheme = nextTheme;- Promise.resolve(- bridge.sendHostContextChange({- theme: nextTheme,- styles: { variables: buildHostStyleVariables() },- }),- ).catch((err: unknown) => logger.error('[MCP App] sendHostContextChange failed', err));+ hostContext = {+ ...hostContext,+ theme: nextTheme,+ styles: { variables: buildHostStyleVariables() },+ };+ bridge.setHostContext(hostContext);});let disposed = false;@@ -258,8 +341,21 @@ export function useAppBridge({viewAbort.abort();cancelActionRef.current?.();themeObserver.disconnect();+ resizeObserver.disconnect();bridge.close();- void queryClient.cancelQueries({ queryKey: resourceQueryKey, exact: true });+ // React Strict Mode immediately replays effects in development. Let an equivalent successor+ // share the in-flight resource read instead of cancelling the query it has just joined. A real+ // unmount, retry, or resource change has no same-key successor and still cancels promptly.+ queueMicrotask(() => {+ const successor = activeEffectRef.current;+ const isEquivalentReplay =+ successor != null &&+ successor.generation !== effectGeneration &&+ successor.queryKey === resourceQueryKeyIdentity;+ if (!isEquivalentReplay) {+ void queryClient.cancelQueries({ queryKey: resourceQueryKey, exact: true });+ }+ });};const interactive = !readOnly;@@ -529,20 +625,6 @@ export function useAppBridge({});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) => {@@ -560,6 +642,22 @@ export function useAppBridge({// 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) {+ // Start listening before navigation so a fresh iframe's synthetic about:blank load cannot+ // consume or race a one-shot load handler. The transport resolves and validates the live+ // iframe WindowProxy and exact sandbox origin for every message, so cross-origin navigation+ // cannot leave it bound to a stale window.+ await bridge+ .connect(new IframePostMessageTransport(() => iframeRef.current))+ .catch((err) => {+ logger.error('[MCP App] bridge.connect failed', err);+ if (!cancelled) {+ onFailedRef.current?.();+ }+ dispose();+ });+ if (cancelled) {+ return;+ }assignSandboxSrc(next?.csp);}};diff --git a/client/src/hooks/MCP/useMCPAppFrame.ts b/client/src/hooks/MCP/useMCPAppFrame.tsindex c6a16892a8..2c4d9aaf35 100644--- a/client/src/hooks/MCP/useMCPAppFrame.ts+++ b/client/src/hooks/MCP/useMCPAppFrame.ts@@ -37,6 +37,7 @@ export type MCPAppFrameState = {status: MCPAppFrameStatus;kind: MCPAppFrameKind;height: number;+ width?: number;attempt: number;canRetry: boolean;sandboxUrl?: string;@@ -89,6 +90,7 @@ export function useMCPAppFrame(const { enabled: mcpAppsEnabled, sandboxUrl: configuredSandboxUrl } = useMCPAppsPolicy();const [status, setStatus] = useState<MCPAppFrameStatus>('loading');const [height, setHeight] = useState<number | undefined>(undefined);+ const [width, setWidth] = useState<number | undefined>(undefined);const [attempt, setAttempt] = useState(0);const sandboxUrl = useMemo(() => getMCPSandboxUrl(configuredSandboxUrl), [configuredSandboxUrl]);const inlineHtml = useMemo(@@ -102,6 +104,7 @@ export function useMCPAppFrame(useEffect(() => {setStatus('loading');setHeight(undefined);+ setWidth(undefined);}, [resourceKey, inlineHtml, resource?.serverBinding]);const kind: MCPAppFrameKind = useMemo(() => {@@ -131,12 +134,16 @@ export function useMCPAppFrame(const onSizeChanged = useCallback((params: { height?: number; width?: number }) => {const clamped = clampAppViewHeight(params.height, { max: maxHeight });- if (clamped == null) {- return;+ const reportedWidth = params.width;+ const validWidth =+ typeof reportedWidth === 'number' && Number.isFinite(reportedWidth) && reportedWidth > 0;+ if (validWidth) setWidth(Math.ceil(reportedWidth));+ if (clamped == null && !validWidth) return;+ if (clamped != null) {+ setHeight(clamped);+ onHeightChange?.(clamped);}- setHeight(clamped);setStatus((prev) => (prev === 'tornDown' ? prev : 'ready'));- onHeightChange?.(clamped);},[maxHeight, onHeightChange],);@@ -162,6 +169,7 @@ export function useMCPAppFrame(canRetryRef.current = false;setStatus('loading');setHeight(undefined);+ setWidth(undefined);setAttempt((current) => current + 1);}, []);@@ -187,6 +195,7 @@ export function useMCPAppFrame(status,kind,height: height ?? defaultHeight,+ width,attempt,canRetry,sandboxUrl: mcpAppsEnabled ? sandboxUrl : undefined,diff --git a/client/src/utils/__tests__/mcpSandbox.spec.ts b/client/src/utils/__tests__/mcpSandbox.spec.tsindex eaaf3b0c29..06f249984e 100644--- a/client/src/utils/__tests__/mcpSandbox.spec.ts+++ b/client/src/utils/__tests__/mcpSandbox.spec.ts@@ -5,8 +5,8 @@ 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.+ * run here: jsdom has no policy containers and no real frame navigation, so the heartbeat's+ * navigation invalidation window remains browser-only.*/const SANDBOX_PATH = path.join(__dirname, '../../../public/mcp-sandbox.html');const SANDBOX_HTML = fs.readFileSync(SANDBOX_PATH, 'utf8');@@ -52,29 +52,10 @@ 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();};}@@ -178,6 +159,10 @@ function loadSandbox(origin: PARENT_ORIGIN,source: parentWindow,});+ const document = frame()?.srcdoc;+ if (document && blobs[blobs.length - 1] !== document) {+ blobs.push(document);+ }patchInnerPost();},loadFrame: (target) => {@@ -495,7 +480,7 @@ describe('mcp-sandbox proxy', () => {params: { nonce: sandbox.bootstrapNonce() },});expect(sandbox.frame()).toBeNull();- expect(sandbox.revoked).toEqual(['blob:mock/1']);+ expect(sandbox.revoked).toHaveLength(0);sandbox.fromInner(APP_NOTIFICATION, inner);sandbox.fromParent(HOST_REQUEST);@@ -505,21 +490,44 @@ describe('mcp-sandbox proxy', () => {).toHaveLength(0);});- it('invalidates on a second load of the live frame', () => {+ it('invalidates every load and requires a fresh bootstrap challenge response', () => {const sandbox = loadSandbox();sandbox.deliverResource();sandbox.attest();sandbox.loadFrame();+ const challenge = sandbox.innerPosts().at(-1)?.params?.challenge;+ const forwarded = () => sandbox.innerPosts().filter((msg) => msg.id === HOST_REQUEST.id);sandbox.fromParent(HOST_REQUEST);- expect(sandbox.innerPosts()).toHaveLength(1);-+ sandbox.attest(); // A queued heartbeat from the old realm cannot restore authority.+ expect(forwarded()).toHaveLength(0);+ sandbox.fromInner({+ jsonrpc: '2.0',+ method: ATTEST,+ params: { nonce: sandbox.bootstrapNonce(), challenge },+ });+ expect(forwarded()).toHaveLength(1);sandbox.loadFrame();- expect(sandbox.frame()).toBeNull();sandbox.fromParent(HOST_REQUEST);- expect(sandbox.innerPosts()).toHaveLength(1);+ sandbox.fromInner({+ jsonrpc: '2.0',+ method: ATTEST,+ params: { nonce: sandbox.bootstrapNonce(), challenge },+ });+ expect(forwarded()).toHaveLength(1);+ const nextChallenge = sandbox+ .innerPosts()+ .filter((msg) => msg.method === 'ui/notifications/sandbox-frame-challenge')+ .at(-1)?.params?.challenge;+ sandbox.fromInner({+ jsonrpc: '2.0',+ method: ATTEST,+ params: { nonce: sandbox.bootstrapNonce(), challenge: nextChallenge },+ });+ expect(forwarded()).toHaveLength(2);+ expect(sandbox.frame()).not.toBeNull();});- it('does not let a stale generation revoke a live blob url', () => {+ it('does not let stale load events restore a detached frame', () => {const sandbox = loadSandbox();sandbox.deliverResource();sandbox.attest();@@ -529,11 +537,11 @@ describe('mcp-sandbox proxy', () => {method: DETACH,params: { nonce: sandbox.bootstrapNonce() },});- expect(sandbox.revoked).toHaveLength(1);+ expect(sandbox.frame()).toBeNull();sandbox.loadFrame(stale);sandbox.loadFrame(stale);- expect(sandbox.revoked).toHaveLength(1);+ expect(sandbox.frame()).toBeNull();});});diff --git a/e2e/setup/fake-mcp-app-server.mjs b/e2e/setup/fake-mcp-app-server.mjsindex 6c644ef102..ff17bbd10d 100644--- a/e2e/setup/fake-mcp-app-server.mjs+++ b/e2e/setup/fake-mcp-app-server.mjs@@ -72,10 +72,13 @@ const appHtml = `<!doctype html><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="call-two-tools" type="button">Call two follow-up tools</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>+ <button data-testid="detach-view" type="button">Send pagehide signal</button>+ <button data-testid="navigate-view" type="button">Navigate away from App</button><output data-testid="operation"></output></main><script type="module">@@ -122,6 +125,7 @@ const appHtml = `<!doctype html>await app.sendSizeChanged({ height: 260, width: 640 });byTestId('call-tool').disabled = !capabilities.serverTools;+ byTestId('call-two-tools').disabled = !capabilities.serverTools;byTestId('read-resource').disabled = !capabilities.serverResources;byTestId('list-resources').disabled = !capabilities.serverResources;byTestId('send-message').disabled = !capabilities.message;@@ -134,6 +138,12 @@ const appHtml = `<!doctype html>});return result.structuredContent;}));+ byTestId('call-two-tools').addEventListener('click', () => run(async () => {+ const results = await Promise.all(['queued-first', 'queued-second'].map((label) =>+ app.callServerTool({ name: 'follow_up', arguments: { label } }),+ ));+ return results.map((result) => result.structuredContent);+ }));byTestId('read-resource').addEventListener('click', () => run(async () => {const result = await app.readServerResource({ uri: '${DETAIL_URI}' });return result.contents[0]?.text;@@ -149,6 +159,10 @@ const appHtml = `<!doctype html>});return 'message-sent';}));+ byTestId('detach-view').addEventListener('click', () =>+ dispatchEvent(new PageTransitionEvent('pagehide')),+ );+ byTestId('navigate-view').addEventListener('click', () => location.replace('about:blank'));byTestId('open-link').addEventListener('click', () => run(async () => {return app.openLink({ url: '${LINK_ORIGIN}/opened' });}));diff --git a/e2e/specs/mock/mcp-apps.spec.ts b/e2e/specs/mock/mcp-apps.spec.tsindex c7e6768073..f735cc2864 100644--- a/e2e/specs/mock/mcp-apps.spec.ts+++ b/e2e/specs/mock/mcp-apps.spec.ts@@ -304,6 +304,7 @@ 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(outerFrame).toHaveCSS('width', '640px');await expect(container).toHaveCSS('height', '260px');}@@ -452,7 +453,9 @@ test.describe('MCP Apps full integration', () => {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');+ expect(new URL(sandboxUrl!).origin).toBe(+ new URL(process.env.E2E_MCP_SANDBOX_URL || 'http://localhost:3080/api/mcp/sandbox').origin,+ );await expect(outerFrame).toHaveAttribute('sandbox','allow-scripts allow-same-origin allow-forms',@@ -509,6 +512,24 @@ test.describe('MCP Apps full integration', () => {await toolDialog.getByRole('button', { name: 'Run tool' }).click();expect((await approvedTool).ok()).toBeTruthy();await expect(app.getByTestId('operation')).toContainText('"followUp":"from-view"');+ // Both requests arrive together, but consent authorizes only the displayed request.+ await app.getByTestId('call-two-tools').click();+ await expect(toolDialog).toContainText('queued-first');+ const queuedCalls = async () =>+ (await readEvents(page)).filter(+ (event) =>+ event.method === 'tools/call:follow_up' &&+ String(event.params.label).startsWith('queued-'),+ );+ expect(await queuedCalls()).toHaveLength(0);+ await toolDialog.getByRole('button', { name: 'Run tool' }).click();+ await expect(toolDialog).toContainText('queued-second');+ await expect+ .poll(queuedCalls)+ .toEqual([expect.objectContaining({ params: { label: 'queued-first' } })]);+ await toolDialog.getByRole('button', { name: 'Run tool' }).click();+ await expect(app.getByTestId('operation')).toContainText('"followUp":"queued-first"');+ await expect(app.getByTestId('operation')).toContainText('"followUp":"queued-second"');await page.screenshot({ path: testInfo.outputPath('settled-app.png'), fullPage: true });await clickAndExpectRoute(page, app, 'read-resource', '/api/mcp/resources/read');@@ -764,6 +785,68 @@ test.describe('MCP Apps full integration', () => {(await readEvents(page)).filter((event) => event.method.startsWith('resources/read:show_')),).toEqual([]);+ // A delivered pagehide signal tears down the inner frame.+ await app.getByTestId('detach-view').click();+ const navigatedFrame = page+ .locator('iframe[title="MCP App: show_app"]')+ .first()+ .contentFrame()+ .locator('iframe');+ await expect(navigatedFrame).toHaveCount(0);++ // Drop detach delivery at the outer boundary to test the independent load challenge.+ await page.addInitScript(() => {+ if (location.pathname !== '/api/mcp/sandbox') return;+ let dropped = 0;+ Object.defineProperty(window, '__mcpAppDroppedDetaches', { get: () => dropped });+ addEventListener(+ 'message',+ (event: MessageEvent) => {+ if (event.data?.method === 'ui/notifications/sandbox-frame-detach') {+ dropped += 1;+ event.stopImmediatePropagation();+ }+ },+ true,+ );+ });+ await page.reload({ waitUntil: 'domcontentloaded' });+ await expectConnectedApp(page, label);+ await app.getByTestId('detach-view').click();+ await expect+ .poll(() =>+ outerFrame+ .contentFrame()+ .locator('body')+ .evaluate(() => Reflect.get(window, '__mcpAppDroppedDetaches')),+ )+ .toBe(1);+ await expect(navigatedFrame).toHaveCount(1);+ await app.getByTestId('navigate-view').click();+ await expect(navigatedFrame).toHaveCount(1);+ await expect.poll(() => app.locator('body').evaluate(() => location.href)).toBe('about:blank');+ const navigatedRead = page+ .waitForRequest((request) => new URL(request.url()).pathname === '/api/mcp/resources/read', {+ timeout: 1500,+ })+ .then(+ () => true,+ () => false,+ );+ await app.locator('body').evaluate(() => {+ window.parent.postMessage(+ {+ jsonrpc: '2.0',+ id: 'navigated-document',+ method: 'resources/read',+ params: { uri: 'ui://e2e/details/current' },+ },+ '*',+ );+ });+ expect(await navigatedRead).toBe(false);+ await expect(page.getByRole('alertdialog')).toHaveCount(0);+const share = await createShare(page, conversationId!);expect(share.shareId).toBeTruthy();const appRequestCountBeforeShare = appRequests.length;diff --git a/packages/api/src/mcp/__tests__/apps.test.ts b/packages/api/src/mcp/__tests__/apps.test.tsindex d24a86d21c..77200fe106 100644--- a/packages/api/src/mcp/__tests__/apps.test.ts+++ b/packages/api/src/mcp/__tests__/apps.test.ts@@ -240,7 +240,7 @@ describe('App request config and auth resolution', () => {return { srv: parsed };},);- const getAllServerConfigs = jest.fn().mockResolvedValue({ srv: effective });+ const getServerConfig = jest.fn().mockResolvedValue(effective);const recoverServerConfig = jest.fn();await expect(@@ -252,14 +252,14 @@ describe('App request config and auth resolution', () => {unrelated: { type: 'stdio', command: 'never-initialized', args: [] },},ensureConfigServers,- getAllServerConfigs,+ getServerConfig,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(getServerConfig).toHaveBeenCalledWith('srv', user.id, { srv: parsed }, user.role);expect(recoverServerConfig).not.toHaveBeenCalled();});@@ -270,7 +270,7 @@ describe('App request config and auth resolution', () => {url: 'https://base.example.com',};const ensureConfigServers = jest.fn().mockResolvedValue({});- const getAllServerConfigs = jest.fn().mockResolvedValue({ srv: effective });+ const getServerConfig = jest.fn().mockResolvedValue(effective);const recoverServerConfig = jest.fn();await expect(@@ -279,14 +279,14 @@ describe('App request config and auth resolution', () => {user,mcpConfig: {},ensureConfigServers,- getAllServerConfigs,+ getServerConfig,recoverServerConfig,isAppServerConfig: jest.fn().mockResolvedValue(false),}),).resolves.toEqual({ serverConfig: effective, connectionOwner: 'principal' });expect(ensureConfigServers).toHaveBeenCalledWith({});- expect(getAllServerConfigs).toHaveBeenCalledWith(user.id, {}, user.role);+ expect(getServerConfig).toHaveBeenCalledWith('srv', user.id, {}, user.role);expect(recoverServerConfig).not.toHaveBeenCalled();});@@ -310,7 +310,7 @@ describe('App request config and auth resolution', () => {user,mcpConfig: {},ensureConfigServers: jest.fn().mockResolvedValue({}),- getAllServerConfigs: jest.fn().mockResolvedValue({ srv: stub }),+ getServerConfig: jest.fn().mockResolvedValue(stub),recoverServerConfig,isAppServerConfig: jest.fn().mockResolvedValue(false),}),@@ -328,7 +328,7 @@ describe('App request config and auth resolution', () => {user,mcpConfig: {},ensureConfigServers: jest.fn().mockResolvedValue({}),- getAllServerConfigs: jest.fn().mockResolvedValue({}),+ getServerConfig: jest.fn().mockResolvedValue(undefined),recoverServerConfig,isAppServerConfig: jest.fn().mockResolvedValue(false),}),diff --git a/packages/api/src/mcp/apps.ts b/packages/api/src/mcp/apps.tsindex 26f7f9c52a..10babc6b0f 100644--- a/packages/api/src/mcp/apps.ts+++ b/packages/api/src/mcp/apps.ts@@ -161,7 +161,7 @@ export async function resolveEffectiveAppServerConfig({user,mcpConfig,ensureConfigServers,- getAllServerConfigs,+ getServerConfig,recoverServerConfig,isAppServerConfig,}: {@@ -171,11 +171,12 @@ export async function resolveEffectiveAppServerConfig({ensureConfigServers: (config: Record<string, t.MCPOptions>,) => Promise<Record<string, t.ParsedServerConfig>>;- getAllServerConfigs: (+ getServerConfig: (+ serverName: string,userId: string,configServers: Record<string, t.ParsedServerConfig>,role?: string,- ) => Promise<Record<string, t.ParsedServerConfig>>;+ ) => Promise<t.ParsedServerConfig | undefined>;recoverServerConfig: (serverName: string,config: t.ParsedServerConfig,@@ -185,8 +186,7 @@ export async function resolveEffectiveAppServerConfig({}): 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 selectedConfig = await getServerConfig(serverName, user.id, configServers, user.role);const serverConfig = selectedConfig?.inspectionFailed? await recoverServerConfig(serverName, selectedConfig, user.id): selectedConfig;diff --git a/packages/api/src/mcp/apps/controller.spec.ts b/packages/api/src/mcp/apps/controller.spec.tsindex 74a5610afc..33e55cd1bc 100644--- a/packages/api/src/mcp/apps/controller.spec.ts+++ b/packages/api/src/mcp/apps/controller.spec.ts@@ -40,6 +40,7 @@ type MockResponse = EventEmitter & {json: jest.Mock;send: jest.Mock;setHeader: jest.Mock;+ removeHeader: jest.Mock;end: jest.Mock;};@@ -63,6 +64,7 @@ const makeResponse = (): MockResponse => {json: jest.fn(),send: jest.fn(),setHeader: jest.fn(),+ removeHeader: jest.fn(),end: jest.fn(),});response.status.mockReturnValue(response);@@ -101,9 +103,7 @@ function makeDependencies(manager: MCPAppsProxyManager) {ensureConfigServers: jest.fn(async () => ({srv: { type: 'stdio', command: 'test', args: [] },})),- getAllServerConfigs: jest.fn(async () => ({- srv: { type: 'stdio', command: 'effective', args: [] },- })),+ getServerConfig: jest.fn(async () => ({ type: 'stdio', command: 'effective', args: [] })),recoverServerConfig: jest.fn(async (_serverName, config) => config),isAppServerConfig: jest.fn(async () => false),resolveCachedAppServerConfig: jest.fn(async () => ({@@ -180,7 +180,7 @@ describe('createMCPAppsController', () => {allowedAddresses: null,});expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(dependencies.recoverServerConfig).not.toHaveBeenCalled();expect(dependencies.getFlowManager).not.toHaveBeenCalled();expect(dependencies.createOAuthCredentialsChanging).not.toHaveBeenCalled();@@ -224,7 +224,8 @@ describe('createMCPAppsController', () => {expect(dependencies.ensureConfigServers).toHaveBeenCalledWith({srv: { type: 'stdio', command: 'test', args: [] },});- expect(dependencies.getAllServerConfigs).toHaveBeenCalledWith(+ expect(dependencies.getServerConfig).toHaveBeenCalledWith(+ 'srv','user-1',{ srv: { type: 'stdio', command: 'test', args: [] } },'USER',@@ -344,7 +345,7 @@ describe('createMCPAppsController', () => {);expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(dependencies.getManager).not.toHaveBeenCalled();expect(manager.readResource).not.toHaveBeenCalled();expect(response.json).not.toHaveBeenCalled();@@ -391,7 +392,7 @@ describe('createMCPAppsController', () => {);expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(dependencies.getManager).not.toHaveBeenCalled();expect(manager.readResource).not.toHaveBeenCalled();expect(response.json).not.toHaveBeenCalled();@@ -400,10 +401,8 @@ describe('createMCPAppsController', () => {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(+ let finishResolution!: (value: { type: 'stdio'; command: string; args: string[] }) => void;+ dependencies.getServerConfig = jest.fn(() =>new Promise((resolve) => {finishResolution = resolve;@@ -427,7 +426,7 @@ describe('createMCPAppsController', () => {await Promise.resolve();request.aborted = true;request.emit('aborted');- finishResolution({ srv: { type: 'stdio', command: 'effective', args: [] } });+ finishResolution({ type: 'stdio', command: 'effective', args: [] });await handled;expect(dependencies.getManager).not.toHaveBeenCalled();@@ -451,7 +450,7 @@ describe('createMCPAppsController', () => {expect(response.status).toHaveBeenCalledWith(401);expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(manager.readResource).not.toHaveBeenCalled();});@@ -469,7 +468,7 @@ describe('createMCPAppsController', () => {expect(response.status).toHaveBeenCalledWith(500);expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(manager.readResource).not.toHaveBeenCalled();});@@ -519,7 +518,7 @@ describe('createMCPAppsController', () => {expect(response.status).toHaveBeenCalledWith(500);expect(next).not.toHaveBeenCalled();expect(dependencies.ensureConfigServers).not.toHaveBeenCalled();- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(manager.readResource).not.toHaveBeenCalled();});@@ -548,7 +547,7 @@ describe('createMCPAppsController', () => {srv: { type: 'stdio', command: 'scoped' },});expect(response.status).toHaveBeenCalledWith(500);- expect(dependencies.getAllServerConfigs).not.toHaveBeenCalled();+ expect(dependencies.getServerConfig).not.toHaveBeenCalled();expect(manager.readResource).not.toHaveBeenCalled();});@@ -561,8 +560,8 @@ describe('createMCPAppsController', () => {source: 'config' as const,inspectionFailed: true,};- dependencies.ensureConfigServers = jest.fn().mockResolvedValue({ srv: stub });- dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.ensureConfigServers = jest.fn().mockResolvedValue(stub);+ dependencies.getServerConfig = jest.fn().mockResolvedValue(stub);dependencies.recoverServerConfig = jest.fn().mockResolvedValue(undefined);const controller = createMCPAppsController(dependencies);const request = makeRequest({@@ -600,7 +599,7 @@ describe('createMCPAppsController', () => {url: 'https://recovered.example.com',source: 'yaml' as const,};- dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.getServerConfig = jest.fn().mockResolvedValue(stub);dependencies.recoverServerConfig = jest.fn().mockResolvedValue(recovered);const controller = createMCPAppsController(dependencies);const request = makeRequest({@@ -632,7 +631,7 @@ describe('createMCPAppsController', () => {source: 'yaml' as const,inspectionFailed: true,};- dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.getServerConfig = jest.fn().mockResolvedValue(stub);dependencies.recoverServerConfig = jest.fn().mockRejectedValue(new Error('recovery failed'));const controller = createMCPAppsController(dependencies);const request = makeRequest({@@ -665,7 +664,7 @@ describe('createMCPAppsController', () => {url: 'https://recovered.example.com',source: 'yaml' as const,};- dependencies.getAllServerConfigs = jest.fn().mockResolvedValue({ srv: stub });+ dependencies.getServerConfig = jest.fn().mockResolvedValue(stub);let recoveryStarted!: () => void;const started = new Promise<void>((resolve) => {recoveryStarted = resolve;@@ -722,6 +721,42 @@ describe('createMCPAppsController', () => {expect(dependencies.getSandboxCspLimits).toHaveBeenCalledTimes(2);});+ it('removes an inherited frame guard when cross-origin ancestors are configured', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();++ await controller.serveMCPSandbox(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(response.removeHeader).toHaveBeenCalledWith('X-Frame-Options');+ expect(response.setHeader).toHaveBeenCalledWith(+ 'Content-Security-Policy',+ expect.arrayContaining(['frame-ancestors https://host.example.com']),+ );+ });++ it('replaces an inherited frame guard with DENY when no ancestors are configured', async () => {+ const manager = makeManager();+ const { dependencies } = makeDependencies(manager);+ dependencies.sandboxFrameAncestors = undefined;+ const controller = createMCPAppsController(dependencies);+ const response = makeResponse();++ await controller.serveMCPSandbox(+ asHandlerRequest(makeRequest()),+ asHandlerResponse(response),+ jest.fn(),+ );++ expect(response.removeHeader).not.toHaveBeenCalledWith('X-Frame-Options');+ expect(response.setHeader).toHaveBeenCalledWith('X-Frame-Options', 'DENY');+ });+it('fails closed when trusted sandbox limits cannot be resolved', async () => {const manager = makeManager();const { dependencies } = makeDependencies(manager);diff --git a/packages/api/src/mcp/apps/controller.ts b/packages/api/src/mcp/apps/controller.tsindex c6ced08f16..609d1f7861 100644--- a/packages/api/src/mcp/apps/controller.ts+++ b/packages/api/src/mcp/apps/controller.ts@@ -64,11 +64,12 @@ export interface MCPAppsControllerDependencies {ensureConfigServers: (mcpConfig: Record<string, t.MCPOptions>,) => Promise<Record<string, t.ParsedServerConfig>>;- getAllServerConfigs: (+ getServerConfig: (+ serverName: string,userId: string,configServers: Record<string, t.ParsedServerConfig>,role?: string,- ) => Promise<Record<string, t.ParsedServerConfig>>;+ ) => Promise<t.ParsedServerConfig | undefined>;recoverServerConfig: (serverName: string,config: t.ParsedServerConfig,@@ -228,7 +229,7 @@ export function createMCPAppsController(dependencies: MCPAppsControllerDependencuser,mcpConfig: getAdmittedMCPConfig(request),ensureConfigServers: dependencies.ensureConfigServers,- getAllServerConfigs: dependencies.getAllServerConfigs,+ getServerConfig: dependencies.getServerConfig,recoverServerConfig: dependencies.recoverServerConfig,isAppServerConfig: dependencies.isAppServerConfig,}),@@ -354,6 +355,9 @@ export function createMCPAppsController(dependencies: MCPAppsControllerDependenccsp: typeof request.query.csp === 'string' ? request.query.csp : undefined,limits,});+ if (!('X-Frame-Options' in headers)) {+ response.removeHeader('X-Frame-Options');+ }for (const [name, value] of Object.entries(headers)) {response.setHeader(name, value);}diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.tsindex 7b62ad31e8..f593fe2c12 100644--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts@@ -434,8 +434,11 @@ export class MCPServersRegistry {allowedDomains?: string[] | null;allowedAddresses?: string[] | null;}): Promise<t.MCPConnectionTarget | undefined> {- const baseConfigs = await this.getBaseServerConfigs(userId, role);- const base = baseConfigs[serverName];+ // Validation concerns exactly one persisted binding. Avoid the all-server path here: besides+ // doing unrelated ACL/decryption work, one slow or malformed server can otherwise prevent an+ // independent inline App from ever reaching its sandbox. getServerConfig applies the same+ // YAML-over-user precedence with an ACL-aware, per-server DB fallback.+ const base = await this.getServerConfig(serverName, userId, undefined, role);const rawConfig = mcpConfig[serverName];let selectedConfig = base;@@ -483,10 +486,11 @@ export class MCPServersRegistry {serverName: string,userId?: string,configServers?: Record<string, t.ParsedServerConfig>,+ role?: string,): Promise<t.ParsedServerConfig | undefined> {const candidate = configServers?.[serverName];- const cacheKey = this.getReadThroughCacheKey(serverName, userId);+ const cacheKey = this.getReadThroughCacheKey(serverName, userId, role);let base: t.ParsedServerConfig | undefined;const cached = await this.readThroughCache.getEntry(cacheKey);if (cached.hit) {@@ -496,7 +500,7 @@ export class MCPServersRegistry {if (configFromYaml) {base = configFromYaml;} else {- base = await this.dbConfigsRepo.get(serverName, userId);+ base = await this.dbConfigsRepo.get(serverName, userId, role);}await this.readThroughCache.set(cacheKey, base, cached.fill);}@@ -1414,8 +1418,10 @@ export class MCPServersRegistry {/** Tenant-scoped because DB-backed lookups are filtered by the active tenant:* an entry populated in one tenant's context must never satisfy another's. */- private getReadThroughCacheKey(serverName: string, userId?: string): string {- return scopedCacheKey(userId ? `${serverName}::${userId}` : serverName);+ private getReadThroughCacheKey(serverName: string, userId?: string, role?: string): string {+ return scopedCacheKey(+ userId ? `${serverName}::${userId}${role != null ? `::role:${role}` : ''}` : serverName,+ );}/**diff --git a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.tsindex 38c0867bd4..77d749deae 100644--- a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts+++ b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts@@ -739,6 +739,7 @@ describe('MCPServersRegistry', () => {'srv',yamlConfig,);+ const getServerConfigSpy = jest.spyOn(registry, 'getServerConfig');await expect(registry.resolveCachedAppServerConfig({@@ -749,6 +750,40 @@ describe('MCPServersRegistry', () => {...allowlists,}),).resolves.toEqual({ serverConfig: storedYamlConfig, connectionOwner: 'operator' });+ expect(getServerConfigSpy).toHaveBeenCalledWith('srv', 'user-1', undefined, 'USER');+ });++ it('rechecks the current role for a persisted App without reusing another role or a legacy cache entry', async () => {+ const roleServer = {+ ...testParsedConfig,+ source: 'user' as const,+ title: 'Role-scoped server',+ };+ const dbGet = jest.spyOn(registry['dbConfigsRepo'], 'get');+ dbGet.mockImplementation(async (_serverName, userId, role) =>+ userId === 'user-1' && (role === 'ADMIN' || role === undefined) ? roleServer : undefined,+ );+ const validate = (role: string) =>+ registry.resolveCachedAppServerConfig({+ serverName: 'srv',+ userId: 'user-1',+ role,+ mcpConfig: {},+ ...allowlists,+ });++ // A roleless caller may already have filled the original per-server cache key.+ await registry.getServerConfig('srv', 'user-1');+ await expect(validate('USER')).resolves.toBeUndefined();+ await expect(validate('ADMIN')).resolves.toMatchObject({ serverConfig: roleServer });+ await expect(validate('USER')).resolves.toBeUndefined();+ await expect(validate('ADMIN')).resolves.toMatchObject({ serverConfig: roleServer });++ expect(dbGet.mock.calls.filter(([, userId]) => userId === 'user-1')).toEqual([+ ['srv', 'user-1', undefined],+ ['srv', 'user-1', 'USER'],+ ['srv', 'user-1', 'ADMIN'],+ ]);});});diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.tsindex 64aca9af07..b4f6cfd4a0 100644--- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts+++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts@@ -1807,9 +1807,77 @@ describe('ServerConfigsDB', () => {expect(result).toBeDefined();expect(result?.title).toBe('Shared Server');});++ it('uses the supplied role for direct and agent-derived server access', async () => {+ const direct = await serverConfigsDB.add('temp', createSSEConfig('Role Direct'), userId);+ const viaAgent = await serverConfigsDB.add('temp', createSSEConfig('Role Agent'), userId);+ const agent = await mongoose.models.Agent.create({+ id: 'role-scoped-agent',+ name: 'Role Scoped Agent',+ provider: 'openai',+ model: 'gpt-4',+ author: new mongoose.Types.ObjectId(userId),+ mcpServerNames: [viaAgent.serverName],+ });+ const serverRole = await mongoose.models.AccessRole.findOne({+ accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,+ });+ const agentRole = await mongoose.models.AccessRole.findOne({+ accessRoleId: AccessRoleIds.AGENT_VIEWER,+ });+ await mongoose.models.AclEntry.create([+ {+ principalType: PrincipalType.ROLE,+ principalModel: PrincipalModel.ROLE,+ principalId: 'ADMIN',+ resourceType: ResourceType.MCPSERVER,+ resourceId: new mongoose.Types.ObjectId(direct.config.dbId!),+ permBits: PermissionBits.VIEW,+ roleId: serverRole!._id,+ },+ {+ principalType: PrincipalType.ROLE,+ principalModel: PrincipalModel.ROLE,+ principalId: 'ADMIN',+ resourceType: ResourceType.AGENT,+ resourceId: agent._id,+ permBits: PermissionBits.VIEW,+ roleId: agentRole!._id,+ },+ ]);++ await expect(+ serverConfigsDB.get(direct.serverName, userId2, 'ADMIN'),+ ).resolves.toMatchObject({ title: 'Role Direct' });+ await expect(+ serverConfigsDB.get(viaAgent.serverName, userId2, 'ADMIN'),+ ).resolves.toMatchObject({ title: 'Role Agent', consumeOnly: true });+ await expect(+ serverConfigsDB.get(direct.serverName, userId2, 'USER'),+ ).resolves.toBeUndefined();+ await expect(+ serverConfigsDB.get(viaAgent.serverName, userId2, 'USER'),+ ).resolves.toBeUndefined();+ });});describe('agent-based access (consumeOnly)', () => {+ it('resolves user principals once for direct and agent access', async () => {+ const created = await serverConfigsDB.add(+ 'temp-name',+ createSSEConfig('Shared Lookup'),+ userId,+ );+ const findByIdSpy = jest.spyOn(mongoose.models.User, 'findById');++ try {+ await serverConfigsDB.get(created.serverName, userId2, 'USER');+ expect(findByIdSpy).toHaveBeenCalledTimes(1);+ } finally {+ findByIdSpy.mockRestore();+ }+ });+it('should return server with consumeOnly when user has access via agent', async () => {const config = createSSEConfig('Agent Accessible Server');const created = await serverConfigsDB.add('temp-name', config, userId);diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.tsindex 6e063a64a7..ae24599b20 100644--- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts+++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts@@ -260,7 +260,11 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {* @param userId - The user ID (optional - if not provided, checks publicly accessible agents)* @returns true if user has VIEW access to at least one agent that has this MCP server*/- private async hasAccessViaAgent(serverName: string, userId?: string): Promise<boolean> {+ private async hasAccessViaAgent(+ serverName: string,+ userId?: string,+ role?: string,+ ): Promise<boolean> {const candidateIds = await this._dbMethods.getAgentIdsByMCPServerName(serverName);if (candidateIds.length === 0) {return false;@@ -269,6 +273,7 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {const accessibleAgentIds = userId? await this._aclService.findAccessibleResources({userId,+ role,requiredPermissions: PermissionBits.VIEW,resourceType: ResourceType.AGENT,resourceIds: candidateIds,@@ -467,55 +472,63 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {* @param userId - the user id provide the scope of the request. If the user Id is not provided, only publicly visible servers are returned.* @returns The parsed server config or undefined if not found. If accessed via agent, consumeOnly will be true.*/- public async get(serverName: string, userId?: string): Promise<ParsedServerConfig | undefined> {- const server = await this._dbMethods.findMCPServerByServerName(serverName);- if (!server) return undefined;-- if (!userId) {- const directlyAccessibleMCPIds = (- await this._aclService.findPubliclyAccessibleResources({+ public async get(+ serverName: string,+ userId?: string,+ role?: string,+ ): Promise<ParsedServerConfig | undefined> {+ if (userId) {+ /** Each lookup is bounded to this server or the agents that reference it. Resolve the+ * principal set once so direct and agent ACL checks can start together. */+ const [server, principalsList, candidateIds] = await Promise.all([+ this._dbMethods.findMCPServerByServerName(serverName),+ this._aclService.getUserPrincipals({ userId, role }),+ this._dbMethods.getAgentIdsByMCPServerName(serverName),+ ]);+ if (!server) return undefined;++ const [directlyAccessibleIds, accessibleAgentIds] = await Promise.all([+ this._aclService.findAccessibleResourcesForPrincipals({+ principalsList,resourceType: ResourceType.MCPSERVER,requiredPermissions: PermissionBits.VIEW,- })- ).map((id) => id.toString());- if (directlyAccessibleMCPIds.indexOf(server._id.toString()) > -1) {+ resourceIds: [server._id],+ }),+ this.findAccessibleAgentIds(candidateIds, userId, principalsList),+ ]);+ if (directlyAccessibleIds.some((id) => id.toString() === server._id.toString())) {+ logger.debug(+ `[ServerConfigsDB.get] getting ${serverName} for user with the UserId: ${userId}`,+ );return await this.mapDBServerToParsedConfig(server);}-- const hasAgentAccess = await this.hasAccessViaAgent(serverName);- if (hasAgentAccess) {+ if (accessibleAgentIds.length > 0) {logger.debug(- `[ServerConfigsDB.get] accessing ${serverName} via public agent (consumeOnly)`,+ `[ServerConfigsDB.get] user ${userId} accessing ${serverName} via agent (consumeOnly)`,);return {...(await this.mapDBServerToParsedConfig(server)),consumeOnly: true,};}-return undefined;}- const userHasDirectAccess = await this._aclService.checkPermission({- userId,- resourceType: ResourceType.MCPSERVER,- requiredPermission: PermissionBits.VIEW,- resourceId: server._id,- });-- if (userHasDirectAccess) {- logger.debug(- `[ServerConfigsDB.get] getting ${serverName} for user with the UserId: ${userId}`,- );+ const server = await this._dbMethods.findMCPServerByServerName(serverName);+ if (!server) return undefined;+ const directlyAccessibleMCPIds = (+ await this._aclService.findPubliclyAccessibleResources({+ resourceType: ResourceType.MCPSERVER,+ requiredPermissions: PermissionBits.VIEW,+ })+ ).map((id) => id.toString());+ if (directlyAccessibleMCPIds.indexOf(server._id.toString()) > -1) {return await this.mapDBServerToParsedConfig(server);}- /** Check agent access (user can VIEW an agent that has this MCP server) */- const hasAgentAccess = await this.hasAccessViaAgent(serverName, userId);+ const hasAgentAccess = await this.hasAccessViaAgent(serverName);if (hasAgentAccess) {- logger.debug(- `[ServerConfigsDB.get] user ${userId} accessing ${serverName} via agent (consumeOnly)`,- );+ logger.debug(`[ServerConfigsDB.get] accessing ${serverName} via public agent (consumeOnly)`);return {...(await this.mapDBServerToParsedConfig(server)),consumeOnly: true,