Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 73 additions & 33 deletions client/src/components/SidePanel/Schedules/Consent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,34 +36,53 @@ 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. */
/**
* 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] ?? [];
return [target.resource.serverName, offered.filter((tool) => allowed.includes(tool))];
const changed = data.changed[target.resource.serverName] ?? [];
return [
target.resource.serverName,
offered.filter((tool) => allowed.includes(tool) && !changed.includes(tool)),
];
}),
);
}

/** The owner's ticks, and the tools that were marked as changed when they were last made. */
interface Edited {
choice: Record<string, string[]>;
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, and a server or tool the agents dropped has no box left to untick.
* 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 loses its tick, so allowing the new
* definition is something the owner does with the warning in view.
*/
function currentChoice(
data: ScheduleMCPConsentView,
edited: Record<string, string[]> | null,
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.changed[serverName] ?? [];
return [
serverName,
(edited[serverName] ?? initial[serverName]).filter((tool) => offered.includes(tool)),
(edited.choice[serverName] ?? initial[serverName]).filter(
(tool) => offered.includes(tool) && (!marked.includes(tool) || seen.includes(tool)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope remembered changed-tool acknowledgments to the grant revision

If the owner ticks a marked tool, then another tab confirms that tool and a subsequent run marks it changed again, the original dialog retains its tick. edited.changed remembers only tool names, so seen.includes(tool) treats the second change as already acknowledged even though it belongs to a different grant. The consent query periodically refetches, and commit() uses the refreshed revision and offer digest, so submitting this dialog successfully clears the new marker without requiring another explicit tick. Store the grant revision with Edited and discard acknowledgments when that revision changes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 912414f. The edit now records the grant revision it was made against (Edited.revision in Consent.tsx), and currentChoice counts a tick on a marked tool only when the mark was in view under that same revision. A tool marked again under a grant confirmed elsewhere is unticked, the confirm button is disabled if nothing else is ticked, and the owner has to tick it again with the warning shown.

Evidence: Consent.spec.tsx › "unticks a tool the owner accepted once it is marked again under a later grant". Dropping the revision comparison makes it fail.

),
];
}),
);
Expand All @@ -89,14 +108,14 @@ export default function Consent({
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<Record<string, string[]> | null>(null);
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) : {};
const chosenCount = Object.values(choice).reduce((count, tools) => count + tools.length, 0);
const setTools = (serverName: string, tools: string[]) =>
setEdited({ ...choice, [serverName]: tools });
setEdited({ choice: { ...choice, [serverName]: tools }, changed: data?.changed ?? {} });
const commit = () => {
if (!data?.offer || chosenCount === 0) return;
setMessage(null);
Expand Down Expand Up @@ -188,15 +207,25 @@ export default function Consent({
serverName={target.resource.serverName}
offered={offeredTools(target)}
chosen={choice[target.resource.serverName] ?? []}
changed={data.changed[target.resource.serverName] ?? []}
disabled={busy}
onChange={(tools) => setTools(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>
<>
<p className="text-text-secondary text-xs">
{localize('com_ui_schedule_consent_allowed', {
tools: (data.allowed[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>
))}
Expand Down Expand Up @@ -256,12 +285,15 @@ function ToolChoice({
serverName,
offered,
chosen,
changed,
disabled,
onChange,
}: {
serverName: string;
offered: string[];
chosen: string[];
/** Tools the server changed since they were allowed. Refused until confirmed again. */
changed: string[];
disabled: boolean;
onChange: (tools: string[]) => void;
}) {
Expand All @@ -285,27 +317,35 @@ function ToolChoice({
</div>
<ul className="space-y-1 pl-6">
{offered.map((tool) => (
<li key={tool} className="flex items-center gap-2">
<Checkbox
id={`${groupId}-${tool}`}
checked={chosen.includes(tool)}
disabled={disabled}
aria-labelledby={`${groupId}-${tool}-label`}
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>
<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>
</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>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const view: ScheduleMCPConsentView = {
},
],
allowed: {},
changed: {},
offer: { digest: 'a'.repeat(64), maxLifetimeHours: 24 },
};
function display() {
Expand Down Expand Up @@ -170,6 +171,85 @@ it('drops ticks for a server or tool that leaves the offer while the dialog is o
),
);
});
it('leaves a tool the server changed unticked and says why, until the owner allows it again', async () => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
state: 'changed',
revision: 'grant',
expiresAtMs: Date.now() + 60_000,
allowed: { warehouse: ['export', 'query'] },
changed: { warehouse: ['query'] },
});
jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view);
display();
const changed = await screen.findByRole('checkbox', { name: 'query' });
expect(changed).not.toBeChecked();
expect(changed).toHaveAccessibleDescription('com_ui_schedule_consent_tool_changed');
const unchanged = screen.getByRole('checkbox', { name: 'export' });
expect(unchanged).toBeChecked();
expect(unchanged).not.toHaveAccessibleDescription();
await userEvent.click(changed);
await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }));
await waitFor(() =>
expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith(
'schedule',
expect.objectContaining({ allow: { warehouse: ['export', 'query'] } }),
),
);
});
it('unticks a tool that is marked as changed while the owner is choosing, until they tick it again', async () => {
const granted = {
...view,
state: 'active' as const,
revision: 'grant',
expiresAtMs: Date.now() + 60_000,
allowed: { warehouse: ['query'] },
};
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(granted);
jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view);
const client = display();
// The owner edits a tick, so the dialog now holds their choice and not the stored one.
await userEvent.click(await screen.findByRole('checkbox', { name: 'export' }));
expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked();
// A run then sees `query` with a different definition, and the offer is read again.
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...granted,
state: 'changed',
changed: { warehouse: ['query'] },
offer: { digest: 'c'.repeat(64), maxLifetimeHours: 24 },
});
await client.invalidateQueries();
const marked = await screen.findByRole('checkbox', {
name: 'query',
description: 'com_ui_schedule_consent_tool_changed',
});
expect(marked).not.toBeChecked();
expect(screen.getByRole('checkbox', { name: 'export' })).toBeChecked();
// Ticked again with the warning in view, it is sent, and stays ticked across later edits.
await userEvent.click(marked);
await userEvent.click(screen.getByRole('checkbox', { name: 'export' }));
expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked();
await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }));
await waitFor(() =>
expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith(
'schedule',
expect.objectContaining({ offerDigest: 'c'.repeat(64), allow: { warehouse: ['query'] } }),
),
);
});
it('names the changed tools when there is nothing to confirm', async () => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
state: 'changed',
revision: 'grant',
allowed: { warehouse: ['export', 'query'] },
changed: { warehouse: ['query'] },
offer: null,
});
display();
expect(await screen.findByText('com_ui_schedule_consent_changed_tools')).toBeVisible();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
});
it('lists the allowed tools without boxes when there is nothing to confirm', async () => {
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
...view,
Expand Down
4 changes: 3 additions & 1 deletion client/src/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -3901,7 +3901,7 @@
"com_ui_schedule_consent_active": "Authorized",
"com_ui_schedule_consent_expired": "Authorization expired. Confirm again to renew.",
"com_ui_schedule_consent_revoked": "Authorization revoked",
"com_ui_schedule_consent_changed": "The agent, schedule or resource binding changed. Review and confirm again.",
"com_ui_schedule_consent_changed": "The agent, schedule, resource binding or an allowed tool changed. Review and confirm again.",
"com_ui_schedule_consent_unsupported": "This deployment cannot resolve this scheduled MCP authorization. Existing schedules are unchanged.",
"com_ui_schedule_consent_deadline": "Absolute expiry: {{time}}",
"com_ui_schedule_consent_hours": "Authorization lifetime (hours)",
Expand All @@ -3915,6 +3915,8 @@
"com_ui_schedule_consent_allow_server": "Allow all tools on {{server}}",
"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_tool_changed": "Changed since you allowed it. Check it to allow the new version.",
"com_ui_schedule_consent_changed_tools": "Changed since allowed, now refused: {{tools}}",
"com_ui_code_checkout_mode": "Checkout mode",
"com_ui_code_checkout_isolated": "Isolated worktree",
"com_ui_code_checkout_isolated_info": "Own Git worktree; uncommitted changes aren't copied",
Expand Down
24 changes: 24 additions & 0 deletions packages/api/src/mcp/__tests__/MCPManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,30 @@ describe('MCPManager', () => {
expect(request).not.toHaveBeenCalled();
});

it('stops dispatching a tool whose definition changed after its first use', async () => {
const { request, snapshot, call } = await setupScheduled();
await call();
snapshot.mockResolvedValue({
tools: [
{
...readTool,
description: 'Read only!',
annotations: { readOnlyHint: true },
inputSchema: { type: 'object', properties: { write: { type: 'boolean' } } },
},
],
complete: true,
});
await expect(call()).rejects.toMatchObject({
failure: { reason: 'binding_mismatch', automaticReplay: false },
});
snapshot.mockResolvedValue({ tools: [readTool], complete: true });
await expect(call('child')).rejects.toMatchObject({
failure: { reason: 'binding_mismatch' },
});
expect(request.mock.calls.filter(([input]) => input.method === 'tools/call')).toHaveLength(1);
});

it('fences consent revoked during live tools/list immediately before dispatch', async () => {
const { fixture, request, snapshot, call } = await setupScheduled();
snapshot.mockImplementation(async () => {
Expand Down
22 changes: 20 additions & 2 deletions packages/api/src/schedules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,26 @@ agent still selects it. Anything else is refused with `tool_policy_denied`.
- Names, MCP annotations and remembered chat approvals confer nothing.

The operator-declared `mcpConsent.readOnlyPolicy` list is retired. The loader warns when the key
is still present and ignores it. Tool definitions are not pinned yet: a server that changes what
an allowed tool does keeps that tool allowed until the pinning follow-up lands.
is still present and ignores it.

### 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
authorized use of a tool (activation preflight or a run) stores a SHA-256 of its whole live
definition on the grant: name, description, input and output schemas, annotations. Every later
use compares the live definition with that pin.

- A different definition is refused with `binding_mismatch` before `tools/call`, and the tool is
marked as changed on the grant. It stays refused even if the server restores the old
definition. The grant's other tools stay allowed.
- The consent view reports `changed` and names the tool. Confirming again with the tool ticked
accepts what the server offers now: the tool is pinned afresh at its next use.
- Confirming again keeps the pins of tools that were not marked, so a renewal cannot quietly
accept a definition swapped since the last run.
- A grant made before pins existed is pinned at its next use.

The pin is trust on first use. The consent offer does not connect to the server, so a
definition that changes between confirming and the first use is the one that gets pinned.

## Host token-provider context

Expand Down
5 changes: 5 additions & 0 deletions packages/api/src/schedules/authorization/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ export interface ScheduledMCPAuthorizationRequest {
/** Set only by the owner-authorized manual trigger or its verified resume metadata. */
readonly manual?: boolean;
readonly selection: ScheduledMCPToolSelection;
/**
* Digest of each selected tool's live definition, by tool. A tool is pinned to the first
* one seen and refused once it differs. Absent at mint, where no catalog is read.
*/
readonly definitions?: Readonly<Record<string, string>>;
}

/** Ephemeral observation, not a transferable grant or permission to cache an allow decision. */
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/schedules/authorization/enrollment.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import type { ScheduledMCPIdentity } from 'librechat-data-provider';
import type { ScheduleMCPEnrollmentDeps } from './enrollment';
import type { ParsedServerConfig } from '~/mcp/types';
import { createScheduleMCPEnrollmentResolver } from './enrollment';
import { allowOffered, pinStorage } from './execution.helper';
import { createScheduleMCPConsentService } from './service';
import { createResolveAgentFireAccess } from '../access';
import { allowOffered } from './execution.helper';

const identity: ScheduledMCPIdentity = {
scheduleId: 's',
Expand Down Expand Up @@ -224,6 +224,7 @@ it.each<Partial<Extract<ParsedServerConfig, { type: 'http' | 'streamable-http' }
},
revokeScheduleMCPConsent: async () => true,
admitScheduleMCPConsent: admit,
...pinStorage(() => snapshot.enrollment),
};
const service = createScheduleMCPConsentService({
storage,
Expand Down Expand Up @@ -344,6 +345,7 @@ it('does not offer owner consent for recipient-defining custom user variables',
confirmScheduleMCPConsent: confirm,
revokeScheduleMCPConsent: async () => true,
admitScheduleMCPConsent: async () => true,
...pinStorage(() => snapshot.enrollment),
},
resolveEnrollment: resolve,
getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),
Expand Down
Loading
Loading