🐣 feat: Authorize Schedules During Creation (#18489)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Backend Unit Tests / backend (push) Blocked by required conditions
Channel Gateway / gateway (push) Waiting to run
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Frontend Unit Tests / frontend (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
Playwright E2E Tests / Codegraph select (push) Waiting to run
Playwright E2E Tests / Shard timings (push) Waiting to run
Playwright E2E Tests / e2e () (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 1) (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 2) (push) Blocked by required conditions
Playwright E2E Tests / MCP Apps (browser and server) (push) Waiting to run
Playwright E2E Tests / e2e (push) Blocked by required conditions
Playwright Shard Timings / Record shard timings (push) Waiting to run
Repository Safety / Confine repository symlinks (push) Waiting to run

* 🪪 feat: Authorize a Schedule in the Same Step That Creates It

Where consent is on, a new schedule was created unauthorized and stayed exempt until
its owner edited it or the operator's deadline passed. The create form now asks what the
schedule may use, from the offer for its agent, and the schedule is created with its
grant in one write. A schedule created without a choice is marked as needing
authorization from the start.

The grant dialog's tool list and choice are split out so the form shows the same thing.

* 🔁 fix: Read the Offer Again When a Create's Authorization Is Turned Down

The create form kept the offer it first read. Once the server refused a choice made
from it, every retry sent the same refused digest. The form now reads the offer again,
keeps the ticks that still apply, and holds the create until the new offer is in.

* 🧭 fix: Check Readiness at Creation for the Tools the Owner Allowed

A schedule being created has no stored grant, so its readiness check covered every
MCP tool the agents select, including servers the owner left out. The grant is now
validated first and handed to the check, which covers what it allows.
This commit is contained in:
Danny Avila 2026-11-19 09:21:33 -05:00 • committed by GitHub
parent bf8dd41a81
commit 56d8660ca0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 1524 additions and 483 deletions

View file

@ -84,10 +84,15 @@ const handlers = createSchedulesHandlers({
// Durable account-deletion barrier. A one-shot disable scan cannot close the
// create race, so every scheduling WRITE consults the user-level flag instead.
isUserDeleting,
// Where consent is on, a schedule is authorized in the same write that creates it.
grant: (identity, choice, options) =>
require('~/server/services/Schedules/consent').consent.service.grant(identity, choice, options),
});
const consentHost = require('~/server/services/Schedules/consent').consent;
/** Before the `/:id` routes: what the owner could allow a schedule of an agent not yet created. */
router.post('/mcp-consent/offer', checkSchedulesCreate, consentHost.handlers.draft);
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);

View file

@ -0,0 +1,49 @@
/**
* Loads the real wiring against the real packages. Only the app's own singletons are stood
* in for, so something the packages do not provide fails here and not when the router loads.
*/
jest.mock('~/models', () => ({
findUser: jest.fn(),
getRoleByName: jest.fn(),
getScheduleById: jest.fn(),
getAgentGraphNodes: jest.fn(),
resolveAgentGraphAccess: jest.fn(),
getScheduleMCPCompletionState: jest.fn(),
}));
jest.mock('~/config', () => ({ getMCPServersRegistry: jest.fn() }));
jest.mock('~/server/services/Config/app', () => ({ getAppConfig: jest.fn() }));
jest.mock('~/server/controllers/ModelController', () => ({ getModelsConfig: jest.fn() }));
jest.mock('./access', () => ({ resolveAgentFireAccess: jest.fn() }));
const { findUser, getRoleByName } = require('~/models');
const { resolveAgentFireAccess } = require('./access');
describe('schedule consent wiring', () => {
it('provides the routes and the service the schedule router uses', () => {
const { consent } = require('./consent');
expect(consent.handlers).toEqual({
draft: expect.any(Function),
get: expect.any(Function),
confirm: expect.any(Function),
revoke: expect.any(Function),
});
expect(consent.service.grant).toEqual(expect.any(Function));
});
it('answers the offer for a schedule not yet created from the caller and the agent it names', async () => {
const { consent } = require('./consent');
const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
// No agent named: there is nothing to make an offer for.
await consent.handlers.draft({ user: { id: 'owner' }, body: {} }, res);
expect(res.status).toHaveBeenCalledWith(404);
findUser.mockResolvedValue({ id: 'owner', role: 'USER' });
getRoleByName.mockResolvedValue({ permissions: {} });
resolveAgentFireAccess.mockResolvedValue('ok');
res.status.mockClear();
// An owner whose role may not use schedules is refused, by the same check as a stored one.
await consent.handlers.draft({ user: { id: 'owner' }, body: { agent_id: 'agent_a' } }, res);
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenLastCalledWith({ code: 'consent_forbidden' });
});
});

View file

@ -1,22 +1,10 @@
import { useState, useId } from 'react';
import { Tools } from 'librechat-data-provider';
import {
Button,
Input,
Label,
Spinner,
Checkbox,
OGDialog,
OGDialogTemplate,
} from '@librechat/client';
import type {
ScheduledMCPTarget,
ScheduleMCPConsentView,
ConfirmScheduleMCPConsent,
} from 'librechat-data-provider';
import { Button, Input, Label, Spinner, OGDialog, OGDialogTemplate } from '@librechat/client';
import type { ScheduleMCPConsentView, ConfirmScheduleMCPConsent } from 'librechat-data-provider';
import type { UseMutationResult, UseQueryResult } from '@tanstack/react-query';
import type { MutableRefObject, ReactNode } from 'react';
import type { TranslationKeys } from '~/hooks';
import GrantTools, { useGrantChoice } from './GrantTools';
import { useLocalize } from '~/hooks';
/** Where a grant is read and written: a schedule's, or an API key's for one agent. */
@ -44,81 +32,12 @@ const statusKeys = {
unsupported: 'com_ui_schedule_consent_unsupported',
} as const;
/** Built-in tools the owner knows by name. Any other, such as an action, is shown by its key. */
const toolKeys = new Map<string, TranslationKeys>([
[Tools.execute_code, 'com_ui_schedule_consent_tool_code'],
[Tools.web_search, 'com_ui_schedule_consent_tool_web'],
[Tools.file_search, 'com_ui_schedule_consent_tool_files'],
]);
const messageKeys = {
error: 'com_ui_schedule_consent_error',
revoked: 'com_ui_schedule_consent_revoked',
success: 'com_ui_schedule_consent_confirmed',
} as const;
/** Every tool on offer for a server, whichever agents selected it. */
function offeredTools(target: ScheduledMCPTarget): string[] {
return [...new Set(target.permittedTools.flatMap((selection) => selection.tools))].sort();
}
/**
* The owner's starting point: what the stored grant already allows and is still on offer.
* A tool whose definition changed starts unticked, so allowing the new one is a decision.
*/
function initialChoice(data: ScheduleMCPConsentView): Record<string, string[]> {
return Object.fromEntries(
data.targets.map((target) => {
const offered = offeredTools(target);
const allowed = data.allowed[target.resource.serverName] ?? [];
const changed = data.changed[target.resource.serverName] ?? [];
return [
target.resource.serverName,
offered.filter((tool) => allowed.includes(tool) && !changed.includes(tool)),
];
}),
);
}
/**
* The owner's ticks, with the grant they were made against and the tools it marked as
* changed at the time. A mark belongs to one grant: the same tool marked again under a later
* grant is a different change, which the owner has not looked at.
*/
interface Edited {
choice: Record<string, string[]>;
revision: string | null;
changed: Record<string, string[]>;
}
/**
* The owner's ticks, kept to what is on offer now. The offer is read again while the dialog
* is open: a server or tool the agents dropped has no box left to untick, and a tool marked
* as changed since the owner last ticked anything, or marked under another grant, loses its
* tick, so allowing the new definition is something the owner does with the warning in view.
*/
function currentChoice(
data: ScheduleMCPConsentView,
edited: Edited | null,
): Record<string, string[]> {
const initial = initialChoice(data);
if (!edited) return initial;
return Object.fromEntries(
data.targets.map((target) => {
const { serverName } = target.resource;
const offered = offeredTools(target);
const marked = data.changed[serverName] ?? [];
const seen = edited.revision === data.revision ? (edited.changed[serverName] ?? []) : [];
return [
serverName,
(edited.choice[serverName] ?? initial[serverName]).filter(
(tool) => offered.includes(tool) && (!marked.includes(tool) || seen.includes(tool)),
),
];
}),
);
}
/**
* The owner's view of one grant: which MCP servers and tools a run may use while nobody is
* watching. `children` sits above the grant, for whatever picks its subject; `subjectKey`
@ -179,102 +98,27 @@ function Grant({
const idle = query.fetchStatus === 'idle' && query.data == null && !query.isError;
const [hours, setHours] = useState(1);
const [message, setMessage] = useState<'success' | 'revoked' | 'error' | null>(null);
/** Null until the owner changes a box, so a refetch cannot overwrite a choice in progress. */
const [edited, setEdited] = useState<Edited | null>(null);
const busy = confirm.isLoading || revoke.isLoading || query.isFetching;
const data: ScheduleMCPConsentView | undefined = query.data;
const choosing = canConfirm && data?.offer != null;
const choice = data ? currentChoice(data, edited) : {};
/** Null until the owner changes an "ask me first" box, with the grant it was changed against. */
const [editedAsking, setEditedAsking] = useState<{
revision: string | null;
tools: Record<string, string[]>;
} | null>(null);
const canAsk = data?.approval === true;
/**
* Kept apart from the ticks. Starts from the stored grant, even where a run cannot pause
* and for a tool that is not ticked right now: one that changed starts unticked, and
* ticking it again must not turn a tool the owner approves each time into an unattended one.
* The owner's edits hold only for the grant they were made against: a question added to a
* grant confirmed elsewhere is not theirs to drop unseen.
*/
const asking =
(editedAsking?.revision === data?.revision ? editedAsking?.tools : undefined) ??
data?.asking ??
{};
const noteId = useId();
const otherId = useId();
/** Null until the owner changes one of the other tools, with the grant it was changed against. */
const [editedOther, setEditedOther] = useState<{
revision: string | null;
tools: string[];
} | null>(null);
/** The agents' tools that are not MCP tools: each one allowed or left out, like an MCP tool. */
const offeredOther = data?.tools.offered ?? [];
const other = (
(editedOther?.revision === data?.revision ? editedOther?.tools : undefined) ??
data?.tools.allowed ??
[]
).filter((tool) => offeredOther.includes(tool));
/** A grant allows something: an MCP tool, or one of the other tools. */
const chosenCount =
Object.values(choice).reduce((count, tools) => count + tools.length, 0) + other.length;
const setOther = (tools: string[]) => setEditedOther({ revision: data?.revision ?? null, tools });
/** One click for an owner who trusts the agent as it is: every server, every tool. */
const allowEverything = () => {
if (!data) return;
setEdited({
choice: Object.fromEntries(
data.targets.map((target) => [target.resource.serverName, offeredTools(target)]),
),
revision: data.revision,
changed: data.changed,
});
setOther(offeredOther);
};
const toolLabel = (tool: string) => {
const key = toolKeys.get(tool);
return key ? localize(key) : tool;
};
const setTools = (serverName: string, tools: string[]) =>
setEdited({
choice: { ...choice, [serverName]: tools },
revision: data?.revision ?? null,
changed: data?.changed ?? {},
});
const setAsking = (serverName: string, tools: string[]) =>
setEditedAsking({
revision: data?.revision ?? null,
tools: { ...asking, [serverName]: tools },
});
/** Sent with the confirmation: of the tools ticked now, the ones the owner asks about. */
const ask = Object.fromEntries(
Object.entries(asking)
.map(([serverName, tools]): [string, string[]] => [
serverName,
tools.filter((tool) => (choice[serverName] ?? []).includes(tool)),
])
.filter(([, tools]) => tools.length > 0),
);
const state = useGrantChoice(data);
const commit = () => {
if (!data?.offer || chosenCount === 0) return;
if (!data?.offer || state.count === 0) return;
setMessage(null);
confirm.mutate(
{
offerDigest: data.offer.digest,
expectedRevision: data.revision,
lifetimeHours: hours,
allow: choice,
allow: state.choice,
// Always sent: left out, the server keeps what the stored grant asks about.
ask,
ask: state.ask,
// Likewise: left out, the server keeps the other tools the stored grant allows.
tools: other,
tools: state.other,
},
{
onSuccess: () => {
setEdited(null);
setEditedAsking(null);
setEditedOther(null);
state.reset();
setMessage('success');
},
onError: () => setMessage('error'),
@ -322,126 +166,7 @@ function Grant({
})}
</p>
)}
{choosing && !canAsk && Object.keys(ask).length > 0 && (
<p id={noteId} className="text-status-warning text-sm">
{localize('com_ui_schedule_consent_ask_unavailable')}
</p>
)}
{choosing && (
<Button variant="outline" disabled={busy} onClick={allowEverything}>
{localize('com_ui_schedule_consent_allow_all')}
</Button>
)}
<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 wrap-anywhere">
{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>
)}
{choosing ? (
<ToolChoice
serverName={target.resource.serverName}
offered={offeredTools(target)}
chosen={choice[target.resource.serverName] ?? []}
changed={data.changed[target.resource.serverName] ?? []}
asking={asking[target.resource.serverName] ?? []}
askable={
canAsk
? offeredTools(target)
: (data.asking[target.resource.serverName] ?? [])
}
askNoteId={canAsk ? undefined : noteId}
disabled={busy}
onChange={(tools) => setTools(target.resource.serverName, tools)}
onAskingChange={(tools) => setAsking(target.resource.serverName, tools)}
/>
) : (
<>
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_allowed', {
tools: (data.allowed[target.resource.serverName] ?? []).join(', '),
})}
</p>
{(data.asking[target.resource.serverName] ?? []).length > 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_asking', {
tools: data.asking[target.resource.serverName].join(', '),
})}
</p>
)}
{(data.changed[target.resource.serverName] ?? []).length > 0 && (
<p className="text-status-warning text-xs">
{localize('com_ui_schedule_consent_changed_tools', {
tools: data.changed[target.resource.serverName].join(', '),
})}
</p>
)}
</>
)}
</li>
))}
</ul>
{choosing && offeredOther.length > 0 && (
<fieldset className="space-y-1" disabled={busy}>
<legend className="text-sm font-medium">
{localize('com_ui_schedule_consent_other_tools')}
</legend>
<ul className="space-y-1 pl-6">
{offeredOther.map((tool) => (
<li key={tool} className="flex items-center gap-2">
<Checkbox
id={`${otherId}-${tool}`}
checked={other.includes(tool)}
disabled={busy}
aria-labelledby={`${otherId}-${tool}-label`}
onCheckedChange={(checked) =>
setOther(
checked === true
? offeredOther.filter((name) => name === tool || other.includes(name))
: other.filter((name) => name !== tool),
)
}
/>
<Label
id={`${otherId}-${tool}-label`}
htmlFor={`${otherId}-${tool}`}
className="text-xs break-all"
>
{toolLabel(tool)}
</Label>
</li>
))}
</ul>
</fieldset>
)}
{!choosing && data.tools.allowed.length > 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_other_allowed', {
tools: data.tools.allowed.map(toolLabel).join(', '),
})}
</p>
)}
<GrantTools data={data} choosing={choosing} state={state} busy={busy} />
{canConfirm && data.offer && (
<>
<Label htmlFor={inputId}>{localize('com_ui_schedule_consent_hours')}</Label>
@ -458,7 +183,7 @@ function Grant({
onClick={commit}
disabled={
busy ||
chosenCount === 0 ||
state.count === 0 ||
!Number.isInteger(hours) ||
hours < 1 ||
hours > data.offer.maxLifetimeHours
@ -466,7 +191,7 @@ function Grant({
>
{localize('com_ui_schedule_consent_confirm')}
</Button>
{chosenCount === 0 && (
{state.count === 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_none_selected')}
</p>
@ -490,111 +215,3 @@ function Grant({
</>
);
}
/** One server's tools: a box for the whole server and one per tool. Unchecked means refused. */
function ToolChoice({
serverName,
offered,
chosen,
changed,
asking,
askable,
askNoteId,
disabled,
onChange,
onAskingChange,
}: {
serverName: string;
offered: string[];
chosen: string[];
/** Tools the server changed since they were allowed. Refused until confirmed again. */
changed: string[];
/** Allowed tools the owner approves call by call. */
asking: string[];
/**
* Tools that get an "ask me first" box. Where a scheduled run cannot pause, only the ones
* the stored grant already asks about, so the owner can keep or drop them but add none.
*/
askable: string[];
/** The note explaining that a run cannot pause here, when it is shown. */
askNoteId?: string;
disabled: boolean;
onChange: (tools: string[]) => void;
onAskingChange: (tools: string[]) => void;
}) {
const localize = useLocalize();
const groupId = useId();
/** Checked only when every tool is: the shared box has no partly-selected appearance. */
const all = offered.length > 0 && offered.every((tool) => chosen.includes(tool));
return (
<fieldset className="mt-2 space-y-1" disabled={disabled}>
<div className="flex items-center gap-2">
<Checkbox
id={`${groupId}-all`}
checked={all}
disabled={disabled}
aria-label={localize('com_ui_schedule_consent_allow_server', { server: serverName })}
onCheckedChange={(checked) => onChange(checked === true ? offered : [])}
/>
<Label htmlFor={`${groupId}-all`} className="text-xs">
{localize('com_ui_schedule_consent_allow_server', { server: serverName })}
</Label>
</div>
<ul className="space-y-1 pl-6">
{offered.map((tool) => (
<li key={tool}>
<div className="flex items-center gap-2">
<Checkbox
id={`${groupId}-${tool}`}
checked={chosen.includes(tool)}
disabled={disabled}
aria-labelledby={`${groupId}-${tool}-label`}
aria-describedby={changed.includes(tool) ? `${groupId}-${tool}-changed` : undefined}
onCheckedChange={(checked) =>
onChange(
checked === true
? offered.filter((name) => name === tool || chosen.includes(name))
: chosen.filter((name) => name !== tool),
)
}
/>
<Label
id={`${groupId}-${tool}-label`}
htmlFor={`${groupId}-${tool}`}
className="text-xs break-all"
>
{tool}
</Label>
{askable.includes(tool) && chosen.includes(tool) && (
<span className="ml-auto flex shrink-0 items-center gap-2">
<Checkbox
id={`${groupId}-${tool}-ask`}
checked={asking.includes(tool)}
disabled={disabled}
aria-label={localize('com_ui_schedule_consent_ask_tool', { tool })}
aria-describedby={askNoteId}
onCheckedChange={(checked) =>
onAskingChange(
checked === true
? [...asking, tool]
: asking.filter((name) => name !== tool),
)
}
/>
<Label htmlFor={`${groupId}-${tool}-ask`} variant="secondary" className="text-xs">
{localize('com_ui_schedule_consent_ask_first')}
</Label>
</span>
)}
</div>
{changed.includes(tool) && (
<p id={`${groupId}-${tool}-changed`} className="text-status-warning pl-6 text-xs">
{localize('com_ui_schedule_consent_tool_changed')}
</p>
)}
</li>
))}
</ul>
</fieldset>
);
}

View file

@ -0,0 +1,452 @@
import { useId, useState } from 'react';
import { Tools } from 'librechat-data-provider';
import { Label, Button, Checkbox } from '@librechat/client';
import type { ScheduledMCPTarget, ScheduleMCPConsentView } from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
import { useLocalize } from '~/hooks';
/** Built-in tools the owner knows by name. Any other, such as an action, is shown by its key. */
const toolKeys = new Map<string, TranslationKeys>([
[Tools.execute_code, 'com_ui_schedule_consent_tool_code'],
[Tools.web_search, 'com_ui_schedule_consent_tool_web'],
[Tools.file_search, 'com_ui_schedule_consent_tool_files'],
]);
/** Every tool on offer for a server, whichever agents selected it. */
function offeredTools(target: ScheduledMCPTarget): string[] {
return [...new Set(target.permittedTools.flatMap((selection) => selection.tools))].sort();
}
/**
* The owner's starting point: what the stored grant already allows and is still on offer.
* A tool whose definition changed starts unticked, so allowing the new one is a decision.
*/
function initialChoice(data: ScheduleMCPConsentView): Record<string, string[]> {
return Object.fromEntries(
data.targets.map((target) => {
const offered = offeredTools(target);
const allowed = data.allowed[target.resource.serverName] ?? [];
const changed = data.changed[target.resource.serverName] ?? [];
return [
target.resource.serverName,
offered.filter((tool) => allowed.includes(tool) && !changed.includes(tool)),
];
}),
);
}
/**
* The owner's ticks, with the grant they were made against and the tools it marked as
* changed at the time. A mark belongs to one grant: the same tool marked again under a later
* grant is a different change, which the owner has not looked at.
*/
interface Edited {
choice: Record<string, string[]>;
revision: string | null;
changed: Record<string, string[]>;
}
/**
* The owner's ticks, kept to what is on offer now. The offer is read again while the dialog
* is open: a server or tool the agents dropped has no box left to untick, and a tool marked
* as changed since the owner last ticked anything, or marked under another grant, loses its
* tick, so allowing the new definition is something the owner does with the warning in view.
*/
function currentChoice(
data: ScheduleMCPConsentView,
edited: Edited | null,
): Record<string, string[]> {
const initial = initialChoice(data);
if (!edited) return initial;
return Object.fromEntries(
data.targets.map((target) => {
const { serverName } = target.resource;
const offered = offeredTools(target);
const marked = data.changed[serverName] ?? [];
const seen = edited.revision === data.revision ? (edited.changed[serverName] ?? []) : [];
return [
serverName,
(edited.choice[serverName] ?? initial[serverName]).filter(
(tool) => offered.includes(tool) && (!marked.includes(tool) || seen.includes(tool)),
),
];
}),
);
}
/** The owner's choice from one offer, and the ways to change it. */
export interface GrantChoice {
/** The MCP tools ticked, by server. */
choice: Record<string, string[]>;
/** The ticked MCP tools the owner approves call by call, by server: what a confirmation sends. */
ask: Record<string, string[]>;
asking: Record<string, string[]>;
/** The other tools ticked. */
other: string[];
offeredOther: string[];
canAsk: boolean;
/** How many tools of either kind are ticked. A grant allows at least one. */
count: number;
setTools: (serverName: string, tools: string[]) => void;
setAsking: (serverName: string, tools: string[]) => void;
setOther: (tools: string[]) => void;
allowEverything: () => void;
/** Back to what the offer starts from, once a choice has been stored. */
reset: () => void;
}
/** The owner's choice from an offer: what is ticked now, starting from what the offer says. */
export function useGrantChoice(data: ScheduleMCPConsentView | undefined): GrantChoice {
/** Null until the owner changes a box, so a refetch cannot overwrite a choice in progress. */
const [edited, setEdited] = useState<Edited | null>(null);
const choice = data ? currentChoice(data, edited) : {};
/** Null until the owner changes an "ask me first" box, with the grant it was changed against. */
const [editedAsking, setEditedAsking] = useState<{
revision: string | null;
tools: Record<string, string[]>;
} | null>(null);
const canAsk = data?.approval === true;
/**
* Kept apart from the ticks. Starts from the stored grant, even where a run cannot pause
* and for a tool that is not ticked right now: one that changed starts unticked, and
* ticking it again must not turn a tool the owner approves each time into an unattended one.
* The owner's edits hold only for the grant they were made against: a question added to a
* grant confirmed elsewhere is not theirs to drop unseen.
*/
const asking =
(editedAsking?.revision === data?.revision ? editedAsking?.tools : undefined) ??
data?.asking ??
{};
/** Null until the owner changes one of the other tools, with the grant it was changed against. */
const [editedOther, setEditedOther] = useState<{
revision: string | null;
tools: string[];
} | null>(null);
/** The agents' tools that are not MCP tools: each one allowed or left out, like an MCP tool. */
const offeredOther = data?.tools.offered ?? [];
const other = (
(editedOther?.revision === data?.revision ? editedOther?.tools : undefined) ??
data?.tools.allowed ??
[]
).filter((tool) => offeredOther.includes(tool));
/** A grant allows something: an MCP tool, or one of the other tools. */
const chosenCount =
Object.values(choice).reduce((count, tools) => count + tools.length, 0) + other.length;
const setOther = (tools: string[]) => setEditedOther({ revision: data?.revision ?? null, tools });
/** One click for an owner who trusts the agent as it is: every server, every tool. */
const allowEverything = () => {
if (!data) return;
setEdited({
choice: Object.fromEntries(
data.targets.map((target) => [target.resource.serverName, offeredTools(target)]),
),
revision: data.revision,
changed: data.changed,
});
setOther(offeredOther);
};
const setTools = (serverName: string, tools: string[]) =>
setEdited({
choice: { ...choice, [serverName]: tools },
revision: data?.revision ?? null,
changed: data?.changed ?? {},
});
const setAsking = (serverName: string, tools: string[]) =>
setEditedAsking({
revision: data?.revision ?? null,
tools: { ...asking, [serverName]: tools },
});
/** Sent with the confirmation: of the tools ticked now, the ones the owner asks about. */
const ask = Object.fromEntries(
Object.entries(asking)
.map(([serverName, tools]): [string, string[]] => [
serverName,
tools.filter((tool) => (choice[serverName] ?? []).includes(tool)),
])
.filter(([, tools]) => tools.length > 0),
);
return {
choice,
ask,
asking,
other,
offeredOther,
canAsk,
count: chosenCount,
setTools,
setAsking,
setOther,
allowEverything,
reset: () => {
setEdited(null);
setEditedAsking(null);
setEditedOther(null);
},
};
}
/**
* The servers and tools of one offer. While the owner is choosing, each is a box to tick;
* otherwise what the stored grant allows is listed.
*/
export default function GrantTools({
data,
choosing,
state,
busy,
}: {
data: ScheduleMCPConsentView;
choosing: boolean;
state: GrantChoice;
busy: boolean;
}) {
const localize = useLocalize();
const noteId = useId();
const otherId = useId();
const {
choice,
ask,
asking,
other,
offeredOther,
canAsk,
setTools,
setAsking,
setOther,
allowEverything,
} = state;
const toolLabel = (tool: string) => {
const key = toolKeys.get(tool);
return key ? localize(key) : tool;
};
return (
<>
{choosing && !canAsk && Object.keys(ask).length > 0 && (
<p id={noteId} className="text-status-warning text-sm">
{localize('com_ui_schedule_consent_ask_unavailable')}
</p>
)}
{choosing && (
<Button variant="outline" disabled={busy} onClick={allowEverything}>
{localize('com_ui_schedule_consent_allow_all')}
</Button>
)}
<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 wrap-anywhere">
{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>
)}
{choosing ? (
<ToolChoice
serverName={target.resource.serverName}
offered={offeredTools(target)}
chosen={choice[target.resource.serverName] ?? []}
changed={data.changed[target.resource.serverName] ?? []}
asking={asking[target.resource.serverName] ?? []}
askable={
canAsk ? offeredTools(target) : (data.asking[target.resource.serverName] ?? [])
}
askNoteId={canAsk ? undefined : noteId}
disabled={busy}
onChange={(tools) => setTools(target.resource.serverName, tools)}
onAskingChange={(tools) => setAsking(target.resource.serverName, tools)}
/>
) : (
<>
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_allowed', {
tools: (data.allowed[target.resource.serverName] ?? []).join(', '),
})}
</p>
{(data.asking[target.resource.serverName] ?? []).length > 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_asking', {
tools: data.asking[target.resource.serverName].join(', '),
})}
</p>
)}
{(data.changed[target.resource.serverName] ?? []).length > 0 && (
<p className="text-status-warning text-xs">
{localize('com_ui_schedule_consent_changed_tools', {
tools: data.changed[target.resource.serverName].join(', '),
})}
</p>
)}
</>
)}
</li>
))}
</ul>
{choosing && offeredOther.length > 0 && (
<fieldset className="space-y-1" disabled={busy}>
<legend className="text-sm font-medium">
{localize('com_ui_schedule_consent_other_tools')}
</legend>
<ul className="space-y-1 pl-6">
{offeredOther.map((tool) => (
<li key={tool} className="flex items-center gap-2">
<Checkbox
id={`${otherId}-${tool}`}
checked={other.includes(tool)}
disabled={busy}
aria-labelledby={`${otherId}-${tool}-label`}
onCheckedChange={(checked) =>
setOther(
checked === true
? offeredOther.filter((name) => name === tool || other.includes(name))
: other.filter((name) => name !== tool),
)
}
/>
<Label
id={`${otherId}-${tool}-label`}
htmlFor={`${otherId}-${tool}`}
className="text-xs break-all"
>
{toolLabel(tool)}
</Label>
</li>
))}
</ul>
</fieldset>
)}
{!choosing && data.tools.allowed.length > 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_other_allowed', {
tools: data.tools.allowed.map(toolLabel).join(', '),
})}
</p>
)}
</>
);
}
/** One server's tools: a box for the whole server and one per tool. Unchecked means refused. */
function ToolChoice({
serverName,
offered,
chosen,
changed,
asking,
askable,
askNoteId,
disabled,
onChange,
onAskingChange,
}: {
serverName: string;
offered: string[];
chosen: string[];
/** Tools the server changed since they were allowed. Refused until confirmed again. */
changed: string[];
/** Allowed tools the owner approves call by call. */
asking: string[];
/**
* Tools that get an "ask me first" box. Where a scheduled run cannot pause, only the ones
* the stored grant already asks about, so the owner can keep or drop them but add none.
*/
askable: string[];
/** The note explaining that a run cannot pause here, when it is shown. */
askNoteId?: string;
disabled: boolean;
onChange: (tools: string[]) => void;
onAskingChange: (tools: string[]) => void;
}) {
const localize = useLocalize();
const groupId = useId();
/** Checked only when every tool is: the shared box has no partly-selected appearance. */
const all = offered.length > 0 && offered.every((tool) => chosen.includes(tool));
return (
<fieldset className="mt-2 space-y-1" disabled={disabled}>
<div className="flex items-center gap-2">
<Checkbox
id={`${groupId}-all`}
checked={all}
disabled={disabled}
aria-label={localize('com_ui_schedule_consent_allow_server', { server: serverName })}
onCheckedChange={(checked) => onChange(checked === true ? offered : [])}
/>
<Label htmlFor={`${groupId}-all`} className="text-xs">
{localize('com_ui_schedule_consent_allow_server', { server: serverName })}
</Label>
</div>
<ul className="space-y-1 pl-6">
{offered.map((tool) => (
<li key={tool}>
<div className="flex items-center gap-2">
<Checkbox
id={`${groupId}-${tool}`}
checked={chosen.includes(tool)}
disabled={disabled}
aria-labelledby={`${groupId}-${tool}-label`}
aria-describedby={changed.includes(tool) ? `${groupId}-${tool}-changed` : undefined}
onCheckedChange={(checked) =>
onChange(
checked === true
? offered.filter((name) => name === tool || chosen.includes(name))
: chosen.filter((name) => name !== tool),
)
}
/>
<Label
id={`${groupId}-${tool}-label`}
htmlFor={`${groupId}-${tool}`}
className="text-xs break-all"
>
{tool}
</Label>
{askable.includes(tool) && chosen.includes(tool) && (
<span className="ml-auto flex shrink-0 items-center gap-2">
<Checkbox
id={`${groupId}-${tool}-ask`}
checked={asking.includes(tool)}
disabled={disabled}
aria-label={localize('com_ui_schedule_consent_ask_tool', { tool })}
aria-describedby={askNoteId}
onCheckedChange={(checked) =>
onAskingChange(
checked === true
? [...asking, tool]
: asking.filter((name) => name !== tool),
)
}
/>
<Label htmlFor={`${groupId}-${tool}-ask`} variant="secondary" className="text-xs">
{localize('com_ui_schedule_consent_ask_first')}
</Label>
</span>
)}
</div>
{changed.includes(tool) && (
<p id={`${groupId}-${tool}-changed`} className="text-status-warning pl-6 text-xs">
{localize('com_ui_schedule_consent_tool_changed')}
</p>
)}
</li>
))}
</ul>
</fieldset>
);
}

