Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🪔 feat: Add Bound Scheduled MCP Consent (#16652)
lia-by-librechat[bot]3f3de656126e
diff --git a/api/server/routes/schedules.js b/api/server/routes/schedules.jsindex d5cc2b1ba5..e3007ebba7 100644--- a/api/server/routes/schedules.js+++ b/api/server/routes/schedules.js@@ -5,6 +5,8 @@ const {SCHEDULE_FILE_HOLD,generateCheckAccess,createSchedulesHandlers,+ createScheduleMCPConsentHost,+ createScheduleMCPEnrollmentResolver,} = require('@librechat/api');const { requireJwtAuth, configMiddleware, messageIpLimiter } = require('~/server/middleware');const {@@ -86,6 +88,34 @@ const handlers = createSchedulesHandlers({isUserDeleting,});+const consentHost = createScheduleMCPConsentHost({+ resolveEnrollment: createScheduleMCPEnrollmentResolver({+ canUseRoot: async (agentId, user) => (await resolveAgentFireAccess(agentId, user)) === 'ok',+ findUser: (id) => methods.findUser({ _id: id }),+ getAppConfig: require('~/server/services/Config/app').getAppConfig,+ resolveGraphAccess: (user) =>+ methods.resolveAgentGraphAccess({+ userId: user.id,+ role: user.role,+ idOnTheSource: user.idOnTheSource,+ }),+ getNodes: methods.getAgentGraphNodes,+ getModelsConfig: (user) =>+ require('~/server/controllers/ModelController').getModelsConfig({ user }),+ getServers: (user, config) =>+ require('~/config').getMCPServersRegistry().getAllServerConfigs(user.id, config, user.role),+ }),+ methods,+ getLimits,+ findUser: (id) => methods.findUser({ _id: id }),+ getRoleByName,+ canViewAgent: async (agentId, user) => (await resolveAgentFireAccess(agentId, user)) === 'ok',+});++router.get('/:id/mcp-consent', consentHost.handlers.get);+router.post('/:id/mcp-consent', checkSchedulesCreate, consentHost.handlers.confirm);+router.delete('/:id/mcp-consent', consentHost.handlers.revoke);+router.get('/', checkSchedulesAccess, handlers.listSchedules);router.get('/:id', checkSchedulesAccess, handlers.getSchedule);router.post('/', checkSchedulesCreate, handlers.createSchedule);diff --git a/client/src/components/SidePanel/Schedules/Consent.tsx b/client/src/components/SidePanel/Schedules/Consent.tsxnew file mode 100644index 0000000000..aece4ae241--- /dev/null+++ b/client/src/components/SidePanel/Schedules/Consent.tsx@@ -0,0 +1,175 @@+import { useState, useId } from 'react';+import { Button, Input, Label, Spinner, OGDialog, OGDialogTemplate } from '@librechat/client';+import type { ScheduleMCPConsentView } from 'librechat-data-provider';+import type { MutableRefObject } from 'react';+import {+ useScheduleMCPConsent,+ useScheduleMCPConsentMutations,+} from '~/data-provider/Schedules/consent';+import { useLocalize } from '~/hooks';++const statusKeys = {+ missing: 'com_ui_schedule_consent_missing',+ active: 'com_ui_schedule_consent_active',+ expired: 'com_ui_schedule_consent_expired',+ revoked: 'com_ui_schedule_consent_revoked',+ changed: 'com_ui_schedule_consent_changed',+ unsupported: 'com_ui_schedule_consent_unsupported',+} as const;++const messageKeys = {+ error: 'com_ui_schedule_consent_error',+ revoked: 'com_ui_schedule_consent_revoked',+ success: 'com_ui_schedule_consent_confirmed',+} as const;++export default function Consent({+ canConfirm = true,+ id,+ name,+ onOpenChange,+ triggerRef,+}: {+ canConfirm?: boolean;+ id: string;+ name: string;+ onOpenChange: (open: boolean) => void;+ triggerRef: MutableRefObject<HTMLButtonElement | null>;+}) {+ const localize = useLocalize();+ const inputId = useId();+ const query = useScheduleMCPConsent(id);+ const { confirm, revoke } = useScheduleMCPConsentMutations(id);+ const [hours, setHours] = useState(1);+ const [message, setMessage] = useState<'success' | 'revoked' | 'error' | null>(null);+ const busy = confirm.isLoading || revoke.isLoading || query.isFetching;+ const data: ScheduleMCPConsentView | undefined = query.data;+ const commit = () => {+ if (!data?.offer) return;+ setMessage(null);+ confirm.mutate(+ { offerDigest: data.offer.digest, expectedRevision: data.revision, lifetimeHours: hours },+ {+ onSuccess: () => setMessage('success'),+ onError: () => setMessage('error'),+ },+ );+ };+ const withdraw = () => {+ if (!data?.revision) return;+ setMessage(null);+ revoke.mutate(data.revision, {+ onSuccess: () => setMessage('revoked'),+ onError: () => setMessage('error'),+ });+ };+ return (+ <OGDialog open onOpenChange={onOpenChange} triggerRef={triggerRef}>+ <OGDialogTemplate+ title={localize('com_ui_schedule_consent_title')}+ className="w-11/12 max-w-lg"+ main={+ <div className="space-y-4">+ <p className="text-text-primary text-sm">{name}</p>+ <p className="text-text-secondary text-sm">+ {localize('com_ui_schedule_consent_boundary')}+ </p>+ {query.isLoading && <Spinner />}+ {!query.isLoading && query.isError && (+ <div role="alert">+ <p>{localize('com_ui_schedule_consent_error')}</p>+ <Button variant="outline" onClick={() => query.refetch()}>+ {localize('com_ui_retry')}+ </Button>+ </div>+ )}+ {!query.isLoading && !query.isError && data && (+ <>+ <p role="status">{localize(statusKeys[data.state])}</p>+ {data.expiresAtMs != null && (+ <p className="text-text-secondary text-sm">+ {localize('com_ui_schedule_consent_deadline', {+ time: new Date(data.expiresAtMs).toLocaleString(),+ })}+ </p>+ )}+ <ul className="space-y-2">+ {data.targets.map((target) => (+ <li key={target.resource.serverName}>+ <p className="text-sm font-medium">{target.resource.serverName}</p>+ <p className="text-text-secondary text-xs break-all">{target.resource.url}</p>+ <p className="text-text-secondary text-xs">+ {target.resource.credentialMode}+ </p>+ {target.resource.issuer && (+ <p className="text-text-secondary text-xs break-all">+ {localize('com_ui_schedule_consent_issuer', {+ issuer: target.resource.issuer,+ })}+ </p>+ )}+ {target.resource.audience && (+ <p className="text-text-secondary text-xs">+ {localize('com_ui_schedule_consent_audience', {+ audience: target.resource.audience,+ })}+ </p>+ )}+ {target.resource.scopes.length > 0 && (+ <p className="text-text-secondary text-xs">+ {localize('com_ui_schedule_consent_scopes', {+ scopes: target.resource.scopes.join(', '),+ })}+ </p>+ )}+ {target.permittedTools.map((selection) => (+ <p className="text-text-secondary text-xs" key={selection.agentId}>+ {selection.agentId}: {selection.tools.join(', ')}+ </p>+ ))}+ </li>+ ))}+ </ul>+ {canConfirm && data.offer && (+ <>+ <Label htmlFor={inputId}>{localize('com_ui_schedule_consent_hours')}</Label>+ <Input+ id={inputId}+ type="number"+ min={1}+ max={data.offer.maxLifetimeHours}+ value={hours}+ disabled={busy}+ onChange={(event) => setHours(Number(event.target.value))}+ />+ <Button+ onClick={commit}+ disabled={+ busy ||+ !Number.isInteger(hours) ||+ hours < 1 ||+ hours > data.offer.maxLifetimeHours+ }+ >+ {localize('com_ui_schedule_consent_confirm')}+ </Button>+ </>+ )}+ {data.revision && data.state !== 'revoked' && (+ <Button variant="outline" disabled={busy} onClick={withdraw}>+ {localize('com_ui_schedule_consent_revoke')}+ </Button>+ )}+ </>+ )}+ {message && (+ <p role={message === 'error' ? 'alert' : 'status'}>+ {localize(messageKeys[message])}+ </p>+ )}+ </div>+ }+ />+ </OGDialog>+ );+}diff --git a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx b/client/src/components/SidePanel/Schedules/ScheduleCard.tsxindex b3d5898bf5..832495ff98 100644--- a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx+++ b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx@@ -38,8 +38,10 @@ import { useAgentsMapContext } from '~/Providers';import ScheduleDialog from './ScheduleDialog';import { describeCadence } from './cadence';import { scheduleRowState } from './state';+import Consent from './Consent';interface ScheduleCardProps {+ consentEnabled?: boolean;schedule: TSchedule;/** Resolved by the panel, which holds ONE project-name lookup for the whole list —* deriving it per card is O(schedules x projects) on every project-list refresh. */@@ -152,7 +154,7 @@ function TrailingState({);}-export default function ScheduleCard({ schedule, projectName }: ScheduleCardProps) {+export default function ScheduleCard({ schedule, projectName, consentEnabled }: ScheduleCardProps) {const localize = useLocalize();const navigate = useNavigate();const lastRunKey = scheduleLastRunKey(schedule);@@ -179,6 +181,8 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardPropconst menuId = useId();const [menuOpen, setMenuOpen] = useState(false);+ const [consentOpen, setConsentOpen] = useState(false);+ const consentButtonRef = useRef<HTMLButtonElement>(null);const [editOpen, setEditOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);const editButtonRef = useRef<HTMLButtonElement>(null);@@ -274,39 +278,59 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardProp};}, [schedule.enabled, schedule.nextRunAt, i18n.language, hour12, localize]);+ const canInspectConsent = consentEnabled || schedule.hasMCPConsent === true;+const dropdownItems = useMemo(() => [- {- label: localize('com_ui_schedule_run_now'),- onClick: handleRunNow,- hideOnClick: false,- disabled: runSchedule.isLoading,- icon: runSchedule.isLoading ? (- <Spinner className="size-4" />- ) : (- <Play className="icon-sm text-text-primary mr-2" aria-hidden="true" />- ),- },- {- label: localize('com_ui_edit'),- onClick: () => setEditOpen(true),- icon: <Pencil className="icon-sm text-text-primary mr-2" aria-hidden="true" />,- ariaHasPopup: 'dialog' as const,- hideOnClick: false,- ref: editButtonRef,- render: (props) => <button {...props} />,- },- {- label: localize('com_ui_delete'),- onClick: () => setDeleteOpen(true),- icon: <Trash className="icon-sm text-text-primary mr-2" aria-hidden="true" />,- ariaHasPopup: 'dialog' as const,- hideOnClick: false,- ref: deleteButtonRef,- render: (props) => <button {...props} />,- },+ ...(canInspectConsent+ ? [+ {+ label: localize('com_ui_schedule_consent_title'),+ onClick: () => setConsentOpen(true),+ ariaHasPopup: 'dialog' as const,+ hideOnClick: false,+ ref: consentButtonRef,+ render: (props: React.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),+ },+ ]+ : []),+ ...(canWrite+ ? [+ {+ label: localize('com_ui_schedule_run_now'),+ onClick: handleRunNow,+ hideOnClick: false,+ disabled: runSchedule.isLoading,+ icon: runSchedule.isLoading ? (+ <Spinner className="size-4" />+ ) : (+ <Play className="icon-sm text-text-primary mr-2" aria-hidden="true" />+ ),+ },+ {+ label: localize('com_ui_edit'),+ onClick: () => setEditOpen(true),+ icon: <Pencil className="icon-sm text-text-primary mr-2" aria-hidden="true" />,+ ariaHasPopup: 'dialog' as const,+ hideOnClick: false,+ ref: editButtonRef,+ render: (props) => <button {...props} />,+ },+ {+ label: localize('com_ui_delete'),+ onClick: () => setDeleteOpen(true),+ icon: <Trash className="icon-sm text-text-primary mr-2" aria-hidden="true" />,+ ariaHasPopup: 'dialog' as const,+ hideOnClick: false,+ ref: deleteButtonRef,+ render: (props) => <button {...props} />,+ },+ ]+ : []),],- [localize, handleRunNow, runSchedule.isLoading],+ [localize, handleRunNow, runSchedule.isLoading, canInspectConsent, canWrite],);const lastRunConvoId = schedule.lastRun?.conversationId;@@ -356,20 +380,22 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardProp{localize('com_ui_schedule_last_run')}</Link>)}- {canWrite && (+ {(canWrite || canInspectConsent) && (/* Not the collapsible slot other rows use: this panel's rows end atthe sidebar's resize handle, and a slot collapsed to zero widthputs the switch's clickable point outside the panel entirely,under that handle, where no hover can ever reveal it. The menutrigger still fades in on row hover by itself. */<div className="flex shrink-0 items-center gap-2">- <Switch- checked={schedule.enabled}- onCheckedChange={handleToggle}- disabled={updateSchedule.isLoading}- aria-label={`${localize('com_ui_schedule_enabled')}: ${schedule.name}`}- className="shrink-0"- />+ {canWrite && (+ <Switch+ checked={schedule.enabled}+ onCheckedChange={handleToggle}+ disabled={updateSchedule.isLoading}+ aria-label={`${localize('com_ui_schedule_enabled')}: ${schedule.name}`}+ className="shrink-0"+ />+ )}<DropdownPopupportal={true}menuId={menuId}@@ -409,6 +435,15 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardProp/></div></div>+ {consentOpen && (+ <Consent+ canConfirm={canWrite}+ id={schedule.id}+ name={schedule.name}+ onOpenChange={setConsentOpen}+ triggerRef={consentButtonRef}+ />+ )}{editOpen && (<ScheduleDialogopen={editOpen}diff --git a/client/src/components/SidePanel/Schedules/SchedulePanel.tsx b/client/src/components/SidePanel/Schedules/SchedulePanel.tsxindex b7b07a961b..eb86eda373 100644--- a/client/src/components/SidePanel/Schedules/SchedulePanel.tsx+++ b/client/src/components/SidePanel/Schedules/SchedulePanel.tsx@@ -65,6 +65,7 @@ export default function SchedulePanel() {<div key={schedule.id} role="listitem"><ScheduleCardschedule={schedule}+ consentEnabled={data?.limits.mcpConsent === true}// The raw id is a poor label but an honest one: it only shows for a// project outside the loaded pages, and beats claiming no scope.projectName={diff --git a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsxnew file mode 100644index 0000000000..7c79fc9744--- /dev/null+++ b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx@@ -0,0 +1,176 @@+import { createRef } from 'react';+import userEvent from '@testing-library/user-event';+import { dataService } from 'librechat-data-provider';+import { render, screen, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { ScheduleMCPConsentView } from 'librechat-data-provider';+import Consent from '../Consent';++jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));+jest.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en-US' } }),+}));+jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getScheduleMCPConsent: jest.fn(),+ confirmScheduleMCPConsent: jest.fn(),+ revokeScheduleMCPConsent: jest.fn(),+ },+ };+});+const view: ScheduleMCPConsentView = {+ state: 'missing',+ revision: null,+ expiresAtMs: null,+ targets: [+ {+ resource: {+ serverName: 'warehouse',+ url: 'https://warehouse.example/mcp',+ issuer: 'https://issuer.example/',+ audience: 'warehouse',+ scopes: ['read'],+ credentialMode: 'resource_bearer',+ configurationRevision: 'v1',+ },+ policyRevision: 'p1',+ permittedTools: [{ agentId: 'root', tools: ['query'] }],+ },+ ],+ offer: { digest: 'a'.repeat(64), maxLifetimeHours: 24 },+};+function display() {+ const client = new QueryClient({+ logger: { log: console.log, warn: console.warn, error: jest.fn() },+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ render(+ <QueryClientProvider client={client}>+ <Consent id="schedule" name="Digest" onOpenChange={jest.fn()} triggerRef={createRef()} />+ </QueryClientProvider>,+ );+ return client;+}+beforeEach(() => {+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(view);+});+it('renders loading, then the exact agent/resource and bounded lifetime', async () => {+ let resolve!: (value: ScheduleMCPConsentView) => void;+ jest.mocked(dataService.getScheduleMCPConsent).mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ display();+ expect(screen.queryByText('warehouse')).not.toBeInTheDocument();+ resolve(view);+ expect(await screen.findByText('warehouse')).toBeVisible();+ expect(screen.getByText('root: query')).toBeVisible();+ expect(screen.getByRole('spinbutton')).toHaveAttribute('max', '24');+});+it('confirms only an offer reference and lifetime, then rereads persisted state', async () => {+ const active = {+ ...view,+ state: 'active' as const,+ revision: 'grant',+ expiresAtMs: Date.now() + 60_000,+ };+ jest.mocked(dataService.confirmScheduleMCPConsent).mockImplementation(async () => {+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(active);+ return active;+ });+ display();+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_schedule_consent_confirm' }),+ );+ await waitFor(() =>+ expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith('schedule', {+ offerDigest: view.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 1,+ }),+ );+ expect(await screen.findByText('com_ui_schedule_consent_active')).toBeVisible();+});+it('reopens with persisted expiry and explicitly revokes without enabling a schedule', async () => {+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({+ ...view,+ state: 'active',+ revision: 'grant',+ expiresAtMs: Date.now() + 60_000,+ });+ jest.mocked(dataService.revokeScheduleMCPConsent).mockImplementation(async () => {+ jest+ .mocked(dataService.getScheduleMCPConsent)+ .mockResolvedValue({ ...view, state: 'revoked', revision: 'revoked', offer: null });+ });+ display();+ expect(await screen.findByText('com_ui_schedule_consent_deadline')).toBeVisible();+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_revoke' }));+ await waitFor(() =>+ expect(dataService.revokeScheduleMCPConsent).toHaveBeenCalledWith('schedule', 'grant'),+ );+ await waitFor(() =>+ expect(+ screen.queryByRole('button', { name: 'com_ui_schedule_consent_revoke' }),+ ).not.toBeInTheDocument(),+ );+});+it('has no confirmation action when no trusted target resolver is installed', async () => {+ jest+ .mocked(dataService.getScheduleMCPConsent)+ .mockResolvedValue({ ...view, state: 'unsupported', targets: [], offer: null });+ display();+ expect(await screen.findByText('com_ui_schedule_consent_unsupported')).toBeVisible();+ expect(+ screen.queryByRole('button', { name: 'com_ui_schedule_consent_confirm' }),+ ).not.toBeInTheDocument();+});+it('shows API errors and retries without silently accepting a grant', async () => {+ jest.mocked(dataService.getScheduleMCPConsent).mockRejectedValueOnce(new Error('offline'));+ display();+ expect(await screen.findByText('com_ui_schedule_consent_error')).toBeVisible();+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ expect(await screen.findByText('warehouse')).toBeVisible();+});+it('reports a stale confirmation and reloads the current offer', async () => {+ jest.mocked(dataService.confirmScheduleMCPConsent).mockRejectedValueOnce(new Error('conflict'));+ display();+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_schedule_consent_confirm' }),+ );+ expect(await screen.findByText('com_ui_schedule_consent_error')).toBeVisible();+ await waitFor(() => expect(dataService.getScheduleMCPConsent).toHaveBeenCalledTimes(2));+});++it('keeps persisted inspection and revocation when CREATE is removed, without offering confirmation', async () => {+ const active = {+ ...view,+ state: 'active' as const,+ revision: 'grant',+ expiresAtMs: Date.now() + 60_000,+ };+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(active);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <Consent+ canConfirm={false}+ id="schedule"+ name="Digest"+ onOpenChange={jest.fn()}+ triggerRef={createRef()}+ />+ </QueryClientProvider>,+ );+ expect(+ await screen.findByRole('button', { name: 'com_ui_schedule_consent_revoke' }),+ ).toBeVisible();+ expect(+ screen.queryByRole('button', { name: 'com_ui_schedule_consent_confirm' }),+ ).not.toBeInTheDocument();+});diff --git a/client/src/components/SidePanel/Schedules/__tests__/ScheduleConsentAccess.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/ScheduleConsentAccess.spec.tsxnew file mode 100644index 0000000000..387fe84408--- /dev/null+++ b/client/src/components/SidePanel/Schedules/__tests__/ScheduleConsentAccess.spec.tsx@@ -0,0 +1,70 @@+import { MemoryRouter } from 'react-router-dom';+import { ToastProvider } from '@librechat/client';+import userEvent from '@testing-library/user-event';+import { render, screen } from '@testing-library/react';+import type { TSchedule } from 'librechat-data-provider';+import ScheduleCard from '../ScheduleCard';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useHasAccess: () => false,+ useClockFormat: () => true,+ useWeekStart: () => 0,+}));+jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({ root: { name: 'Root' } }) }));+jest.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en-US' } }),+ Trans: () => null,+}));+jest.mock('~/data-provider', () => ({+ useGetAgentByIdQuery: () => ({}),+ useDeleteScheduleMutation: () => ({ mutate: jest.fn(), isLoading: false }),+ useUpdateScheduleMutation: () => ({ mutate: jest.fn(), isLoading: false }),+ useRunScheduleNowMutation: () => ({ mutate: jest.fn(), isLoading: false }),+}));+jest.mock('../Consent', () => ({+ __esModule: true,+ default: ({ canConfirm }: { canConfirm: boolean }) => (+ <div data-testid="consent-inspection">{String(canConfirm)}</div>+ ),+}));+const schedule: TSchedule = {+ id: 'schedule',+ user: 'owner',+ name: 'Digest',+ prompt: 'Read',+ agent_id: 'root',+ cadence: { frequency: 'daily', hour: 8, minute: 0 },+ timezone: 'UTC',+ target: 'new',+ enabled: false,+ runCount: 0,+ failureCount: 0,+ createdAt: '',+ updatedAt: '',+};++it.each([false, true])(+ 'keeps inspection after CREATE removal, feature disabled=%s',+ async (disabled) => {+ render(+ <MemoryRouter>+ <ToastProvider>+ <ScheduleCard+ schedule={{ ...schedule, hasMCPConsent: disabled }}+ consentEnabled={!disabled}+ />+ </ToastProvider>+ </MemoryRouter>,+ );+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_options: Digest' }));+ await userEvent.click(+ await screen.findByRole('menuitem', { name: 'com_ui_schedule_consent_title' }),+ );+ expect(screen.getByTestId('consent-inspection')).toHaveTextContent('false');+ expect(+ screen.queryByRole('menuitem', { name: 'com_ui_schedule_run_now' }),+ ).not.toBeInTheDocument();+ expect(screen.queryByRole('switch')).not.toBeInTheDocument();+ },+);diff --git a/client/src/data-provider/Schedules/consent.ts b/client/src/data-provider/Schedules/consent.tsnew file mode 100644index 0000000000..dda80fae42--- /dev/null+++ b/client/src/data-provider/Schedules/consent.ts@@ -0,0 +1,34 @@+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';+import { QueryKeys, MutationKeys, dataService } from 'librechat-data-provider';+import type { ScheduleMCPConsentView, ConfirmScheduleMCPConsent } from 'librechat-data-provider';++export function useScheduleMCPConsent(id: string) {+ return useQuery<ScheduleMCPConsentView>(+ [QueryKeys.scheduleMCPConsent, id],+ () => dataService.getScheduleMCPConsent(id),+ {+ retry: false,+ refetchOnWindowFocus: true,+ refetchInterval: 30_000,+ },+ );+}++export function useScheduleMCPConsentMutations(id: string) {+ const queryClient = useQueryClient();+ const refresh = () => {+ void queryClient.invalidateQueries([QueryKeys.scheduleMCPConsent, id]);+ void queryClient.invalidateQueries([QueryKeys.schedules]);+ };+ const confirm = useMutation(+ [MutationKeys.confirmScheduleMCPConsent, id],+ (payload: ConfirmScheduleMCPConsent) => dataService.confirmScheduleMCPConsent(id, payload),+ { onSettled: refresh },+ );+ const revoke = useMutation(+ [MutationKeys.revokeScheduleMCPConsent, id],+ (revision: string) => dataService.revokeScheduleMCPConsent(id, revision),+ { onSettled: refresh },+ );+ return { confirm, revoke };+}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex d5c24812b6..4f702f5192 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -2122,7 +2122,7 @@"com_ui_passkey_never_used": "Never used","com_ui_passkey_password_incorrect": "Incorrect password. Please try again.","com_ui_passkey_remove": "Remove passkey",- "com_ui_passkey_remove_confirm": "Remove \u201c{{name}}\u201d?",+ "com_ui_passkey_remove_confirm": "Remove “{{name}}”?","com_ui_passkey_remove_description": "This passkey will no longer be available for sign-in.","com_ui_passkey_remove_error": "Could not remove the passkey","com_ui_passkey_removed": "Passkey removed",@@ -2267,7 +2267,6 @@"com_ui_asking_questions": "Asking {{0}} questions","com_ui_question_unanswered": "No answer was given","com_ui_queue": "Queue",- "com_ui_convert_to_queue": "Queue for after the response","com_ui_queue_edit_blocked": "Clear the message box in this chat, or finish answering the question, to edit this message.","com_ui_queue_moved": "Moved to {{0}} of {{1}}","com_ui_queue_reorder_blocked": "Queued turns already acknowledged by the server cannot be reordered.",@@ -3281,5 +3280,22 @@"com_insights_invalid_date_range": "Choose an end date after the start date, within {{days}} days.","com_insights_sparkline_accessibility": "{{label}} over time","com_nav_mobile_drawer_strip": "Show chat beside the sidebar on mobile",- "com_nav_mobile_drawer_strip_info": "The sidebar stops short of the edge so a strip of the conversation stays visible. Tapping it closes the sidebar."+ "com_nav_mobile_drawer_strip_info": "The sidebar stops short of the edge so a strip of the conversation stays visible. Tapping it closes the sidebar.",+ "com_ui_schedule_consent_title": "Scheduled MCP authorization",+ "com_ui_schedule_consent_boundary": "Authorize only the listed agent and resources until the fixed deadline. This does not reconnect a provider, enable the schedule or permit writes.",+ "com_ui_schedule_consent_missing": "Authorization required",+ "com_ui_schedule_consent_active": "Authorized",+ "com_ui_schedule_consent_expired": "Authorization expired. Confirm again to renew.",+ "com_ui_schedule_consent_revoked": "Authorization revoked",+ "com_ui_schedule_consent_changed": "The agent, schedule or resource binding changed. Review and confirm again.",+ "com_ui_schedule_consent_unsupported": "This deployment cannot resolve this scheduled MCP authorization. Existing schedules are unchanged.",+ "com_ui_schedule_consent_deadline": "Absolute expiry: {{time}}",+ "com_ui_schedule_consent_hours": "Authorization lifetime (hours)",+ "com_ui_schedule_consent_confirm": "Confirm authorization",+ "com_ui_schedule_consent_confirmed": "Authorization recorded. The schedule remains unchanged.",+ "com_ui_schedule_consent_revoke": "Revoke authorization",+ "com_ui_schedule_consent_error": "Authorization could not be updated. Reload the current state and try again.",+ "com_ui_schedule_consent_issuer": "Issuer: {{issuer}}",+ "com_ui_schedule_consent_audience": "Audience: {{audience}}",+ "com_ui_schedule_consent_scopes": "Scopes: {{scopes}}"}diff --git a/packages/api/src/schedules/authorization/configuration.spec.ts b/packages/api/src/schedules/authorization/configuration.spec.tsnew file mode 100644index 0000000000..758eb71dfd--- /dev/null+++ b/packages/api/src/schedules/authorization/configuration.spec.ts@@ -0,0 +1,241 @@+import type { ScheduledMCPResourceBinding } from 'librechat-data-provider';+import type { ParsedServerConfig } from '~/mcp/types';+import { getScheduledMCPConfigurationRevision } from './configuration';++const binding: ScheduledMCPResourceBinding = {+ url: 'https://warehouse.example/mcp',+ credentialMode: 'resource_bearer',+ issuer: 'https://issuer.example/',+ audience: 'warehouse',+ scopes: ['read'],+};+const config: Extract<ParsedServerConfig, { type: 'http' | 'streamable-http' }> = {+ type: 'streamable-http',+ url: binding.url,+ headers: { 'X-Workspace': 'catalog', Accept: 'application/json' },+ requestHeaders: { 'X-Workspace': 'chat', 'X-Account': 'account-1' },+ proxy: 'http://proxy-a.example/',+ dbId: 'server-1',+ source: 'config',+ author: 'author-1',+ oauth: {+ authorization_url: 'https://issuer.example/authorize',+ token_url: 'https://issuer.example/token',+ client_id: 'client-1',+ client_secret: 'fixture-secret',+ scope: 'read',+ audience: 'warehouse',+ },+ oauth_headers: { 'X-Authorization-Tenant': 'tenant-1' },+ apiKey: {+ source: 'admin',+ authorization_type: 'custom',+ custom_header: 'X-Api-Key',+ key: 'fixture-key',+ },+};++it.each<Partial<Extract<ParsedServerConfig, { type: 'http' | 'streamable-http' }>>>([+ { headers: { ...config.headers, 'X-Workspace': 'catalog-2' } },+ { requestHeaders: { ...config.requestHeaders, 'X-Workspace': 'chat-2' } },+ { proxy: 'http://proxy-b.example/' },+ { dbId: 'server-2' },+ { source: 'user' },+ { author: 'author-2' },+ { oauth: { ...config.oauth, audience: 'other-recipient' } },+ { oauth: { ...config.oauth, scope: 'read write' } },+ { oauth_headers: { 'X-Authorization-Tenant': 'tenant-2' } },+ { apiKey: { ...config.apiKey!, custom_header: 'X-Other-Key' } },+])('changes the consent fence for changed routing or trust: %j', (change) => {+ expect(getScheduledMCPConfigurationRevision({ ...config, ...change }, binding)).not.toBe(+ getScheduledMCPConfigurationRevision(config, binding),+ );+});++it('does not collapse catalog routing into request-header overrides', () => {+ const first = {+ ...config,+ headers: { 'X-Workspace': 'catalog-1' },+ requestHeaders: { 'X-Workspace': 'chat' },+ };+ expect(getScheduledMCPConfigurationRevision(first, binding)).not.toBe(+ getScheduledMCPConfigurationRevision(+ { ...first, headers: { 'X-Workspace': 'catalog-2' } },+ binding,+ ),+ );+});++it('canonicalizes map order and scope sets without widening a recipient', () => {+ const reordered = {+ ...config,+ headers: { Accept: 'application/json', 'X-Workspace': 'catalog' },+ requestHeaders: { 'X-Account': 'account-1', 'X-Workspace': 'chat' },+ oauth: Object.fromEntries(Object.entries(config.oauth!).reverse()),+ };+ expect(+ getScheduledMCPConfigurationRevision(reordered, { ...binding, scopes: ['read', 'read'] }),+ ).toBe(getScheduledMCPConfigurationRevision(config, binding));+});++it('excludes rotating client/API secrets and display/inspection bookkeeping', () => {+ expect(+ getScheduledMCPConfigurationRevision(+ {+ ...config,+ oauth: { ...config.oauth, client_secret: 'rotated-fixture-secret' },+ apiKey: { ...config.apiKey!, key: 'rotated-fixture-key' },+ title: 'A new title',+ description: 'A new description',+ updatedAt: 2000,+ resolvedInstructions: 'A new inspection result',+ },+ binding,+ ),+ ).toBe(getScheduledMCPConfigurationRevision(config, binding));+});++it('fences effective operator routing across environment changes', () => {+ const variable = 'LC_SCHEDULE_CONSENT_ROUTE_FIXTURE';+ const previous = process.env[variable];+ const declared: ParsedServerConfig = {+ ...config,+ dbId: undefined,+ source: 'yaml',+ headers: { 'X-Workspace': `\${${variable}}` },+ requestHeaders: { 'X-Workspace': `\${${variable}}` },+ };+ try {+ process.env[variable] = 'workspace-a';+ const before = getScheduledMCPConfigurationRevision(declared, binding);+ process.env[variable] = 'workspace-b';+ expect(getScheduledMCPConfigurationRevision(declared, binding)).not.toBe(before);+ expect(declared.headers).toEqual({ 'X-Workspace': `\${${variable}}` });+ expect(declared.requestHeaders).toEqual({ 'X-Workspace': `\${${variable}}` });+ } finally {+ if (previous === undefined) delete process.env[variable];+ else process.env[variable] = previous;+ }+});++it('preserves literal templates for DB/plugin sources rather than reading host environment', () => {+ const variable = 'LC_SCHEDULE_CONSENT_LITERAL_FIXTURE';+ const previous = process.env[variable];+ try {+ for (const source of ['user', 'plugin'] as const) {+ const declared: ParsedServerConfig = {+ type: 'streamable-http',+ url: binding.url,+ source,+ dbId: source === 'user' ? 'server-1' : undefined,+ headers: { 'X-Workspace': `\${${variable}}` },+ };+ process.env[variable] = 'workspace-a';+ const before = getScheduledMCPConfigurationRevision(declared, binding);+ process.env[variable] = 'workspace-b';+ expect(getScheduledMCPConfigurationRevision(declared, binding)).toBe(before);+ }+ } finally {+ if (previous === undefined) delete process.env[variable];+ else process.env[variable] = previous;+ }+});++it.each(['headers', 'requestHeaders', 'oauth_headers'] as const)(+ 'refuses unresolved custom routing in %s rather than hashing an unbound template',+ (field) => {+ expect(() =>+ getScheduledMCPConfigurationRevision(+ {+ ...config,+ [field]: { 'X-Workspace': '{{WORKSPACE}}' },+ customUserVars: {+ WORKSPACE: { title: 'Workspace', description: 'Routing recipient', sensitive: false },+ },+ },+ binding,+ ),+ ).toThrow('consent_unavailable');+ },+);+it('refuses dynamic user/body routing and custom placeholders in authorization headers', () => {+ for (const template of [+ '{{LIBRECHAT_USER_EMAIL}}',+ '{{LIBRECHAT_BODY_CONVERSATIONID}}',+ '{{WORKSPACE}}',+ ]) {+ expect(() =>+ getScheduledMCPConfigurationRevision(+ { ...config, headers: { 'X-Workspace': template } },+ binding,+ ),+ ).toThrow('consent_unavailable');+ expect(() =>+ getScheduledMCPConfigurationRevision(+ { ...config, headers: { Authorization: `Bearer ${template}` } },+ binding,+ ),+ ).toThrow('consent_unavailable');+ }+});+it('refuses routing templates introduced by operator environment resolution', () => {+ const variable = 'LC_CONSENT_UNBOUND_ROUTE_FIXTURE';+ const previous = process.env[variable];+ try {+ process.env[variable] = '{{WORKSPACE}}';+ expect(() =>+ getScheduledMCPConfigurationRevision(+ {+ ...config,+ dbId: undefined,+ source: 'yaml',+ headers: { 'X-Workspace': `\${${variable}}` },+ },+ binding,+ ),+ ).toThrow('consent_unavailable');+ } finally {+ if (previous === undefined) delete process.env[variable];+ else process.env[variable] = previous;+ }+});+it('preserves literal-source resource and OAuth URLs across replica environment changes', () => {+ const variable = 'LC_CONSENT_LITERAL_URL_FIXTURE';+ const previous = process.env[variable];+ try {+ for (const source of ['user', 'plugin'] as const) {+ const declared: ParsedServerConfig = {+ type: 'streamable-http',+ url: `https://warehouse.example/\${${variable}}`,+ dbId: source === 'user' ? 'server' : undefined,+ source,+ proxy: `http://proxy.example/\${${variable}}`,+ oauth: {+ authorization_url: `https://issuer.example/\${${variable}}/authorize`,+ token_url: `https://issuer.example/\${${variable}}/token`,+ },+ };+ process.env[variable] = 'one';+ const before = getScheduledMCPConfigurationRevision(declared, {+ ...binding,+ url: declared.url!,+ });+ process.env[variable] = 'two';+ expect(+ getScheduledMCPConfigurationRevision(declared, { ...binding, url: declared.url! }),+ ).toBe(before);+ expect(declared.url).toContain(`\${${variable}}`);+ }+ } finally {+ if (previous === undefined) delete process.env[variable];+ else process.env[variable] = previous;+ }+});+it('keeps plugin custom templates literal because their runtime never substitutes them', () => {+ const literal = {+ ...config,+ source: 'plugin' as const,+ headers: { 'X-Workspace': '{{WORKSPACE}}' },+ };+ expect(getScheduledMCPConfigurationRevision(literal, binding)).toMatch(/^[a-f0-9]{64}$/);+});diff --git a/packages/api/src/schedules/authorization/configuration.ts b/packages/api/src/schedules/authorization/configuration.tsnew file mode 100644index 0000000000..cc6474d1c7--- /dev/null+++ b/packages/api/src/schedules/authorization/configuration.ts@@ -0,0 +1,98 @@+import { createHash } from 'node:crypto';+import type { ScheduledMCPResourceBinding } from 'librechat-data-provider';+import type { ParsedServerConfig } from '~/mcp/types';+import { processMCPEnv, isPluginSourced } from '~/utils/env';+import { ScheduleMCPConsentError } from './service';++type IdentityValue =+ | string+ | number+ | boolean+ | null+ | undefined+ | IdentityValue[]+ | { [key: string]: IdentityValue };++function canonical(value: IdentityValue): IdentityValue {+ if (Array.isArray(value)) return value.map(canonical);+ if (value == null || typeof value !== 'object') return value;+ return Object.fromEntries(+ Object.keys(value)+ .sort()+ .map((key) => [key, canonical(value[key])]),+ );+}++function hasTemplate(value: IdentityValue): boolean {+ if (typeof value === 'string') return value.includes('{{');+ if (Array.isArray(value)) return value.some(hasTemplate);+ return value != null && typeof value === 'object' && Object.values(value).some(hasTemplate);+}++/** Live provider credentials may vary; unbound routing variables may not. */+function hasRoutingTemplate(headers?: Record<string, string>): boolean {+ return Object.entries(headers ?? {}).some(([name, value]) => {+ const routing =+ name.toLowerCase() === 'authorization'+ ? value.replace(+ /\{\{LIBRECHAT_(?:OPENID_(?:ACCESS_TOKEN|ID_TOKEN|TOKEN)|GRAPH_ACCESS_TOKEN)\}\}/g,+ '',+ )+ : value;+ return hasTemplate(name) || hasTemplate(routing);+ });+}++/** Binds effective routing and trust without retaining tokens or rotating client/API secrets. */+export function getScheduledMCPConfigurationRevision(+ config: ParsedServerConfig,+ binding: ScheduledMCPResourceBinding,+): string {+ if (config.type !== 'sse' && config.type !== 'http' && config.type !== 'streamable-http')+ throw new ScheduleMCPConsentError('consent_unavailable');+ const declared = {+ type: config.type,+ url: config.url,+ dbId: config.dbId,+ source: config.source,+ headers: config.headers,+ requestHeaders: config.requestHeaders,+ proxy: config.proxy,+ requiresOAuth: config.requiresOAuth,+ oauth: config.oauth && { ...config.oauth, client_secret: undefined },+ oauth_headers: config.oauth_headers,+ obo: config.obo,+ apiKey: config.apiKey && { ...config.apiKey, key: undefined },+ };+ const runtime = processMCPEnv({ options: declared });+ if (runtime.type !== 'sse' && runtime.type !== 'http' && runtime.type !== 'streamable-http')+ throw new ScheduleMCPConsentError('consent_unavailable');+ const request = processMCPEnv({ options: { ...declared, headers: config.requestHeaders } });+ const requestHeaders = 'headers' in request ? request.headers : undefined;+ if (+ !isPluginSourced(config) &&+ (hasTemplate([runtime.url, runtime.proxy, runtime.oauth, runtime.obo]) ||+ hasRoutingTemplate(runtime.headers) ||+ hasRoutingTemplate(requestHeaders) ||+ hasRoutingTemplate(runtime.oauth_headers))+ )+ throw new ScheduleMCPConsentError('consent_unavailable');+ // Do not reparse through transforming schemas: plugin/DB URLs must remain literal.+ return createHash('sha256')+ .update(+ JSON.stringify(+ canonical([+ { ...runtime, requestHeaders },+ config.dbId ?? null,+ config.source ?? null,+ config.author ?? null,+ binding.url,+ binding.credentialMode,+ binding.issuer,+ binding.audience,+ [...new Set(binding.scopes)].sort(),+ ]),+ ),+ )+ .digest('hex');+}diff --git a/packages/api/src/schedules/authorization/contract.ts b/packages/api/src/schedules/authorization/contract.tsindex 30946c9dfe..c90b16869e 100644--- a/packages/api/src/schedules/authorization/contract.ts+++ b/packages/api/src/schedules/authorization/contract.ts@@ -1,47 +1,17 @@-import type { ScheduleMCPOutcome } from 'librechat-data-provider';-import type { ScheduledTokenContext } from '../context';--export type ScheduledMCPCredentialMode =- | 'stored_oauth'- | 'browser_bearer'- | 'renewable_obo'- | 'resource_bearer'- | 'static'- | 'anonymous';--/** agentId remains the enrolled root, including during child execution. */-export interface ScheduledMCPIdentity extends Omit<ScheduledTokenContext, 'tenantId'> {- readonly tenantId: string | null;-}--/** Resolved by trusted configuration, never by model arguments or token scopes. */-export interface ScheduledMCPResource {- readonly serverName: string;- readonly url: string;- readonly configurationRevision: string;- readonly credentialMode: ScheduledMCPCredentialMode;- readonly issuer: string | null;- readonly audience: string | null;- readonly scopes: readonly string[];-}--export interface ScheduledMCPToolSelection {- readonly agentId: string;- readonly tools: readonly string[];-}--export interface ScheduledMCPConsent {- readonly id: string;- readonly revision: string;- readonly identity: ScheduledMCPIdentity;- readonly resource: ScheduledMCPResource;- readonly permittedTools: readonly ScheduledMCPToolSelection[];- readonly policyRevision: string;- readonly grantedAtMs: number;- /** Fixed consent deadline; credential renewal cannot extend it. */- readonly absoluteExpiresAtMs: number;- readonly revokedAtMs: number | null;-}+import type {+ ScheduleMCPOutcome,+ ScheduledMCPIdentity,+ ScheduledMCPResource,+ ScheduledMCPConsent,+ ScheduledMCPToolSelection,+} from 'librechat-data-provider';+export type {+ ScheduledMCPCredentialMode,+ ScheduledMCPIdentity,+ ScheduledMCPResource,+ ScheduledMCPConsent,+ ScheduledMCPToolSelection,+} from 'librechat-data-provider';export type ScheduledMCPFailureReason =| 'consent_missing'diff --git a/packages/api/src/schedules/authorization/enrollment.spec.ts b/packages/api/src/schedules/authorization/enrollment.spec.tsnew file mode 100644index 0000000000..8513efe12a--- /dev/null+++ b/packages/api/src/schedules/authorization/enrollment.spec.ts@@ -0,0 +1,356 @@+import { Types } from 'mongoose';+import { Permissions, PermissionTypes } from 'librechat-data-provider';+import type { ScheduleMCPConsentStorage, ScheduleConsentSnapshot } from '@librechat/data-schemas';+import type { IUser, AppConfig, AgentGraphAccessContext } from '@librechat/data-schemas';+import type { ScheduledMCPIdentity } from 'librechat-data-provider';+import type { ScheduleMCPEnrollmentDeps } from './enrollment';+import type { ParsedServerConfig } from '~/mcp/types';+import { createScheduleMCPEnrollmentResolver } from './enrollment';+import { createScheduleMCPConsentService } from './service';+import { createResolveAgentFireAccess } from '../access';++const identity: ScheduledMCPIdentity = {+ scheduleId: 's',+ ownerId: 'u',+ tenantId: 't',+ agentId: 'root',+ invocationMode: 'delegated',+};+function setup() {+ const deps: ScheduleMCPEnrollmentDeps = {+ getModelsConfig: jest.fn(async () => ({ test: ['test'] })),+ canUseRoot: jest.fn(async () => true),+ findUser: jest.fn(async () => ({ id: 'u', tenantId: 't', role: 'USER' }) as IUser),+ getAppConfig: jest.fn(async () =>+ Object.assign({} as AppConfig, {+ interfaceConfig: {+ schedules: {+ mcpConsent: {+ enabled: true,+ resources: {+ warehouse: {+ url: 'https://warehouse.example/mcp',+ credentialMode: 'resource_bearer',+ issuer: 'https://issuer.example/',+ audience: 'warehouse',+ scopes: ['read'],+ },+ },+ },+ },+ },+ mcpConfig: {+ warehouse: { type: 'streamable-http', url: 'https://warehouse.example/mcp' },+ },+ }),+ ),+ resolveGraphAccess: jest.fn(async () => ({}) as AgentGraphAccessContext),+ getNodes: jest.fn(async (ids) =>+ ids.map((id) => ({ id, provider: 'test', model: 'test', tools: ['query_mcp_warehouse'] })),+ ),+ getServers: jest.fn(async (_user, config) => config),+ };+ return { deps, resolve: createScheduleMCPEnrollmentResolver(deps) };+}+it('resolves the configured root and declared resource without credentials or a connection', async () => {+ const { resolve, deps } = setup();+ const targets = await resolve(identity, {});+ expect(targets).toHaveLength(1);+ expect(targets[0].permittedTools).toEqual([{ agentId: 'root', tools: ['query'] }]);+ expect(targets[0].resource.audience).toBe('warehouse');+ expect(targets[0].resource.configurationRevision).toMatch(/^[a-f0-9]{64}$/);+ expect(deps.getServers).toHaveBeenCalledTimes(1);+});+it('binds reachable persisted child selections without transferring the enrolled root', async () => {+ const { deps, resolve } = setup();+ jest.mocked(deps.getNodes).mockImplementation(async (ids) =>+ ids.map((id) => ({+ id,+ provider: 'test',+ model: 'test',+ tools: ['query_mcp_warehouse'],+ agent_ids: id === 'root' ? ['child'] : [],+ })),+ );+ expect((await resolve(identity, {}))[0].permittedTools.map((s) => s.agentId)).toEqual([+ 'child',+ 'root',+ ]);+});+it('does not enroll an inaccessible child that runtime skips', async () => {+ const { deps, resolve } = setup();+ jest+ .mocked(deps.getNodes)+ .mockResolvedValueOnce([+ {+ id: 'root',+ provider: 'test',+ model: 'test',+ tools: ['query_mcp_warehouse'],+ agent_ids: ['private-child'],+ },+ ])+ .mockResolvedValueOnce([]);+ expect((await resolve(identity, {}))[0].permittedTools.map((s) => s.agentId)).toEqual(['root']);+});+it('requires operator-declared recipient metadata, not a successful login or tool hint', async () => {+ const { deps, resolve } = setup();+ jest.mocked(deps.getAppConfig).mockResolvedValue({+ interfaceConfig: { schedules: { mcpConsent: { enabled: true } } },+ } as AppConfig);+ expect(await resolve(identity, {})).toEqual([]);+});+it('denies a changed resource URL even if the configured server name is unchanged', async () => {+ const { deps, resolve } = setup();+ jest.mocked(deps.getServers).mockResolvedValue({+ warehouse: { type: 'streamable-http', url: 'https://other.example/mcp' },+ });+ await expect(resolve(identity, {})).rejects.toMatchObject({ code: 'consent_unavailable' });+});+it('does not expand wildcard tools into rolling consent', async () => {+ const { deps, resolve } = setup();+ jest+ .mocked(deps.getNodes)+ .mockResolvedValue([+ { id: 'root', provider: 'test', model: 'test', tools: ['sys__all__sys_mcp_warehouse'] },+ ]);+ await expect(resolve(identity, {})).rejects.toMatchObject({ code: 'consent_unavailable' });+});+it('denies an owner/tenant mismatch and cancellation before resolving resources', async () => {+ const { deps, resolve } = setup();+ await expect(resolve({ ...identity, tenantId: 'other' }, {})).rejects.toMatchObject({+ code: 'consent_forbidden',+ });+ const controller = new AbortController();+ controller.abort();+ await expect(resolve(identity, { signal: controller.signal })).rejects.toThrow();+ expect(deps.getServers).not.toHaveBeenCalled();+});++it('honors capability-only root access without bypassing descendant VIEW checks', async () => {+ const { deps, resolve } = setup();+ const rootAccess = createResolveAgentFireAccess({+ findAgentObjectId: async () => ({ _id: new Types.ObjectId() }),+ getRoleByName: async () => ({+ permissions: { [PermissionTypes.AGENTS]: { [Permissions.USE]: true } },+ }),+ hasCapability: async () => true,+ checkPermission: async () => false,+ });+ deps.canUseRoot = jest.fn(async (id, user) => (await rootAccess(id, user)) === 'ok');+ jest.mocked(deps.getNodes).mockImplementation(async (ids, access) => {+ if (ids.includes('root'))+ return access+ ? []+ : [+ {+ id: 'root',+ provider: 'test',+ model: 'test',+ tools: ['query_mcp_warehouse'],+ agent_ids: ['child'],+ },+ ];+ return [{ id: 'child', provider: 'test', model: 'test', tools: ['query_mcp_warehouse'] }];+ });+ expect((await resolve(identity, {}))[0].permittedTools.map((s) => s.agentId)).toEqual([+ 'child',+ 'root',+ ]);+ expect(deps.canUseRoot).toHaveBeenCalledWith(+ 'root',+ expect.objectContaining({ id: 'u', tenantId: 't' }),+ );+ expect(deps.getNodes).toHaveBeenNthCalledWith(1, ['root']);+ expect(deps.getNodes).toHaveBeenNthCalledWith(2, ['child'], expect.any(Object));+});+it('does not load an unauthorized root through the unfiltered loader', async () => {+ const { deps, resolve } = setup();+ jest.mocked(deps.canUseRoot).mockResolvedValue(false);+ await expect(resolve(identity, {})).rejects.toMatchObject({ code: 'consent_forbidden' });+ expect(deps.getNodes).not.toHaveBeenCalled();+});++it('does not expand saved edges of a legacy-chain member', async () => {+ const { deps, resolve } = setup();+ jest.mocked(deps.getNodes).mockImplementation(async (ids) =>+ ids.map((id) => ({+ id,+ provider: 'test',+ model: 'test',+ tools: ['query_mcp_warehouse'],+ agent_ids: id === 'root' ? ['legacy'] : [],+ edges: id === 'legacy' ? [{ from: 'legacy', to: 'private-child' }] : [],+ })),+ );+ expect((await resolve(identity, {}))[0].permittedTools.map((s) => s.agentId)).toEqual([+ 'legacy',+ 'root',+ ]);+ expect(jest.mocked(deps.getNodes).mock.calls.flatMap(([ids]) => ids)).not.toContain(+ 'private-child',+ );+});++it.each<Partial<Extract<ParsedServerConfig, { type: 'http' | 'streamable-http' }>>>([+ { headers: { 'X-Workspace': 'other' } },+ { requestHeaders: { 'X-Account': 'other' } },+ { proxy: 'http://other-proxy.example/' },+ { dbId: 'other-server' },+])('requires fresh confirmation at every stage after a routing change: %j', async (change) => {+ const { deps, resolve } = setup();+ let server: Extract<ParsedServerConfig, { type: 'http' | 'streamable-http' }> = {+ type: 'streamable-http',+ url: 'https://warehouse.example/mcp',+ headers: { 'X-Workspace': 'original' },+ requestHeaders: { 'X-Account': 'original' },+ proxy: 'http://proxy.example/',+ dbId: 'original-server',+ };+ jest.mocked(deps.getServers).mockImplementation(async () => ({ warehouse: server }));+ const snapshot: ScheduleConsentSnapshot = {+ agentId: 'root',+ enabled: true,+ configRevision: 0,+ enrollment: null,+ };+ const admit = jest.fn(async () => true);+ const storage: ScheduleMCPConsentStorage = {+ readScheduleMCPConsent: async () => structuredClone(snapshot),+ confirmScheduleMCPConsent: async ({ enrollment }) => {+ snapshot.enrollment = enrollment;+ return true;+ },+ revokeScheduleMCPConsent: async () => true,+ admitScheduleMCPConsent: admit,+ };+ const service = createScheduleMCPConsentService({+ storage,+ resolveEnrollment: resolve,+ getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),+ canUse: async () => true,+ checkToolPolicy: async () => true,+ now: () => 1000,+ });+ const preview = await service.view(identity);+ const input = { offerDigest: preview.offer!.digest, expectedRevision: null, lifetimeHours: 1 };+ const enrolled = await service.confirm(identity, input);+ const oldResource = snapshot.enrollment!.consents[0].resource;+ server = { ...server, ...change };+ expect((await service.view(identity)).state).toBe('changed');+ await expect(+ service.confirm(identity, { ...input, expectedRevision: enrolled.revision }),+ ).rejects.toMatchObject({ code: 'consent_changed' });+ for (const stage of ['activation', 'mint', 'invoke', 'resume'] as const) {+ expect(+ await service.authority.authorize(+ {+ identity,+ resource: oldResource,+ stage,+ selection: { agentId: 'root', tools: ['query'] },+ },+ {},+ ),+ ).toMatchObject({ state: 'denied', failure: { reason: 'binding_mismatch' } });+ }+ expect(admit).not.toHaveBeenCalled();+ const fresh = await service.view(identity);+ await service.confirm(identity, {+ ...input,+ offerDigest: fresh.offer!.digest,+ expectedRevision: fresh.revision,+ });+ expect(+ await service.authority.authorize(+ {+ identity,+ resource: snapshot.enrollment!.consents[0].resource,+ stage: 'invoke',+ selection: { agentId: 'root', tools: ['query'] },+ },+ {},+ ),+ ).toMatchObject({ state: 'authorized' });+});++it('does not bind consent to renewed user tokens or client secrets', async () => {+ const { deps, resolve } = setup();+ const user = Object.assign({} as IUser, {+ id: 'u',+ tenantId: 't',+ role: 'USER',+ federatedTokens: {+ access_token: 'fixture-access-one',+ refresh_token: 'fixture-refresh-one',+ expires_at: 10000,+ },+ });+ let secret = 'fixture-secret-one';+ jest.mocked(deps.findUser).mockImplementation(async () => user);+ jest.mocked(deps.getServers).mockImplementation(async () => ({+ warehouse: {+ type: 'streamable-http',+ url: 'https://warehouse.example/mcp',+ headers: {+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ 'X-Workspace': 'original',+ },+ oauth: {+ client_id: 'client',+ client_secret: secret,+ authorization_url: 'https://issuer.example/authorize',+ token_url: 'https://issuer.example/token',+ },+ },+ }));+ const before = await resolve(identity, {});+ secret = 'fixture-secret-two';+ user.federatedTokens = {+ access_token: 'fixture-access-two',+ refresh_token: 'fixture-refresh-two',+ expires_at: 20000,+ };+ expect(await resolve(identity, {})).toEqual(before);+});++it('does not offer owner consent for recipient-defining custom user variables', async () => {+ const { deps, resolve } = setup();+ jest.mocked(deps.getServers).mockResolvedValue({+ warehouse: {+ type: 'streamable-http',+ url: 'https://warehouse.example/mcp',+ headers: { 'X-Workspace': '{{WORKSPACE}}' },+ customUserVars: {+ WORKSPACE: { title: 'Workspace', description: 'Recipient', sensitive: false },+ },+ },+ });+ const snapshot: ScheduleConsentSnapshot = {+ agentId: 'root',+ enabled: true,+ configRevision: 0,+ enrollment: null,+ };+ const confirm = jest.fn(async () => true);+ const service = createScheduleMCPConsentService({+ storage: {+ readScheduleMCPConsent: async () => snapshot,+ confirmScheduleMCPConsent: confirm,+ revokeScheduleMCPConsent: async () => true,+ admitScheduleMCPConsent: async () => true,+ },+ resolveEnrollment: resolve,+ getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),+ canUse: async () => true,+ });+ await expect(service.view(identity)).rejects.toMatchObject({ code: 'consent_unavailable' });+ await expect(+ service.confirm(identity, {+ offerDigest: 'a'.repeat(64),+ expectedRevision: null,+ lifetimeHours: 1,+ }),+ ).rejects.toMatchObject({ code: 'consent_unavailable' });+ expect(confirm).not.toHaveBeenCalled();+});diff --git a/packages/api/src/schedules/authorization/enrollment.ts b/packages/api/src/schedules/authorization/enrollment.tsnew file mode 100644index 0000000000..182876b53e--- /dev/null+++ b/packages/api/src/schedules/authorization/enrollment.ts@@ -0,0 +1,130 @@+import { createHash } from 'node:crypto';+import {+ Constants,+ buildServerNameAliases,+ splitMCPToolKey,+ scheduledMCPResourceBindingSchema,+} from 'librechat-data-provider';+import type {+ AgentGraphAccessContext,+ AgentGraphNode,+ IUser,+ AppConfig,+} from '@librechat/data-schemas';+import type { ScheduledMCPTarget, TModelsConfig } from 'librechat-data-provider';+import type { ScheduleMCPEnrollmentResolver } from './service';+import type { GetAppConfigOptions } from '~/app/service';+import type { ParsedServerConfig } from '~/mcp/types';+import { getScheduledMCPConfigurationRevision } from './configuration';+import { resolveScheduledMCPRequirements } from '../requirements';+import { getAppConfigOptionsFromUser } from '~/app/service';+import { ScheduleMCPConsentError } from './service';++export interface ScheduleMCPEnrollmentDeps {+ findUser: (id: string) => Promise<IUser | null>;+ canUseRoot: (agentId: string, user: IUser) => Promise<boolean>;+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig | undefined>;+ resolveGraphAccess: (user: IUser) => Promise<AgentGraphAccessContext>;+ getNodes: (ids: string[], access?: AgentGraphAccessContext) => Promise<AgentGraphNode[]>;+ getModelsConfig: (user: IUser) => Promise<TModelsConfig>;+ getServers: (+ user: IUser,+ config: Record<string, ParsedServerConfig>,+ ) => Promise<Record<string, ParsedServerConfig>>;+}++/** Resolves persisted selections and operator-declared recipients without connecting or minting. */+export function createScheduleMCPEnrollmentResolver(+ deps: ScheduleMCPEnrollmentDeps,+): ScheduleMCPEnrollmentResolver {+ return async (identity, { signal }) => {+ signal?.throwIfAborted();+ const user = await deps.findUser(identity.ownerId);+ if (!user || (user.tenantId ?? null) !== identity.tenantId)+ throw new ScheduleMCPConsentError('consent_forbidden');+ user.id = identity.ownerId;+ if (!(await deps.canUseRoot(identity.agentId, user)))+ throw new ScheduleMCPConsentError('consent_forbidden');+ const appConfig = await deps.getAppConfig({+ ...getAppConfigOptionsFromUser(user),+ failClosed: true,+ });+ const schedules = appConfig?.interfaceConfig?.schedules;+ const bindings = typeof schedules === 'object' ? schedules?.mcpConsent?.resources : undefined;+ if (!bindings || !Object.keys(bindings).length) return [];+ const servers = await deps.getServers(+ user,+ (appConfig?.mcpConfig ?? {}) as Record<string, ParsedServerConfig>,+ );+ const names = Object.keys(servers);+ const aliases = buildServerNameAliases(names);+ const candidates = [...names, ...aliases.keys()];+ const { tools } = await resolveScheduledMCPRequirements(+ identity.agentId,+ user,+ {+ getAgentGraphNodes: deps.getNodes,+ resolveAgentGraphAccess: () => deps.resolveGraphAccess(user),+ getModelsConfig: deps.getModelsConfig,+ },+ async () => appConfig,+ signal,+ );+ const selected = new Map<string, Map<string, Set<string>>>();+ for (const { name: key, agentId } of tools) {+ if (+ !key.includes(Constants.mcp_delimiter) ||+ key.startsWith(`${Constants.mcp_server}${Constants.mcp_delimiter}`)+ )+ continue;+ if (key.startsWith(`${Constants.mcp_all}${Constants.mcp_delimiter}`))+ throw new ScheduleMCPConsentError('consent_unavailable');+ const [tool, alias] = splitMCPToolKey(key, candidates);+ if (!alias) throw new ScheduleMCPConsentError('consent_unavailable');+ const name = servers[alias] ? alias : aliases.get(alias);+ if (!name || !tool) throw new ScheduleMCPConsentError('consent_unavailable');+ const agents = selected.get(name) ?? new Map<string, Set<string>>();+ const names_ = agents.get(agentId) ?? new Set<string>();+ names_.add(tool);+ agents.set(agentId, names_);+ selected.set(name, agents);+ }+ const targets = new Map<string, ScheduledMCPTarget>();+ for (const [name, agents] of selected) {+ const config = servers[name];+ const binding = scheduledMCPResourceBindingSchema.safeParse(bindings[name]);+ if (+ !binding.success ||+ !config ||+ !('url' in config) ||+ config.url !== binding.data.url ||+ binding.data.credentialMode === 'browser_bearer'+ )+ throw new ScheduleMCPConsentError('consent_unavailable');+ const metadata = binding.data;+ if (+ ['stored_oauth', 'renewable_obo', 'resource_bearer'].includes(metadata.credentialMode) &&+ (!metadata.issuer || !metadata.audience)+ )+ throw new ScheduleMCPConsentError('consent_unavailable');+ const configurationRevision = getScheduledMCPConfigurationRevision(config, metadata);+ targets.set(name, {+ resource: { ...metadata, serverName: name, configurationRevision },+ policyRevision: '',+ permittedTools: [...agents].map(([agentId, selectedTools]) => ({+ agentId,+ tools: [...selectedTools].sort(),+ })),+ });+ }+ signal?.throwIfAborted();+ for (const target of targets.values()) {+ target.permittedTools.sort((a, b) => a.agentId.localeCompare(b.agentId));+ // Selection revision is not read-only certification; invocation still requires trusted policy.+ target.policyRevision = createHash('sha256')+ .update(JSON.stringify(target.permittedTools))+ .digest('hex');+ }+ return [...targets.values()];+ };+}diff --git a/packages/api/src/schedules/authorization/failures.ts b/packages/api/src/schedules/authorization/failures.tsnew file mode 100644index 0000000000..b050dc9a52--- /dev/null+++ b/packages/api/src/schedules/authorization/failures.ts@@ -0,0 +1,89 @@+import type { ScheduledMCPFailure } from './contract';++export const failureFixtures: Readonly<Record<ScheduledMCPFailure['reason'], ScheduledMCPFailure>> =+ {+ consent_missing: {+ reason: 'consent_missing',+ status: 'mcp_reauth_required',+ recovery: 'authorize',+ automaticReplay: false,+ },+ consent_expired: {+ reason: 'consent_expired',+ status: 'mcp_reauth_required',+ recovery: 'authorize',+ automaticReplay: false,+ },+ consent_revoked: {+ reason: 'consent_revoked',+ status: 'mcp_reauth_required',+ recovery: 'authorize',+ automaticReplay: false,+ },+ binding_mismatch: {+ reason: 'binding_mismatch',+ status: 'mcp_reauth_required',+ recovery: 'authorize',+ automaticReplay: false,+ },+ rbac_denied: {+ reason: 'rbac_denied',+ status: 'mcp_permission_denied',+ recovery: 'restore_permission',+ automaticReplay: false,+ },+ tool_policy_denied: {+ reason: 'tool_policy_denied',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ },+ approval_required: {+ reason: 'approval_required',+ status: 'mcp_permission_denied',+ recovery: 'configure',+ automaticReplay: false,+ },+ credential_missing: {+ reason: 'credential_missing',+ status: 'mcp_reauth_required',+ recovery: 'authorize',+ automaticReplay: false,+ },+ credential_rejected: {+ reason: 'credential_rejected',+ status: 'mcp_reauth_required',+ recovery: 'authorize',+ automaticReplay: false,+ },+ resource_permission_denied: {+ reason: 'resource_permission_denied',+ status: 'mcp_permission_denied',+ recovery: 'restore_permission',+ automaticReplay: false,+ },+ provider_missing: {+ reason: 'provider_missing',+ status: 'mcp_configuration_missing',+ recovery: 'configure',+ automaticReplay: false,+ },+ resource_unverified: {+ reason: 'resource_unverified',+ status: 'mcp_configuration_missing',+ recovery: 'configure',+ automaticReplay: false,+ },+ unsupported_mode: {+ reason: 'unsupported_mode',+ status: 'mcp_configuration_missing',+ recovery: 'configure',+ automaticReplay: false,+ },+ dependency_unavailable: {+ reason: 'dependency_unavailable',+ status: 'mcp_unavailable',+ recovery: 'retry_later',+ automaticReplay: false,+ },+ };diff --git a/packages/api/src/schedules/authorization/fixtures.helper.ts b/packages/api/src/schedules/authorization/fixtures.helper.tsindex e59ce2371d..9580cee4ee 100644--- a/packages/api/src/schedules/authorization/fixtures.helper.ts+++ b/packages/api/src/schedules/authorization/fixtures.helper.ts@@ -263,90 +263,4 @@ export const authorizationFixtures: readonly AuthorizationFixture[] = [},];-export const failureFixtures: Readonly<Record<ScheduledMCPFailure['reason'], ScheduledMCPFailure>> =- {- consent_missing: {- reason: 'consent_missing',- status: 'mcp_reauth_required',- recovery: 'authorize',- automaticReplay: false,- },- consent_expired: {- reason: 'consent_expired',- status: 'mcp_reauth_required',- recovery: 'authorize',- automaticReplay: false,- },- consent_revoked: {- reason: 'consent_revoked',- status: 'mcp_reauth_required',- recovery: 'authorize',- automaticReplay: false,- },- binding_mismatch: {- reason: 'binding_mismatch',- status: 'mcp_reauth_required',- recovery: 'authorize',- automaticReplay: false,- },- rbac_denied: {- reason: 'rbac_denied',- status: 'mcp_permission_denied',- recovery: 'restore_permission',- automaticReplay: false,- },- tool_policy_denied: {- reason: 'tool_policy_denied',- status: 'mcp_permission_denied',- recovery: 'configure',- automaticReplay: false,- },- approval_required: {- reason: 'approval_required',- status: 'mcp_permission_denied',- recovery: 'configure',- automaticReplay: false,- },- credential_missing: {- reason: 'credential_missing',- status: 'mcp_reauth_required',- recovery: 'authorize',- automaticReplay: false,- },- credential_rejected: {- reason: 'credential_rejected',- status: 'mcp_reauth_required',- recovery: 'authorize',- automaticReplay: false,- },- resource_permission_denied: {- reason: 'resource_permission_denied',- status: 'mcp_permission_denied',- recovery: 'restore_permission',- automaticReplay: false,- },- provider_missing: {- reason: 'provider_missing',- status: 'mcp_configuration_missing',- recovery: 'configure',- automaticReplay: false,- },- resource_unverified: {- reason: 'resource_unverified',- status: 'mcp_configuration_missing',- recovery: 'configure',- automaticReplay: false,- },- unsupported_mode: {- reason: 'unsupported_mode',- status: 'mcp_configuration_missing',- recovery: 'configure',- automaticReplay: false,- },- dependency_unavailable: {- reason: 'dependency_unavailable',- status: 'mcp_unavailable',- recovery: 'retry_later',- automaticReplay: false,- },- };+export { failureFixtures } from './failures';diff --git a/packages/api/src/schedules/authorization/handlers.ts b/packages/api/src/schedules/authorization/handlers.tsnew file mode 100644index 0000000000..ba75dd2505--- /dev/null+++ b/packages/api/src/schedules/authorization/handlers.ts@@ -0,0 +1,72 @@+import {+ confirmScheduleMCPConsentSchema,+ revokeScheduleMCPConsentSchema,+} from 'librechat-data-provider';+import type { ScheduledMCPIdentity } from 'librechat-data-provider';+import type { Response } from 'express';+import type { ScheduleMCPConsentService } from './service';+import type { ServerRequest } from '~/types';+import { ScheduleMCPConsentError } from './service';++export interface ScheduleMCPConsentHandlers {+ get: (req: ServerRequest, res: Response) => Promise<void>;+ confirm: (req: ServerRequest, res: Response) => Promise<void>;+ revoke: (req: ServerRequest, res: Response) => Promise<void>;+}++export function createScheduleMCPConsentHandlers(deps: {+ service: ScheduleMCPConsentService;+ resolveIdentity: (req: ServerRequest) => Promise<ScheduledMCPIdentity | null>;+}): ScheduleMCPConsentHandlers {+ const handler =+ (+ operation: (+ req: ServerRequest,+ res: Response,+ identity: ScheduledMCPIdentity,+ ) => Promise<void>,+ ) =>+ async (req: ServerRequest, res: Response): Promise<void> => {+ try {+ const identity = await deps.resolveIdentity(req);+ if (!identity) {+ res.status(404).json({ code: 'consent_not_found' });+ return;+ }+ await operation(req, res, identity);+ } catch (error) {+ const code = error instanceof ScheduleMCPConsentError ? error.code : 'consent_unavailable';+ const statuses = {+ consent_not_found: 404,+ consent_forbidden: 403,+ consent_changed: 409,+ consent_invalid: 400,+ consent_unavailable: 503,+ };+ const status = statuses[code];+ res.status(status).json({ code });+ }+ };+ return {+ get: handler(async (_req, res, identity) => {+ res.json(await deps.service.view(identity));+ }),+ confirm: handler(async (req, res, identity) => {+ const parsed = confirmScheduleMCPConsentSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ code: 'consent_invalid' });+ return;+ }+ res.json(await deps.service.confirm(identity, parsed.data));+ }),+ revoke: handler(async (req, res, identity) => {+ const parsed = revokeScheduleMCPConsentSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ code: 'consent_invalid' });+ return;+ }+ await deps.service.revoke(identity, parsed.data.expectedRevision);+ res.status(204).end();+ }),+ };+}diff --git a/packages/api/src/schedules/authorization/host.ts b/packages/api/src/schedules/authorization/host.tsnew file mode 100644index 0000000000..23d8837e51--- /dev/null+++ b/packages/api/src/schedules/authorization/host.ts@@ -0,0 +1,101 @@+import {+ Permissions,+ PermissionTypes,+ DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS,+} from 'librechat-data-provider';+import type { ScheduleMCPConsentStorage } from '@librechat/data-schemas';+import type { ScheduledMCPIdentity } from 'librechat-data-provider';+import type { IUser } from '@librechat/data-schemas';+import type {+ ScheduleMCPEnrollmentResolver,+ ScheduleMCPConsentDeps,+ ScheduleMCPConsentService,+} from './service';+import type { ScheduleMCPConsentHandlers } from './handlers';+import type { CheckAccessParams } from '~/middleware/access';+import type { SchedulesHandlersDeps } from '../handlers';+import { createScheduleMCPConsentHandlers } from './handlers';+import { createScheduleMCPConsentService } from './service';+import { checkAccess } from '~/middleware/access';++export function createScheduleMCPConsentHost(deps: {+ methods: ScheduleMCPConsentStorage & Pick<SchedulesHandlersDeps['methods'], 'getScheduleById'>;+ getLimits: SchedulesHandlersDeps['getLimits'];+ findUser: (id: string) => Promise<IUser | null>;+ getRoleByName: CheckAccessParams['getRoleByName'];+ canViewAgent: (agentId: string, user: IUser) => Promise<boolean>;+ resolveEnrollment?: ScheduleMCPEnrollmentResolver;+ checkToolPolicy?: ScheduleMCPConsentDeps['checkToolPolicy'];+}): { service: ScheduleMCPConsentService; handlers: ScheduleMCPConsentHandlers } {+ const pendingPrincipals = new Map<string, Promise<IUser | null>>();+ const loadPrincipal = (identity: ScheduledMCPIdentity): Promise<IUser | null> => {+ const key = JSON.stringify([identity.ownerId, identity.tenantId]);+ const pending = pendingPrincipals.get(key);+ if (pending) return pending;+ const lookup = Promise.resolve()+ .then(() => deps.findUser(identity.ownerId))+ .then((user) => {+ if (!user || (user.tenantId ?? null) !== identity.tenantId) return null;+ user.id = identity.ownerId;+ return user;+ })+ .finally(() => {+ pendingPrincipals.delete(key);+ });+ pendingPrincipals.set(key, lookup);+ return lookup;+ };+ const service = createScheduleMCPConsentService({+ storage: deps.methods,+ getLimits: async (identity) => {+ const user = await loadPrincipal(identity);+ if (!user)+ return { enabled: false, maxLifetimeHours: DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS };+ const limits = await deps.getLimits(user);+ return {+ enabled: limits.enabled && limits.mcpConsent?.enabled === true,+ maxLifetimeHours:+ limits.mcpConsent?.maxLifetimeHours ?? DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS,+ };+ },+ canUse: async (identity) => {+ const user = await loadPrincipal(identity);+ if (!user) return false;+ const permissions = await Promise.all([+ checkAccess({+ user,+ getRoleByName: deps.getRoleByName,+ permissionType: PermissionTypes.SCHEDULES,+ permissions: [Permissions.USE, Permissions.CREATE],+ }),+ checkAccess({+ user,+ getRoleByName: deps.getRoleByName,+ permissionType: PermissionTypes.MCP_SERVERS,+ permissions: [Permissions.USE],+ }),+ ]);+ return permissions.every(Boolean) && (await deps.canViewAgent(identity.agentId, user));+ },+ resolveEnrollment: deps.resolveEnrollment,+ checkToolPolicy: deps.checkToolPolicy,+ });+ const handlers = createScheduleMCPConsentHandlers({+ service,+ resolveIdentity: async (req): Promise<ScheduledMCPIdentity | null> => {+ const user = req.user;+ const { id } = req.params as { id: string };+ if (!user) return null;+ const schedule = await deps.methods.getScheduleById(id, user.id);+ if (!schedule || (schedule.tenantId ?? null) !== (user.tenantId ?? null)) return null;+ return {+ scheduleId: schedule.id,+ ownerId: user.id,+ tenantId: user.tenantId ?? null,+ agentId: schedule.agent_id,+ invocationMode: 'delegated',+ };+ },+ });+ return { service, handlers };+}diff --git a/packages/api/src/schedules/authorization/service.spec.ts b/packages/api/src/schedules/authorization/service.spec.tsnew file mode 100644index 0000000000..4a91370ef7--- /dev/null+++ b/packages/api/src/schedules/authorization/service.spec.ts@@ -0,0 +1,294 @@+import type { ScheduleMCPConsentStorage, ScheduleConsentSnapshot } from '@librechat/data-schemas';+import type { ScheduledMCPIdentity, ScheduledMCPTarget } from 'librechat-data-provider';+import { createScheduleMCPConsentHandlers } from './handlers';+import { createScheduleMCPConsentService } from './service';++const identity: ScheduledMCPIdentity = {+ scheduleId: 's',+ ownerId: 'u',+ tenantId: 't',+ agentId: 'root',+ invocationMode: 'delegated',+};+const target: ScheduledMCPTarget = {+ resource: {+ serverName: 'warehouse',+ url: 'https://warehouse.example/mcp',+ configurationRevision: 'v1',+ credentialMode: 'resource_bearer',+ issuer: 'https://issuer.example/',+ audience: 'warehouse',+ scopes: ['read'],+ },+ permittedTools: [+ { agentId: 'root', tools: ['query'] },+ { agentId: 'child', tools: ['query'] },+ ],+ policyRevision: 'p1',+};+function setup() {+ let time = 1000;+ const snapshot: ScheduleConsentSnapshot = {+ agentId: 'root',+ enabled: true,+ configRevision: 0,+ enrollment: null,+ };+ let targets = [structuredClone(target)];+ let allowed = true;+ let policy = true;+ const storage: ScheduleMCPConsentStorage = {+ readScheduleMCPConsent: jest.fn(async () => structuredClone(snapshot)),+ confirmScheduleMCPConsent: jest.fn(async (input) => {+ if (+ snapshot.configRevision !== input.expectedConfigRevision ||+ (snapshot.enrollment?.revision ?? null) !== input.expectedRevision+ )+ return false;+ snapshot.enrollment = structuredClone(input.enrollment);+ return true;+ }),+ revokeScheduleMCPConsent: jest.fn(async (_identity, revision) => {+ if (snapshot.enrollment?.revision !== revision) return false;+ snapshot.enrollment.revision = 'revoked';+ snapshot.enrollment.consents = snapshot.enrollment.consents.map((c) => ({+ ...c,+ revision: 'revoked',+ revokedAtMs: time,+ }));+ return true;+ }),+ admitScheduleMCPConsent: jest.fn(+ async ({ revision }) =>+ snapshot.enabled &&+ snapshot.enrollment?.revision === revision &&+ snapshot.enrollment.consents.every(+ (c) => c.revokedAtMs == null && c.absoluteExpiresAtMs > time,+ ),+ ),+ };+ const service = createScheduleMCPConsentService({+ storage,+ canUse: async () => allowed,+ getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),+ resolveEnrollment: async () => targets,+ checkToolPolicy: async () => policy,+ now: () => time,+ });+ const enroll = async () => {+ const view = await service.view(identity);+ return service.confirm(identity, {+ offerDigest: view.offer!.digest,+ expectedRevision: view.revision,+ lifetimeHours: 1,+ });+ };+ return {+ service,+ storage,+ snapshot,+ enroll,+ setTime: (value: number) => {+ time = value;+ },+ changeTarget: (value: ScheduledMCPTarget) => {+ targets = [value];+ },+ deny: () => {+ allowed = false;+ },+ denyPolicy: () => {+ policy = false;+ },+ };+}+const request = (stage: 'activation' | 'mint' | 'invoke' | 'resume') => ({+ identity,+ resource: target.resource,+ selection: { agentId: 'root', tools: ['query'] },+ stage,+});++it.each(['activation', 'mint', 'invoke', 'resume'] as const)(+ 'checks durable consent and live RBAC at %s',+ async (stage) => {+ const s = setup();+ expect(await s.service.authority.authorize(request(stage), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'consent_missing' },+ });+ await s.enroll();+ expect(await s.service.authority.authorize(request(stage), {})).toMatchObject({+ state: 'authorized',+ });+ s.deny();+ expect(await s.service.authority.authorize(request(stage), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'rbac_denied' },+ });+ },+);+it('keeps expiry fixed across mint/use and denies approval resume at the absolute boundary', async () => {+ const s = setup();+ await s.enroll();+ const deadline = s.snapshot.enrollment!.consents[0].absoluteExpiresAtMs;+ await s.service.authority.authorize(request('mint'), {});+ expect(s.snapshot.enrollment!.consents[0].absoluteExpiresAtMs).toBe(deadline);+ s.setTime(deadline);+ expect((await s.service.view(identity)).state).toBe('expired');+ expect(await s.service.authority.authorize(request('resume'), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'consent_expired' },+ });+});+it('stops use/resume after revocation even when mint previously succeeded', async () => {+ const s = setup();+ const enrolled = await s.enroll();+ await s.service.authority.authorize(request('mint'), {});+ await s.service.revoke(identity, enrolled.revision!);+ for (const stage of ['invoke', 'resume'] as const)+ expect(await s.service.authority.authorize(request(stage), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'consent_revoked' },+ });+});+it('does not authorize by mutable schedule-agent equality alone', async () => {+ const s = setup();+ await s.enroll();+ s.snapshot.agentId = 'other';+ s.snapshot.configRevision++;+ expect(+ await s.service.authority.authorize(+ { ...request('invoke'), identity: { ...identity, agentId: 'other' } },+ {},+ ),+ ).toMatchObject({ state: 'denied', failure: { reason: 'binding_mismatch' } });+});+it.each(['url', 'issuer', 'audience', 'configurationRevision'] as const)(+ 'invalidates a changed %s binding',+ async (field) => {+ const s = setup();+ await s.enroll();+ s.changeTarget({+ ...target,+ resource: {+ ...target.resource,+ [field]: ['url', 'issuer'].includes(field) ? 'https://other.example/' : 'different',+ },+ });+ expect((await s.service.view(identity)).state).toBe('changed');+ expect(await s.service.authority.authorize(request('invoke'), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'binding_mismatch' },+ });+ },+);+it('requires enrolled child tools and authoritative tool policy', async () => {+ const s = setup();+ await s.enroll();+ expect(+ await s.service.authority.authorize(+ { ...request('invoke'), selection: { agentId: 'child', tools: ['query'] } },+ {},+ ),+ ).toMatchObject({ state: 'authorized' });+ expect(+ await s.service.authority.authorize(+ { ...request('invoke'), selection: { agentId: 'child', tools: ['write'] } },+ {},+ ),+ ).toMatchObject({ state: 'denied', failure: { reason: 'tool_policy_denied' } });+ s.denyPolicy();+ expect(await s.service.authority.authorize(request('invoke'), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'tool_policy_denied' },+ });+});+it('rejects stale offers/excessive lifetimes without writing', async () => {+ const s = setup();+ const view = await s.service.view(identity);+ await expect(+ s.service.confirm(identity, {+ offerDigest: view.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 25,+ }),+ ).rejects.toMatchObject({ code: 'consent_invalid' });+ s.changeTarget({ ...target, policyRevision: 'p2' });+ await expect(+ s.service.confirm(identity, {+ offerDigest: view.offer!.digest,+ expectedRevision: null,+ lifetimeHours: 1,+ }),+ ).rejects.toMatchObject({ code: 'consent_changed' });+ expect(s.storage.confirmScheduleMCPConsent).not.toHaveBeenCalled();+});+it('keeps owner revocation available after permission removal', async () => {+ const s = setup();+ const enrolled = await s.enroll();+ s.deny();+ await s.service.revoke(identity, enrolled.revision!);+ expect((await s.service.view(identity)).state).toBe('revoked');+ expect((await s.service.view(identity)).offer).toBeNull();+});+it('denies without a trusted resolver and preserves cancellation', async () => {+ const s = setup();+ const service = createScheduleMCPConsentService({+ storage: s.storage,+ canUse: async () => true,+ getLimits: async () => ({ enabled: false, maxLifetimeHours: 24 }),+ });+ expect((await service.view(identity)).state).toBe('unsupported');+ expect(await service.authority.authorize(request('mint'), {})).toMatchObject({+ state: 'denied',+ failure: { reason: 'provider_missing' },+ });+ const controller = new AbortController();+ controller.abort();+ expect(+ await service.authority.authorize(request('resume'), { signal: controller.signal }),+ ).toEqual({ state: 'cancelled' });+});+it('does not turn a storage outage into absent consent or leak it from the owner API', async () => {+ const s = setup();+ jest+ .mocked(s.storage.readScheduleMCPConsent)+ .mockRejectedValue(new Error('secret-token-in-cause'));+ await expect(s.service.authority.lookupConsent(identity, target.resource, {})).rejects.toThrow(+ 'secret-token-in-cause',+ );+ const handlers = createScheduleMCPConsentHandlers({+ service: s.service,+ resolveIdentity: async () => identity,+ });+ const res = Object.assign({} as Parameters<typeof handlers.get>[1], {+ status: jest.fn().mockReturnThis(),+ json: jest.fn(),+ });+ await handlers.get({} as Parameters<typeof handlers.get>[0], res);+ expect(res.status).toHaveBeenCalledWith(503);+ expect(res.json).toHaveBeenCalledWith({ code: 'consent_unavailable' });+});++it('denies a removed child selection even without a policy revision change', async () => {+ const s = setup();+ await s.enroll();+ s.changeTarget({ ...target, permittedTools: [{ agentId: 'root', tools: ['query'] }] });+ expect(+ await s.service.authority.authorize(+ { ...request('invoke'), selection: { agentId: 'child', tools: ['query'] } },+ {},+ ),+ ).toMatchObject({ state: 'denied', failure: { reason: 'tool_policy_denied' } });+});++it('offers no overwrite of an incompatible stored grant', async () => {+ const s = setup();+ s.snapshot.compatible = false;+ expect(await s.service.view(identity)).toMatchObject({+ state: 'unsupported',+ offer: null,+ revision: null,+ });+});diff --git a/packages/api/src/schedules/authorization/service.ts b/packages/api/src/schedules/authorization/service.tsnew file mode 100644index 0000000000..fe961e70cb--- /dev/null+++ b/packages/api/src/schedules/authorization/service.ts@@ -0,0 +1,355 @@+import { createHash, randomUUID } from 'node:crypto';+import { scheduledMCPTargetSchema } from 'librechat-data-provider';+import type {+ ScheduledMCPIdentity,+ ScheduledMCPResource,+ ScheduledMCPTarget,+ ScheduleMCPConsentView,+ ConfirmScheduleMCPConsent,+ ScheduledMCPEnrollment,+} from 'librechat-data-provider';+import type { ScheduleMCPConsentStorage } from '@librechat/data-schemas';+import type {+ ScheduledMCPAuthority,+ ScheduledMCPAuthorizationRequest,+ ScheduledMCPFailureReason,+} from './contract';+import { failureFixtures } from './failures';++export interface ScheduleMCPConsentLimits {+ enabled: boolean;+ maxLifetimeHours: number;+}+export type ScheduleMCPEnrollmentResolver = (+ identity: ScheduledMCPIdentity,+ options: { signal?: AbortSignal },+) => Promise<readonly ScheduledMCPTarget[]>;++export interface ScheduleMCPConsentDeps {+ storage: ScheduleMCPConsentStorage;+ getLimits: (identity: ScheduledMCPIdentity) => Promise<ScheduleMCPConsentLimits>;+ /** Loads current user/tenant/role and schedule/agent/resource access; no role snapshot. */+ canUse: (identity: ScheduledMCPIdentity, options: { signal?: AbortSignal }) => Promise<boolean>;+ resolveEnrollment?: ScheduleMCPEnrollmentResolver;+ /** Trusted tool classification and current graph reachability, never MCP annotations. */+ checkToolPolicy?: (+ request: ScheduledMCPAuthorizationRequest,+ options: { signal?: AbortSignal },+ ) => Promise<boolean>;+ now?: () => number;+}++export class ScheduleMCPConsentError extends Error {+ constructor(+ readonly code:+ | 'consent_unavailable'+ | 'consent_forbidden'+ | 'consent_not_found'+ | 'consent_changed'+ | 'consent_invalid',+ ) {+ super(code);+ this.name = 'ScheduleMCPConsentError';+ }+}++function canonicalTargets(targets: readonly ScheduledMCPTarget[]): ScheduledMCPTarget[] {+ if (!targets.length || targets.length > 32)+ throw new ScheduleMCPConsentError('consent_unavailable');+ const servers = new Set<string>();+ return targets+ .map((target) => {+ const parsed = scheduledMCPTargetSchema.parse(target);+ if (+ servers.has(parsed.resource.serverName) ||+ parsed.resource.credentialMode === 'browser_bearer'+ )+ throw new ScheduleMCPConsentError('consent_invalid');+ servers.add(parsed.resource.serverName);+ const agents = new Set<string>();+ const permittedTools = parsed.permittedTools+ .map((selection) => {+ if (agents.has(selection.agentId)) throw new ScheduleMCPConsentError('consent_invalid');+ agents.add(selection.agentId);+ return { agentId: selection.agentId, tools: [...new Set(selection.tools)].sort() };+ })+ .sort((a, b) => a.agentId.localeCompare(b.agentId));+ return {+ ...parsed,+ permittedTools,+ resource: { ...parsed.resource, scopes: [...new Set(parsed.resource.scopes)].sort() },+ };+ })+ .sort((a, b) => a.resource.serverName.localeCompare(b.resource.serverName));+}++function sameResource(left: ScheduledMCPResource, right: ScheduledMCPResource): boolean {+ const binding = (resource: ScheduledMCPResource) => [+ resource.serverName,+ resource.url,+ resource.configurationRevision,+ resource.credentialMode,+ resource.issuer,+ resource.audience,+ [...new Set(resource.scopes)].sort(),+ ];+ return JSON.stringify(binding(left)) === JSON.stringify(binding(right));+}++export interface ScheduleMCPConsentService {+ view: (+ identity: ScheduledMCPIdentity,+ options?: { signal?: AbortSignal },+ ) => Promise<ScheduleMCPConsentView>;+ confirm: (+ identity: ScheduledMCPIdentity,+ input: ConfirmScheduleMCPConsent,+ options?: { signal?: AbortSignal },+ ) => Promise<ScheduleMCPConsentView>;+ revoke: (identity: ScheduledMCPIdentity, revision: string) => Promise<void>;+ authority: ScheduledMCPAuthority;+}++export function createScheduleMCPConsentService(+ deps: ScheduleMCPConsentDeps,+): ScheduleMCPConsentService {+ const now = deps.now ?? Date.now;+ const denial = (reason: ScheduledMCPFailureReason) => ({+ state: 'denied' as const,+ failure: failureFixtures[reason],+ });+ const identityMatches = (a: ScheduledMCPIdentity, b: ScheduledMCPIdentity): boolean =>+ a.scheduleId === b.scheduleId &&+ a.ownerId === b.ownerId &&+ a.tenantId === b.tenantId &&+ a.agentId === b.agentId &&+ a.invocationMode === 'delegated' &&+ b.invocationMode === 'delegated';++ async function view(+ identity: ScheduledMCPIdentity,+ options: { signal?: AbortSignal } = {},+ ): Promise<ScheduleMCPConsentView> {+ options.signal?.throwIfAborted();+ const [snapshot, limits, allowed] = await Promise.all([+ deps.storage.readScheduleMCPConsent(identity),+ deps.getLimits(identity),+ deps.canUse(identity, options),+ ]);+ if (!snapshot) throw new ScheduleMCPConsentError('consent_not_found');+ if (snapshot.agentId !== identity.agentId) throw new ScheduleMCPConsentError('consent_changed');+ const enrollment = snapshot.enrollment;+ const expiresAtMs = enrollment+ ? Math.min(...enrollment.consents.map((c) => c.absoluteExpiresAtMs))+ : null;+ let state: ScheduleMCPConsentView['state'] = 'active';+ if (!enrollment) state = 'missing';+ else if (enrollment.consents.some((c) => c.revokedAtMs != null)) state = 'revoked';+ else if (expiresAtMs! <= now()) state = 'expired';+ else if (+ enrollment.scheduleRevision !== snapshot.configRevision ||+ enrollment.consents.some((c) => !identityMatches(c.identity, identity))+ )+ state = 'changed';+ let targets: ScheduledMCPTarget[] =+ enrollment?.consents.map(({ resource, permittedTools, policyRevision }) => ({+ resource,+ permittedTools,+ policyRevision,+ })) ?? [];+ let offer: ScheduleMCPConsentView['offer'] = null;+ if (snapshot.compatible === false) {+ return { state: 'unsupported', revision: null, expiresAtMs: null, targets: [], offer: null };+ }+ if (allowed && limits.enabled && deps.resolveEnrollment) {+ let resolved: readonly ScheduledMCPTarget[];+ try {+ resolved = await deps.resolveEnrollment(identity, options);+ } catch (error) {+ if (!(error instanceof ScheduleMCPConsentError) || !enrollment) throw error;+ return {+ state: 'changed',+ revision: enrollment.revision,+ expiresAtMs,+ targets,+ offer: null,+ };+ }+ if (resolved.length === 0)+ return {+ state: enrollment ? 'changed' : 'unsupported',+ revision: enrollment?.revision ?? null,+ expiresAtMs,+ targets,+ offer: null,+ };+ targets = canonicalTargets(resolved);+ const digest = createHash('sha256')+ .update(JSON.stringify({ identity, configRevision: snapshot.configRevision, targets }))+ .digest('hex');+ offer = { digest, maxLifetimeHours: limits.maxLifetimeHours };+ if (+ state === 'active' &&+ JSON.stringify(targets) !==+ JSON.stringify(+ canonicalTargets(+ enrollment!.consents.map(({ resource, permittedTools, policyRevision }) => ({+ resource,+ permittedTools,+ policyRevision,+ })),+ ),+ )+ )+ state = 'changed';+ } else if (!enrollment) state = 'unsupported';+ options.signal?.throwIfAborted();+ return { state, revision: enrollment?.revision ?? null, expiresAtMs, targets, offer };+ }++ async function confirm(+ identity: ScheduledMCPIdentity,+ input: ConfirmScheduleMCPConsent,+ options: { signal?: AbortSignal } = {},+ ): Promise<ScheduleMCPConsentView> {+ if (!(await deps.canUse(identity, options)))+ throw new ScheduleMCPConsentError('consent_forbidden');+ const current = await view(identity, options);+ if (!current.offer) throw new ScheduleMCPConsentError('consent_unavailable');+ if (input.offerDigest !== current.offer.digest || input.expectedRevision !== current.revision)+ throw new ScheduleMCPConsentError('consent_changed');+ if (+ !Number.isInteger(input.lifetimeHours) ||+ input.lifetimeHours < 1 ||+ input.lifetimeHours > current.offer.maxLifetimeHours+ )+ throw new ScheduleMCPConsentError('consent_invalid');+ const snapshot = await deps.storage.readScheduleMCPConsent(identity);+ if (!snapshot) throw new ScheduleMCPConsentError('consent_not_found');+ // Recompute the digest with the final observed row so an edit cannot reuse an old offer.+ const digest = createHash('sha256')+ .update(+ JSON.stringify({+ identity,+ configRevision: snapshot.configRevision,+ targets: current.targets,+ }),+ )+ .digest('hex');+ if (digest !== input.offerDigest) throw new ScheduleMCPConsentError('consent_changed');+ options.signal?.throwIfAborted();+ const grantedAtMs = now();+ const revision = randomUUID();+ const enrollment: ScheduledMCPEnrollment = {+ version: 1,+ revision,+ scheduleRevision: snapshot.configRevision,+ consents: current.targets.map((target) => ({+ ...target,+ identity,+ id: randomUUID(),+ revision,+ grantedAtMs,+ absoluteExpiresAtMs: grantedAtMs + input.lifetimeHours * 3_600_000,+ revokedAtMs: null,+ })),+ };+ const committed = await deps.storage.confirmScheduleMCPConsent({+ identity,+ expectedRevision: input.expectedRevision,+ expectedConfigRevision: snapshot.configRevision,+ enrollment,+ });+ if (!committed) throw new ScheduleMCPConsentError('consent_changed');+ return view(identity, options);+ }++ async function revoke(identity: ScheduledMCPIdentity, revision: string): Promise<void> {+ // Revocation remains available after access, resource configuration or agent changes.+ if (!(await deps.storage.revokeScheduleMCPConsent(identity, revision)))+ throw new ScheduleMCPConsentError('consent_changed');+ }++ const authority: ScheduledMCPAuthority = {+ async lookupConsent(identity, resource, options) {+ options.signal?.throwIfAborted();+ const row = await deps.storage.readScheduleMCPConsent(identity);+ const consent = row?.enrollment?.consents.find(+ (c) => c.resource.serverName === resource.serverName,+ );+ return consent ? { state: 'found', consent } : { state: 'missing' };+ },+ async authorize(request, options) {+ if (options.signal?.aborted) return { state: 'cancelled' };+ const [snapshot, allowed, limits] = await Promise.all([+ deps.storage.readScheduleMCPConsent(request.identity),+ deps.canUse(request.identity, options),+ deps.getLimits(request.identity),+ ]);+ if (options.signal?.aborted) return { state: 'cancelled' };+ if (!limits.enabled || !deps.resolveEnrollment) return denial('provider_missing');+ if (!allowed) return denial('rbac_denied');+ const enrollment = snapshot?.enrollment;+ const consent = enrollment?.consents.find(+ (c) => c.resource.serverName === request.resource.serverName,+ );+ if (!consent) return denial('consent_missing');+ if (consent.revokedAtMs != null) return denial('consent_revoked');+ if (request.resource.credentialMode === 'browser_bearer') return denial('unsupported_mode');+ if (now() >= consent.absoluteExpiresAtMs) return denial('consent_expired');+ if (+ !snapshot!.enabled ||+ snapshot!.agentId !== request.identity.agentId ||+ enrollment!.scheduleRevision !== snapshot!.configRevision ||+ !identityMatches(consent.identity, request.identity) ||+ !sameResource(consent.resource, request.resource)+ )+ return denial('binding_mismatch');+ const targets = canonicalTargets(await deps.resolveEnrollment(request.identity, options));+ const target = targets.find((t) => t.resource.serverName === request.resource.serverName);+ if (+ !target ||+ !sameResource(target.resource, consent.resource) ||+ target.policyRevision !== consent.policyRevision+ )+ return denial('binding_mismatch');+ const selection = consent.permittedTools.find((s) => s.agentId === request.selection.agentId);+ const currentSelection = target.permittedTools.find(+ (s) => s.agentId === request.selection.agentId,+ );+ if (+ !selection ||+ !currentSelection ||+ !request.selection.tools.length ||+ request.selection.tools.some(+ (tool) => !selection.tools.includes(tool) || !currentSelection.tools.includes(tool),+ )+ )+ return denial('tool_policy_denied');+ if (!deps.checkToolPolicy || !(await deps.checkToolPolicy(request, options)))+ return denial('tool_policy_denied');+ if (options.signal?.aborted) return { state: 'cancelled' };+ const admitted = await deps.storage.admitScheduleMCPConsent({+ identity: request.identity,+ expectedConfigRevision: snapshot!.configRevision,+ revision: enrollment!.revision,+ consentId: consent.id,+ });+ if (!admitted) {+ const latest = await authority.lookupConsent(request.identity, request.resource, options);+ if (latest.state !== 'found') return denial('consent_missing');+ if (latest.consent.revokedAtMs != null) return denial('consent_revoked');+ if (now() >= latest.consent.absoluteExpiresAtMs) return denial('consent_expired');+ return denial('binding_mismatch');+ }+ return {+ state: 'authorized',+ consentId: consent.id,+ consentRevision: consent.revision,+ policyRevision: consent.policyRevision,+ validUntilMs: consent.absoluteExpiresAtMs,+ };+ },+ };+ return { view, confirm, revoke, authority };+}diff --git a/packages/api/src/schedules/handlers.spec.ts b/packages/api/src/schedules/handlers.spec.tsindex 787b19fbf2..59d081a275 100644--- a/packages/api/src/schedules/handlers.spec.ts+++ b/packages/api/src/schedules/handlers.spec.ts@@ -93,6 +93,20 @@ describe('toWireSchedule', () => {}});+ it('projects typed consent availability without exposing the enrollment record', () => {+ const enrollment = {+ version: 1 as const,+ revision: 'grant',+ scheduleRevision: 0,+ consents: [],+ };+ const wire = toWireSchedule(fullScheduleDoc({ mcpConsent: enrollment }));+ const available: boolean | undefined = wire.hasMCPConsent;+ expect(available).toBe(true);+ expect(wire).not.toHaveProperty('mcpConsent');+ expect(toWireSchedule(fullScheduleDoc()).hasMCPConsent).toBeUndefined();+ });+it('preserves the public field values', () => {const wire = toWireSchedule(fullScheduleDoc());expect(wire.id).toBe('sched-1');diff --git a/packages/api/src/schedules/handlers.ts b/packages/api/src/schedules/handlers.tsindex 1d30f50ca2..8df26b8a20 100644--- a/packages/api/src/schedules/handlers.ts+++ b/packages/api/src/schedules/handlers.ts@@ -5,7 +5,12 @@ import {updateSchedulePayloadSchema,isCronCadence,} from 'librechat-data-provider';-import type { TScheduleCadence, TCreateSchedule, TUpdateSchedule } from 'librechat-data-provider';+import type {+ TScheduleCadence,+ TCreateSchedule,+ TUpdateSchedule,+ TSchedule,+} from 'librechat-data-provider';import type { ScheduleMethods, ISchedule, IScheduleRun } from '@librechat/data-schemas';import type { Response } from 'express';import type {@@ -246,10 +251,11 @@ export type WireSchedule = Pick<| 'configRevision'| 'createdAt'| 'updatedAt'-> & {- /** See `TSchedule.inFlight`: the generating occurrences, from their own run rows. */- inFlight?: Array<{ conversationId: string }>;-};+> &+ Pick<TSchedule, 'hasMCPConsent'> & {+ /** See `TSchedule.inFlight`: the generating occurrences, from their own run rows. */+ inFlight?: Array<{ conversationId: string }>;+ };/** Only generating occurrences are read for the list. `ScheduleRun` is indexed by* status, not by user, and `started` rows are bounded globally by the capacity@@ -297,6 +303,7 @@ export function toWireSchedule(): WireSchedule {return {id: schedule.id,+ ...(schedule.mcpConsent && { hasMCPConsent: true }),user: schedule.user,name: schedule.name,prompt: schedule.prompt,@@ -583,6 +590,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH),limits: {maxPerUser: limits.maxPerUser,+ ...(limits.mcpConsent?.enabled && { mcpConsent: true }),// minIntervalMinutes ships with the list so the dialog can refuse a cadence// the floor would reject, instead of surfacing it as a 400 after submit.minIntervalMinutes: limits.minIntervalMinutes,diff --git a/packages/api/src/schedules/index.ts b/packages/api/src/schedules/index.tsindex 709c9a6cfd..554a154d89 100644--- a/packages/api/src/schedules/index.ts+++ b/packages/api/src/schedules/index.ts@@ -9,3 +9,10 @@ export * from './readiness';export * from './trigger';export * from './types';export * from './mcp';++export * from './authorization/service';+export * from './authorization/host';+export * from './authorization/handlers';+export type * from './authorization/contract';++export * from './authorization/enrollment';diff --git a/packages/api/src/schedules/mcp.ts b/packages/api/src/schedules/mcp.tsindex 7697f133c2..6e15ef5a9f 100644--- a/packages/api/src/schedules/mcp.ts+++ b/packages/api/src/schedules/mcp.ts@@ -3,16 +3,11 @@ import {AgentCapabilities,Constants,EModelEndpoint,- MAX_SUBAGENT_DEPTH,- MAX_SUBAGENT_GRAPH_NODES,- MAX_SUBAGENT_RUN_CONFIGS,Permissions,PermissionTypes,- isActionTool,buildServerNameAliases,normalizeMCPToolKey,normalizeServerName,- resolveModelCatalogKey,} from 'librechat-data-provider';import type {IUser,@@ -47,11 +42,11 @@ import {import { MCPConfigInitializationCanceledError } from '../mcp/registry/MCPServersRegistry';import { createMCPRequestContext, cleanupMCPRequestContext } from '../mcp/request';import { isScheduleFireRequest, readScheduleFireContext } from './trigger';+import { resolveScheduledMCPRequirements } from './requirements';import { getAppConfigOptionsFromUser } from '../app/service';import { createConcurrencyLimiter } from '../utils/promise';import { OboTokenResolutionError } from '../mcp/oauth/obo';import { OpenIDReauthRequiredError } from '../utils/oidc';-import { resolveReachableGraph } from '../agents/edges';import { formatMCPServerTools } from '../mcp/tools';import { checkAccess } from '../middleware/access';import { detachOnAbort } from '../utils/promises';@@ -215,314 +210,13 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPr});return appConfig;};- const tools: Array<{ name: string; agentId: string }> = [];- const serverHints = new Set<string>();- const graphEdges: NonNullable<AgentGraphNode['edges']> = [];- const explicitSeeds = new Set<string>([agentId]);- const attempted = new Set<string>();- const expanded = new Set<string>();- const expandedHandoffs = new Set<string>();- const expandedHandoffEdges = new Set<string>();- const viewableById = new Map<string, AgentGraphNode>();- const accessibleById = new Map<string, AgentGraphNode>();- const subagentGraphIds = new Set<string>();- const accessIdentity = {- userId: user.id,- role: user.role,- idOnTheSource: user.idOnTheSource,- };- let accessContext: AgentGraphAccessContext | undefined;- let modelsConfig: TModelsConfig | undefined;-- const loadNodes = async (ids: string[]): Promise<void> => {- const frontier = [...new Set(ids)].filter(- (id) => !attempted.has(id) && id !== '__start__' && id !== '__end__' && id.length > 0,- );- if (frontier.length === 0) return;- frontier.forEach((id) => attempted.add(id));- let loaded: AgentGraphNode[] = [];- if (frontier.includes(agentId)) {- const root = await deps.getAgentGraphNodes([agentId]);- const descendants = frontier.filter((id) => id !== agentId);- loaded = [- ...root,- ...(descendants.length > 0- ? await deps.getAgentGraphNodes(- descendants,- (accessContext ??= await deps.resolveAgentGraphAccess(accessIdentity)),- )- : []),- ];- } else {- loaded = await deps.getAgentGraphNodes(- frontier,- (accessContext ??= await deps.resolveAgentGraphAccess(accessIdentity)),- );- }- throwIfAborted();- const descendants = loaded.filter((agent) => agent.id !== agentId);- if (descendants.length > 0) {- modelsConfig ??= await deps.getModelsConfig(user);- }- for (const agent of loaded) {- viewableById.set(agent.id, agent);- const availableModels =- agent.id === agentId- ? undefined- : modelsConfig?.[resolveModelCatalogKey(agent.provider, modelsConfig)];- if (- agent.id === agentId ||- (agent.model.length > 0 && availableModels?.includes(agent.model) === true)- ) {- accessibleById.set(agent.id, agent);- }- }- };-- // Match discoverConnectedAgents first: handoff agents are initialized and pruned- // before any isolated subagent descriptors or graph definitions are considered.- type HandoffCandidate = { id: string; expandEdges: boolean };- let handoffFrontier: HandoffCandidate[] = [{ id: agentId, expandEdges: true }];- while (handoffFrontier.length > 0) {- const frontier = handoffFrontier;- handoffFrontier = [];- await loadNodes(frontier.map(({ id }) => id));- for (const { id, expandEdges } of frontier) {- const agent = accessibleById.get(id);- if (!agent) continue;- expandedHandoffs.add(id);- expanded.add(id);- if (agent.id === agentId) {- let previousId = agent.id;- for (const childId of agent.agent_ids ?? []) {- if (childId === agent.id || childId.length === 0) continue;- graphEdges.push({ from: previousId, to: childId });- // discoverConnectedAgents initializes legacy chain members only after- // recursive handoff discovery and never collects their persisted edges.- handoffFrontier.push({ id: childId, expandEdges: false });- previousId = childId;- }- }- if (!expandEdges || expandedHandoffEdges.has(id)) continue;- expandedHandoffEdges.add(id);- graphEdges.push(...(agent.edges ?? []));- for (const edge of agent.edges ?? []) {- handoffFrontier.push(- ...[edge.from, edge.to].flat().map((childId) => ({- id: childId,- expandEdges: true,- })),- );- }- }- }-- const handoffSkippedIds = new Set(- [...attempted].filter((id) => id !== agentId && !accessibleById.has(id)),- );- const { reachable: reachableHandoffIds } = resolveReachableGraph(- new Set([agentId]),- expandedHandoffs,- graphEdges,- handoffSkippedIds,- );- const rootConfigs = [...reachableHandoffIds]- .map((id) => accessibleById.get(id))- .filter((agent): agent is AgentGraphNode => agent != null);- const rootConfigIds = new Set(rootConfigs.map((agent) => agent.id));- const directValidationContexts: Array<{- id: string;- ancestors: Set<string>;- acceptedGraphCount: number;- }> = [];- const acceptedGraphCounts = new Map<string, number>();- let expandedSubagentConfigs = 0;- let subagentsAvailable: boolean | undefined;- const canUseSubagents = async (): Promise<boolean> => {- if (subagentsAvailable != null) return subagentsAvailable;- const config = await loadAppConfig();- subagentsAvailable = (- config?.endpoints?.[EModelEndpoint.agents]?.capabilities ?? []- ).includes(AgentCapabilities.subagents);- return subagentsAvailable;- };- const addGraphBudgetMember = (id: string): void => {- if (id === agentId || subagentGraphIds.has(id)) return;- if (subagentGraphIds.size >= MAX_SUBAGENT_GRAPH_NODES) {- throw new Error(- `Subagent graph exceeds the maximum of ${MAX_SUBAGENT_GRAPH_NODES} unique agents.`,- );- }- subagentGraphIds.add(id);- };- const countExpandedSubagentConfig = (): void => {- expandedSubagentConfigs += 1;- if (expandedSubagentConfigs > MAX_SUBAGENT_RUN_CONFIGS) {- throw new Error(- `Subagent run configuration exceeds the maximum of ${MAX_SUBAGENT_RUN_CONFIGS} expanded entries.`,- );- }- };- const includeGraph = async (ids: string[], parentRunnable: boolean): Promise<boolean> => {- await loadNodes(ids);- if (!parentRunnable || ids.some((id) => !accessibleById.has(id))) return false;- for (const id of ids) {- explicitSeeds.add(id);- expanded.add(id);- }- return true;- };- const processDirectGraphs = async (- agent: AgentGraphNode,- parentRunnable: boolean,- ): Promise<number> => {- if (!agent.subagents?.enabled || !(await canUseSubagents())) return 0;- const definitions = agent.subagents.graphs ?? [];- let acceptedGraphCount = 0;- const memberIds = [...new Set(definitions.flatMap((graph) => graph.agent_ids ?? []))].filter(- (id) => id !== agent.id && id !== agentId && !rootConfigIds.has(id),- );- const staged = memberIds.filter((id) => !subagentGraphIds.has(id));- if (subagentGraphIds.size + staged.length > MAX_SUBAGENT_GRAPH_NODES) {- throw new Error(- `Subagent graph exceeds the maximum of ${MAX_SUBAGENT_GRAPH_NODES} unique agents.`,- );- }- staged.forEach((id) => subagentGraphIds.add(id));- await loadNodes(memberIds);- for (const definition of definitions) {- const ids = [...new Set(definition.agent_ids ?? [])];- if (await includeGraph(ids, parentRunnable)) {- acceptedGraphCount += 1;- }- }- return acceptedGraphCount;- };- const visitDirectTree = async (- agent: AgentGraphNode,- depth: number,- ancestors: Set<string>,- parentRunnable: boolean,- ): Promise<void> => {- if (!agent.subagents?.enabled || !(await canUseSubagents())) return;- if (agent.subagents.allowSelf !== false) countExpandedSubagentConfig();- const directIds = [...new Set(agent.subagents.agent_ids ?? [])].filter(- (id) => id.length > 0 && id !== agent.id,- );- if (directIds.length > 0 && depth >= MAX_SUBAGENT_DEPTH) {- throw new Error(- `Subagent graph exceeds the maximum depth of ${MAX_SUBAGENT_DEPTH} at agent ${agent.id}.`,- );- }- await loadNodes(directIds);- const nextAncestors = new Set(ancestors);- nextAncestors.add(agent.id);- for (const childId of directIds) {- if (nextAncestors.has(childId) || handoffSkippedIds.has(childId)) continue;- // Lazy runtime initialization loads VIEW-checked metadata before model- // validation. Even an invalid-model descriptor consumes depth, expanded-- // config, and graph-node budgets, but its MCP tools can never execute.- const child = viewableById.get(childId);- if (!child) continue;- addGraphBudgetMember(childId);- countExpandedSubagentConfig();- const childRunnable = parentRunnable && accessibleById.has(childId);- const validationContext = childRunnable- ? { id: childId, ancestors: nextAncestors, acceptedGraphCount: 0 }- : undefined;- if (validationContext) {- directValidationContexts.push(validationContext);- explicitSeeds.add(childId);- expanded.add(childId);- }- await visitDirectTree(child, depth + 1, nextAncestors, childRunnable);- // initializeClient preloads a direct child's graph members only after its- // complete nested direct tree, before root-level graphs are resolved.- const acceptedGraphCount = await processDirectGraphs(child, childRunnable);- if (validationContext) validationContext.acceptedGraphCount = acceptedGraphCount;- }- };-- for (const root of rootConfigs) {- await visitDirectTree(root, 0, new Set(), true);- }- // Root and handoff graph definitions run after every direct tree. Each definition- // is skipped atomically when its new members would exceed the shared runtime budget.- for (const root of rootConfigs) {- if (!root.subagents?.enabled || !(await canUseSubagents())) continue;- for (const definition of root.subagents.graphs ?? []) {- const ids = [...new Set(definition.agent_ids ?? [])];- const staged = ids.filter(- (id) => id !== agentId && !rootConfigIds.has(id) && !subagentGraphIds.has(id),- );- if (subagentGraphIds.size + staged.length > MAX_SUBAGENT_GRAPH_NODES) continue;- staged.forEach((id) => subagentGraphIds.add(id));- if (await includeGraph(ids, true)) {- acceptedGraphCounts.set(root.id, (acceptedGraphCounts.get(root.id) ?? 0) + 1);- }- }- }- const validateRunConfigTree = (- agent: AgentGraphNode,- state: { count: number },- ancestors: Set<string>,- acceptedGraphCount = acceptedGraphCounts.get(agent.id) ?? 0,- ): void => {- if (!agent.subagents?.enabled || subagentsAvailable !== true) return;- const count = (): void => {- state.count += 1;- if (state.count > MAX_SUBAGENT_RUN_CONFIGS) {- throw new Error(- `Subagent run configuration exceeds the maximum of ${MAX_SUBAGENT_RUN_CONFIGS} expanded entries.`,- );- }- };- if (agent.subagents.allowSelf !== false) count();- const nextAncestors = new Set(ancestors);- nextAncestors.add(agent.id);- for (const childId of new Set(agent.subagents.agent_ids ?? [])) {- if (childId === agent.id || nextAncestors.has(childId)) continue;- const child = viewableById.get(childId);- if (!child) continue;- count();- // Only already initialized handoff configs are eager in the initial run.- // Other direct children resolve lazily with their own fresh counter below.- if (rootConfigIds.has(childId)) {- validateRunConfigTree(child, state, nextAncestors);- }- }- for (let index = 0; index < acceptedGraphCount; index++) count();- };- const initialRunState = { count: 0 };- for (const root of rootConfigs) {- validateRunConfigTree(root, initialRunState, new Set());- }- for (const { id: directId, ancestors, acceptedGraphCount } of directValidationContexts) {- if (rootConfigIds.has(directId)) continue;- const direct = accessibleById.get(directId);- if (!direct) continue;- // createLazySubagentConfig seeds the selected child's resolution at one.- validateRunConfigTree(direct, { count: 1 }, ancestors, acceptedGraphCount);- }- const skippedAgentIds = new Set(- [...attempted].filter((id) => id !== agentId && !accessibleById.has(id)),- );- const { reachable } = resolveReachableGraph(- explicitSeeds,- expanded,- graphEdges,- skippedAgentIds,+ const { tools, serverHints } = await resolveScheduledMCPRequirements(+ agentId,+ user,+ deps,+ loadAppConfig,+ signal,);- for (const id of reachable) {- const agent = accessibleById.get(id);- if (!agent || !expanded.has(id)) continue;- tools.push(- ...(agent.tools ?? [])- .filter((tool) => !isActionTool(tool))- .map((name) => ({ name, agentId: agent.id })),- );- for (const name of agent.mcpServerNames ?? []) serverHints.add(name);- }const selectedTools = tools.filter(({ name }) =>name.includes(Constants.mcp_delimiter) &&diff --git a/packages/api/src/schedules/requirements.ts b/packages/api/src/schedules/requirements.tsnew file mode 100644index 0000000000..61699d197b--- /dev/null+++ b/packages/api/src/schedules/requirements.ts@@ -0,0 +1,347 @@+import {+ AgentCapabilities,+ EModelEndpoint,+ MAX_SUBAGENT_DEPTH,+ MAX_SUBAGENT_GRAPH_NODES,+ MAX_SUBAGENT_RUN_CONFIGS,+ isActionTool,+ resolveModelCatalogKey,+} from 'librechat-data-provider';+import type {+ AgentMethods,+ IUser,+ AppConfig,+ AgentGraphNode,+ AgentGraphAccessContext,+} from '@librechat/data-schemas';+import type { TModelsConfig } from 'librechat-data-provider';+import { resolveReachableGraph } from '../agents/edges';++export type ScheduleMCPGraphDeps = Pick<+ AgentMethods,+ 'getAgentGraphNodes' | 'resolveAgentGraphAccess'+> & {+ getModelsConfig: (user: IUser) => Promise<TModelsConfig>;+};+export interface ScheduledMCPRequirements {+ tools: Array<{ name: string; agentId: string }>;+ serverHints: Set<string>;+}++/** The runtime's bounded graph expansion, shared by readiness and enrollment metadata. */+export async function resolveScheduledMCPRequirements(+ agentId: string,+ user: IUser,+ deps: ScheduleMCPGraphDeps,+ loadAppConfig: () => Promise<AppConfig | undefined>,+ signal?: AbortSignal,+): Promise<ScheduledMCPRequirements> {+ const throwIfAborted = (): void => {+ if (signal?.aborted) throw signal.reason ?? new Error('MCP requirements aborted');+ };+ throwIfAborted();+ const tools: Array<{ name: string; agentId: string }> = [];+ const serverHints = new Set<string>();+ const graphEdges: NonNullable<AgentGraphNode['edges']> = [];+ const explicitSeeds = new Set<string>([agentId]);+ const attempted = new Set<string>();+ const expanded = new Set<string>();+ const expandedHandoffs = new Set<string>();+ const expandedHandoffEdges = new Set<string>();+ const viewableById = new Map<string, AgentGraphNode>();+ const accessibleById = new Map<string, AgentGraphNode>();+ const subagentGraphIds = new Set<string>();+ const accessIdentity = {+ userId: user.id,+ role: user.role,+ idOnTheSource: user.idOnTheSource,+ };+ let accessContext: AgentGraphAccessContext | undefined;+ let modelsConfig: TModelsConfig | undefined;++ const loadNodes = async (ids: string[]): Promise<void> => {+ const frontier = [...new Set(ids)].filter(+ (id) => !attempted.has(id) && id !== '__start__' && id !== '__end__' && id.length > 0,+ );+ if (frontier.length === 0) return;+ frontier.forEach((id) => attempted.add(id));+ let loaded: AgentGraphNode[] = [];+ if (frontier.includes(agentId)) {+ const root = await deps.getAgentGraphNodes([agentId]);+ const descendants = frontier.filter((id) => id !== agentId);+ loaded = [+ ...root,+ ...(descendants.length > 0+ ? await deps.getAgentGraphNodes(+ descendants,+ (accessContext ??= await deps.resolveAgentGraphAccess(accessIdentity)),+ )+ : []),+ ];+ } else {+ loaded = await deps.getAgentGraphNodes(+ frontier,+ (accessContext ??= await deps.resolveAgentGraphAccess(accessIdentity)),+ );+ }+ throwIfAborted();+ const descendants = loaded.filter((agent) => agent.id !== agentId);+ if (descendants.length > 0) {+ modelsConfig ??= await deps.getModelsConfig(user);+ }+ for (const agent of loaded) {+ viewableById.set(agent.id, agent);+ const availableModels =+ agent.id === agentId+ ? undefined+ : modelsConfig?.[resolveModelCatalogKey(agent.provider, modelsConfig)];+ if (+ agent.id === agentId ||+ (agent.model.length > 0 && availableModels?.includes(agent.model) === true)+ ) {+ accessibleById.set(agent.id, agent);+ }+ }+ };++ // Match discoverConnectedAgents first: handoff agents are initialized and pruned+ // before any isolated subagent descriptors or graph definitions are considered.+ type HandoffCandidate = { id: string; expandEdges: boolean };+ let handoffFrontier: HandoffCandidate[] = [{ id: agentId, expandEdges: true }];+ while (handoffFrontier.length > 0) {+ const frontier = handoffFrontier;+ handoffFrontier = [];+ await loadNodes(frontier.map(({ id }) => id));+ for (const { id, expandEdges } of frontier) {+ const agent = accessibleById.get(id);+ if (!agent) continue;+ expandedHandoffs.add(id);+ expanded.add(id);+ if (agent.id === agentId) {+ let previousId = agent.id;+ for (const childId of agent.agent_ids ?? []) {+ if (childId === agent.id || childId.length === 0) continue;+ graphEdges.push({ from: previousId, to: childId });+ // discoverConnectedAgents initializes legacy chain members only after+ // recursive handoff discovery and never collects their persisted edges.+ handoffFrontier.push({ id: childId, expandEdges: false });+ previousId = childId;+ }+ }+ if (!expandEdges || expandedHandoffEdges.has(id)) continue;+ expandedHandoffEdges.add(id);+ graphEdges.push(...(agent.edges ?? []));+ for (const edge of agent.edges ?? []) {+ handoffFrontier.push(+ ...[edge.from, edge.to].flat().map((childId) => ({+ id: childId,+ expandEdges: true,+ })),+ );+ }+ }+ }++ const handoffSkippedIds = new Set(+ [...attempted].filter((id) => id !== agentId && !accessibleById.has(id)),+ );+ const { reachable: reachableHandoffIds } = resolveReachableGraph(+ new Set([agentId]),+ expandedHandoffs,+ graphEdges,+ handoffSkippedIds,+ );+ const rootConfigs = [...reachableHandoffIds]+ .map((id) => accessibleById.get(id))+ .filter((agent): agent is AgentGraphNode => agent != null);+ const rootConfigIds = new Set(rootConfigs.map((agent) => agent.id));+ const directValidationContexts: Array<{+ id: string;+ ancestors: Set<string>;+ acceptedGraphCount: number;+ }> = [];+ const acceptedGraphCounts = new Map<string, number>();+ let expandedSubagentConfigs = 0;+ let subagentsAvailable: boolean | undefined;+ const canUseSubagents = async (): Promise<boolean> => {+ if (subagentsAvailable != null) return subagentsAvailable;+ const config = await loadAppConfig();+ subagentsAvailable = (config?.endpoints?.[EModelEndpoint.agents]?.capabilities ?? []).includes(+ AgentCapabilities.subagents,+ );+ return subagentsAvailable;+ };+ const addGraphBudgetMember = (id: string): void => {+ if (id === agentId || subagentGraphIds.has(id)) return;+ if (subagentGraphIds.size >= MAX_SUBAGENT_GRAPH_NODES) {+ throw new Error(+ `Subagent graph exceeds the maximum of ${MAX_SUBAGENT_GRAPH_NODES} unique agents.`,+ );+ }+ subagentGraphIds.add(id);+ };+ const countExpandedSubagentConfig = (): void => {+ expandedSubagentConfigs += 1;+ if (expandedSubagentConfigs > MAX_SUBAGENT_RUN_CONFIGS) {+ throw new Error(+ `Subagent run configuration exceeds the maximum of ${MAX_SUBAGENT_RUN_CONFIGS} expanded entries.`,+ );+ }+ };+ const includeGraph = async (ids: string[], parentRunnable: boolean): Promise<boolean> => {+ await loadNodes(ids);+ if (!parentRunnable || ids.some((id) => !accessibleById.has(id))) return false;+ for (const id of ids) {+ explicitSeeds.add(id);+ expanded.add(id);+ }+ return true;+ };+ const processDirectGraphs = async (+ agent: AgentGraphNode,+ parentRunnable: boolean,+ ): Promise<number> => {+ if (!agent.subagents?.enabled || !(await canUseSubagents())) return 0;+ const definitions = agent.subagents.graphs ?? [];+ let acceptedGraphCount = 0;+ const memberIds = [...new Set(definitions.flatMap((graph) => graph.agent_ids ?? []))].filter(+ (id) => id !== agent.id && id !== agentId && !rootConfigIds.has(id),+ );+ const staged = memberIds.filter((id) => !subagentGraphIds.has(id));+ if (subagentGraphIds.size + staged.length > MAX_SUBAGENT_GRAPH_NODES) {+ throw new Error(+ `Subagent graph exceeds the maximum of ${MAX_SUBAGENT_GRAPH_NODES} unique agents.`,+ );+ }+ staged.forEach((id) => subagentGraphIds.add(id));+ await loadNodes(memberIds);+ for (const definition of definitions) {+ const ids = [...new Set(definition.agent_ids ?? [])];+ if (await includeGraph(ids, parentRunnable)) {+ acceptedGraphCount += 1;+ }+ }+ return acceptedGraphCount;+ };+ const visitDirectTree = async (+ agent: AgentGraphNode,+ depth: number,+ ancestors: Set<string>,+ parentRunnable: boolean,+ ): Promise<void> => {+ if (!agent.subagents?.enabled || !(await canUseSubagents())) return;+ if (agent.subagents.allowSelf !== false) countExpandedSubagentConfig();+ const directIds = [...new Set(agent.subagents.agent_ids ?? [])].filter(+ (id) => id.length > 0 && id !== agent.id,+ );+ if (directIds.length > 0 && depth >= MAX_SUBAGENT_DEPTH) {+ throw new Error(+ `Subagent graph exceeds the maximum depth of ${MAX_SUBAGENT_DEPTH} at agent ${agent.id}.`,+ );+ }+ await loadNodes(directIds);+ const nextAncestors = new Set(ancestors);+ nextAncestors.add(agent.id);+ for (const childId of directIds) {+ if (nextAncestors.has(childId) || handoffSkippedIds.has(childId)) continue;+ // Lazy runtime initialization loads VIEW-checked metadata before model+ // validation. Even an invalid-model descriptor consumes depth, expanded-+ // config, and graph-node budgets, but its MCP tools can never execute.+ const child = viewableById.get(childId);+ if (!child) continue;+ addGraphBudgetMember(childId);+ countExpandedSubagentConfig();+ const childRunnable = parentRunnable && accessibleById.has(childId);+ const validationContext = childRunnable+ ? { id: childId, ancestors: nextAncestors, acceptedGraphCount: 0 }+ : undefined;+ if (validationContext) {+ directValidationContexts.push(validationContext);+ explicitSeeds.add(childId);+ expanded.add(childId);+ }+ await visitDirectTree(child, depth + 1, nextAncestors, childRunnable);+ // initializeClient preloads a direct child's graph members only after its+ // complete nested direct tree, before root-level graphs are resolved.+ const acceptedGraphCount = await processDirectGraphs(child, childRunnable);+ if (validationContext) validationContext.acceptedGraphCount = acceptedGraphCount;+ }+ };++ for (const root of rootConfigs) {+ await visitDirectTree(root, 0, new Set(), true);+ }+ // Root and handoff graph definitions run after every direct tree. Each definition+ // is skipped atomically when its new members would exceed the shared runtime budget.+ for (const root of rootConfigs) {+ if (!root.subagents?.enabled || !(await canUseSubagents())) continue;+ for (const definition of root.subagents.graphs ?? []) {+ const ids = [...new Set(definition.agent_ids ?? [])];+ const staged = ids.filter(+ (id) => id !== agentId && !rootConfigIds.has(id) && !subagentGraphIds.has(id),+ );+ if (subagentGraphIds.size + staged.length > MAX_SUBAGENT_GRAPH_NODES) continue;+ staged.forEach((id) => subagentGraphIds.add(id));+ if (await includeGraph(ids, true)) {+ acceptedGraphCounts.set(root.id, (acceptedGraphCounts.get(root.id) ?? 0) + 1);+ }+ }+ }+ const validateRunConfigTree = (+ agent: AgentGraphNode,+ state: { count: number },+ ancestors: Set<string>,+ acceptedGraphCount = acceptedGraphCounts.get(agent.id) ?? 0,+ ): void => {+ if (!agent.subagents?.enabled || subagentsAvailable !== true) return;+ const count = (): void => {+ state.count += 1;+ if (state.count > MAX_SUBAGENT_RUN_CONFIGS) {+ throw new Error(+ `Subagent run configuration exceeds the maximum of ${MAX_SUBAGENT_RUN_CONFIGS} expanded entries.`,+ );+ }+ };+ if (agent.subagents.allowSelf !== false) count();+ const nextAncestors = new Set(ancestors);+ nextAncestors.add(agent.id);+ for (const childId of new Set(agent.subagents.agent_ids ?? [])) {+ if (childId === agent.id || nextAncestors.has(childId)) continue;+ const child = viewableById.get(childId);+ if (!child) continue;+ count();+ // Only already initialized handoff configs are eager in the initial run.+ // Other direct children resolve lazily with their own fresh counter below.+ if (rootConfigIds.has(childId)) {+ validateRunConfigTree(child, state, nextAncestors);+ }+ }+ for (let index = 0; index < acceptedGraphCount; index++) count();+ };+ const initialRunState = { count: 0 };+ for (const root of rootConfigs) {+ validateRunConfigTree(root, initialRunState, new Set());+ }+ for (const { id: directId, ancestors, acceptedGraphCount } of directValidationContexts) {+ if (rootConfigIds.has(directId)) continue;+ const direct = accessibleById.get(directId);+ if (!direct) continue;+ // createLazySubagentConfig seeds the selected child's resolution at one.+ validateRunConfigTree(direct, { count: 1 }, ancestors, acceptedGraphCount);+ }+ const skippedAgentIds = new Set(+ [...attempted].filter((id) => id !== agentId && !accessibleById.has(id)),+ );+ const { reachable } = resolveReachableGraph(explicitSeeds, expanded, graphEdges, skippedAgentIds);+ for (const id of reachable) {+ const agent = accessibleById.get(id);+ if (!agent || !expanded.has(id)) continue;+ tools.push(+ ...(agent.tools ?? [])+ .filter((tool) => !isActionTool(tool))+ .map((name) => ({ name, agentId: agent.id })),+ );+ for (const name of agent.mcpServerNames ?? []) serverHints.add(name);+ }+ return { tools, serverHints };+}diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.tsindex 63715062f9..57bd44c60c 100644--- a/packages/api/src/schedules/service.ts+++ b/packages/api/src/schedules/service.ts@@ -1,3 +1,4 @@+import { DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS } from 'librechat-data-provider';import { logger, runAsSystem, tenantStorage, isRuntimeDisabled } from '@librechat/data-schemas';import { getRefillEligibilityDate, Permissions, PermissionTypes } from 'librechat-data-provider';import type { ScheduleMethods, AppConfig, IBalance, IChatProject } from '@librechat/data-schemas';@@ -409,6 +410,13 @@ export function createSchedulesService(const projectId = config.projectId?.trim() || undefined;return {enabled: config.use !== false,+ ...(config.mcpConsent && {+ mcpConsent: {+ enabled: config.mcpConsent.enabled === true,+ maxLifetimeHours:+ config.mcpConsent.maxLifetimeHours ?? DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS,+ },+ }),maxPerUser: config.maxPerUser ?? DEFAULT_SCHEDULE_LIMITS.maxPerUser,minIntervalMinutes: config.minIntervalMinutes ?? DEFAULT_SCHEDULE_LIMITS.minIntervalMinutes,autoDisableAfterFailures:diff --git a/packages/api/src/schedules/types.ts b/packages/api/src/schedules/types.tsindex 1e4c659a3f..b247c3d7e5 100644--- a/packages/api/src/schedules/types.ts+++ b/packages/api/src/schedules/types.ts@@ -12,6 +12,7 @@ import type { SlotClaimResult } from './capacity';export interface ScheduleLimits {/** Feature-level switch: when false the engine claims/fires nothing. */enabled: boolean;+ mcpConsent?: { enabled: boolean; maxLifetimeHours: number };maxPerUser: number;minIntervalMinutes: number;autoDisableAfterFailures: number;diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex f520e8ffd8..369526788d 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -458,6 +458,7 @@ export const getAllPromptGroups = () => `${prompts()}/all`;/* Scheduled chats */export const schedules = () => `${BASE_URL}/api/schedules`;export const schedule = (id: string) => `${schedules()}/${encodeURIComponent(id)}`;+export const scheduleMCPConsent = (id: string) => `${schedule(id)}/mcp-consent`;export const runSchedule = (id: string) => `${schedule(id)}/run`;/* Skills */diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex b38b0e98b7..c57bff3c9f 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -33,6 +33,7 @@ import {MIN_BALANCE_RESERVATION_TTL_MS,DEFAULT_BALANCE_RESERVATION_TTL_MS,} from './balance';+import { scheduledMCPResourceBindingSchema } from './types/scheduleConsent';export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_DEFAULT = 24 * 1024;export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_HARD_MAX = 64 * 1024;@@ -2593,6 +2594,13 @@ export const interfaceSchema = zautoDisableAfterFailures: z.number().int().min(1).optional(),admissionConcurrency: z.number().int().min(1).max(100).optional(),fireConcurrency: z.number().int().min(1).optional(),+ mcpConsent: z+ .object({+ enabled: z.boolean().optional(),+ maxLifetimeHours: z.number().int().min(1).max(8760).optional(),+ resources: z.record(scheduledMCPResourceBindingSchema).optional(),+ })+ .optional(),mcpPreflightConcurrency: z.number().int().min(1).max(10).optional(),mcpPreflightTimeoutMs: z.number().int().min(1000).max(600000).optional(),/** Refuse schedules that are not filed under a chat project. Enforced ondiff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 08b89f7c1d..4b2087e2de 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -7,6 +7,7 @@ import type {TTraceRecordDetail,} from './types/traces';import type { TInsightsAccessResponse, TInsightsParams, TInsightsResponse } from './types/insights';+import type { ScheduleMCPConsentView, ConfirmScheduleMCPConsent } from './types/scheduleConsent';import type { TFileConfig } from './file-config';import type * as tl from './types/tools';import type * as t from './types';@@ -1804,3 +1805,18 @@ export interface ActiveJobsResponse {export const getActiveJobs = (): Promise<ActiveJobsResponse> => {return request.get(endpoints.activeJobs());};++export function getScheduleMCPConsent(id: string): Promise<ScheduleMCPConsentView> {+ return request.get(endpoints.scheduleMCPConsent(id));+}+export function confirmScheduleMCPConsent(+ id: string,+ payload: ConfirmScheduleMCPConsent,+): Promise<ScheduleMCPConsentView> {+ return request.post(endpoints.scheduleMCPConsent(id), payload);+}+export function revokeScheduleMCPConsent(id: string, expectedRevision: string): Promise<void> {+ return request.deleteWithOptions(endpoints.scheduleMCPConsent(id), {+ data: { expectedRevision },+ });+}diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 04c3883ff2..402026a88e 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -91,3 +91,5 @@ export * from './codeEnvRef';export * from './code/worker';export * from './code/approval';export * from './code/workspace';++export * from './types/scheduleConsent';diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex f81b97e5e7..73e5816521 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -99,6 +99,7 @@ export enum QueryKeys {favorites = 'favorites',/* Scheduled chats */schedules = 'schedules',+ scheduleMCPConsent = 'scheduleMCPConsent',schedule = 'schedule',parentSubagents = 'parentSubagents',subagentThread = 'subagentThread',@@ -181,6 +182,8 @@ export enum MutationKeys {updateSchedule = 'updateSchedule',deleteSchedule = 'deleteSchedule',runSchedule = 'runSchedule',+ confirmScheduleMCPConsent = 'confirmScheduleMCPConsent',+ revokeScheduleMCPConsent = 'revokeScheduleMCPConsent',pairCodeEnvironment = 'pairCodeEnvironment',updateCodeEnvironmentSettings = 'updateCodeEnvironmentSettings',deleteCodeEnvironment = 'deleteCodeEnvironment',diff --git a/packages/data-provider/src/types/index.ts b/packages/data-provider/src/types/index.tsindex 7320b3a307..c8d1f11246 100644--- a/packages/data-provider/src/types/index.ts+++ b/packages/data-provider/src/types/index.ts@@ -3,3 +3,5 @@ export * from './mcpServers';export * from './subagents';export * from './background';export * from './queuedTurns';++export * from './scheduleConsent';diff --git a/packages/data-provider/src/types/scheduleConsent.spec.ts b/packages/data-provider/src/types/scheduleConsent.spec.tsnew file mode 100644index 0000000000..f8fcfa6487--- /dev/null+++ b/packages/data-provider/src/types/scheduleConsent.spec.ts@@ -0,0 +1,69 @@+import {+ confirmScheduleMCPConsentSchema,+ scheduledMCPResourceSchema,+ scheduledMCPIdentitySchema,+ scheduledMCPEnrollmentSchema,+} from './scheduleConsent';+import { configSchema } from '../config';++it('keeps scheduled consent opt-in and bounds its absolute lifetime', () => {+ const config = configSchema.parse({+ version: '1.3.8',+ interface: { schedules: { mcpConsent: {} } },+ });+ expect(config.interface?.schedules).toMatchObject({+ mcpConsent: {},+ });+ expect(+ configSchema.safeParse({+ version: '1.3.8',+ interface: { schedules: { mcpConsent: { maxLifetimeHours: 0 } } },+ }).success,+ ).toBe(false);+});+it('requires an explicit tenant binding and delegated mode', () => {+ const identity = { scheduleId: 's', ownerId: 'u', agentId: 'a', invocationMode: 'delegated' };+ expect(scheduledMCPIdentitySchema.safeParse(identity).success).toBe(false);+ expect(scheduledMCPIdentitySchema.safeParse({ ...identity, tenantId: null }).success).toBe(true);+ expect(+ scheduledMCPIdentitySchema.safeParse({+ ...identity,+ tenantId: null,+ invocationMode: 'autonomous',+ }).success,+ ).toBe(false);+});+it.each([+ 'https://token:[email protected]/mcp',+ 'https://example.com/mcp?token=secret',+ 'file:///tmp/mcp',+ 'https://example.com/mcp#secret',+])('rejects unsafe resource binding %s', (url) => {+ expect(+ scheduledMCPResourceSchema.safeParse({+ serverName: 'server',+ url,+ configurationRevision: 'v1',+ credentialMode: 'anonymous',+ issuer: null,+ audience: null,+ scopes: [],+ }).success,+ ).toBe(false);+});+it('accepts only a reviewed offer reference and bounded duration from the owner', () => {+ const valid = { offerDigest: 'a'.repeat(64), expectedRevision: null, lifetimeHours: 1 };+ expect(confirmScheduleMCPConsentSchema.safeParse(valid).success).toBe(true);+ expect(+ confirmScheduleMCPConsentSchema.safeParse({ ...valid, accessToken: 'secret' }).success,+ ).toBe(false);+ expect(+ confirmScheduleMCPConsentSchema.safeParse({ ...valid, lifetimeHours: Infinity }).success,+ ).toBe(false);+});+it('does not accept an unknown persisted consent version', () => {+ expect(+ scheduledMCPEnrollmentSchema.safeParse({ version: 2, revision: 'future', consents: [] })+ .success,+ ).toBe(false);+});diff --git a/packages/data-provider/src/types/scheduleConsent.ts b/packages/data-provider/src/types/scheduleConsent.tsnew file mode 100644index 0000000000..adc6cb8e95--- /dev/null+++ b/packages/data-provider/src/types/scheduleConsent.ts@@ -0,0 +1,120 @@+import { z } from 'zod';++export const DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS = 168;++const identifier = z.string().trim().min(1).max(256);+const timestamp = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);+const safeUrl = z+ .string()+ .url()+ .max(2048)+ .refine((value) => {+ try {+ const url = new URL(value);+ return (+ ['https:', 'http:'].includes(url.protocol) &&+ !url.username &&+ !url.password &&+ !url.search &&+ !url.hash+ );+ } catch {+ return false;+ }+ });++export const scheduledMCPIdentitySchema = z+ .object({+ scheduleId: identifier,+ ownerId: identifier,+ tenantId: identifier.nullable(),+ agentId: identifier,+ invocationMode: z.literal('delegated'),+ })+ .strict();+export type ScheduledMCPIdentity = z.infer<typeof scheduledMCPIdentitySchema>;++export const scheduledMCPResourceSchema = z+ .object({+ serverName: identifier,+ url: safeUrl,+ configurationRevision: identifier,+ credentialMode: z.enum([+ 'stored_oauth',+ 'browser_bearer',+ 'renewable_obo',+ 'resource_bearer',+ 'static',+ 'anonymous',+ ]),+ issuer: safeUrl.nullable(),+ audience: identifier.nullable(),+ scopes: z.array(identifier).max(128),+ })+ .strict();+export const scheduledMCPResourceBindingSchema = scheduledMCPResourceSchema.omit({+ serverName: true,+ configurationRevision: true,+});+export type ScheduledMCPResourceBinding = z.infer<typeof scheduledMCPResourceBindingSchema>;+export type ScheduledMCPResource = z.infer<typeof scheduledMCPResourceSchema>;+export type ScheduledMCPCredentialMode = ScheduledMCPResource['credentialMode'];++export const scheduledMCPToolSelectionSchema = z+ .object({+ agentId: identifier,+ tools: z.array(identifier).min(1).max(256),+ })+ .strict();+export type ScheduledMCPToolSelection = z.infer<typeof scheduledMCPToolSelectionSchema>;++export const scheduledMCPTargetSchema = z+ .object({+ resource: scheduledMCPResourceSchema,+ permittedTools: z.array(scheduledMCPToolSelectionSchema).min(1).max(100),+ policyRevision: identifier,+ })+ .strict();+export type ScheduledMCPTarget = z.infer<typeof scheduledMCPTargetSchema>;++export const scheduledMCPConsentSchema = scheduledMCPTargetSchema+ .extend({+ id: identifier,+ revision: identifier,+ identity: scheduledMCPIdentitySchema,+ grantedAtMs: timestamp,+ absoluteExpiresAtMs: timestamp,+ revokedAtMs: timestamp.nullable(),+ })+ .strict()+ .refine((value) => value.absoluteExpiresAtMs > value.grantedAtMs);+export type ScheduledMCPConsent = z.infer<typeof scheduledMCPConsentSchema>;++export const scheduledMCPEnrollmentSchema = z+ .object({+ version: z.literal(1),+ scheduleRevision: z.number().int().nonnegative(),+ revision: identifier,+ consents: z.array(scheduledMCPConsentSchema).min(1).max(32),+ })+ .strict();+export type ScheduledMCPEnrollment = z.infer<typeof scheduledMCPEnrollmentSchema>;++export const confirmScheduleMCPConsentSchema = z+ .object({+ offerDigest: z.string().regex(/^[a-f0-9]{64}$/),+ expectedRevision: identifier.nullable(),+ lifetimeHours: z.number().int().min(1).max(8760),+ })+ .strict();+export type ConfirmScheduleMCPConsent = z.infer<typeof confirmScheduleMCPConsentSchema>;++export const revokeScheduleMCPConsentSchema = z.object({ expectedRevision: identifier }).strict();++export interface ScheduleMCPConsentView {+ state: 'missing' | 'active' | 'expired' | 'revoked' | 'changed' | 'unsupported';+ revision: string | null;+ expiresAtMs: number | null;+ targets: ScheduledMCPTarget[];+ offer: { digest: string; maxLifetimeHours: number } | null;+}diff --git a/packages/data-provider/src/types/schedules.ts b/packages/data-provider/src/types/schedules.tsindex b62f492d69..2074663768 100644--- a/packages/data-provider/src/types/schedules.ts+++ b/packages/data-provider/src/types/schedules.ts@@ -125,6 +125,7 @@ export type TScheduleLastRun = {};export type TSchedule = {+ hasMCPConsent?: boolean;id: string;user: string;name: string;@@ -171,6 +172,7 @@ export type TScheduleRun = {* per-principal `interface.schedules` resolution the write handlers and the fire* path enforce, so the form can never offer a choice the server would refuse. */export type TScheduleLimits = {+ mcpConsent?: boolean;maxPerUser: number;/** Served with the list so the dialog can refuse a cadence the floor would reject* rather than surfacing it as a 400 after submit. */diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.tsindex a05d75f828..464c662fc3 100644--- a/packages/data-schemas/src/methods/index.ts+++ b/packages/data-schemas/src/methods/index.ts@@ -1,3 +1,7 @@+import type { ScheduleMCPConsentStorage } from './scheduleConsent';+import { createScheduleMCPConsentStorage } from './scheduleConsent';+export { createScheduleMCPConsentStorage } from './scheduleConsent';+export type { ScheduleMCPConsentStorage, ScheduleConsentSnapshot } from './scheduleConsent';import type {FileMethods,FileOwnerScope,@@ -277,6 +281,7 @@ export type AllMethods = UserMethods &SkillSyncMethods &AgentTriggerDeliveryMethods &AgentQueuedTurnMethods &+ ScheduleMCPConsentStorage &ScheduleMethods &AgentMethods &ConfigMethods &@@ -516,6 +521,7 @@ export function createMethods(...agentTriggerDeliveryMethods,...agentQueuedTurnMethods,...createScheduleMethods(mongoose),+ ...createScheduleMCPConsentStorage(mongoose),/* Tier 5 */...agentMethods,/* Config */diff --git a/packages/data-schemas/src/methods/scheduleConsent.spec.ts b/packages/data-schemas/src/methods/scheduleConsent.spec.tsnew file mode 100644index 0000000000..c007177eba--- /dev/null+++ b/packages/data-schemas/src/methods/scheduleConsent.spec.ts@@ -0,0 +1,215 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import type { ScheduledMCPIdentity, ScheduledMCPEnrollment } from 'librechat-data-provider';+import type { ScheduleMCPConsentStorage } from './scheduleConsent';+import { createScheduleMCPConsentStorage } from './scheduleConsent';+import { createScheduleMethods } from './schedule';+import { createModels } from '../models';++let mongo: MongoMemoryServer;+let storage: ScheduleMCPConsentStorage;+let identity: ScheduledMCPIdentity;+const owner = new mongoose.Types.ObjectId();++function enrollment(+ revision = 'grant-1',+ overrides: Partial<ScheduledMCPEnrollment> = {},+): ScheduledMCPEnrollment {+ return {+ version: 1,+ revision,+ scheduleRevision: 0,+ consents: [+ {+ id: 'consent-1',+ revision,+ identity,+ resource: {+ serverName: 'warehouse',+ url: 'https://warehouse.example/mcp',+ configurationRevision: 'config-1',+ credentialMode: 'resource_bearer',+ issuer: 'https://issuer.example/',+ audience: 'warehouse',+ scopes: ['read'],+ },+ permittedTools: [{ agentId: 'root', tools: ['query'] }],+ policyRevision: 'policy-1',+ grantedAtMs: Date.now() - 1000,+ absoluteExpiresAtMs: Date.now() + 600_000,+ revokedAtMs: null,+ },+ ],+ ...overrides,+ };+}++beforeAll(async () => {+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });+ await mongoose.connect(mongo.getUri());+ createModels(mongoose);+ await mongoose.models.Schedule.init();+ storage = createScheduleMCPConsentStorage(mongoose);+}, 60_000);+afterAll(async () => {+ await mongoose.disconnect();+ await mongo?.stop();+}, 60_000);+beforeEach(async () => {+ await mongoose.models.Schedule.deleteMany({});+ identity = {+ scheduleId: 'schedule-1',+ ownerId: owner.toString(),+ tenantId: 'tenant-1',+ agentId: 'root',+ invocationMode: 'delegated',+ };+ await createScheduleMethods(mongoose).createSchedule({+ id: identity.scheduleId,+ user: owner,+ tenantId: 'tenant-1',+ agent_id: 'root',+ name: 'Digest',+ prompt: 'Read',+ cadence: { frequency: 'hourly', minute: 0, hour: 1 },+ timezone: 'UTC',+ enabled: true,+ });+});++const confirm = (expectedRevision: string | null = null, grant = enrollment()) =>+ storage.confirmScheduleMCPConsent({+ identity,+ expectedConfigRevision: 0,+ expectedRevision,+ enrollment: grant,+ });+const admit = (revision = 'grant-1') =>+ storage.admitScheduleMCPConsent({+ identity,+ revision,+ expectedConfigRevision: 0,+ consentId: 'consent-1',+ });++it('leaves legacy schedules unenrolled and does not change enabled/default scheduling state', async () => {+ expect((await storage.readScheduleMCPConsent(identity))?.enrollment).toBeNull();+ expect(await confirm()).toBe(true);+ const freshStorage = createScheduleMCPConsentStorage(mongoose);+ expect(+ (await freshStorage.readScheduleMCPConsent(identity))?.enrollment?.consents[0].identity.agentId,+ ).toBe('root');+ expect((await freshStorage.readScheduleMCPConsent(identity))?.enabled).toBe(true);+});+it('has one winner among concurrent confirmations', async () => {+ const results = await Promise.all(+ Array.from({ length: 6 }, (_, n) => confirm(null, enrollment(`grant-${n}`))),+ );+ expect(results.filter(Boolean)).toHaveLength(1);+});+it('does not extend the deadline when an admission is recorded', async () => {+ const grant = enrollment();+ await confirm(null, grant);+ expect(await admit()).toBe(true);+ expect(await admit()).toBe(true);+ expect(+ (await storage.readScheduleMCPConsent(identity))?.enrollment?.consents[0].absoluteExpiresAtMs,+ ).toBe(grant.consents[0].absoluteExpiresAtMs);+});+it('rejects expired consent at the storage write boundary', async () => {+ const grant = enrollment();+ grant.consents[0].grantedAtMs = Date.now() - 5000;+ grant.consents[0].absoluteExpiresAtMs = Date.now() - 1000;+ expect(await confirm(null, grant)).toBe(false);+ await confirm();+ await mongoose.models.Schedule.updateOne(+ { id: identity.scheduleId },+ { $set: { 'mcpConsent.consents.0.absoluteExpiresAtMs': Date.now() - 1 } },+ );+ expect(await admit()).toBe(false);+});+it('fences use after revocation and invalidates a confirmation prepared before revocation', async () => {+ await confirm();+ await storage.revokeScheduleMCPConsent(identity, 'grant-1');+ expect(await admit()).toBe(false);+ expect(await confirm('grant-1', enrollment('grant-2'))).toBe(false);+ const row = await storage.readScheduleMCPConsent(identity);+ expect(row?.enrollment?.consents[0].revokedAtMs).not.toBeNull();+ expect(await confirm(row!.enrollment!.revision, enrollment('fresh-grant'))).toBe(true);+});+it('makes revoke/use races linearizable at the atomic admission boundary', async () => {+ await confirm();+ await Promise.all([admit(), storage.revokeScheduleMCPConsent(identity, 'grant-1')]);+ expect(await admit()).toBe(false);+});+it('cannot enroll or use after a root-agent change or config edit', async () => {+ await confirm();+ await mongoose.models.Schedule.updateOne(+ { id: identity.scheduleId },+ { $set: { agent_id: 'other' }, $inc: { configRevision: 1 } },+ );+ expect(await admit()).toBe(false);+ expect(await confirm('grant-1', enrollment('fresh'))).toBe(false);+ expect(await storage.revokeScheduleMCPConsent({ ...identity, agentId: 'other' }, 'grant-1')).toBe(+ true,+ );+});+it('isolates owners and tenants even for an identical schedule id', async () => {+ await confirm();+ for (const wrong of [+ { ...identity, ownerId: new mongoose.Types.ObjectId().toString() },+ { ...identity, tenantId: 'tenant-2' },+ { ...identity, tenantId: null },+ ]) {+ expect(await storage.readScheduleMCPConsent(wrong)).toBeNull();+ expect(await storage.revokeScheduleMCPConsent(wrong, 'grant-1')).toBe(false);+ expect(+ await storage.admitScheduleMCPConsent({+ identity: wrong,+ revision: 'grant-1',+ expectedConfigRevision: 0,+ consentId: 'consent-1',+ }),+ ).toBe(false);+ }+});+it.each(['deleting', 'erased'])('denies grants and admission for %s schedules', async (field) => {+ await confirm();+ await mongoose.models.Schedule.updateOne(+ { id: identity.scheduleId },+ { $set: { [field]: true } },+ );+ expect(await admit()).toBe(false);+ expect(await storage.readScheduleMCPConsent(identity)).toBeNull();+});+it('fails closed on an unknown stored version without overwriting it', async () => {+ await mongoose.models.Schedule.updateOne(+ { id: identity.scheduleId },+ { $set: { mcpConsent: { version: 2, revision: 'future' } } },+ );+ expect((await storage.readScheduleMCPConsent(identity))?.enrollment).toBeNull();+ expect(await confirm()).toBe(false);+ expect(await admit('future')).toBe(false);+});+it('rejects credential-bearing or mismatched records at the persistence boundary', async () => {+ const bad = enrollment();+ bad.consents[0].identity = { ...identity, agentId: 'changed' };+ await expect(confirm(null, bad)).rejects.toThrow('binding');+ const secret = enrollment();+ Object.assign(secret.consents[0].resource, { accessToken: 'do-not-store' });+ await expect(confirm(null, secret)).rejects.toThrow();+});++it('uses only classic update operators for confirmation, revocation and admission', async () => {+ const update = jest.spyOn(mongoose.models.Schedule, 'updateOne');+ await confirm();+ await admit();+ await storage.revokeScheduleMCPConsent(identity, 'grant-1');+ for (const call of update.mock.calls) {+ const [filter, operation] = Array.from(call);+ expect(Array.isArray(operation)).toBe(false);+ expect(JSON.stringify(filter)).not.toContain('$$NOW');+ expect(JSON.stringify(operation)).not.toContain('$$NOW');+ expect(Object.keys(operation!)).toEqual(['$set']);+ }+});diff --git a/packages/data-schemas/src/methods/scheduleConsent.ts b/packages/data-schemas/src/methods/scheduleConsent.tsnew file mode 100644index 0000000000..d19976da4c--- /dev/null+++ b/packages/data-schemas/src/methods/scheduleConsent.ts@@ -0,0 +1,158 @@+import { randomUUID } from 'node:crypto';+import { scheduledMCPEnrollmentSchema } from 'librechat-data-provider';+import type { ScheduledMCPIdentity, ScheduledMCPEnrollment } from 'librechat-data-provider';+import type { Model } from 'mongoose';+import type { IScheduleDocument } from '~/types/schedule';++export interface ScheduleConsentSnapshot {+ compatible?: boolean;+ agentId: string;+ enabled: boolean;+ configRevision: number;+ enrollment: ScheduledMCPEnrollment | null;+}++export interface ScheduleMCPConsentStorage {+ readScheduleMCPConsent: (+ identity: ScheduledMCPIdentity,+ ) => Promise<ScheduleConsentSnapshot | null>;+ confirmScheduleMCPConsent: (input: {+ identity: ScheduledMCPIdentity;+ expectedConfigRevision: number;+ expectedRevision: string | null;+ enrollment: ScheduledMCPEnrollment;+ }) => Promise<boolean>;+ revokeScheduleMCPConsent: (identity: ScheduledMCPIdentity, revision: string) => Promise<boolean>;+ admitScheduleMCPConsent: (input: {+ identity: ScheduledMCPIdentity;+ expectedConfigRevision: number;+ revision: string;+ consentId: string;+ }) => Promise<boolean>;+}++export function createScheduleMCPConsentStorage(+ mongoose: typeof import('mongoose'),+ options: { now?: () => number } = {},+): ScheduleMCPConsentStorage {+ const now = options.now ?? Date.now;+ const model = (): Model<IScheduleDocument> =>+ mongoose.models.Schedule as Model<IScheduleDocument>;+ const scope = (identity: ScheduledMCPIdentity) => ({+ id: identity.scheduleId,+ user: identity.ownerId,+ tenantId: identity.tenantId,+ deleting: { $ne: true },+ erased: { $ne: true },+ deletionSuspension: { $exists: false },+ });+ const revisionFilter = (revision: string | null) =>+ revision == null+ ? { mcpConsent: { $exists: false } }+ : { 'mcpConsent.version': 1, 'mcpConsent.revision': revision };+ const configFilter = (revision: number) =>+ revision === 0+ ? { $or: [{ configRevision: 0 }, { configRevision: { $exists: false } }] }+ : { configRevision: revision };++ return {+ async readScheduleMCPConsent(identity) {+ const row = await model()+ .findOne(scope(identity))+ .select('agent_id enabled configRevision mcpConsent')+ .read('primary')+ .lean();+ if (!row) return null;+ const parsed = scheduledMCPEnrollmentSchema.safeParse(row.mcpConsent);+ return {+ agentId: row.agent_id,+ enabled: row.enabled,+ configRevision: row.configRevision ?? 0,+ enrollment: parsed.success ? parsed.data : null,+ compatible: row.mcpConsent === undefined || parsed.success,+ };+ },+ async confirmScheduleMCPConsent(input) {+ const enrollment = scheduledMCPEnrollmentSchema.parse(input.enrollment);+ if (+ enrollment.scheduleRevision !== input.expectedConfigRevision ||+ enrollment.consents.some(+ (consent) =>+ consent.identity.scheduleId !== input.identity.scheduleId ||+ consent.identity.ownerId !== input.identity.ownerId ||+ consent.identity.tenantId !== input.identity.tenantId ||+ consent.identity.agentId !== input.identity.agentId ||+ consent.identity.invocationMode !== 'delegated' ||+ consent.revision !== enrollment.revision ||+ consent.revokedAtMs != null,+ )+ )+ throw new Error('Invalid scheduled MCP enrollment binding');+ if (enrollment.consents.some((consent) => consent.absoluteExpiresAtMs <= now())) return false;+ const result = await model().updateOne(+ {+ ...scope(input.identity),+ ...configFilter(input.expectedConfigRevision),+ ...revisionFilter(input.expectedRevision),+ agent_id: input.identity.agentId,+ },+ { $set: { mcpConsent: enrollment } },+ { runValidators: true },+ );+ return result.matchedCount === 1;+ },+ async revokeScheduleMCPConsent(identity, revision) {+ const snapshot = await model()+ .findOne({ ...scope(identity), ...revisionFilter(revision) })+ .select('mcpConsent')+ .read('primary')+ .lean();+ const parsed = scheduledMCPEnrollmentSchema.safeParse(snapshot?.mcpConsent);+ if (!parsed.success) return false;+ const revokedRevision = randomUUID();+ const revokedAtMs = now();+ const enrollment = {+ ...parsed.data,+ revision: revokedRevision,+ consents: parsed.data.consents.map((consent) => ({+ ...consent,+ revision: revokedRevision,+ revokedAtMs: consent.revokedAtMs ?? revokedAtMs,+ })),+ };+ const result = await model().updateOne(+ { ...scope(identity), ...revisionFilter(revision) },+ { $set: { mcpConsent: enrollment } },+ { runValidators: true },+ );+ return result.matchedCount === 1;+ },+ async admitScheduleMCPConsent(input) {+ const result = await model().updateOne(+ {+ ...scope(input.identity),+ ...configFilter(input.expectedConfigRevision),+ ...revisionFilter(input.revision),+ agent_id: input.identity.agentId,+ enabled: true,+ 'mcpConsent.consents': {+ $elemMatch: { id: input.consentId, revision: input.revision, revokedAtMs: null },+ },+ 'mcpConsent.consents.0': { $exists: true },+ $nor: [+ {+ 'mcpConsent.consents': {+ $elemMatch: {+ $or: [{ revokedAtMs: { $ne: null } }, { absoluteExpiresAtMs: { $lte: now() } }],+ },+ },+ },+ ],+ },+ { $set: { 'mcpConsent.revision': input.revision } },+ { timestamps: false },+ );+ return result.matchedCount === 1;+ },+ };+}diff --git a/packages/data-schemas/src/schema/schedule.ts b/packages/data-schemas/src/schema/schedule.tsindex e52cf95863..df7b6a040e 100644--- a/packages/data-schemas/src/schema/schedule.ts+++ b/packages/data-schemas/src/schema/schedule.ts@@ -1,5 +1,6 @@import { Schema } from 'mongoose';import { SCHEDULE_CRON_MAX_LENGTH } from 'librechat-data-provider';+import { scheduledMCPEnrollmentSchema } from 'librechat-data-provider';import type { IScheduleDocument } from '~/types/schedule';/** `cadence` is a nested path rather than a subdocument, so a validator on@@ -104,6 +105,12 @@ const scheduleSchema: Schema<IScheduleDocument> = new Schema(type: [String],default: undefined,},+ mcpConsent: {+ type: Schema.Types.Mixed,+ default: undefined,+ validate: (value: import('librechat-data-provider').ScheduledMCPEnrollment) =>+ scheduledMCPEnrollmentSchema.safeParse(value).success,+ },cron: {type: String,},diff --git a/packages/data-schemas/src/types/schedule.ts b/packages/data-schemas/src/types/schedule.tsindex 52be372a35..812804adbb 100644--- a/packages/data-schemas/src/types/schedule.ts+++ b/packages/data-schemas/src/types/schedule.ts@@ -3,6 +3,7 @@ import type {ScheduleDisabledReason,TScheduleCadence,} from 'librechat-data-provider';+import type { ScheduledMCPEnrollment } from 'librechat-data-provider';import type { ScheduleMCPOutcome } from 'librechat-data-provider';import type { Document, Types } from 'mongoose';@@ -22,6 +23,7 @@ export interface ISchedule {chatProjectId?: string;file_ids?: string[];tools?: string[];+ mcpConsent?: ScheduledMCPEnrollment;cron?: string;enabled: boolean;disabledReason?: ScheduleDisabledReason;