From e396ea9c7b14e40cfe9a2fb296bc7000cc67f935 Mon Sep 17 00:00:00 2001 From: "lia-by-librechat[bot]" <328778573+lia-by-librechat[bot]@users.noreply.github.com> Date: Thu, 24 Sep 2026 18:00:13 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=AB=B8=20fix:=20Gate=20MCP=20App=20Views?= =?UTF-8?q?=20and=20Actions=20on=20User=20Intent=20(#16297)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🫸 fix: Gate MCP App Views and Actions on User Intent * 🧪 ci: Run MCP Apps Browser Checks on Repository Bot PRs * 🧲 test: Open App Before Checking Tool-Call Frames * 🔎 fix: Wait for Stable App Views in Restored Browser Tests * 🧪 test: Trace Grouped App View Activation in Browser CI * 🧪 test: Diagnose Grouped App Click Propagation * 🧪 test: Distinguish Native and React App Click Delivery * 🧪 test: Inspect Grouped App Button Hit Target * 🎟️ test: Open Grouped App Views After Scrolling Into Place * 🧯 fix: Revoke App Approval Before Teardown Handshake * 🫸 fix: Configure App Limits and Suspend Denied Actions * 🧾 test: Expect Configured MCP App Limits in API Suites * 🧱 fix: Isolate Approved App Messages From Composer Drafts * 🛟 fix: Suspend Aborted App Actions and Restore View Focus * 🦮 fix: Preserve Focus on App-Initiated Teardown * 🧳 fix: Exclude Draft Agent State From App Messages * 🧭 test: Preserve Legacy Null File Overrides * 🧰 fix: Retain Selected MCP Tools Across App Messages * 🧾 fix: Acknowledge Accepted App Turns and Disclose Selected Tools --------- Co-authored-by: Lia (cherry picked from commit 6866732a88b0df0eb738d964dbdefe5b73cfcfc1) Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16297 --- .github/workflows/playwright-mock.yml | 16 +- api/server/routes/__tests__/config.spec.js | 6 + api/server/routes/__tests__/mcp.spec.js | 2 + api/server/routes/config.js | 2 + api/server/services/__tests__/MCP.spec.js | 2 + api/server/services/initializeMCPs.spec.js | 14 + client/src/Providers/MCPAppsPolicyContext.tsx | 72 ++++- .../__tests__/MCPAppsPolicyContext.spec.tsx | 66 ++++- .../Messages/Content/ToolCallLimitNotice.tsx | 12 +- .../Content/__tests__/ToolCall.test.tsx | 42 ++- .../__tests__/ToolCallLimitNotice.test.tsx | 12 +- .../components/MCPUIResource/MCPAppViews.tsx | 203 ++++++++++++- .../__tests__/MCPAppViews.test.tsx | 154 +++++++++- .../useChatFunctions.regenerate.spec.tsx | 141 +++++++++- client/src/hooks/Chat/useChatFunctions.ts | 12 +- .../src/hooks/MCP/__tests__/approval.spec.tsx | 185 ++++++++++++ .../hooks/MCP/__tests__/useAppBridge.spec.tsx | 266 +++++++++++++++++- client/src/hooks/MCP/approval.tsx | 136 +++++++++ client/src/hooks/MCP/useAppBridge.ts | 115 ++++++-- client/src/locales/en/translation.json | 13 + docs/mcp-apps.md | 57 +++- e2e/mcp-apps/workflow.test.mjs | 30 ++ e2e/specs/mock/mcp-apps.spec.ts | 71 ++++- librechat.example.yaml | 2 + .../__tests__/MCPServersRegistry.test.ts | 6 + packages/data-provider/src/config.spec.ts | 26 ++ packages/data-provider/src/config.ts | 26 ++ 27 files changed, 1595 insertions(+), 94 deletions(-) create mode 100644 client/src/hooks/MCP/__tests__/approval.spec.tsx create mode 100644 client/src/hooks/MCP/approval.tsx create mode 100644 e2e/mcp-apps/workflow.test.mjs diff --git a/.github/workflows/playwright-mock.yml b/.github/workflows/playwright-mock.yml index 43122021e9..eb28e256ce 100644 --- a/.github/workflows/playwright-mock.yml +++ b/.github/workflows/playwright-mock.yml @@ -165,7 +165,8 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request != null && - contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association))) + (contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) || + github.event.pull_request.head.repo.full_name == github.repository))) runs-on: ubuntu-latest timeout-minutes: 30 # Separate runners isolate each shard's user, MongoDB, Redis and fixture state. @@ -413,7 +414,8 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request != null && - contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association))) + (contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) || + github.event.pull_request.head.repo.full_name == github.repository))) runs-on: ubuntu-latest timeout-minutes: 30 strategy: @@ -564,7 +566,8 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request != null && - contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association)) + (contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) || + github.event.pull_request.head.repo.full_name == github.repository)) runs-on: ubuntu-latest timeout-minutes: 45 env: @@ -599,8 +602,8 @@ jobs: - name: Verify Chrome is present run: google-chrome --version - - name: Check MCP Apps result gating - run: node --test e2e/mcp-apps/results.test.mjs + - name: Check MCP Apps result gating and same-repository PR eligibility + run: node --test e2e/mcp-apps/results.test.mjs e2e/mcp-apps/workflow.test.mjs - name: Check real SDK server fixture run: node --test e2e/mcp-apps/server.test.mjs @@ -643,7 +646,8 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request != null && - contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association))) + (contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) || + github.event.pull_request.head.repo.full_name == github.repository))) needs: [codegraph_select, e2e_shards, mcp_tool_list_changed, mcp_apps] runs-on: ubuntu-latest steps: diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 3cf1e60c40..42848ffb4a 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -408,6 +408,8 @@ describe('GET /api/config', () => { cspLimits: { maxSourcesPerDirective: 32, maxSerializedLength: 4096 }, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }); }); @@ -420,6 +422,8 @@ describe('GET /api/config', () => { maxSourcesPerDirective: 64, maxSerializedLength: 8192, maxAdmissionRequestsPerMinute: 480, + maxActiveViews: 7, + maxActionPreviewChars: 32768, }, }); const response = await request(createApp(mockUser)).get('/api/config'); @@ -430,6 +434,8 @@ describe('GET /api/config', () => { cspLimits: { maxSourcesPerDirective: 64, maxSerializedLength: 8192 }, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 480, + maxActiveViews: 7, + maxActionPreviewChars: 32768, sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox', }); }); diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js index 27e4b4596b..59e9227d13 100644 --- a/api/server/routes/__tests__/mcp.spec.js +++ b/api/server/routes/__tests__/mcp.spec.js @@ -47,6 +47,8 @@ const defaultMCPAppsPolicy = { enabled: false, legacyHtmlEnabled: true, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, maxPersistedAppBytes: 1048576, }; diff --git a/api/server/routes/config.js b/api/server/routes/config.js index bc25d6b6bc..f0e5b456a2 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -324,6 +324,8 @@ router.get('/', async function (req, res) { appConfig?.mcpAppSandbox?.maxPersistedAppBytes, appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute, appConfig?.mcpAppSandbox?.url, + appConfig?.mcpAppSandbox?.maxActiveViews, + appConfig?.mcpAppSandbox?.maxActionPreviewChars, ), ...(codeEnvironmentMoveVersion != null ? { codeEnvironmentMoveVersion } : {}), ...(cloudFront ? { cloudFront } : {}), diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.js index 3fe4e79273..3cd0d8e3de 100644 --- a/api/server/services/__tests__/MCP.spec.js +++ b/api/server/services/__tests__/MCP.spec.js @@ -8,6 +8,8 @@ const defaultMCPAppsPolicy = { enabled: false, legacyHtmlEnabled: true, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, maxPersistedAppBytes: 1048576, }; diff --git a/api/server/services/initializeMCPs.spec.js b/api/server/services/initializeMCPs.spec.js index 0f76546a16..9b78ab67ae 100644 --- a/api/server/services/initializeMCPs.spec.js +++ b/api/server/services/initializeMCPs.spec.js @@ -157,6 +157,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: true, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }, ); }); @@ -180,6 +182,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: true, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }, ); }); @@ -202,6 +206,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: true, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }, ); }); @@ -214,6 +220,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: true, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }, ], [ @@ -223,6 +231,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: false, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }, ], ])('normalizes the startup MCP Apps policy for apps=%s', async (apps, expected) => { @@ -250,6 +260,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: true, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 480, + maxActiveViews: 3, + maxActionPreviewChars: 16384, sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox', }); }); @@ -288,6 +300,8 @@ describe('initializeMCPs', () => { legacyHtmlEnabled: true, maxPersistedAppBytes: 1048576, maxAdmissionRequestsPerMinute: 240, + maxActiveViews: 3, + maxActionPreviewChars: 16384, }, }); }); diff --git a/client/src/Providers/MCPAppsPolicyContext.tsx b/client/src/Providers/MCPAppsPolicyContext.tsx index 97a0e7d61c..84617b8c56 100644 --- a/client/src/Providers/MCPAppsPolicyContext.tsx +++ b/client/src/Providers/MCPAppsPolicyContext.tsx @@ -1,17 +1,37 @@ -import { createContext, useContext, useMemo } from 'react'; +import { createContext, useCallback, useContext, useMemo } from 'react'; +import { atom, createStore, useAtomValue } from 'jotai'; import { DEFAULT_MCP_APPS_POLICY, + DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS, + DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS, + MAX_MCP_APP_ACTIVE_VIEWS, + MAX_MCP_APP_ACTION_PREVIEW_CHARS, resolveMCPAppCspLimits, type TMCPAppsPolicy, type TStartupConfig, } from 'librechat-data-provider'; +/** One store per host provider; never share capacity across conversations or signed-in users. */ +const activeAppViewsAtom = atom>(new Set()); + +function validLimit(value: unknown, fallback: number, max: number): number { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= max + ? value + : fallback; +} + type MCPAppsHostContextValue = { + reserveView: (key: string) => boolean; + releaseView: (key: string) => void; + activeViewStore: ReturnType; policy: Readonly; userId?: string; }; const DEFAULT_MCP_APPS_HOST: MCPAppsHostContextValue = { + reserveView: () => false, + releaseView: () => undefined, + activeViewStore: createStore(), policy: DEFAULT_MCP_APPS_POLICY, }; @@ -29,7 +49,20 @@ function getPublishedPolicy( ) { return DEFAULT_MCP_APPS_POLICY; } - return { ...policy, cspLimits: resolveMCPAppCspLimits(policy.cspLimits) }; + return { + ...policy, + cspLimits: resolveMCPAppCspLimits(policy.cspLimits), + maxActiveViews: validLimit( + policy.maxActiveViews, + DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS, + MAX_MCP_APP_ACTIVE_VIEWS, + ), + maxActionPreviewChars: validLimit( + policy.maxActionPreviewChars, + DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS, + MAX_MCP_APP_ACTION_PREVIEW_CHARS, + ), + }; } export function MCPAppsPolicyProvider({ @@ -44,10 +77,32 @@ export function MCPAppsPolicyProvider({ userId?: string; }) { const policy = useMemo(() => getPublishedPolicy(startupConfig, ready), [ready, startupConfig]); + const activeViewStore = useMemo(() => createStore(), []); + const reserveView = useCallback( + (key: string) => { + const active = activeViewStore.get(activeAppViewsAtom); + if (active.has(key)) return true; + if (active.size >= (policy.maxActiveViews ?? DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS)) return false; + activeViewStore.set(activeAppViewsAtom, new Set(active).add(key)); + return true; + }, + [activeViewStore, policy.maxActiveViews], + ); + const releaseView = useCallback( + (key: string) => { + const active = activeViewStore.get(activeAppViewsAtom); + if (active.has(key)) { + const next = new Set(active); + next.delete(key); + activeViewStore.set(activeAppViewsAtom, next); + } + }, + [activeViewStore], + ); const authenticatedUserId = typeof userId === 'string' && userId.trim() ? userId : undefined; const value = useMemo( - () => ({ policy, userId: authenticatedUserId }), - [authenticatedUserId, policy], + () => ({ policy, userId: authenticatedUserId, reserveView, releaseView, activeViewStore }), + [authenticatedUserId, policy, reserveView, releaseView, activeViewStore], ); return {children}; @@ -60,3 +115,12 @@ export function useMCPAppsPolicy(): Readonly { export function useMCPAppsHost(): MCPAppsHostContextValue { return useContext(MCPAppsPolicyContext); } + +/** Subscribe only a capacity notice, not every historical placeholder, to shared View changes. */ +export function useMCPAppViewAtCapacity(): boolean { + const { activeViewStore, policy } = useMCPAppsHost(); + return ( + useAtomValue(activeAppViewsAtom, { store: activeViewStore }).size >= + (policy.maxActiveViews ?? DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS) + ); +} diff --git a/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsx b/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsx index 0e354fce28..d6da3d83a2 100644 --- a/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsx +++ b/client/src/Providers/__tests__/MCPAppsPolicyContext.spec.tsx @@ -1,3 +1,4 @@ +import React from 'react'; import { act, render, screen, waitFor } from '@testing-library/react'; import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query'; import type { TStartupConfig } from 'librechat-data-provider'; @@ -21,8 +22,11 @@ function LimitsProbe() { } function SandboxPolicyProbe() { - const { sandboxUrl, maxAdmissionRequestsPerMinute } = useMCPAppsPolicy(); - return {`${sandboxUrl ?? 'none'}:${maxAdmissionRequestsPerMinute ?? 'none'}`}; + const { sandboxUrl, maxAdmissionRequestsPerMinute, maxActiveViews, maxActionPreviewChars } = + useMCPAppsPolicy(); + return ( + {`${sandboxUrl ?? 'none'}:${maxAdmissionRequestsPerMinute ?? 'none'}:${maxActiveViews ?? 'none'}:${maxActionPreviewChars ?? 'none'}`} + ); } function CachedPolicyProvider({ children }: { children: React.ReactNode }) { @@ -103,6 +107,8 @@ describe('MCPAppsPolicyProvider', () => { legacyHtmlEnabled: true, sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox', maxAdmissionRequestsPerMinute: 480, + maxActiveViews: 7, + maxActionPreviewChars: 32768, }, } as TStartupConfig } @@ -113,10 +119,64 @@ describe('MCPAppsPolicyProvider', () => { ); expect( - screen.getByText('https://mcp-sandbox.example.com/api/mcp/sandbox:480'), + screen.getByText('https://mcp-sandbox.example.com/api/mcp/sandbox:480:7:32768'), ).toBeInTheDocument(); }); + it('falls back to bounded policy values when a published startup payload is malformed', () => { + render( + + + , + ); + expect(screen.getByText('none:none:3:16384')).toBeInTheDocument(); + }); + + it('keeps App capacity in an isolated per-host Jotai store', () => { + function Reserve({ label }: { label: string }) { + const { reserveView } = useMCPAppsHost(); + const [accepted, setAccepted] = React.useState(false); + return ( + <> + + {`${label}:${accepted}`} + + ); + } + const config = { + mcpApps: { enabled: true, legacyHtmlEnabled: true, maxActiveViews: 1 }, + } as TStartupConfig; + render( + <> + + + + + + + , + ); + // Each provider owns its own capacity; the other user's View remains independent. + act(() => { + screen.getByRole('button', { name: 'first' }).click(); + screen.getByRole('button', { name: 'second' }).click(); + }); + expect(screen.getByText('first:true')).toBeInTheDocument(); + expect(screen.getByText('second:true')).toBeInTheDocument(); + }); + it('tracks the startup cache without exposing pending, missing, or malformed policy', async () => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); render( diff --git a/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx b/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx index fe1c6234e6..4695393f3f 100644 --- a/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx +++ b/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx @@ -57,7 +57,7 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage }) /** * Empty overrides are authoritative: a recovery prompt is not the user's next * compose, so `ask` must not attach or drain files, skills, or quotes already - * staged in the composer. + * staged in the composer. The agent and MCP server selection remains in scope. */ const recover = (text: string) => chat?.ask({ text }, { overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] }); @@ -66,7 +66,7 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })
setDismissed(true)} >