View file

@ -0,0 +1,93 @@
import { useEffect, useId, useState } from 'react';
import { Input, Label, Button, Spinner } from '@librechat/client';
import type { ScheduleAuthorization } from 'librechat-data-provider';
import GrantTools, { useGrantChoice } from '~/components/MCP/GrantTools';
import { useScheduleMCPOffer } from '~/data-provider/Schedules/consent';
import { useLocalize } from '~/hooks';
/** What the form needs to know: the owner's choice, and whether one is owed before creating. */
export interface Authorization {
value: ScheduleAuthorization | null;
/** There is something to allow, so the schedule is not created until something is. */
owed: boolean;
}
/**
* What a schedule may use while its owner is away, chosen as it is created. Mounted per
* agent (`key`), so a choice made for one agent is never carried to the next.
*/
export default function Authorize({
agentId,
onChange,
}: {
agentId: string;
onChange: (authorization: Authorization) => void;
}) {
const localize = useLocalize();
const inputId = useId();
const query = useScheduleMCPOffer(agentId);
const state = useGrantChoice(query.data);
const [hours, setHours] = useState(1);
const offer = query.data?.offer ?? null;
/** Not while the offer is being read again: its digest is the one just turned down. */
const valid =
offer != null &&
!query.isFetching &&
state.count > 0 &&
Number.isInteger(hours) &&
hours >= 1 &&
hours <= offer.maxLifetimeHours;
/** Compared by value: the choice is rebuilt on every render, and the form is told on change. */
const chosen = valid
? JSON.stringify({
offerDigest: offer.digest,
lifetimeHours: hours,
allow: state.choice,
ask: state.ask,
tools: state.other,
})
: null;
const owed = offer != null;
useEffect(() => {
onChange({ value: chosen ? (JSON.parse(chosen) as ScheduleAuthorization) : null, owed });
}, [chosen, owed, onChange]);
if (query.isLoading && query.fetchStatus !== 'idle') return <Spinner />;
if (query.isError)
return (
<div role="alert" className="space-y-2">
<p className="text-text-primary text-sm">
{localize('com_ui_schedule_authorize_unavailable')}
</p>
<Button variant="outline" onClick={() => query.refetch()}>
{localize('com_ui_retry')}
</Button>
</div>
);
if (!query.data || !offer) return null;
return (
<fieldset className="space-y-3">
<legend className="text-text-primary text-sm font-medium">
{localize('com_ui_schedule_authorize_title')}
</legend>
<p className="text-text-secondary text-sm">{localize('com_ui_schedule_consent_boundary')}</p>
<GrantTools data={query.data} choosing state={state} busy={false} />
<div className="space-y-1">
<Label htmlFor={inputId}>{localize('com_ui_schedule_consent_hours')}</Label>
<Input
id={inputId}
type="number"
min={1}
max={offer.maxLifetimeHours}
value={hours}
onChange={(event) => setHours(Number(event.target.value))}
/>
</div>
{state.count === 0 && (
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_none_selected')}
</p>
)}
</fieldset>
);
}

