diff --git a/client/src/components/SidePanel/Schedules/Consent.tsx b/client/src/components/SidePanel/Schedules/Consent.tsx index ca656986365..9be6be078ee 100644 --- a/client/src/components/SidePanel/Schedules/Consent.tsx +++ b/client/src/components/SidePanel/Schedules/Consent.tsx @@ -36,24 +36,44 @@ 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 { 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, 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; + revision: string | null; + changed: Record; +} + /** * 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, 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: Record | null, + edited: Edited | null, ): Record { const initial = initialChoice(data); if (!edited) return initial; @@ -61,9 +81,13 @@ function currentChoice( 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[serverName] ?? initial[serverName]).filter((tool) => offered.includes(tool)), + (edited.choice[serverName] ?? initial[serverName]).filter( + (tool) => offered.includes(tool) && (!marked.includes(tool) || seen.includes(tool)), + ), ]; }), ); @@ -89,14 +113,18 @@ 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 | null>(null); + const [edited, setEdited] = useState(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 }, + revision: data?.revision ?? null, + changed: data?.changed ?? {}, + }); const commit = () => { if (!data?.offer || chosenCount === 0) return; setMessage(null); @@ -188,15 +216,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)} /> ) : ( -

- {localize('com_ui_schedule_consent_allowed', { - tools: (data.allowed[target.resource.serverName] ?? []).join(', '), - })} -

+ <> +

+ {localize('com_ui_schedule_consent_allowed', { + tools: (data.allowed[target.resource.serverName] ?? []).join(', '), + })} +

+ {(data.changed[target.resource.serverName] ?? []).length > 0 && ( +

+ {localize('com_ui_schedule_consent_changed_tools', { + tools: data.changed[target.resource.serverName].join(', '), + })} +

+ )} + )} ))} @@ -256,12 +294,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; }) { @@ -285,27 +326,35 @@ function ToolChoice({
    {offered.map((tool) => ( -
  • - - onChange( - checked === true - ? offered.filter((name) => name === tool || chosen.includes(name)) - : chosen.filter((name) => name !== tool), - ) - } - /> - +
  • +
    + + onChange( + checked === true + ? offered.filter((name) => name === tool || chosen.includes(name)) + : chosen.filter((name) => name !== tool), + ) + } + /> + +
    + {changed.includes(tool) && ( +

    + {localize('com_ui_schedule_consent_tool_changed')} +

    + )}
  • ))}
diff --git a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx index 63940e0c6db..1ea46c110eb 100644 --- a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx +++ b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx @@ -45,6 +45,7 @@ const view: ScheduleMCPConsentView = { }, ], allowed: {}, + changed: {}, offer: { digest: 'a'.repeat(64), maxLifetimeHours: 24 }, }; function display() { @@ -170,6 +171,121 @@ 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('unticks a tool the owner accepted once it is marked again under a later grant', async () => { + const marked = { + ...view, + state: 'changed' as const, + revision: 'grant-1', + expiresAtMs: Date.now() + 60_000, + allowed: { warehouse: ['query'] }, + changed: { warehouse: ['query'] }, + }; + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(marked); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view); + const client = display(); + await userEvent.click(await screen.findByRole('checkbox', { name: 'query' })); + expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked(); + // Confirmed elsewhere, then a run marks the tool again: the same name, another change. + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({ + ...marked, + revision: 'grant-2', + offer: { digest: 'd'.repeat(64), maxLifetimeHours: 24 }, + }); + await client.invalidateQueries(); + await waitFor(() => expect(screen.getByRole('checkbox', { name: 'query' })).not.toBeChecked()); + expect(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })).toBeDisabled(); + await userEvent.click(screen.getByRole('checkbox', { name: 'query' })); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ + offerDigest: 'd'.repeat(64), + expectedRevision: 'grant-2', + 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, diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 778a10a22be..57f7f6acc06 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -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)", @@ -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", diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.ts index 23b83c7af03..2e4968839c9 100644 --- a/packages/api/src/mcp/__tests__/MCPManager.test.ts +++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts @@ -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 () => { diff --git a/packages/api/src/schedules/README.md b/packages/api/src/schedules/README.md index 0a5de909677..68e625bc90e 100644 --- a/packages/api/src/schedules/README.md +++ b/packages/api/src/schedules/README.md @@ -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 diff --git a/packages/api/src/schedules/authorization/contract.ts b/packages/api/src/schedules/authorization/contract.ts index bc881703ba3..d5f893bb39a 100644 --- a/packages/api/src/schedules/authorization/contract.ts +++ b/packages/api/src/schedules/authorization/contract.ts @@ -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>; } /** Ephemeral observation, not a transferable grant or permission to cache an allow decision. */ diff --git a/packages/api/src/schedules/authorization/enrollment.spec.ts b/packages/api/src/schedules/authorization/enrollment.spec.ts index 609f0e33129..f40c4985370 100644 --- a/packages/api/src/schedules/authorization/enrollment.spec.ts +++ b/packages/api/src/schedules/authorization/enrollment.spec.ts @@ -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', @@ -224,6 +224,7 @@ it.each true, admitScheduleMCPConsent: admit, + ...pinStorage(() => snapshot.enrollment), }; const service = createScheduleMCPConsentService({ storage, @@ -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 }), diff --git a/packages/api/src/schedules/authorization/execution.helper.ts b/packages/api/src/schedules/authorization/execution.helper.ts index cc131a5df3a..1b5a181da24 100644 --- a/packages/api/src/schedules/authorization/execution.helper.ts +++ b/packages/api/src/schedules/authorization/execution.helper.ts @@ -1,9 +1,13 @@ +import type { + ScheduledMCPIdentity, + ScheduledMCPTarget, + ScheduledMCPEnrollment, +} from 'librechat-data-provider'; import type { ScheduleMCPConsentStorage, ScheduleConsentSnapshot, IUser, } from '@librechat/data-schemas'; -import type { ScheduledMCPIdentity, ScheduledMCPTarget } from 'librechat-data-provider'; import type { Tool } from '@modelcontextprotocol/sdk/types.js'; import type { ParsedServerConfig } from '~/mcp/types'; import { getScheduledMCPConfigurationRevision } from './configuration'; @@ -21,6 +25,65 @@ export function allowOffered(targets: readonly ScheduledMCPTarget[]): Record> = {}, +): boolean { + const consent = enrollment?.consents.find((item) => item.id === consentId); + return Object.entries(definitions).every( + ([tool, digest]) => + !consent?.changedTools?.includes(tool) && + !consent?.definitions?.some((pin) => pin.tool === tool && pin.digest !== digest), + ); +} + +/** What a confirmation checks in its write: no pin or mark was added to the grant it read. */ +export function untouchedSince( + enrollment: ScheduledMCPEnrollment | null | undefined, + basis: ScheduledMCPEnrollment | null | undefined, +): boolean { + return (basis?.consents ?? []).every((seen) => { + const stored = enrollment?.consents.find((item) => item.id === seen.id); + return ( + stored != null && + (stored.definitions?.length ?? 0) === (seen.definitions?.length ?? 0) && + (stored.changedTools?.length ?? 0) === (seen.changedTools?.length ?? 0) + ); + }); +} + +/** The two pin writes over an enrollment a fake keeps in memory, with the real fences. */ +export function pinStorage( + current: () => ScheduledMCPEnrollment | null | undefined, +): Pick { + const find = (revision: string, consentId: string) => { + const enrollment = current(); + if (enrollment?.revision !== revision) return; + return enrollment.consents.find((consent) => consent.id === consentId); + }; + return { + pinScheduleMCPToolDefinition: async ({ revision, consentId, tool, digest }) => { + const consent = find(revision, consentId); + if ( + !consent || + consent.revokedAtMs != null || + consent.definitions?.some((pin) => pin.tool === tool) + ) + return false; + consent.definitions = [...(consent.definitions ?? []), { tool, digest }]; + return true; + }, + flagScheduleMCPToolChange: async ({ revision, consentId, tool }) => { + const consent = find(revision, consentId); + if (!consent?.definitions?.some((pin) => pin.tool === tool)) return false; + consent.changedTools = [...new Set([...(consent.changedTools ?? []), tool])]; + return true; + }, + }; +} + export const readTool: Tool = { name: 'query', description: 'Read a fixed resource', @@ -95,8 +158,10 @@ export async function executionFixture( snapshot.enrollment?.revision === input.revision && snapshot.enrollment.consents.every( (c) => c.revokedAtMs == null && c.absoluteExpiresAtMs > time, - ), + ) && + admitsDefinitions(snapshot.enrollment, input.consentId, input.definitions), ), + ...pinStorage(() => snapshot.enrollment), }; const service = createScheduleMCPConsentService({ storage, diff --git a/packages/api/src/schedules/authorization/execution.spec.ts b/packages/api/src/schedules/authorization/execution.spec.ts index 3268bfa7767..d2812c4490b 100644 --- a/packages/api/src/schedules/authorization/execution.spec.ts +++ b/packages/api/src/schedules/authorization/execution.spec.ts @@ -100,6 +100,59 @@ it('keeps an allowed tool authorized after the agent selects another tool', asyn ).resolves.toBeUndefined(); }); +it('pins the live definition on first use and refuses the tool once the server changes it', async () => { + const fixture = await executionFixture(); + const call = (tool: Tool = readTool, agentId = 'root') => + fixture.invocation(agentId).authorize({ + user: fixture.user, + serverName: 'warehouse', + serverConfig: fixture.config, + toolName: 'query', + loadTools: async () => catalog([tool]), + }); + await call(); + // Key order is not a change; a new description, schema or annotation is. + await call({ + inputSchema: readTool.inputSchema, + description: readTool.description, + name: 'query', + }); + for (const changed of [ + { ...readTool, description: 'Read a fixed resource, then forward it' }, + { ...readTool, inputSchema: { type: 'object' as const, properties: { to: {} } } }, + { ...readTool, annotations: { readOnlyHint: true } }, + ]) { + const other = await executionFixture(); + await other.invocation().authorize({ + user: other.user, + serverName: 'warehouse', + serverConfig: other.config, + toolName: 'query', + loadTools: async () => catalog(), + }); + await expect( + other.invocation().authorize({ + user: other.user, + serverName: 'warehouse', + serverConfig: other.config, + toolName: 'query', + loadTools: async () => catalog([changed]), + }), + ).rejects.toMatchObject({ failure: { reason: 'binding_mismatch' } }); + } + await expect(call({ ...readTool, description: 'Changed' })).rejects.toMatchObject({ + failure: { reason: 'binding_mismatch', status: 'mcp_reauth_required' }, + }); + // The other agent's use of the same tool is refused too, and so is the original definition. + await expect(call(readTool, 'child')).rejects.toMatchObject({ + failure: { reason: 'binding_mismatch' }, + }); + expect(await fixture.service.view(fixture.identity)).toMatchObject({ + state: 'changed', + changed: { warehouse: ['query'] }, + }); +}); + it('refuses an incomplete snapshot and ambiguous duplicate definitions', async () => { const f = await executionFixture(); for (const snapshot of [{ ...catalog(), complete: false }, catalog([readTool, readTool])]) { diff --git a/packages/api/src/schedules/authorization/execution.ts b/packages/api/src/schedules/authorization/execution.ts index bf7e2426a03..e827fdb6c0e 100644 --- a/packages/api/src/schedules/authorization/execution.ts +++ b/packages/api/src/schedules/authorization/execution.ts @@ -13,11 +13,11 @@ import type { ParsedServerConfig, RequestScopedMCPConnectionStore } from '~/mcp/ import type { MCPToolsSnapshot } from '~/mcp/connection'; import type { ScheduledMCPAuthority } from './contract'; import type { ScheduledTokenContext } from '../context'; +import { getScheduledMCPToolDefinitionDigest, ScheduledMCPPolicyError } from './policy'; import { getScheduledMCPConfigurationRevision } from './configuration'; import { ScheduledMCPBearerError } from '~/mcp/errors'; import { findMCPRequestContext } from '~/mcp/request'; import { ScheduleMCPConsentError } from './service'; -import { ScheduledMCPPolicyError } from './policy'; import { isOwnedAbortError } from '~/utils/errors'; import { waitUntilDeadline } from '~/mcp/utils'; @@ -260,6 +260,9 @@ export function createScheduleMCPExecution(deps: ScheduleMCPExecutionDeps): { stage, ...(manual && { manual: true }), selection: { agentId: agentId!, tools: [selectionName] }, + definitions: { + [selectionName]: getScheduledMCPToolDefinitionDigest(definitions[0]), + }, }, { signal }, ); diff --git a/packages/api/src/schedules/authorization/policy.ts b/packages/api/src/schedules/authorization/policy.ts index 9e9da5ef5bd..31b1a3714d9 100644 --- a/packages/api/src/schedules/authorization/policy.ts +++ b/packages/api/src/schedules/authorization/policy.ts @@ -6,6 +6,7 @@ import type { ScheduledMCPFailureReason, ScheduleMCPOutcome, } from 'librechat-data-provider'; +import type { Tool } from '@modelcontextprotocol/sdk/types.js'; import type { ScheduledMCPFailure } from './contract'; import { failureFixtures } from './failures'; @@ -36,6 +37,13 @@ function canonical(value: unknown): unknown { return value; } +/** Covers the whole upstream definition: name, description, schemas and annotations. */ +export function getScheduledMCPToolDefinitionDigest(tool: Tool): string { + return createHash('sha256') + .update(JSON.stringify(canonical(tool))) + .digest('hex'); +} + /** Identifies one set of permitted selections; a grant and its bearer cache entries bind to it. */ export function getScheduledMCPPolicyRevision( selections: readonly ScheduledMCPToolSelection[], diff --git a/packages/api/src/schedules/authorization/service.spec.ts b/packages/api/src/schedules/authorization/service.spec.ts index fbaad376c88..71745358345 100644 --- a/packages/api/src/schedules/authorization/service.spec.ts +++ b/packages/api/src/schedules/authorization/service.spec.ts @@ -1,5 +1,6 @@ import type { ScheduleMCPConsentStorage, ScheduleConsentSnapshot } from '@librechat/data-schemas'; import type { ScheduledMCPIdentity, ScheduledMCPTarget } from 'librechat-data-provider'; +import { pinStorage, untouchedSince, admitsDefinitions } from './execution.helper'; import { createScheduleMCPConsentHandlers } from './handlers'; import { createScheduleMCPConsentService } from './service'; @@ -26,6 +27,10 @@ const target: ScheduledMCPTarget = { ], policyRevision: 'p1', }; +const jestPins = (pins: ReturnType) => ({ + pinScheduleMCPToolDefinition: jest.fn(pins.pinScheduleMCPToolDefinition), + flagScheduleMCPToolChange: jest.fn(pins.flagScheduleMCPToolChange), +}); function setup() { let time = 1000; const snapshot: ScheduleConsentSnapshot = { @@ -41,7 +46,8 @@ function setup() { confirmScheduleMCPConsent: jest.fn(async (input) => { if ( snapshot.configRevision !== input.expectedConfigRevision || - (snapshot.enrollment?.revision ?? null) !== input.expectedRevision + (snapshot.enrollment?.revision ?? null) !== input.expectedRevision || + !untouchedSince(snapshot.enrollment, input.basis) ) return false; snapshot.enrollment = structuredClone(input.enrollment); @@ -58,13 +64,15 @@ function setup() { return true; }), admitScheduleMCPConsent: jest.fn( - async ({ revision }) => + async ({ revision, consentId, definitions }) => snapshot.enabled && snapshot.enrollment?.revision === revision && snapshot.enrollment.consents.every( (c) => c.revokedAtMs == null && c.absoluteExpiresAtMs > time, - ), + ) && + admitsDefinitions(snapshot.enrollment, consentId, definitions), ), + ...jestPins(pinStorage(() => snapshot.enrollment)), }; const service = createScheduleMCPConsentService({ storage, @@ -386,3 +394,245 @@ it('offers no overwrite of an incompatible stored grant', async () => { revision: null, }); }); + +describe('definition pins', () => { + const first = 'a'.repeat(64); + const second = 'b'.repeat(64); + const use = (digest: string, tool = 'query') => ({ + ...request('invoke'), + selection: { agentId: 'root', tools: [tool] }, + definitions: { [tool]: digest }, + }); + const consent = (s: ReturnType) => s.snapshot.enrollment!.consents[0]; + + it('pins a tool on first use and refuses it once the definition differs', async () => { + const s = setup(); + await s.enroll(); + expect(consent(s).definitions).toBeUndefined(); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'authorized', + }); + expect(consent(s).definitions).toEqual([{ tool: 'query', digest: first }]); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'authorized', + }); + expect(await s.service.authority.authorize(use(second), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch', recovery: 'authorize' }, + }); + expect(consent(s).definitions).toEqual([{ tool: 'query', digest: first }]); + expect(await s.service.view(identity)).toMatchObject({ + state: 'changed', + changed: { warehouse: ['query'] }, + }); + }); + + it('keeps a changed tool refused after the server restores the old definition', async () => { + const s = setup(); + await s.enroll(); + await s.service.authority.authorize(use(first), {}); + await s.service.authority.authorize(use(second), {}); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + }); + + it('refuses only the changed tool and still mints for the server', async () => { + const s = setup(); + s.changeTarget({ ...target, permittedTools: [{ agentId: 'root', tools: ['list', 'query'] }] }); + await s.enroll({ warehouse: ['list', 'query'] }); + await s.service.authority.authorize(use(first), {}); + await s.service.authority.authorize(use(second), {}); + expect(await s.service.authority.authorize(use(first, 'list'), {})).toMatchObject({ + state: 'authorized', + }); + expect( + await s.service.authority.authorize( + { ...request('mint'), selection: { agentId: 'root', tools: ['list', 'query'] } }, + {}, + ), + ).toMatchObject({ state: 'authorized' }); + }); + + it('carries pins through a renewal and re-pins a changed tool the owner allows again', async () => { + const s = setup(); + s.changeTarget({ ...target, permittedTools: [{ agentId: 'root', tools: ['list', 'query'] }] }); + await s.enroll({ warehouse: ['list', 'query'] }); + await s.service.authority.authorize(use(first), {}); + await s.service.authority.authorize(use(first, 'list'), {}); + await s.service.authority.authorize(use(second), {}); + const renewed = await s.enroll({ warehouse: ['list', 'query'] }); + expect(renewed).toMatchObject({ state: 'active', changed: {} }); + // `list` keeps its pin, so a definition swapped before the renewal is still caught. + expect(consent(s).definitions).toEqual([{ tool: 'list', digest: first }]); + expect(await s.service.authority.authorize(use(second, 'list'), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + expect(await s.service.authority.authorize(use(second), {})).toMatchObject({ + state: 'authorized', + }); + expect(consent(s).definitions).toContainEqual({ tool: 'query', digest: second }); + }); + + it('drops pins when the grant moves to a different recipient', async () => { + const s = setup(); + await s.enroll(); + await s.service.authority.authorize(use(first), {}); + s.changeTarget({ + ...target, + resource: { ...target.resource, url: 'https://other.example/mcp' }, + }); + await s.enroll(); + expect(consent(s).definitions).toBeUndefined(); + }); + + it('accepts a pin another replica wrote first only when it matches', async () => { + const s = setup(); + await s.enroll(); + const lose = (digest: string) => + jest + .mocked(s.storage.pinScheduleMCPToolDefinition) + .mockImplementationOnce(async ({ tool }) => { + consent(s).definitions = [{ tool, digest }]; + return false; + }); + lose(first); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'authorized', + }); + consent(s).definitions = undefined; + lose(second); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + // The loser marks the tool, so the definition that won the race is refused as well. + expect(consent(s).changedTools).toEqual(['query']); + expect(await s.service.authority.authorize(use(second), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + expect(await s.service.view(identity)).toMatchObject({ + state: 'changed', + changed: { warehouse: ['query'] }, + }); + }); + + it('does not let a dialog opened before a tool was marked confirm past the mark', async () => { + const s = setup(); + await s.enroll(); + await s.service.authority.authorize(use(first), {}); + const opened = await s.service.view(identity); + // A run sees a different definition while the dialog is open. + await s.service.authority.authorize(use(second), {}); + const stale = { + offerDigest: opened.offer!.digest, + expectedRevision: opened.revision, + lifetimeHours: 1, + allow: { warehouse: ['query'] }, + }; + jest.mocked(s.storage.confirmScheduleMCPConsent).mockClear(); + await expect(s.service.confirm(identity, stale)).rejects.toMatchObject({ + code: 'consent_changed', + }); + expect(s.storage.confirmScheduleMCPConsent).not.toHaveBeenCalled(); + expect(consent(s).changedTools).toEqual(['query']); + // Read again, the owner is shown the mark and can decide. + const shown = await s.service.view(identity); + expect(shown.offer!.digest).not.toBe(opened.offer!.digest); + expect(shown.changed).toEqual({ warehouse: ['query'] }); + await expect( + s.service.confirm(identity, { ...stale, offerDigest: shown.offer!.digest }), + ).resolves.toMatchObject({ state: 'active', changed: {} }); + }); + + it('keeps the digest of an offer in which nothing is marked', async () => { + const s = setup(); + const before = await s.service.view(identity); + await s.enroll(); + await s.service.authority.authorize(use(first), {}); + // Pinning is not a change the owner has to look at again. + expect((await s.service.view(identity)).offer!.digest).toBe(before.offer!.digest); + }); + + /** Runs `between` after the next use has read the grant and before it is admitted. */ + const beforeAdmission = (s: ReturnType, between: () => Promise) => { + const admit = jest.mocked(s.storage.admitScheduleMCPConsent); + const real = admit.getMockImplementation()!; + admit.mockImplementationOnce(async (input) => { + await between(); + return real(input); + }); + }; + + it('refuses a use whose tool was marked after it read the grant', async () => { + const s = setup(); + await s.enroll(); + await s.service.authority.authorize(use(first), {}); + // Another use sees a different definition and marks the tool before this one is admitted. + beforeAdmission(s, () => s.service.authority.authorize(use(second), {})); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + expect(consent(s).changedTools).toEqual(['query']); + }); + + it('refuses and marks a first use that another first use beat with a different definition', async () => { + const s = setup(); + await s.enroll(); + beforeAdmission(s, () => s.service.authority.authorize(use(second), {})); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + expect(consent(s)).toMatchObject({ + definitions: [{ tool: 'query', digest: second }], + changedTools: ['query'], + }); + expect(s.storage.pinScheduleMCPToolDefinition).toHaveBeenCalledTimes(1); + }); + + it('does not let a confirmation drop a pin or a mark stored while it was being made', async () => { + const s = setup(); + s.changeTarget({ ...target, permittedTools: [{ agentId: 'root', tools: ['list', 'query'] }] }); + await s.enroll({ warehouse: ['list', 'query'] }); + await s.service.authority.authorize(use(first), {}); + const confirm = jest.mocked(s.storage.confirmScheduleMCPConsent); + const real = confirm.getMockImplementation()!; + const during = (run: () => Promise) => + confirm.mockImplementationOnce(async (input) => { + await run(); + return real(input); + }); + // `list` is used for the first time after the confirmation read the grant. + during(() => s.service.authority.authorize(use(first, 'list'), {})); + await expect(s.enroll({ warehouse: ['list', 'query'] })).rejects.toMatchObject({ + code: 'consent_changed', + }); + expect(consent(s).definitions).toEqual([ + { tool: 'query', digest: first }, + { tool: 'list', digest: first }, + ]); + // `query` is marked after the confirmation checked what the owner was shown. + during(() => s.service.authority.authorize(use(second), {})); + await expect(s.enroll({ warehouse: ['list', 'query'] })).rejects.toMatchObject({ + code: 'consent_changed', + }); + expect(consent(s).changedTools).toEqual(['query']); + await expect(s.enroll({ warehouse: ['list'] })).resolves.toMatchObject({ state: 'active' }); + expect(consent(s).definitions).toEqual([{ tool: 'list', digest: first }]); + }); + + it('does not authorize a first use whose pin could not be stored', async () => { + const s = setup(); + await s.enroll(); + jest.mocked(s.storage.pinScheduleMCPToolDefinition).mockResolvedValueOnce(false); + expect(await s.service.authority.authorize(use(first), {})).toMatchObject({ + state: 'denied', + failure: { reason: 'binding_mismatch' }, + }); + }); +}); diff --git a/packages/api/src/schedules/authorization/service.ts b/packages/api/src/schedules/authorization/service.ts index 9c20c7afab6..f2ef89a0dab 100644 --- a/packages/api/src/schedules/authorization/service.ts +++ b/packages/api/src/schedules/authorization/service.ts @@ -4,6 +4,7 @@ import type { ScheduledMCPIdentity, ScheduledMCPResource, ScheduledMCPTarget, + ScheduledMCPConsent, ScheduleMCPConsentView, ConfirmScheduleMCPConsent, ScheduledMCPEnrollment, @@ -150,6 +151,57 @@ function coversGrant( }); } +/** Allowed tools a run saw with a definition other than their pin, by server. */ +function changedTools(consents: readonly ScheduledMCPConsent[]): Record { + return Object.fromEntries( + consents + .filter((consent) => consent.changedTools?.length) + .map((consent) => [consent.resource.serverName, [...consent.changedTools!].sort()]), + ); +} + +/** + * Pins survive a renewal so confirming again cannot quietly accept a definition nobody has + * looked at. A tool marked as changed loses its pin: confirming it is the owner's decision + * to accept what the server offers now, and its next use is pinned afresh. + */ +function carriedPins( + target: ScheduledMCPTarget, + prior?: ScheduledMCPConsent, +): Pick { + if (!prior?.definitions || !sameResource(prior.resource, target.resource)) return {}; + const allowed = new Set(target.permittedTools.flatMap((selection) => selection.tools)); + const marked = new Set(prior.changedTools); + const definitions = prior.definitions.filter( + (pin) => allowed.has(pin.tool) && !marked.has(pin.tool), + ); + return definitions.length ? { definitions } : {}; +} + +/** + * Names what the owner was shown: the subject, its configuration, what is on offer, and which + * allowed tools were marked as changed. A dialog opened before a tool was marked cannot + * confirm past the mark; it is told the offer changed and reads it again. + */ +function offerDigest( + identity: ScheduledMCPIdentity, + configRevision: number, + targets: readonly ScheduledMCPTarget[], + changed: Record, +): string { + return createHash('sha256') + .update( + JSON.stringify({ + identity, + configRevision, + targets, + // Left out while nothing is marked, so an offer made before marks existed still holds. + ...(Object.keys(changed).length > 0 && { changed }), + }), + ) + .digest('hex'); +} + export interface ScheduleMCPConsentService { view: ( identity: ScheduledMCPIdentity, @@ -212,6 +264,8 @@ export function createScheduleMCPConsentService( policyRevision, })) ?? []; const allowedByServer = allowedTools(granted); + const changedByServer = changedTools(enrollment?.consents ?? []); + if (state === 'active' && Object.keys(changedByServer).length > 0) state = 'changed'; let targets = granted; let offer: ScheduleMCPConsentView['offer'] = null; if (snapshot.compatible === false) { @@ -221,6 +275,7 @@ export function createScheduleMCPConsentService( expiresAtMs: null, targets: [], allowed: {}, + changed: {}, offer: null, }; } @@ -236,6 +291,7 @@ export function createScheduleMCPConsentService( expiresAtMs, targets, allowed: allowedByServer, + changed: changedByServer, offer: null, }; } @@ -246,12 +302,11 @@ export function createScheduleMCPConsentService( expiresAtMs, targets, allowed: allowedByServer, + changed: changedByServer, offer: null, }; targets = canonicalTargets(resolved); - const digest = createHash('sha256') - .update(JSON.stringify({ identity, configRevision: snapshot.configRevision, targets })) - .digest('hex'); + const digest = offerDigest(identity, snapshot.configRevision, targets, changedByServer); offer = { digest, maxLifetimeHours: limits.maxLifetimeHours }; if (state === 'active' && !coversGrant(targets, granted)) state = 'changed'; } else if (!enrollment) state = 'unsupported'; @@ -262,6 +317,7 @@ export function createScheduleMCPConsentService( expiresAtMs, targets, allowed: allowedByServer, + changed: changedByServer, offer, }; } @@ -286,15 +342,12 @@ export function createScheduleMCPConsentService( const snapshot = await deps.storage.readScheduleMCPConsent(identity); if (!snapshot) throw new ScheduleMCPConsentError('consent_not_found'); // Recompute the digest with the final observed row so an edit cannot reuse an old offer. - const digest = createHash('sha256') - .update( - JSON.stringify({ - identity, - configRevision: snapshot.configRevision, - targets: current.targets, - }), - ) - .digest('hex'); + const digest = offerDigest( + identity, + snapshot.configRevision, + current.targets, + changedTools(snapshot.enrollment?.consents ?? []), + ); if (digest !== input.offerDigest) throw new ScheduleMCPConsentError('consent_changed'); const chosen = selectAllowed(current.targets, input.allow); options.signal?.throwIfAborted(); @@ -306,6 +359,12 @@ export function createScheduleMCPConsentService( 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, @@ -319,6 +378,8 @@ export function createScheduleMCPConsentService( expectedRevision: input.expectedRevision, expectedConfigRevision: snapshot.configRevision, enrollment, + // A pin or mark a run adds after this read is neither carried nor shown to the owner. + basis: snapshot.enrollment, }); if (!committed) throw new ScheduleMCPConsentError('consent_changed'); return view(identity, options); @@ -389,21 +450,74 @@ export function createScheduleMCPConsentService( ) ) return denial('tool_policy_denied'); + const live = Object.entries(request.definitions ?? {}).filter(([tool]) => + request.selection.tools.includes(tool), + ); + const pinned = (source: ScheduledMCPConsent, tool: string, digest: string) => + !source.changedTools?.includes(tool) && + source.definitions?.find((pin) => pin.tool === tool)?.digest === digest; + const grant = { identity: request.identity, revision: enrollment!.revision }; + /** Marks every tool `source` pins to a definition other than the one this request saw. */ + const markDisagreements = async (source: ScheduledMCPConsent): Promise => { + const tools = live + .filter(([tool, digest]) => + source.definitions?.some((pin) => pin.tool === tool && pin.digest !== digest), + ) + .map(([tool]) => tool); + await Promise.all( + tools.map((tool) => + deps.storage.flagScheduleMCPToolChange({ ...grant, consentId: consent.id, tool }), + ), + ); + return tools.length > 0; + }; + if (live.some(([tool]) => consent.changedTools?.includes(tool))) + return denial('binding_mismatch'); + if (await markDisagreements(consent)) return denial('binding_mismatch'); if (options.signal?.aborted) return { state: 'cancelled' }; + // The grant was read a moment ago. Admission checks the marks and pins again in the same + // write, so a mark or a first pin stored since then refuses this use as well. const admitted = await deps.storage.admitScheduleMCPConsent({ identity: request.identity, expectedConfigRevision: snapshot!.configRevision, revision: enrollment!.revision, consentId: consent.id, requireEnabled: request.stage !== 'activation' && request.manual !== true, + ...(live.length > 0 && { definitions: Object.fromEntries(live) }), }); if (!admitted) { const latest = await authority.lookupConsent(request.identity, request.resource, options); if (latest.state !== 'found') return denial('consent_missing'); if (latest.consent.revokedAtMs != null) return denial('consent_revoked'); if (now() >= latest.consent.absoluteExpiresAtMs) return denial('consent_expired'); + if (latest.consent.id === consent.id) await markDisagreements(latest.consent); return denial('binding_mismatch'); } + // First use: remember what the tool looked like. Another replica may have got there first. + const unpinned = live.filter( + ([tool]) => !consent.definitions?.some((pin) => pin.tool === tool), + ); + const stored = await Promise.all( + unpinned.map(([tool, digest]) => + deps.storage.pinScheduleMCPToolDefinition({ + ...grant, + consentId: consent.id, + tool, + digest, + }), + ), + ); + if (stored.includes(false)) { + const latest = await authority.lookupConsent(request.identity, request.resource, options); + const current = + latest.state === 'found' && latest.consent.id === consent.id ? latest.consent : undefined; + if (!current || unpinned.some(([tool, digest]) => !pinned(current, tool, digest))) { + // Two first uses saw two definitions. The one that lost leaves the same mark a later + // mismatch would, so the tool is refused and the owner is told, whichever won. + if (current) await markDisagreements(current); + return denial('binding_mismatch'); + } + } if (options.signal?.aborted) return { state: 'cancelled' }; if (now() >= consent.absoluteExpiresAtMs) return denial('consent_expired'); return { diff --git a/packages/api/src/schedules/bearer.spec.ts b/packages/api/src/schedules/bearer.spec.ts index 6af39b90959..64651dd8ddf 100644 --- a/packages/api/src/schedules/bearer.spec.ts +++ b/packages/api/src/schedules/bearer.spec.ts @@ -36,6 +36,7 @@ import { createScheduleMCPConsentService } from './authorization/service'; import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry'; import { restoreExecutionContext } from '~/agents/authority/context'; import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory'; +import { pinStorage } from './authorization/execution.helper'; import { createScheduleMCPPreflight } from './mcp'; import { FlowStateManager } from '~/flow/manager'; import { MCPConnection } from '~/mcp/connection'; @@ -102,6 +103,7 @@ async function bearerFixture(serverConfig = config) { snapshot.enrollment.consents.every( (c) => c.revokedAtMs == null && c.absoluteExpiresAtMs > time, ), + ...pinStorage(() => snapshot.enrollment), }; const resolveEnrollment = jest.fn(async () => [structuredClone(target)]); const consent = createScheduleMCPConsentService({ diff --git a/packages/data-provider/src/types/scheduleConsent.spec.ts b/packages/data-provider/src/types/scheduleConsent.spec.ts index 092704b3302..e5d162fd650 100644 --- a/packages/data-provider/src/types/scheduleConsent.spec.ts +++ b/packages/data-provider/src/types/scheduleConsent.spec.ts @@ -75,6 +75,50 @@ it('does not accept an unknown persisted consent version', () => { ).toBe(false); }); +it('reads a grant with or without definition pins, and nothing but a digest as a pin', () => { + const identity = { + scheduleId: 'schedule', + ownerId: 'owner', + tenantId: 'tenant', + agentId: 'root', + invocationMode: 'delegated' as const, + }; + const consent = { + id: 'consent', + revision: 'grant', + identity, + resource: { + serverName: 'warehouse', + url: 'https://warehouse.example/mcp', + configurationRevision: 'v1', + credentialMode: 'anonymous' as const, + issuer: null, + audience: null, + scopes: [], + }, + permittedTools: [{ agentId: 'root', tools: ['query'] }], + policyRevision: 'p1', + grantedAtMs: 1, + absoluteExpiresAtMs: 2, + revokedAtMs: null, + }; + const parse = (extra: object) => + scheduledMCPEnrollmentSchema.safeParse({ + version: 1, + scheduleRevision: 0, + revision: 'grant', + consents: [{ ...consent, ...extra }], + }).success; + expect(parse({})).toBe(true); + expect( + parse({ definitions: [{ tool: 'query', digest: 'a'.repeat(64) }], changedTools: ['query'] }), + ).toBe(true); + expect(parse({ definitions: [{ tool: 'query', digest: 'short' }] })).toBe(false); + expect( + parse({ definitions: [{ tool: 'query', digest: 'a'.repeat(64), description: 'text' }] }), + ).toBe(false); +}); + it.each([ ['no choice at all', undefined], ['no servers', {}], diff --git a/packages/data-provider/src/types/scheduleConsent.ts b/packages/data-provider/src/types/scheduleConsent.ts index 9668d94f5b9..06be4d56385 100644 --- a/packages/data-provider/src/types/scheduleConsent.ts +++ b/packages/data-provider/src/types/scheduleConsent.ts @@ -103,6 +103,15 @@ export const scheduledMCPTargetSchema = z .strict(); export type ScheduledMCPTarget = z.infer; +/** What an allowed tool looked like the first time an authorized run used it. */ +export const scheduledMCPToolPinSchema = z + .object({ + tool: identifier, + digest: z.string().regex(/^[a-f0-9]{64}$/), + }) + .strict(); +export type ScheduledMCPToolPin = z.infer; + export const scheduledMCPConsentSchema = scheduledMCPTargetSchema .extend({ id: identifier, @@ -111,6 +120,10 @@ export const scheduledMCPConsentSchema = scheduledMCPTargetSchema grantedAtMs: timestamp, absoluteExpiresAtMs: timestamp, revokedAtMs: timestamp.nullable(), + /** Absent until a tool is first used. One entry per tool, never rewritten. */ + definitions: z.array(scheduledMCPToolPinSchema).max(MAX_SCHEDULED_MCP_SERVER_TOOLS).optional(), + /** Tools a run saw with a definition other than their pin. Refused until confirmed again. */ + changedTools: z.array(identifier).max(MAX_SCHEDULED_MCP_SERVER_TOOLS).optional(), }) .strict() .refine((value) => value.absoluteExpiresAtMs > value.grantedAtMs); @@ -153,5 +166,7 @@ export interface ScheduleMCPConsentView { targets: ScheduledMCPTarget[]; /** The tools the stored grant allows, by server. Empty when there is none. */ allowed: Record; + /** Allowed tools whose definition changed since first use, by server. Refused until confirmed again. */ + changed: Record; offer: { digest: string; maxLifetimeHours: number } | null; } diff --git a/packages/data-schemas/src/methods/scheduleConsent.spec.ts b/packages/data-schemas/src/methods/scheduleConsent.spec.ts index a6d1fc21664..c09db482ae8 100644 --- a/packages/data-schemas/src/methods/scheduleConsent.spec.ts +++ b/packages/data-schemas/src/methods/scheduleConsent.spec.ts @@ -160,19 +160,25 @@ it('never overwrites revocation racing an activation edit or carries consent acr ).not.toBeNull(); }); -const confirm = (expectedRevision: string | null = null, grant = enrollment()) => +const confirm = ( + expectedRevision: string | null = null, + grant = enrollment(), + basis?: ScheduledMCPEnrollment | null, +) => storage.confirmScheduleMCPConsent({ identity, expectedConfigRevision: 0, expectedRevision, enrollment: grant, + basis, }); -const admit = (revision = 'grant-1') => +const admit = (revision = 'grant-1', definitions?: Record) => storage.admitScheduleMCPConsent({ identity, revision, expectedConfigRevision: 0, consentId: 'consent-1', + definitions, }); it('leaves legacy schedules unenrolled and does not change enabled/default scheduling state', async () => { @@ -296,3 +302,137 @@ it('uses only classic update operators for confirmation, revocation and admissio expect(Object.keys(operation!)).toEqual(['$set']); } }); + +describe('definition pins', () => { + const first = 'a'.repeat(64); + const second = 'b'.repeat(64); + const pin = (digest = first, tool = 'query', revision = 'grant-1') => + storage.pinScheduleMCPToolDefinition({ + identity, + revision, + consentId: 'consent-1', + tool, + digest, + }); + const flag = (tool = 'query', revision = 'grant-1') => + storage.flagScheduleMCPToolChange({ identity, revision, consentId: 'consent-1', tool }); + const stored = async () => (await storage.readScheduleMCPConsent(identity))?.enrollment; + + it('keeps the first definition a tool was pinned to', async () => { + await confirm(); + expect(await pin(first)).toBe(true); + expect(await pin(second)).toBe(false); + expect(await pin(second, 'list')).toBe(true); + expect((await stored())?.consents[0].definitions).toEqual([ + { tool: 'query', digest: first }, + { tool: 'list', digest: second }, + ]); + }); + + it('has one winner among concurrent first uses', async () => { + await confirm(); + const digests = Array.from({ length: 6 }, (_, n) => String(n).repeat(64)); + const results = await Promise.all(digests.map((digest) => pin(digest))); + expect(results.filter(Boolean)).toHaveLength(1); + expect((await stored())?.consents[0].definitions).toEqual([ + { tool: 'query', digest: digests[results.indexOf(true)] }, + ]); + }); + + it('marks a pinned tool as changed without rewriting its pin', async () => { + await confirm(); + expect(await flag()).toBe(false); + await pin(); + expect(await flag()).toBe(true); + expect(await flag()).toBe(true); + expect((await stored())?.consents[0]).toMatchObject({ + definitions: [{ tool: 'query', digest: first }], + changedTools: ['query'], + }); + expect((await storage.readScheduleMCPConsent(identity))?.compatible).toBe(true); + }); + + it('writes nothing to a revoked or replaced grant', async () => { + await confirm(); + expect(await pin(first, 'query', 'grant-0')).toBe(false); + expect(await flag('query', 'grant-0')).toBe(false); + await storage.revokeScheduleMCPConsent(identity, 'grant-1'); + const revoked = (await stored())!.revision; + expect(await pin(first, 'query', revoked)).toBe(false); + expect((await stored())?.consents[0].definitions).toBeUndefined(); + }); + + it('rejects a malformed pin before it reaches the record', async () => { + await confirm(); + await expect(pin('not-a-digest')).rejects.toThrow(); + expect((await stored())?.consents[0].definitions).toBeUndefined(); + }); + + it('does not extend the deadline or change the grant revision', async () => { + const grant = enrollment(); + await confirm(null, grant); + await pin(); + await flag(); + expect(await stored()).toMatchObject({ + revision: 'grant-1', + consents: [{ absoluteExpiresAtMs: grant.consents[0].absoluteExpiresAtMs }], + }); + expect(await admit()).toBe(true); + }); + + it('admits a tool only while it is unmarked and pinned to the definition in use', async () => { + await confirm(); + expect(await admit('grant-1', { query: first })).toBe(true); + await pin(first); + expect(await admit('grant-1', { query: first })).toBe(true); + expect(await admit('grant-1', { query: second })).toBe(false); + // A tool with no pin yet, and a use that reads no definition, are not held back by it. + expect(await admit('grant-1', { list: second })).toBe(true); + expect(await admit('grant-1', { query: second, list: second })).toBe(false); + await flag(); + expect(await admit('grant-1', { query: first })).toBe(false); + expect(await admit('grant-1', { list: second })).toBe(true); + expect(await admit()).toBe(true); + }); + + it('refuses a confirmation built from a grant that has since gained a pin or a mark', async () => { + await confirm(); + const unpinned = await stored(); + await pin(); + expect(await confirm('grant-1', enrollment('grant-2'), unpinned)).toBe(false); + const unmarked = await stored(); + await flag(); + expect(await confirm('grant-1', enrollment('grant-2'), unmarked)).toBe(false); + expect((await stored())?.revision).toBe('grant-1'); + expect(await confirm('grant-1', enrollment('grant-2'), await stored())).toBe(true); + expect((await stored())?.revision).toBe('grant-2'); + }); + + it('revokes without dropping a pin stored between its read and its write', async () => { + await confirm(); + const model = mongoose.models.Schedule; + const write = model.updateOne.bind(model); + const update = jest + .spyOn(model, 'updateOne') + .mockImplementationOnce(((...args: Parameters) => + pin().then(() => write(...args))) as typeof model.updateOne); + expect(await storage.revokeScheduleMCPConsent(identity, 'grant-1')).toBe(true); + update.mockRestore(); + expect((await stored())?.consents[0]).toMatchObject({ + revokedAtMs: expect.any(Number), + definitions: [{ tool: 'query', digest: first }], + }); + }); + + it('uses only classic update operators', async () => { + await confirm(); + const update = jest.spyOn(mongoose.models.Schedule, 'updateOne'); + await pin(); + await flag(); + expect(update.mock.calls.map((call) => Object.keys(Array.from(call)[1]!))).toEqual([ + ['$push'], + ['$addToSet'], + ]); + update.mockRestore(); + }); +}); diff --git a/packages/data-schemas/src/methods/scheduleConsent.ts b/packages/data-schemas/src/methods/scheduleConsent.ts index 962159e7213..66cceaba3bd 100644 --- a/packages/data-schemas/src/methods/scheduleConsent.ts +++ b/packages/data-schemas/src/methods/scheduleConsent.ts @@ -1,5 +1,9 @@ import { randomUUID } from 'node:crypto'; -import { scheduledMCPEnrollmentSchema } from 'librechat-data-provider'; +import { + scheduledMCPToolPinSchema, + scheduledMCPEnrollmentSchema, + MAX_SCHEDULED_MCP_SERVER_TOOLS, +} from 'librechat-data-provider'; import type { ScheduledMCPIdentity, ScheduledMCPEnrollment } from 'librechat-data-provider'; import type { Model } from 'mongoose'; import type { IScheduleDocument } from '~/types/schedule'; @@ -21,6 +25,11 @@ export interface ScheduleMCPConsentStorage { expectedConfigRevision: number; expectedRevision: string | null; enrollment: ScheduledMCPEnrollment; + /** + * The stored grant the new one was built from. The write is refused when a run has added + * a pin or a mark to it since, so the caller reads again instead of dropping the addition. + */ + basis?: ScheduledMCPEnrollment | null; }) => Promise; revokeScheduleMCPConsent: (identity: ScheduledMCPIdentity, revision: string) => Promise; admitScheduleMCPConsent: (input: { @@ -29,7 +38,64 @@ export interface ScheduleMCPConsentStorage { revision: string; consentId: string; requireEnabled?: boolean; + /** + * The live definition digest of each tool about to be used. Admission is refused when one + * of them is marked as changed or pinned to another digest at the moment of the write. + */ + definitions?: Readonly>; }) => Promise; + /** + * Records the definition an allowed tool had on first use. False when the tool already has + * a pin or the grant is no longer the live one; the caller reads again to tell which. + */ + pinScheduleMCPToolDefinition: (input: { + identity: ScheduledMCPIdentity; + revision: string; + consentId: string; + tool: string; + digest: string; + }) => Promise; + /** Marks a pinned tool as changed. The mark stays until the owner confirms again. */ + flagScheduleMCPToolChange: (input: { + identity: ScheduledMCPIdentity; + revision: string; + consentId: string; + tool: string; + }) => Promise; +} + +/** A revocation that keeps losing to pin writes gives up; pins per grant are bounded. */ +const REVOKE_ATTEMPTS = 4; + +/** + * Matches while no pin or mark has been added to `basis`. Both lists only ever grow within a + * grant revision, so an element at the old length is the whole difference. + */ +function untouchedSince(basis: ScheduledMCPEnrollment | null | undefined) { + if (!basis?.consents.length) return {}; + return { + $and: basis.consents.map((consent) => ({ + 'mcpConsent.consents': { + $elemMatch: { + id: consent.id, + [`definitions.${consent.definitions?.length ?? 0}`]: { $exists: false }, + [`changedTools.${consent.changedTools?.length ?? 0}`]: { $exists: false }, + }, + }, + })), + }; +} + +/** Matches a consent in which none of the tools is marked or pinned to a different digest. */ +function unchangedDefinitions(definitions: Readonly> | undefined) { + const live = Object.entries(definitions ?? {}); + if (live.length === 0) return {}; + return { + changedTools: { $nin: live.map(([tool]) => tool) }, + $nor: live.map(([tool, digest]) => ({ + definitions: { $elemMatch: { tool, digest: { $ne: digest } } }, + })), + }; } export function createScheduleMCPConsentStorage( @@ -95,6 +161,7 @@ export function createScheduleMCPConsentStorage( ...scope(input.identity), ...configFilter(input.expectedConfigRevision), ...revisionFilter(input.expectedRevision), + ...untouchedSince(input.basis), agent_id: input.identity.agentId, }, { $set: { mcpConsent: enrollment } }, @@ -103,30 +170,35 @@ export function createScheduleMCPConsentStorage( return result.matchedCount === 1; }, async revokeScheduleMCPConsent(identity, revision) { - const snapshot = await model() - .findOne({ ...scope(identity), ...revisionFilter(revision) }) - .select('mcpConsent') - .read('primary') - .lean(); - const parsed = scheduledMCPEnrollmentSchema.safeParse(snapshot?.mcpConsent); - if (!parsed.success) return false; - const revokedRevision = randomUUID(); - const revokedAtMs = now(); - const enrollment = { - ...parsed.data, - revision: revokedRevision, - consents: parsed.data.consents.map((consent) => ({ - ...consent, + // The grant is rewritten whole. A pin or mark a run adds between the read and the write + // would be dropped, and the next grant would carry one pin fewer, so read again instead. + for (let attempt = 0; attempt < REVOKE_ATTEMPTS; attempt++) { + const snapshot = await model() + .findOne({ ...scope(identity), ...revisionFilter(revision) }) + .select('mcpConsent') + .read('primary') + .lean(); + const parsed = scheduledMCPEnrollmentSchema.safeParse(snapshot?.mcpConsent); + if (!parsed.success) return false; + const revokedRevision = randomUUID(); + const revokedAtMs = now(); + const enrollment = { + ...parsed.data, revision: revokedRevision, - revokedAtMs: consent.revokedAtMs ?? revokedAtMs, - })), - }; - const result = await model().updateOne( - { ...scope(identity), ...revisionFilter(revision) }, - { $set: { mcpConsent: enrollment } }, - { runValidators: true }, - ); - return result.matchedCount === 1; + consents: parsed.data.consents.map((consent) => ({ + ...consent, + revision: revokedRevision, + revokedAtMs: consent.revokedAtMs ?? revokedAtMs, + })), + }; + const result = await model().updateOne( + { ...scope(identity), ...revisionFilter(revision), ...untouchedSince(parsed.data) }, + { $set: { mcpConsent: enrollment } }, + { runValidators: true }, + ); + if (result.matchedCount === 1) return true; + } + return false; }, async admitScheduleMCPConsent(input) { const result = await model().updateOne( @@ -137,7 +209,12 @@ export function createScheduleMCPConsentStorage( agent_id: input.identity.agentId, ...(input.requireEnabled !== false && { enabled: true }), 'mcpConsent.consents': { - $elemMatch: { id: input.consentId, revision: input.revision, revokedAtMs: null }, + $elemMatch: { + id: input.consentId, + revision: input.revision, + revokedAtMs: null, + ...unchangedDefinitions(input.definitions), + }, }, 'mcpConsent.consents.0': { $exists: true }, $nor: [ @@ -155,5 +232,42 @@ export function createScheduleMCPConsentStorage( ); return result.matchedCount === 1; }, + async pinScheduleMCPToolDefinition(input) { + const pin = scheduledMCPToolPinSchema.parse({ tool: input.tool, digest: input.digest }); + const result = await model().updateOne( + { + ...scope(input.identity), + ...revisionFilter(input.revision), + agent_id: input.identity.agentId, + 'mcpConsent.consents': { + $elemMatch: { + id: input.consentId, + revision: input.revision, + revokedAtMs: null, + // No entry for this tool yet, and room for one more. + 'definitions.tool': { $ne: pin.tool }, + [`definitions.${MAX_SCHEDULED_MCP_SERVER_TOOLS - 1}`]: { $exists: false }, + }, + }, + }, + { $push: { 'mcpConsent.consents.$.definitions': pin } }, + { timestamps: false }, + ); + return result.matchedCount === 1; + }, + async flagScheduleMCPToolChange(input) { + const result = await model().updateOne( + { + ...scope(input.identity), + ...revisionFilter(input.revision), + 'mcpConsent.consents': { + $elemMatch: { id: input.consentId, 'definitions.tool': input.tool }, + }, + }, + { $addToSet: { 'mcpConsent.consents.$.changedTools': input.tool } }, + { timestamps: false }, + ); + return result.matchedCount === 1; + }, }; }