View file

@ -33,6 +33,7 @@ import type {
TScheduleCadence,
ScheduleFrequency,
} from 'librechat-data-provider';
import type { Authorization } from './Authorize';
import type { TranslationKeys } from '~/hooks';
import {
describeCadence,
@ -50,12 +51,18 @@ import {
useCreateScheduleMutation,
useUpdateScheduleMutation,
} from '~/data-provider';
import { scheduleMCPErrorMessage, scheduleMCPErrorOutcomes } from './errors';
import {
scheduleMCPErrorMessage,
scheduleMCPErrorOutcomes,
scheduleAuthorizationRejected,
} from './errors';
import { useScheduleMCPOfferRefresh } from '~/data-provider/Schedules/consent';
import { useLocalize, useClockFormat, useWeekStart } from '~/hooks';
import { useChatProjectPicker } from './useScheduleProjects';
import { VariableEditor } from '~/components/Variables';
import ScheduleMCPRecovery from './ScheduleMCPRecovery';
import { rotateWeekFrom } from '~/utils/clock';
import Authorize from './Authorize';
import { cn } from '~/utils';
interface ScheduleDialogProps {
@ -248,6 +255,9 @@ export default function ScheduleDialog({
const pinnedProjectId = schedulesData?.limits.projectId;
const minIntervalMinutes = schedulesData?.limits.minIntervalMinutes;
const requireProject = schedulesData?.limits.requireProject === true;
/** Where consent is on, a new schedule is authorized in the same step that creates it. */
const authorizes = schedule == null && schedulesData?.limits.mcpConsent === true;
const [authorization, setAuthorization] = useState<Authorization>({ value: null, owed: false });
const {
items: loadedProjectItems,
namesById: projectNames,
@ -327,6 +337,7 @@ export default function ScheduleDialog({
/** Fingerprint of the payload the current key was last attempted with. */
const lastAttemptedPayload = useRef<string | null>(null);
const refreshOffer = useScheduleMCPOfferRefresh();
const createSchedule = useCreateScheduleMutation({
onSuccess: () => {
setMCPRecoveryOutcomes([]);
@ -337,8 +348,14 @@ export default function ScheduleDialog({
},
onError: (error) => {
setMCPRecoveryOutcomes(scheduleMCPErrorOutcomes(error));
// What could be allowed changed under the owner's choice. The form stays open on the
// new offer, with the ticks that still apply, so the next create is not turned down too.
const rejected = scheduleAuthorizationRejected(error);
if (rejected) refreshOffer();
showToast({
message: scheduleMCPErrorMessage(error, localize) ?? localize('com_ui_error'),
message:
scheduleMCPErrorMessage(error, localize) ??
localize(rejected ? 'com_ui_schedule_authorize_changed' : 'com_ui_error'),
status: 'error',
});
},
@ -436,6 +453,7 @@ export default function ScheduleDialog({
timezone: values.timezone,
target: 'new' as const,
enabled: true,
...(authorizes && authorization.value && { authorization: authorization.value }),
};
// STABLE across retries of the SAME intent, which is the whole point: the server
// commits the row and arms it in two writes, so a failure between them leaves the
@ -524,7 +542,13 @@ export default function ScheduleDialog({
return null;
};
const cadenceError = resolveCadenceError();
const canSubmit = cronIsValid && daysAreValid && !belowFloor && !isLoading;
const canSubmit =
cronIsValid &&
daysAreValid &&
!belowFloor &&
!isLoading &&
// Something to allow, and nothing allowed yet: the schedule would only be refused its tools.
!(authorizes && authorization.owed && authorization.value == null);
/** The offset disambiguates two similar names, which matters now that the zone is
* something the user picks rather than the browser's own. Memoized because it
@ -969,6 +993,13 @@ export default function ScheduleDialog({
</div>
)}
</div>
{authorizes && selectedAgentId !== '' && (
<Authorize
key={selectedAgentId}
agentId={selectedAgentId}
onChange={setAuthorization}
/>
)}
</form>
}
buttons={

View file

@ -2,9 +2,10 @@ import { createElement } from 'react';
import { MemoryRouter } from 'react-router-dom';
import { ToastProvider } from '@librechat/client';
import userEvent from '@testing-library/user-event';
import { dataService } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, render, screen, waitFor, within } from '@testing-library/react';
import type { TSchedule } from 'librechat-data-provider';
import type { TSchedule, ScheduleMCPConsentView } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import ScheduleDialog from '../ScheduleDialog';
@ -33,6 +34,7 @@ let mockLimits: {
minIntervalMinutes: number;
requireProject: boolean;
projectId?: string;
mcpConsent?: boolean;
} = {
maxPerUser: 10,
minIntervalMinutes: 0,
@ -76,6 +78,44 @@ jest.mock('~/data-provider', () => ({
useUpdateScheduleMutation: () => ({ mutate: mockMutate, isLoading: false }),
}));
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
dataService: { ...actual.dataService, getScheduleMCPOffer: jest.fn() },
};
});
/** What a schedule of an agent could be allowed, as the server offers it before creation. */
const offerFor = (tools: string[], other: string[] = []): ScheduleMCPConsentView => ({
state: 'missing',
revision: null,
expiresAtMs: null,
targets: [
{
resource: {
serverName: 'warehouse',
url: 'https://warehouse.example/mcp',
issuer: null,
audience: null,
scopes: [],
credentialMode: 'anonymous',
configurationRevision: 'v1',
},
policyRevision: 'p1',
permittedTools: [{ agentId: 'root', tools }],
},
],
allowed: {},
changed: {},
asking: {},
tools: { offered: other, allowed: [] },
approval: false,
required: false,
requireAfterMs: null,
offer: { digest: 'a'.repeat(64), maxLifetimeHours: 24 },
});
const renderDialog = (schedule?: Partial<TSchedule>, onOpenChange = jest.fn()) => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
@ -762,4 +802,144 @@ describe('ScheduleDialog', () => {
expect(mockMutate.mock.calls[0][0]).not.toHaveProperty('chatProjectId');
});
});
describe('authorizing a schedule as it is created', () => {
const create = () => screen.getByRole('button', { name: 'com_ui_create' });
it('asks nothing and sends no authorization where consent is off', async () => {
const user = userEvent.setup();
renderDialog();
await fillRequiredFields(user);
await user.click(create());
expect(dataService.getScheduleMCPOffer).not.toHaveBeenCalled();
expect(mockMutate.mock.calls[0][0]).not.toHaveProperty('authorization');
});
it('shows what the agent could be allowed, and creates only once something is', async () => {
mockLimits = { ...mockLimits, mcpConsent: true };
jest
.mocked(dataService.getScheduleMCPOffer)
.mockResolvedValue(offerFor(['export', 'query'], ['web_search']));
const user = userEvent.setup();
renderDialog();
await fillRequiredFields(user);
expect(await screen.findByText('com_ui_schedule_authorize_title')).toBeVisible();
expect(dataService.getScheduleMCPOffer).toHaveBeenCalledWith('agent-1');
// Something to allow and nothing allowed: the schedule would only be refused its tools.
await waitFor(() => expect(create()).toBeDisabled());
await user.click(screen.getByRole('checkbox', { name: 'query' }));
await user.click(screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_tool_web' }));
await waitFor(() => expect(create()).toBeEnabled());
await user.click(create());
expect(mockMutate).toHaveBeenCalledWith(
expect.objectContaining({
agent_id: 'agent-1',
authorization: {
offerDigest: 'a'.repeat(64),
lifetimeHours: 1,
allow: { warehouse: ['query'] },
ask: {},
tools: ['web_search'],
},
}),
);
});
it('starts over when another agent is picked', async () => {
mockLimits = { ...mockLimits, mcpConsent: true };
jest
.mocked(dataService.getScheduleMCPOffer)
.mockImplementation(async (agentId) =>
offerFor(agentId === 'agent-1' ? ['query'] : ['deploy', 'query']),
);
const user = userEvent.setup();
renderDialog();
await fillRequiredFields(user);
await user.click(await screen.findByRole('checkbox', { name: 'query' }));
await waitFor(() => expect(create()).toBeEnabled());
const dialog = screen.getByRole('dialog');
await user.click(within(dialog).getByRole('combobox', { name: 'com_ui_agent' }));
await user.click(await within(dialog).findByRole('option', { name: /Digest Agent/ }));
expect(await screen.findByRole('checkbox', { name: 'deploy' })).not.toBeChecked();
// The same tool name on the same server, for another agent: not carried over.
expect(screen.getByRole('checkbox', { name: 'query' })).not.toBeChecked();
await waitFor(() => expect(create()).toBeDisabled());
});
it('reads the offer again when the server turns the authorization down, and sends the new one', async () => {
mockLimits = { ...mockLimits, mcpConsent: true };
jest.mocked(dataService.getScheduleMCPOffer).mockResolvedValue(offerFor(['export', 'query']));
const user = userEvent.setup();
renderDialog();
await fillRequiredFields(user);
await user.click(await screen.findByRole('checkbox', { name: 'query' }));
await waitFor(() => expect(create()).toBeEnabled());
await user.click(create());
expect(mockMutate).toHaveBeenCalledTimes(1);
const failed = (status: number, code?: string) =>
Object.assign(new Error('rejected'), { response: { status, data: { code } } });
// Any other failure leaves the offer alone.
act(() => createMutationOptions!.onError(failed(500)));
expect(dataService.getScheduleMCPOffer).toHaveBeenCalledTimes(1);
// The agent dropped a tool after the form read the offer.
let answer!: (offer: ScheduleMCPConsentView) => void;
jest.mocked(dataService.getScheduleMCPOffer).mockReturnValue(
new Promise((resolve) => {
answer = resolve;
}),
);
act(() => createMutationOptions!.onError(failed(409, 'consent_changed')));
// The offer in hand is the one just turned down: nothing is sent until the new one is read.
await waitFor(() => expect(create()).toBeDisabled());
await act(async () =>
answer({ ...offerFor(['query']), offer: { digest: 'b'.repeat(64), maxLifetimeHours: 24 } }),
);
await waitFor(() =>
expect(screen.queryByRole('checkbox', { name: 'export' })).not.toBeInTheDocument(),
);
expect(dataService.getScheduleMCPOffer).toHaveBeenCalledTimes(2);
// The tick that still applies is kept, and the next create carries the offer just read.
expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked();
await waitFor(() => expect(create()).toBeEnabled());
await user.click(create());
expect(mockMutate).toHaveBeenCalledTimes(2);
expect(mockMutate.mock.calls[1][0]).toMatchObject({
authorization: { offerDigest: 'b'.repeat(64), allow: { warehouse: ['query'] } },
});
});
it('creates as before when the agent has nothing to be allowed', async () => {
mockLimits = { ...mockLimits, mcpConsent: true };
jest.mocked(dataService.getScheduleMCPOffer).mockResolvedValue({
...offerFor([]),
state: 'unsupported',
targets: [],
offer: null,
});
const user = userEvent.setup();
renderDialog();
await fillRequiredFields(user);
await waitFor(() => expect(dataService.getScheduleMCPOffer).toHaveBeenCalled());
expect(screen.queryByText('com_ui_schedule_authorize_title')).not.toBeInTheDocument();
await user.click(create());
expect(mockMutate.mock.calls[0][0]).not.toHaveProperty('authorization');
});
it('says so when the offer cannot be loaded, lets the owner retry, and does not block creating', async () => {
mockLimits = { ...mockLimits, mcpConsent: true };
jest.mocked(dataService.getScheduleMCPOffer).mockRejectedValueOnce(new Error('down'));
const user = userEvent.setup();
renderDialog();
await fillRequiredFields(user);
expect(await screen.findByRole('alert')).toHaveTextContent(
'com_ui_schedule_authorize_unavailable',
);
expect(create()).toBeEnabled();
jest.mocked(dataService.getScheduleMCPOffer).mockResolvedValue(offerFor(['query']));
await user.click(screen.getByRole('button', { name: 'com_ui_retry' }));
expect(await screen.findByRole('checkbox', { name: 'query' })).toBeVisible();
});
});
});

View file

@ -99,6 +99,12 @@ export function scheduleMCPErrorMessage(
: undefined;
}
/** The server turned down the authorization sent with a create, by one of its `consent_` codes. */
export function scheduleAuthorizationRejected(error: Error): boolean {
const code = (error as Error & { response?: { data?: { code?: unknown } } }).response?.data?.code;
return typeof code === 'string' && code.startsWith('consent_');
}
/** Preserves the structured recovery projection for immediate create, update, and
* Run Now failures. The message formatter and every recovery surface consume the
* same parsed outcome rather than independently interpreting the response. */

View file

@ -1,3 +1,4 @@
import { useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { QueryKeys, MutationKeys, dataService } from 'librechat-data-provider';
import type { ScheduleMCPConsentView, ConfirmScheduleMCPConsent } from 'librechat-data-provider';
@ -14,6 +15,26 @@ export function useScheduleMCPConsent(id: string) {
);
}
/** What a schedule of this agent could be allowed, before the schedule exists. */
export function useScheduleMCPOffer(agentId: string) {
return useQuery<ScheduleMCPConsentView>(
[QueryKeys.scheduleMCPOffer, agentId],
() => dataService.getScheduleMCPOffer(agentId),
{ enabled: agentId !== '', retry: false, refetchOnWindowFocus: false },
);
}
/**
* Reads the offer again. A choice is made from one offer and the server checks it against
* its own: once it turns a choice down, the offer in hand can only be turned down again.
*/
export function useScheduleMCPOfferRefresh(): () => void {
const queryClient = useQueryClient();
return useCallback(() => {
void queryClient.invalidateQueries([QueryKeys.scheduleMCPOffer]);
}, [queryClient]);
}
export function useScheduleMCPConsentMutations(id: string) {
const queryClient = useQueryClient();
const refresh = () => {

View file

@ -3938,6 +3938,9 @@
"com_ui_schedule_consent_allowed": "Allowed tools: {{tools}}",
"com_ui_schedule_consent_none_selected": "Choose at least one tool to confirm.",
"com_ui_schedule_consent_allow_all": "Allow everything",
"com_ui_schedule_authorize_title": "What this schedule may use",
"com_ui_schedule_authorize_changed": "What this schedule may use has changed. Review your choices and create it again.",
"com_ui_schedule_authorize_unavailable": "What this schedule may use could not be loaded. You can create it and authorize it afterwards; until then none of its tools will run.",
"com_ui_schedule_consent_other_tools": "Other tools",
"com_ui_schedule_consent_other_allowed": "Other tools allowed: {{tools}}",
"com_ui_schedule_consent_tool_code": "Code execution",

View file

@ -136,6 +136,19 @@ A schedule whose agent uses an MCP server the operator has not declared under
`mcpConsent.resources` cannot be authorized, so the deadline stops it until the server is
declared. Declare every server scheduled agents rely on before setting the date.
### A schedule authorized as it is created
Where consent is on, the create form asks what the new schedule may use and the schedule is
created with its grant. `POST /api/schedules/mcp-consent/offer` (`{ agent_id }`) answers what a
schedule of that agent could be allowed before it exists; its digest is bound to the owner and
the agent, not to a schedule id. `POST /api/schedules` takes the choice as `authorization`
(`offerDigest`, `lifetimeHours`, `allow`, `ask`, `tools`), checks it against a fresh offer
(`service.grant`), and writes the grant in the same insert as the schedule. A choice that no
longer fits is refused and nothing is created.
A schedule created without one, by another client for instance, is marked as needing
authorization from the start, so none of its tools runs until its owner confirms.
### A tool that changes after it was allowed
The owner allows a tool by name, so the grant also remembers what the tool was. The first

View file

@ -9,6 +9,8 @@ import type { ServerRequest } from '~/types';
import { ScheduleMCPConsentError } from './service';
export interface ScheduleMCPConsentHandlers {
/** The offer for a subject that is not stored yet. Absent where there is no such thing. */
draft?: (req: ServerRequest, res: Response) => Promise<void>;
get: (req: ServerRequest, res: Response) => Promise<void>;
confirm: (req: ServerRequest, res: Response) => Promise<void>;
revoke: (req: ServerRequest, res: Response) => Promise<void>;
@ -19,12 +21,17 @@ export function createScheduleMCPConsentHandlers<
>(deps: {
service: ScheduleMCPConsentService<Identity>;
resolveIdentity: (req: ServerRequest) => Promise<Identity | null>;
/** Who a subject being created would act for, from the request that asks about it. */
resolveDraft?: (req: ServerRequest) => Promise<Identity | null>;
}): ScheduleMCPConsentHandlers {
const handler =
(operation: (req: ServerRequest, res: Response, identity: Identity) => Promise<void>) =>
(
operation: (req: ServerRequest, res: Response, identity: Identity) => Promise<void>,
resolve = deps.resolveIdentity,
) =>
async (req: ServerRequest, res: Response): Promise<void> => {
try {
const identity = await deps.resolveIdentity(req);
const identity = await resolve(req);
if (!identity) {
res.status(404).json({ code: 'consent_not_found' });
return;
@ -43,7 +50,13 @@ export function createScheduleMCPConsentHandlers<
res.status(status).json({ code });
}
};
const { resolveDraft } = deps;
return {
...(resolveDraft && {
draft: handler(async (_req, res, identity) => {
res.json(await deps.service.draft(identity));
}, resolveDraft),
}),
get: handler(async (_req, res, identity) => {
res.json(await deps.service.view(identity));
}),

View file

@ -3,6 +3,7 @@ import {
EModelEndpoint,
PermissionTypes,
DEFAULT_SCHEDULE_MCP_CONSENT_LIFETIME_HOURS,
scheduleOfferRequestSchema,
} from 'librechat-data-provider';
import type { ScheduleMCPConsentStorage, AppConfig, IUser } from '@librechat/data-schemas';
import type { ScheduledMCPIdentity, TCheckpointerConfig } from 'librechat-data-provider';
@ -124,6 +125,18 @@ export function createScheduleMCPConsentHost(deps: {
});
const handlers = createScheduleMCPConsentHandlers({
service,
// A schedule being created has no id yet. The offer is bound to its owner and agent.
resolveDraft: async (req): Promise<ScheduledMCPIdentity | null> => {
const parsed = scheduleOfferRequestSchema.safeParse(req.body);
if (!req.user || !parsed.success) return null;
return {
scheduleId: 'draft',
ownerId: req.user.id,
tenantId: req.user.tenantId ?? null,
agentId: parsed.data.agent_id,
invocationMode: 'delegated',
};
},
resolveIdentity: async (req): Promise<ScheduledMCPIdentity | null> => {
const user = req.user;
const { id } = req.params as { id: string };

View file

@ -832,6 +832,91 @@ describe('an owner whose role may not use MCP servers', () => {
});
});
describe('a schedule being created with its grant', () => {
/** Nothing is stored for it yet: the grant comes with the readiness check. */
async function creating(
candidates: string[],
choice: { allow: Record<string, string[]>; tools?: string[] },
) {
const f = await setup();
f.snapshot.enrollment = null;
f.setCandidates(candidates);
const offer = await f.host.consent.service.view(f.identity);
await f.host.consent.service.confirm(f.identity, {
offerDigest: offer.offer!.digest,
expectedRevision: offer.revision,
lifetimeHours: 1,
...choice,
});
const grant = f.snapshot.enrollment!;
jest.mocked(f.storage.readScheduleMCPConsent).mockResolvedValue(null);
f.connect.mockClear();
const check = (withGrant = true) =>
f.preflight('root', f.user, {
scheduleId: 'sched_new',
stage: 'activation',
concurrency: 3,
...(withGrant && { grant }),
});
return { ...f, check };
}
it('is ready on the MCP tools the grant allows, and connects to no server it leaves out', async () => {
const f = await setup();
const archive = { type: 'streamable-http' as const, url: 'https://archive.example/mcp' };
f.servers.archive = archive;
Object.assign(f.config.mcpConfig as object, { archive });
const consent = (f.config.interfaceConfig!.schedules as { mcpConsent: { resources: object } })
.mcpConsent;
Object.assign(consent.resources, {
archive: {
url: archive.url,
credentialMode: 'anonymous',
issuer: null,
audience: null,
scopes: [],
},
});
f.snapshot.enrollment = null;
f.setCandidates(['query_mcp_warehouse', 'purge_mcp_archive']);
const offer = await f.host.consent.service.view(f.identity);
await f.host.consent.service.confirm(f.identity, {
offerDigest: offer.offer!.digest,
expectedRevision: offer.revision,
lifetimeHours: 1,
allow: { warehouse: ['query'] },
});
const grant = f.snapshot.enrollment!;
jest.mocked(f.storage.readScheduleMCPConsent).mockResolvedValue(null);
f.connect.mockClear();
const options = { scheduleId: 'sched_new', stage: 'activation' as const, concurrency: 3 };
await expect(f.preflight('root', f.user, { ...options, grant })).resolves.toEqual([
{ server: 'warehouse', status: 'ready' },
]);
expect(f.connect).toHaveBeenCalledTimes(1);
expect(f.connect).toHaveBeenCalledWith(expect.objectContaining({ serverName: 'warehouse' }));
// Without the grant, the same check reaches for both servers.
f.connect.mockClear();
await f.preflight('root', f.user, options).catch(() => undefined);
expect(f.connect).toHaveBeenCalledWith(expect.objectContaining({ serverName: 'archive' }));
});
it('is ready with nothing to connect when the grant allows no MCP tool, whatever the role', async () => {
const f = await creating(['web_search', 'query_mcp_warehouse'], {
allow: {},
tools: ['web_search'],
});
f.getRoleByName.mockResolvedValue({
permissions: {
[PermissionTypes.SCHEDULES]: { [Permissions.USE]: true, [Permissions.CREATE]: true },
},
} as IRole);
await expect(f.check()).resolves.toEqual([]);
expect(f.connect).not.toHaveBeenCalled();
await expect(f.check(false)).rejects.toMatchObject({ code: 'mcp_permission_denied' });
});
});
describe('a schedule its owner never authorized', () => {
async function unauthorized() {
const f = await setup();

View file

@ -537,6 +537,99 @@ describe("the agents' tools that are not MCP tools", () => {
});
});
describe('a schedule that is authorized as it is created', () => {
const draft = { ...identity, scheduleId: 'draft' };
const created = { ...identity, scheduleId: 'sched_new' };
it('offers what the agent could be allowed without any stored schedule', async () => {
const s = setup();
s.offerTools({ agentId: 'root', tools: ['web_search'] });
const offer = await s.service.draft(draft);
expect(offer).toMatchObject({
state: 'missing',
revision: null,
targets: [
expect.objectContaining({ resource: expect.objectContaining({ serverName: 'warehouse' }) }),
],
tools: { offered: ['web_search'], allowed: [] },
offer: { maxLifetimeHours: 24 },
});
expect(s.storage.readScheduleMCPConsent).not.toHaveBeenCalled();
// Bound to the owner and the agent, so it holds for the id the schedule is then given.
expect((await s.service.draft(created)).offer!.digest).toBe(offer.offer!.digest);
expect((await s.service.draft({ ...draft, agentId: 'other' })).offer!.digest).not.toBe(
offer.offer!.digest,
);
});
it("builds the grant for the new schedule from the owner's choice, and stores nothing", async () => {
const s = setup();
s.offerTools({ agentId: 'root', tools: ['execute_code', 'web_search'] });
const offer = await s.service.draft(draft);
const grant = await s.service.grant(created, {
offerDigest: offer.offer!.digest,
lifetimeHours: 2,
allow: { warehouse: ['query'] },
tools: ['web_search'],
});
expect(grant).toMatchObject({
version: 1,
scheduleRevision: 0,
consents: [
{
identity: created,
permittedTools: [
{ agentId: 'child', tools: ['query'] },
{ agentId: 'root', tools: ['query'] },
],
absoluteExpiresAtMs: 1000 + 2 * 3_600_000,
},
],
tools: [{ agentId: 'root', tools: ['web_search'] }],
grantedAtMs: 1000,
absoluteExpiresAtMs: 1000 + 2 * 3_600_000,
revokedAtMs: null,
});
expect(s.storage.confirmScheduleMCPConsent).not.toHaveBeenCalled();
});
it.each([
['an offer that has since changed', { offerDigest: 'b'.repeat(64) }, 'consent_changed'],
['nothing allowed', { allow: {}, tools: [] }, 'consent_invalid'],
['a tool that is not on offer', { tools: ['file_search'] }, 'consent_invalid'],
["a lifetime past the operator's limit", { lifetimeHours: 25 }, 'consent_invalid'],
])('refuses a choice with %s', async (_label, change, code) => {
const s = setup();
s.offerTools({ agentId: 'root', tools: ['web_search'] });
const offer = await s.service.draft(draft);
await expect(
s.service.grant(created, {
offerDigest: offer.offer!.digest,
lifetimeHours: 1,
allow: { warehouse: ['query'] },
tools: ['web_search'],
...change,
}),
).rejects.toMatchObject({ code });
});
it('offers nothing to an owner who may not use the agent, and refuses to ask first where a run cannot pause', async () => {
const s = setup();
s.cannotPause();
const offer = await s.service.draft(draft);
await expect(
s.service.grant(created, {
offerDigest: offer.offer!.digest,
lifetimeHours: 1,
allow: { warehouse: ['query'] },
ask: { warehouse: ['query'] },
}),
).rejects.toMatchObject({ code: 'consent_invalid' });
s.deny();
await expect(s.service.draft(draft)).rejects.toMatchObject({ code: 'consent_forbidden' });
});
});
describe('definition pins', () => {
const first = 'a'.repeat(64);
const second = 'b'.repeat(64);

View file

@ -8,6 +8,7 @@ import type {
ScheduledMCPResource,
ScheduledMCPTarget,
ScheduleMCPConsentView,
ScheduleAuthorization,
ScheduledMCPToolSelection,
ConfirmScheduleMCPConsent,
} from 'librechat-data-provider';
@ -85,8 +86,12 @@ export class ScheduleMCPConsentError extends Error {
}
}
function canonicalTargets(targets: readonly ScheduledMCPTarget[]): ScheduledMCPTarget[] {
if (!targets.length || targets.length > 32)
function canonicalTargets(
targets: readonly ScheduledMCPTarget[],
/** A grant for other tools only names no MCP server. */
options: { empty?: boolean } = {},
): ScheduledMCPTarget[] {
if ((!targets.length && options.empty !== true) || targets.length > 32)
throw new ScheduleMCPConsentError('consent_unavailable');
const servers = new Set<string>();
return targets
@ -168,7 +173,7 @@ function selectAllowed(
});
}
// No MCP tool chosen: the grant may still allow the agents' other tools.
return chosen.length > 0 ? canonicalTargets(chosen) : [];
return canonicalTargets(chosen, { empty: true });
}
/**
@ -291,7 +296,8 @@ function carriedPins(
* confirm past the mark; it is told the offer changed and reads it again.
*/
function offerDigest(
identity: MCPGrantIdentity,
/** The subject, or for a schedule that is not stored yet, its owner and agent. */
identity: object,
configRevision: number,
targets: readonly ScheduledMCPTarget[],
changed: Record<string, string[]>,
@ -316,6 +322,17 @@ export interface ScheduleMCPConsentService<
Identity extends MCPGrantIdentity = ScheduledMCPIdentity,
> {
view: (identity: Identity, options?: { signal?: AbortSignal }) => Promise<ScheduleMCPConsentView>;
/** The offer for a subject that is not stored yet. */
draft: (
identity: Identity,
options?: { signal?: AbortSignal },
) => Promise<ScheduleMCPConsentView>;
/** The grant for a subject about to be created. Stores nothing. */
grant: (
identity: Identity,
input: ScheduleAuthorization,
options?: { signal?: AbortSignal },
) => Promise<MCPGrantEnrollment<Identity>>;
confirm: (
identity: Identity,
input: ConfirmScheduleMCPConsent,
@ -442,7 +459,7 @@ export function createScheduleMCPConsentService<
requireAfterMs,
offer: null,
};
targets = resolved.length > 0 ? canonicalTargets(resolved) : [];
targets = canonicalTargets(resolved, { empty: true });
const digest = offerDigest(
identity,
snapshot.configRevision,
@ -472,6 +489,141 @@ export function createScheduleMCPConsentService<
return result;
}
/** A grant for what the owner chose, from now for the lifetime they chose. */
function build(input: {
identity: Identity;
configRevision: number;
lifetimeHours: number;
chosen: readonly ScheduledMCPTarget[];
others: readonly ScheduledMCPToolSelection[];
asking: Record<string, string[]>;
prior?: readonly MCPGrantConsent<Identity>[];
}): MCPGrantEnrollment<Identity> {
const grantedAtMs = now();
const absoluteExpiresAtMs = grantedAtMs + input.lifetimeHours * 3_600_000;
const revision = randomUUID();
return {
version: 1,
revision,
scheduleRevision: input.configRevision,
consents: input.chosen.map((target) => ({
...target,
...carriedPins(
target,
input.prior?.find((prior) => prior.resource.serverName === target.resource.serverName),
),
identity: input.identity,
id: randomUUID(),
revision,
grantedAtMs,
absoluteExpiresAtMs,
revokedAtMs: null,
...(input.asking[target.resource.serverName] && {
askTools: input.asking[target.resource.serverName],
}),
})),
...(input.others.length > 0 && { tools: [...input.others] }),
// The grant's own lifetime: one that allows no MCP server has no consent to carry it.
grantedAtMs,
absoluteExpiresAtMs,
revokedAtMs: null,
};
}
/** Within what the operator allows a grant to last. */
const validLifetime = (hours: number, maxLifetimeHours: number): boolean =>
Number.isInteger(hours) && hours >= 1 && hours <= maxLifetimeHours;
/**
* What the owner could allow a schedule that is not stored yet. There is no grant, edit or
* mark to read, so the offer is bound to the owner and the agent alone.
*/
async function draft(
identity: Identity,
options: { signal?: AbortSignal } = {},
): Promise<ScheduleMCPConsentView> {
options.signal?.throwIfAborted();
const [limits, allowed, approval] = await Promise.all([
deps.getLimits(identity),
deps.canUse(identity, options),
deps.canPause?.(identity) ?? false,
]);
if (!allowed) throw new ScheduleMCPConsentError('consent_forbidden');
const none: ScheduleMCPConsentView = {
state: 'unsupported',
revision: null,
expiresAtMs: null,
targets: [],
allowed: {},
changed: {},
asking: {},
tools: { offered: [], allowed: [] },
approval,
required: false,
requireAfterMs: null,
offer: null,
};
if (!limits.enabled || !deps.resolveEnrollment) return none;
const [resolved, others] = await Promise.all([
deps.resolveEnrollment(identity, options),
deps.resolveTools?.(identity, options) ?? [],
]);
if (resolved.length === 0 && others.length === 0) return none;
const targets = canonicalTargets(resolved, { empty: true });
const subject = {
ownerId: identity.ownerId,
tenantId: identity.tenantId,
agentId: identity.agentId,
};
const result: ScheduleMCPConsentView = {
...none,
state: 'missing',
targets,
tools: { offered: toolNames(others), allowed: [] },
offer: {
digest: offerDigest(subject, 0, targets, {}, others),
maxLifetimeHours: limits.maxLifetimeHours,
},
};
offers.set(result, others);
return result;
}
/**
* The grant for a schedule about to be created, from the owner's choice of its draft offer.
* Nothing is stored: the caller writes it in the same insert as the schedule.
*/
async function grant(
identity: Identity,
input: ScheduleAuthorization,
options: { signal?: AbortSignal } = {},
): Promise<MCPGrantEnrollment<Identity>> {
const current = await draft(identity, options);
if (!current.offer) throw new ScheduleMCPConsentError('consent_unavailable');
if (input.offerDigest !== current.offer.digest)
throw new ScheduleMCPConsentError('consent_changed');
if (!validLifetime(input.lifetimeHours, current.offer.maxLifetimeHours))
throw new ScheduleMCPConsentError('consent_invalid');
const chosen = selectAllowed(current.targets, input.allow);
const others = selectTools(offers.get(current) ?? [], input.tools ?? []);
const asking = selectAsking(chosen, input.ask ?? {}, {});
// Something must be allowed, and a tool nobody can approve would only ever be refused.
if (
(chosen.length === 0 && others.length === 0) ||
(!current.approval && Object.keys(asking).length > 0)
)
throw new ScheduleMCPConsentError('consent_invalid');
options.signal?.throwIfAborted();
return build({
identity,
configRevision: 0,
lifetimeHours: input.lifetimeHours,
chosen,
others,
asking,
});
}
async function confirm(
identity: Identity,
input: ConfirmScheduleMCPConsent,
@ -483,11 +635,7 @@ export function createScheduleMCPConsentService<
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
)
if (!validLifetime(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');
@ -519,36 +667,15 @@ export function createScheduleMCPConsentService<
)
throw new ScheduleMCPConsentError('consent_invalid');
options.signal?.throwIfAborted();
const grantedAtMs = now();
const revision = randomUUID();
const enrollment: MCPGrantEnrollment<Identity> = {
version: 1,
revision,
scheduleRevision: snapshot.configRevision,
consents: chosen.map((target) => ({
...target,
...carriedPins(
target,
snapshot.enrollment?.consents.find(
(prior) => prior.resource.serverName === target.resource.serverName,
),
),
identity,
id: randomUUID(),
revision,
grantedAtMs,
absoluteExpiresAtMs: grantedAtMs + input.lifetimeHours * 3_600_000,
revokedAtMs: null,
...(asking[target.resource.serverName] && {
askTools: asking[target.resource.serverName],
}),
})),
...(others.length > 0 && { tools: others }),
// The grant's own lifetime: one that allows no MCP server has no consent to carry it.
grantedAtMs,
absoluteExpiresAtMs: grantedAtMs + input.lifetimeHours * 3_600_000,
revokedAtMs: null,
};
const enrollment = build({
identity,
configRevision: snapshot.configRevision,
lifetimeHours: input.lifetimeHours,
chosen,
others,
asking,
prior: snapshot.enrollment?.consents,
});
const committed = await deps.storage.confirmScheduleMCPConsent({
identity,
expectedRevision: input.expectedRevision,
@ -722,5 +849,5 @@ export function createScheduleMCPConsentService<
};
},
};
return { view, confirm, revoke, requiresGrant: requiresGrantFor, authority };
return { view, draft, grant, confirm, revoke, requiresGrant: requiresGrantFor, authority };
}

View file

@ -1497,6 +1497,147 @@ it('allows repointing a disabled schedule without MCP preflight', async () => {
expect(deps.methods.updateScheduleById).toHaveBeenCalled();
});
describe('createSchedule where the owner authorizes a schedule as it is created', () => {
const limits = (consent: boolean) => async () => ({
enabled: true,
maxPerUser: 10,
minIntervalMinutes: 60,
autoDisableAfterFailures: 5,
admissionConcurrency: 20,
fireConcurrency: 5,
mcpPreflightConcurrency: 3,
mcpPreflightTimeoutMs: 300_000,
requireProject: false,
...(consent && { mcpConsent: { enabled: true, maxLifetimeHours: 24 } }),
});
const authorization = {
offerDigest: 'a'.repeat(64),
lifetimeHours: 1,
allow: { warehouse: ['query'] },
tools: ['web_search'],
};
const stored = { version: 1, revision: 'grant-1' } as unknown as NonNullable<
ISchedule['mcpConsent']
>;
const create = async (
body: Record<string, unknown>,
over: Partial<SchedulesHandlersDeps> = {},
consent = true,
) => {
const deps = makeCreateDeps({
isUserDeleting: jest.fn(async () => false),
getLimits: limits(consent),
...over,
});
const { res, captured } = makeRes();
await createSchedulesHandlers(deps).createSchedule(
{ ...makeCreateReq(), body: { ...CREATE_BODY, ...body } } as unknown as ServerRequest,
res,
);
const insert = (deps.methods.createScheduleWithSlot as jest.Mock).mock.calls[0]?.[0] as
| (Partial<ISchedule> & { authorization?: unknown })
| undefined;
return { captured, insert };
};
it('writes the grant in the same insert as the schedule, for the schedule about to exist', async () => {
const grant = jest.fn(async () => stored);
const { insert } = await create({ authorization }, { grant });
expect(insert).toMatchObject({ mcpConsent: stored });
expect(insert).not.toHaveProperty('mcpConsentRequired');
// The owner's choice is not a field of the schedule.
expect(insert).not.toHaveProperty('authorization');
expect(grant).toHaveBeenCalledWith(
{
scheduleId: insert!.id,
ownerId: 'user-1',
tenantId: 't1',
agentId: CREATE_BODY.agent_id,
invocationMode: 'delegated',
},
authorization,
{ signal: expect.any(AbortSignal) },
);
});
it('checks readiness for what the owner allowed, once the choice is accepted', async () => {
const order: string[] = [];
const grant = jest.fn(async () => {
order.push('grant');
return stored;
});
const preflightMCP = jest.fn(async () => {
order.push('readiness');
return [];
});
const { insert } = await create({ authorization }, { grant, preflightMCP });
expect(order).toEqual(['grant', 'readiness']);
expect(preflightMCP).toHaveBeenCalledWith(
CREATE_BODY.agent_id,
expect.anything(),
expect.objectContaining({ scheduleId: insert!.id, stage: 'activation', grant: stored }),
);
// A choice that is turned down is answered as that, with no server probed for it.
const { ScheduleMCPConsentError } = jest.requireActual('./authorization/service');
preflightMCP.mockClear();
await create(
{ authorization },
{
grant: jest.fn().mockRejectedValue(new ScheduleMCPConsentError('consent_changed')),
preflightMCP,
},
);
expect(preflightMCP).not.toHaveBeenCalled();
// With no choice there is no grant to limit it: every selected MCP tool is checked.
await create({}, { grant, preflightMCP });
expect(preflightMCP).toHaveBeenLastCalledWith(
CREATE_BODY.agent_id,
expect.anything(),
expect.not.objectContaining({ grant: expect.anything() }),
);
});
it('creates a schedule that needs authorization when none came with it', async () => {
const grant = jest.fn();
const { insert } = await create({}, { grant });
expect(insert).toMatchObject({ mcpConsentRequired: true });
expect(insert).not.toHaveProperty('mcpConsent');
expect(grant).not.toHaveBeenCalled();
});
it('creates nothing when the choice does not fit what can be offered', async () => {
const { ScheduleMCPConsentError } = jest.requireActual('./authorization/service');
for (const [code, status] of [
['consent_changed', 409],
['consent_invalid', 409],
['consent_forbidden', 403],
] as const) {
const { captured, insert } = await create(
{ authorization },
{ grant: jest.fn().mockRejectedValue(new ScheduleMCPConsentError(code)) },
);
expect(captured.status).toBe(status);
expect(captured.body).toMatchObject({ code });
expect(insert).toBeUndefined();
}
});
it('ignores the choice and marks nothing where consent is off', async () => {
const grant = jest.fn();
const { insert } = await create({ authorization }, { grant }, false);
expect(insert).not.toHaveProperty('mcpConsent');
expect(insert).not.toHaveProperty('mcpConsentRequired');
expect(insert).not.toHaveProperty('authorization');
expect(grant).not.toHaveBeenCalled();
});
it('makes the choice part of what a retry must repeat, and leaves older retries matching', () => {
const base = { ...CREATE_BODY, target: 'new' as const, enabled: true };
expect(computeCreateDigest(base)).toBe(createBodyDigest());
expect(computeCreateDigest({ ...base, authorization })).not.toBe(createBodyDigest());
});
});
describe('updateSchedule on a schedule its owner never authorized', () => {
const limits = (mcpConsent?: { enabled: boolean; maxLifetimeHours: number }) => async () => ({
enabled: true,

View file

@ -10,6 +10,9 @@ import type {
TCreateSchedule,
TUpdateSchedule,
TSchedule,
ScheduledMCPIdentity,
ScheduleAuthorization,
ScheduledMCPEnrollment,
} from 'librechat-data-provider';
import type { ScheduleMethods, ISchedule, IScheduleRun } from '@librechat/data-schemas';
import type { Response } from 'express';
@ -29,6 +32,7 @@ import {
isValidTimezone,
} from './cadence';
import { ScheduleMCPError, getScheduleMCPFailureCode } from './mcp';
import { ScheduleMCPConsentError } from './authorization/service';
import { resolveScheduleProjectId } from './types';
export interface SchedulesHandlersDeps {
@ -37,6 +41,16 @@ export interface SchedulesHandlersDeps {
getLimits: (user?: ScheduleUserContext) => Promise<ScheduleLimits>;
/** Agent existence + VIEW access for the requesting user. */
canViewAgent: (agentId: string, req: ServerRequest) => Promise<boolean>;
/**
* The grant for a schedule about to be created, from its owner's choice. Throws a
* `ScheduleMCPConsentError` when the choice does not fit what can be offered. Absent, a
* schedule cannot be authorized as it is created.
*/
grant?: (
identity: ScheduledMCPIdentity,
choice: ScheduleAuthorization,
options: { signal?: AbortSignal },
) => Promise<ScheduledMCPEnrollment>;
/** Whether the requesting user owns this chat project. Projects are user-owned,
* so existence and authorization are the same question. */
canUseProject: (projectId: string, userId: string) => Promise<boolean>;
@ -156,6 +170,8 @@ export function computeCreateDigest(payload: TCreateSchedule): string {
// for the pinned row, i.e. success for the opposite of what it asked. A pre-scope
// client never sent the field at all, so nothing legacy can carry an explicit null.
...(payload.chatProjectId !== undefined && { chatProjectId: payload.chatProjectId }),
// Likewise omitted unless sent: what the owner allowed is part of what they asked for.
...(payload.authorization !== undefined && { authorization: payload.authorization }),
});
return createHash('sha256').update(canonical).digest('hex');
}
@ -395,6 +411,8 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH
signal: AbortSignal,
limits: ScheduleLimits,
scheduleId: string,
/** The grant a schedule is being created with: not stored yet, so not found by its id. */
grant?: ISchedule['mcpConsent'],
): Promise<boolean> {
try {
await deps.preflightMCP(agentId, requestUser(req), {
@ -403,6 +421,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH
signal,
concurrency: limits.mcpPreflightConcurrency,
deadlineMs: Date.now() + limits.mcpPreflightTimeoutMs,
...(grant && { grant }),
});
return true;
} catch (error) {
@ -717,9 +736,48 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH
return;
}
const id = `sched_${randomUUID()}`;
const { authorization, ...fields } = parsed.data;
/**
* Where consent is on, a schedule is authorized as it is created: the grant is written
* in the same insert. One created without a choice needs authorization from the start,
* so none of its tools runs until its owner confirms.
*/
let consent: Pick<ISchedule, 'mcpConsent' | 'mcpConsentRequired'> = {};
if (limits.mcpConsent?.enabled === true) {
if (authorization == null || deps.grant == null) {
consent = { mcpConsentRequired: true };
} else {
try {
consent = {
mcpConsent: await deps.grant(
{
scheduleId: id,
ownerId: user.id,
tenantId: user.tenantId ?? null,
agentId: fields.agent_id,
invocationMode: 'delegated',
},
authorization,
{ signal: mcpSignal },
),
};
} catch (error) {
if (mcpSignal.aborted) return;
if (!(error instanceof ScheduleMCPConsentError)) throw error;
// The owner's choice no longer fits what can be offered, or never did.
const status = error.code === 'consent_forbidden' ? 403 : 409;
res
.status(status)
.json({ error: 'Schedule authorization was not accepted', code: error.code });
return;
}
}
}
// After the grant: readiness is about the MCP tools the owner allowed, and a server
// they left out is neither connected to nor a reason to refuse the schedule.
if (
parsed.data.enabled &&
!(await validateMCP(parsed.data.agent_id, req, res, mcpSignal, limits, id))
fields.enabled &&
!(await validateMCP(fields.agent_id, req, res, mcpSignal, limits, id, consent.mcpConsent))
)
return;
// Project policy applies to a NEW insert only, and is therefore resolved AFTER every
@ -794,7 +852,8 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH
// a permanent state.
const created = await deps.methods.createScheduleWithSlot(
{
...parsed.data,
...fields,
...consent,
chatProjectId: chatProjectId ?? undefined,
id,
user: user.id as never,

View file

@ -332,9 +332,21 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPr
),
);
};
/** The MCP tools a grant allows: the stored grant's, or the one a schedule is created with. */
const pending =
options.grant &&
new Map(
options.grant.consents.map(({ resource, permittedTools }) => [
resource.serverName,
new Map(permittedTools.map(({ agentId: owner, tools }) => [owner, new Set(tools)])),
]),
);
const grants: ScheduleMCPExecution['grants'] | undefined = execution?.enrolled
? execution.grants
: pending && ((owner, server, tool) => pending.get(server)?.get(owner)?.has(tool) === true);
// A run under a grant needs the permission only for the MCP tools the grant allows, so
// it is held to it below, once the tools the owner left out are set aside.
if (!permitted && !execution?.enrolled) refuse();
if (!permitted && !grants) refuse();
// Resolve once more against the ACL-filtered registry before initializing config.
// Exact accessible identities must beat normalized aliases from another tier, just
// as they do in the interactive runtime.
@ -354,13 +366,12 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPr
authoritativeAliases,
new Set([...Object.keys(accessibleServers), ...configNames]),
));
if (execution?.enrolled) {
if (grants) {
// The owner may have allowed only some of what the agents select. Readiness is about
// what the run is allowed to use: a tool or a whole server left out of the grant is
// refused when called, and must not keep the schedule from running.
const allowed = execution;
const isGranted = (server: string, toolKey: string, owner: string): boolean =>
allowed.grants(owner, server, splitMCPToolKey(toolKey, authoritativeCandidates)[0]);
grants(owner, server, splitMCPToolKey(toolKey, authoritativeCandidates)[0]);
for (const [server, serverTools] of toolAgentIds) {
for (const [toolKey, owners] of serverTools) {
for (const owner of owners) if (!isGranted(server, toolKey, owner)) owners.delete(owner);

View file

@ -4,6 +4,7 @@ import type {
AgentTriggerDeliveryStatus,
AgentTriggerDeliveryFailure,
} from '@librechat/data-schemas';
import type { ScheduledMCPEnrollment } from 'librechat-data-provider';
import type { ScheduledMCPIdentity } from 'librechat-data-provider';
import type { ScheduleMCPOutcome } from 'librechat-data-provider';
import type { Types } from 'mongoose';
@ -363,6 +364,11 @@ export type ScheduleMCPPreflight = (
stage?: 'activation' | 'invoke' | 'resume';
/** Trusted fire host provenance, never a body-provided permission. */
manual?: boolean;
/**
* The grant a schedule is being created with. Nothing is stored for it yet, so it is
* handed over: readiness then covers the MCP tools it allows, as for a stored grant.
*/
grant?: Pick<ScheduledMCPEnrollment, 'consents'>;
},
) => Promise<ScheduleMCPOutcome[]>;

View file

@ -574,6 +574,8 @@ export const getAllPromptGroups = () => `${prompts()}/all`;
export const schedules = () => `${BASE_URL}/api/schedules`;
export const schedule = (id: string) => `${schedules()}/${encodeURIComponent(id)}`;
export const scheduleMCPConsent = (id: string) => `${schedule(id)}/mcp-consent`;
/** What a schedule of an agent could be allowed, asked before the schedule exists. */
export const scheduleMCPOffer = () => `${schedules()}/mcp-consent/offer`;
export const runSchedule = (id: string) => `${schedule(id)}/run`;
/* Skills */

View file

@ -2263,6 +2263,9 @@ export const getActiveJobs = (): Promise<ActiveJobsResponse> => {
export function getScheduleMCPConsent(id: string): Promise<ScheduleMCPConsentView> {
return request.get(endpoints.scheduleMCPConsent(id));
}
export function getScheduleMCPOffer(agentId: string): Promise<ScheduleMCPConsentView> {
return request.post(endpoints.scheduleMCPOffer(), { agent_id: agentId });
}
export function confirmScheduleMCPConsent(
id: string,
payload: ConfirmScheduleMCPConsent,

View file

@ -122,6 +122,7 @@ export enum QueryKeys {
/* Scheduled chats */
schedules = 'schedules',
scheduleMCPConsent = 'scheduleMCPConsent',
scheduleMCPOffer = 'scheduleMCPOffer',
schedule = 'schedule',
parentSubagents = 'parentSubagents',
subagentThread = 'subagentThread',

View file

@ -223,41 +223,52 @@ export type MCPGrantEnrollment<Identity extends MCPGrantIdentity = ScheduledMCPI
'consents'
> & { consents: MCPGrantConsent<Identity>[] };
export const confirmScheduleMCPConsentSchema = z
.object({
offerDigest: z.string().regex(/^[a-f0-9]{64}$/),
expectedRevision: identifier.nullable(),
lifetimeHours: z.number().int().min(1).max(8760),
/**
* The tools the owner allows, by server, chosen from the offer. A server left out, or
* listed with no tools, is not allowed. Anything not listed here is refused at run time.
*/
allow: z
.record(identifier, z.array(identifier).max(MAX_SCHEDULED_MCP_SERVER_TOOLS))
.refine((value) => Object.keys(value).length <= 32),
/**
* Of the allowed tools, the ones the owner wants to approve call by call, by server.
* Each must also be listed in `allow`.
*/
ask: z
.record(identifier, z.array(identifier).max(MAX_SCHEDULED_MCP_SERVER_TOOLS))
.refine((value) => Object.keys(value).length <= 32)
.optional(),
/**
* Of the offered tools that are not MCP tools, the ones the owner allows. Left out, the
* stored grant's choice is kept for the tools still on offer.
*/
tools: z.array(identifier).max(MAX_AGENT_TOOLS).optional(),
})
.strict()
// Something must be allowed: an MCP tool, or one of the other tools.
.refine(
(value) =>
Object.values(value.allow).some((tools) => tools.length > 0) ||
(value.tools?.length ?? 0) > 0,
);
const consentChoice = z.object({
offerDigest: z.string().regex(/^[a-f0-9]{64}$/),
expectedRevision: identifier.nullable(),
lifetimeHours: z.number().int().min(1).max(8760),
/**
* The tools the owner allows, by server, chosen from the offer. A server left out, or
* listed with no tools, is not allowed. Anything not listed here is refused at run time.
*/
allow: z
.record(identifier, z.array(identifier).max(MAX_SCHEDULED_MCP_SERVER_TOOLS))
.refine((value) => Object.keys(value).length <= 32),
/**
* Of the allowed tools, the ones the owner wants to approve call by call, by server.
* Each must also be listed in `allow`.
*/
ask: z
.record(identifier, z.array(identifier).max(MAX_SCHEDULED_MCP_SERVER_TOOLS))
.refine((value) => Object.keys(value).length <= 32)
.optional(),
/**
* Of the offered tools that are not MCP tools, the ones the owner allows. Left out, the
* stored grant's choice is kept for the tools still on offer.
*/
tools: z.array(identifier).max(MAX_AGENT_TOOLS).optional(),
});
/** Something must be allowed: an MCP tool, or one of the other tools. */
const allowsSomething = (value: { allow: Record<string, string[]>; tools?: string[] }): boolean =>
Object.values(value.allow).some((tools) => tools.length > 0) || (value.tools?.length ?? 0) > 0;
export const confirmScheduleMCPConsentSchema = consentChoice.strict().refine(allowsSomething);
export type ConfirmScheduleMCPConsent = z.infer<typeof confirmScheduleMCPConsentSchema>;
/**
* The owner's choice for a schedule that is being created, made from the offer for its agent.
* There is no stored grant yet, so no revision to expect.
*/
export const scheduleAuthorizationSchema = consentChoice
.omit({ expectedRevision: true })
.strict()
.refine(allowsSomething);
export type ScheduleAuthorization = z.infer<typeof scheduleAuthorizationSchema>;
/** Asks what the owner could allow a schedule of this agent, before the schedule exists. */
export const scheduleOfferRequestSchema = z.object({ agent_id: identifier }).strict();
export const revokeScheduleMCPConsentSchema = z.object({ expectedRevision: identifier }).strict();
export interface ScheduleMCPConsentView {

View file

@ -1,5 +1,5 @@
import { z } from 'zod';
import { scheduledMCPFailureReasonSchema } from './scheduleConsent';
import { scheduledMCPFailureReasonSchema, scheduleAuthorizationSchema } from './scheduleConsent';
import { partialWithoutDefaults } from '../zod';
/** Cadences the dialog builds from structured pickers (hour, minute, weekday). */
@ -99,6 +99,12 @@ export const createSchedulePayloadSchema = z.object({
* that omits it, which is exactly the failure the key exists to close.
*/
clientRequestId: z.string().trim().min(1).max(128),
/**
* What the owner allows the schedule to use while they are away, chosen from the offer for
* its agent. Read only where schedule consent is on. Left out there, the schedule is created
* needing authorization and none of its tools runs until the owner confirms.
*/
authorization: scheduleAuthorizationSchema.optional(),
});
export type TCreateSchedule = z.infer<typeof createSchedulePayloadSchema>;