From bc0ddc6b14ef1af968f59cc9b2e481ec26044bc7 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Thu, 19 Nov 2026 17:16:20 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=84=EF=B8=8F=20feat:=20Let=20a=20Sched?= =?UTF-8?q?ule's=20Owner=20Allow=20Every=20Tool=20on=20a=20Declared=20MCP?= =?UTF-8?q?=20Server=20(#18554)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ๐Ÿ—„๏ธ feat: Let a Schedule's Owner Allow Every Tool on a Declared MCP Server An agent may select a declared server as a whole instead of naming its tools. An owner authorizing tool by tool had nothing to tick for that, so those tools were left out unless they allowed the whole agent. The selection is now one item for the server, and it stands for every tool there, including ones added later. * ๐Ÿ“Œ fix: Keep Pins, Approvals and Change Warnings Working Under a Whole-Server Grant Renewing a grant of the whole server dropped the pins of the tools used under it, since none is named in it. An agent granted the whole server was not paused for a tool the owner approves each time. And the dialog showed no warning, and left the item ticked, when a tool used under it had changed. * ๐Ÿ™‹ fix: Keep a Stored Approval for a Tool the Whole-Server Item Still Covers A question about a named tool was dropped on renewal once no agent named the tool, even where an agent still reached it through a grant of the whole server. The tool then ran unattended. It is kept while anything on the server still covers it, by the service and in what the dialog sends. * ๐Ÿงพ fix: Keep Every Whole-Server Warning, Question and Stored Choice in View A changed tool on a server now unticks the whole-server item as well as the tool's own box, so the owner looks at every change the item covers. A question the grant holds about a tool with no ticked box of its own gets a row under the whole-server item, where the owner can keep it or stop it. Tools a stored whole-server grant already allows start ticked once the agents name them. --- client/src/components/MCP/GrantTools.tsx | 137 ++++++++--- .../Schedules/__tests__/Consent.spec.tsx | 223 ++++++++++++++++++ client/src/locales/en/translation.json | 2 + packages/api/src/schedules/README.md | 11 + .../schedules/authorization/execution.spec.ts | 49 ++++ .../src/schedules/authorization/execution.ts | 34 ++- .../schedules/authorization/runtime.spec.ts | 41 ++++ .../schedules/authorization/service.spec.ts | 171 +++++++++++++- .../src/schedules/authorization/service.ts | 63 ++--- packages/api/src/schedules/bearer.spec.ts | 31 ++- packages/api/src/schedules/bearer.ts | 13 +- 11 files changed, 694 insertions(+), 81 deletions(-) diff --git a/client/src/components/MCP/GrantTools.tsx b/client/src/components/MCP/GrantTools.tsx index b19ccf8699..62138c88c0 100644 --- a/client/src/components/MCP/GrantTools.tsx +++ b/client/src/components/MCP/GrantTools.tsx @@ -52,9 +52,24 @@ function offeredTools(target: ScheduledMCPTarget): string[] { return [...new Set(target.permittedTools.flatMap((selection) => selection.tools))].sort(); } +/** + * Whether a ticked item survives the marks. A named tool answers for its own. The whole server + * covers every tool on it, named elsewhere or not, so it answers for all of them: left ticked + * over a change it would allow the new definition with nobody having looked at it. + */ +function unmarked(tool: string, marked: readonly string[], seen: readonly string[] = []): boolean { + const every: string = Constants.mcp_all; + if (tool !== every) return !marked.includes(tool) || seen.includes(tool); + return marked.every((name) => seen.includes(name)); +} + /** * 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. + * + * A grant of the whole server allows every tool there. When the agents come to name tools the + * grant never named, those start ticked too: they are authorized now, and confirming as shown + * must not take them away. */ function initialChoice(data: ScheduleMCPConsentView): Record { return Object.fromEntries( @@ -64,7 +79,11 @@ function initialChoice(data: ScheduleMCPConsentView): Record { const changed = data.changed[target.resource.serverName] ?? []; return [ target.resource.serverName, - offered.filter((tool) => allowed.includes(tool) && !changed.includes(tool)), + offered.filter( + (tool) => + (allowed.includes(tool) || allowed.includes(Constants.mcp_all)) && + unmarked(tool, changed), + ), ]; }), ); @@ -102,7 +121,7 @@ function currentChoice( return [ serverName, (edited.choice[serverName] ?? initial[serverName]).filter( - (tool) => offered.includes(tool) && (!marked.includes(tool) || seen.includes(tool)), + (tool) => offered.includes(tool) && unmarked(tool, marked, seen), ), ]; }), @@ -227,13 +246,18 @@ export function useGrantChoice(data: ScheduleMCPConsentView | undefined): GrantC revision: data?.revision ?? null, tools: { ...asking, [serverName]: tools }, }); - /** Sent with the confirmation: of the tools ticked now, the ones the owner asks about. */ + /** + * Sent with the confirmation: of the tools allowed now, the ones the owner asks about. A + * tool is allowed when it is ticked, or when the whole of its server is: a question about a + * tool the whole-server item still covers is not dropped because its own box went away. + */ const ask = Object.fromEntries( Object.entries(asking) - .map(([serverName, tools]): [string, string[]] => [ - serverName, - tools.filter((tool) => (choice[serverName] ?? []).includes(tool)), - ]) + .map(([serverName, tools]): [string, string[]] => { + const ticked = choice[serverName] ?? []; + const every = ticked.includes(Constants.mcp_all); + return [serverName, tools.filter((tool) => every || ticked.includes(tool))]; + }) .filter(([, tools]) => tools.length > 0), ); return { @@ -426,7 +450,15 @@ export default function GrantTools({ {!data.everything && (

{localize('com_ui_schedule_consent_allowed', { - tools: (data.allowed[target.resource.serverName] ?? []).join(', '), + tools: (data.allowed[target.resource.serverName] ?? []) + .map((tool) => + tool === Constants.mcp_all + ? localize('com_ui_schedule_consent_server_every', { + server: target.resource.serverName, + }) + : tool, + ) + .join(', '), })}

)} @@ -527,24 +559,47 @@ function ToolChoice({ }) { const localize = useLocalize(); const groupId = useId(); + /** + * A selection of the whole server is one item of its own, listed first: every tool there, + * including ones the server gains later. It is not what ticking each named tool means, so + * the shared box below leaves it as the owner set it. + */ + const every: string = Constants.mcp_all; + const named = offered.filter((tool) => tool !== every); + const items = [...offered.filter((tool) => tool === every), ...named]; + const kept = chosen.filter((tool) => tool === every); + /** The whole-server item covers every changed tool there: they are named beside it. */ + const warns = (tool: string): boolean => + tool === every ? changed.length > 0 : changed.includes(tool); + /** + * Questions the grant holds about tools whose own ask box is not showing: a tool with no row + * (reached only through the whole server), or one whose row is unticked. While the whole + * server is ticked they are still allowed and still asked about, so each gets a row under + * that item, where the owner can keep asking or stop. + */ + const retained = chosen.includes(every) + ? asking.filter((tool) => tool !== every && !(named.includes(tool) && chosen.includes(tool))) + : []; /** 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)); + const all = named.length > 0 && named.every((tool) => chosen.includes(tool)); return (
-
- onChange(checked === true ? offered : [])} - /> - -
+ {named.length > 0 && ( +
+ onChange(checked === true ? [...kept, ...named] : kept)} + /> + +
+ )}
    - {offered.map((tool) => ( + {items.map((tool) => (
  • onChange( checked === true @@ -566,9 +621,11 @@ function ToolChoice({ htmlFor={`${groupId}-${tool}`} className="text-xs break-all" > - {tool} + {tool === every + ? localize('com_ui_schedule_consent_server_every', { server: serverName }) + : tool} - {askable.includes(tool) && chosen.includes(tool) && ( + {tool !== every && askable.includes(tool) && chosen.includes(tool) && ( )}
    - {changed.includes(tool) && ( + {warns(tool) && (

    - {localize('com_ui_schedule_consent_tool_changed')} + {tool === every + ? localize('com_ui_schedule_consent_server_changed', { + tools: changed.join(', '), + }) + : localize('com_ui_schedule_consent_tool_changed')}

    )} + {tool === every && retained.length > 0 && ( +
      + {retained.map((asked) => ( +
    • + { + if (checked !== true) + onAskingChange(asking.filter((name) => name !== asked)); + }} + /> + +
    • + ))} +
    + )}
  • ))}
diff --git a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx index 1ee78dedb3..49cd5079a8 100644 --- a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx +++ b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx @@ -513,6 +513,229 @@ it('reads the tool and the server out of a key against the servers in use, not b expect(splitToolKey('send_action_mail.example', ['notes'])).toBeUndefined(); }); +it('offers a selection of a whole server as its own item, apart from ticking each tool', async () => { + const whole: ScheduleMCPConsentView = { + ...view, + approval: true, + targets: [ + { + ...view.targets[0], + permittedTools: [{ agentId: 'root', tools: ['query', 'sys__all__sys'] }], + }, + ], + }; + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(whole); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(whole); + display(); + const every = await screen.findByRole('checkbox', { + name: 'com_ui_schedule_consent_server_every', + }); + expect(every).not.toBeChecked(); + expect(screen.queryByRole('checkbox', { name: 'sys__all__sys' })).not.toBeInTheDocument(); + // Ticking every named tool is not allowing whatever the server gains later. + await userEvent.click( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_allow_server' }), + ); + expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked(); + expect(every).not.toBeChecked(); + await userEvent.click(every); + // It names no tool, so there is nothing to be asked about for it. + expect( + screen.getAllByRole('checkbox', { name: 'com_ui_schedule_consent_ask_tool' }), + ).toHaveLength(1); + // Unticking the named tools leaves it as the owner set it. + await userEvent.click( + screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_allow_server' }), + ); + expect(every).toBeChecked(); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ allow: { warehouse: ['sys__all__sys'] } }), + ), + ); +}); + +it('unticks the whole-server item and names the tools that changed under it', async () => { + const stored: ScheduleMCPConsentView = { + ...view, + state: 'changed', + revision: 'grant', + targets: [ + { + ...view.targets[0], + permittedTools: [{ agentId: 'root', tools: ['query', 'sys__all__sys'] }], + }, + ], + // `export` was used under the whole server and has changed. It is not listed by name. + allowed: { warehouse: ['query', 'sys__all__sys'] }, + changed: { warehouse: ['export'] }, + }; + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(stored); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(stored); + display(); + const every = await screen.findByRole('checkbox', { + name: 'com_ui_schedule_consent_server_every', + }); + // Allowing the new definition is a decision, made with the warning in view. + expect(every).not.toBeChecked(); + expect(every).toHaveAccessibleDescription('com_ui_schedule_consent_server_changed'); + expect(screen.getByRole('checkbox', { name: 'query' })).toBeChecked(); + await userEvent.click(every); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ allow: { warehouse: ['query', 'sys__all__sys'] } }), + ), + ); +}); + +it('keeps sending a question about a tool the whole-server item still covers', async () => { + // The grant asks about `query`. No agent names `query` any more: only the whole server. + const stored: ScheduleMCPConsentView = { + ...view, + approval: true, + state: 'active', + revision: 'grant', + targets: [ + { ...view.targets[0], permittedTools: [{ agentId: 'root', tools: ['sys__all__sys'] }] }, + ], + allowed: { warehouse: ['sys__all__sys'] }, + asking: { warehouse: ['query'] }, + }; + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(stored); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(stored); + display(); + expect( + await screen.findByRole('checkbox', { name: 'com_ui_schedule_consent_server_every' }), + ).toBeChecked(); + await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' })); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ + allow: { warehouse: ['sys__all__sys'] }, + ask: { warehouse: ['query'] }, + }), + ), + ); +}); + +describe('the whole-server item beside named tools', () => { + const every = () => + screen.findByRole('checkbox', { name: 'com_ui_schedule_consent_server_every' }); + const confirm = () => screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }); + const stored = ( + over: Partial, + tools: string[], + ): ScheduleMCPConsentView => ({ + ...view, + approval: true, + state: 'active', + revision: 'grant', + targets: [{ ...view.targets[0], permittedTools: [{ agentId: 'root', tools }] }], + ...over, + }); + + it('is unticked by a change to a tool that also has a box of its own', async () => { + // The root holds the whole server, the child names `query`, and `query` has changed. + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue( + stored( + { + state: 'changed', + allowed: { warehouse: ['query', 'sys__all__sys'] }, + changed: { warehouse: ['query'] }, + }, + ['query', 'sys__all__sys'], + ), + ); + display(); + // Left ticked, the whole server would allow the new definition for the root unseen. + expect(await every()).not.toBeChecked(); + expect(await every()).toHaveAccessibleDescription('com_ui_schedule_consent_server_changed'); + expect(screen.getByRole('checkbox', { name: 'query' })).not.toBeChecked(); + expect(confirm()).toBeDisabled(); + }); + + it('lets the owner stop a question about a tool that has no box of its own', async () => { + const data = stored( + { allowed: { warehouse: ['sys__all__sys'] }, asking: { warehouse: ['query'] } }, + ['sys__all__sys'], + ); + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(data); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(data); + display(); + expect(await every()).toBeChecked(); + // No agent names `query`, so it has no row. Its question does. + expect(screen.queryByRole('checkbox', { name: 'query' })).not.toBeInTheDocument(); + const asked = screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_ask_tool' }); + expect(asked).toBeChecked(); + await userEvent.click(asked); + expect( + screen.queryByRole('checkbox', { name: 'com_ui_schedule_consent_ask_tool' }), + ).not.toBeInTheDocument(); + await userEvent.click(confirm()); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ allow: { warehouse: ['sys__all__sys'] }, ask: {} }), + ), + ); + }); + + it('keeps a question in view when its tool is unticked and the whole server still covers it', async () => { + const data = stored( + { + allowed: { warehouse: ['query', 'sys__all__sys'] }, + asking: { warehouse: ['query'] }, + }, + ['query', 'sys__all__sys'], + ); + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(data); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(data); + display(); + expect(await every()).toBeChecked(); + // Ticked, `query` shows its own ask box. Unticked, the root still reaches it through the + // whole server and is still asked: the question moves under that item, it is not hidden. + const asks = () => + screen.getAllByRole('checkbox', { name: 'com_ui_schedule_consent_ask_tool' }); + expect(asks()).toHaveLength(1); + await userEvent.click(screen.getByRole('checkbox', { name: 'query' })); + expect(asks()).toHaveLength(1); + expect(asks()[0]).toBeChecked(); + await userEvent.click(confirm()); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ + allow: { warehouse: ['sys__all__sys'] }, + ask: { warehouse: ['query'] }, + }), + ), + ); + }); + + it('starts the tools a whole-server grant already allows as ticked, once the agents name them', async () => { + // Granted as a whole. The agent now names its tools, and no longer selects the whole. + const data = stored({ allowed: { warehouse: ['sys__all__sys'] } }, ['export', 'query']); + jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(data); + jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(data); + display(); + expect(await screen.findByRole('checkbox', { name: 'query' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'export' })).toBeChecked(); + // Confirming as shown keeps what is authorized now. + await userEvent.click(confirm()); + await waitFor(() => + expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith( + 'schedule', + expect.objectContaining({ allow: { warehouse: ['export', 'query'] } }), + ), + ); + }); +}); + it('authorizes a schedule whose agent uses no MCP server, once one of its tools is ticked', async () => { jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({ ...view, diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index e3c8691575..22abc7abb4 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -3942,6 +3942,7 @@ "com_ui_schedule_consent_audience": "Audience: {{audience}}", "com_ui_schedule_consent_scopes": "Scopes: {{scopes}}", "com_ui_schedule_consent_allow_server": "Allow all tools on {{server}}", + "com_ui_schedule_consent_server_every": "Every tool on {{server}}, including ones added later", "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", @@ -3965,6 +3966,7 @@ "com_ui_schedule_consent_asking": "Asks you before each use: {{tools}}", "com_ui_schedule_consent_ask_unavailable": "Scheduled runs cannot pause for your approval here right now. A tool set to ask me first is refused until they can. Clear its box to let it run without asking.", "com_ui_schedule_consent_tool_changed": "Changed since you allowed it. Check it to allow the new version.", + "com_ui_schedule_consent_server_changed": "Changed since you allowed them: {{tools}}. Check it to allow the new versions.", "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", diff --git a/packages/api/src/schedules/README.md b/packages/api/src/schedules/README.md index 942e6ad9cf..b9c815a043 100644 --- a/packages/api/src/schedules/README.md +++ b/packages/api/src/schedules/README.md @@ -144,6 +144,17 @@ does is done with tools that are items of their own (code execution for a skill' tool is registered, and manual or always-apply skills are not primed, so the model is not offered what it would be refused. +### Every tool on a declared server + +An agent may select a declared server as a whole instead of naming its tools. That +selection is offered as one item for the server (`sys__all__sys`) beside any tools the agents +do name. Ticked, it stands for every tool on that server for that agent, including ones the +server gains later: its key loads, any tool there is authorized, and a connection is admitted +for whatever the agents select. Each tool used under it is still pinned on first use and +refused once its definition changes. It names no tool, so it cannot be asked about call by +call. A grant that names tools keeps meaning those tools when the agent later selects the +whole server. + ### Tools on a server the operator did not declare A server with nothing under `mcpConsent.resources` has no recipient to hold a consent for: a diff --git a/packages/api/src/schedules/authorization/execution.spec.ts b/packages/api/src/schedules/authorization/execution.spec.ts index d544414158..58139c4508 100644 --- a/packages/api/src/schedules/authorization/execution.spec.ts +++ b/packages/api/src/schedules/authorization/execution.spec.ts @@ -736,6 +736,55 @@ describe('the tools a run loads under a grant', () => { expect(limited.execution.grants('root', 'notes', 'lookup')).toBe(false); }); + it('loads every key on a declared server once the owner allowed the whole server', async () => { + const keys = [ + 'query_mcp_warehouse', + 'export_mcp_warehouse', + 'sys__all__sys_mcp_warehouse', + 'sys__server__sys_mcp_warehouse', + 'purge_mcp_archive', + ]; + const whole = await executionFixture('invoke', readTool, undefined, { + offered: ['sys__all__sys'], + allow: ['sys__all__sys'], + }); + // A grant that lists its tools, with one item ticked: every tool on that server. + expect(whole.snapshot.enrollment).not.toHaveProperty('everything'); + expect(whole.execution.narrow('root', keys)).toEqual(keys.slice(0, 4)); + expect(whole.execution.grants('root', 'warehouse', 'anything')).toBe(true); + expect(whole.execution.grants('stranger', 'warehouse', 'anything')).toBe(false); + // With only a tool named, the key for the whole server is still not loaded. + const named = await executionFixture('invoke', readTool, undefined, { + offered: ['sys__all__sys'], + }); + expect(named.execution.narrow('root', keys)).toEqual([ + 'query_mcp_warehouse', + 'sys__server__sys_mcp_warehouse', + ]); + expect(named.execution.grants('root', 'warehouse', 'export')).toBe(false); + }); + + it('pauses an agent granted the whole server for a tool the owner approves each time', async () => { + const fixture = await executionFixture('invoke', readTool, undefined, { + offered: ['sys__all__sys'], + allow: ['query', 'sys__all__sys'], + ask: ['query'], + }); + // The root has the whole server and names no tool. The child names the tool asked about. + for (const consent of fixture.snapshot.enrollment!.consents) + consent.permittedTools = [ + { agentId: 'child', tools: ['query'] }, + { agentId: 'root', tools: ['sys__all__sys'] }, + ]; + const execution = (await fixture.factory.resolve(fixture.identity, 'invoke'))!; + expect(execution.asksAbout('child', 'query_mcp_warehouse')).toBe(true); + // The root can call it through the whole server, so it is asked about for the root too. + expect(execution.asksAbout('root', 'query_mcp_warehouse')).toBe(true); + expect(execution.asksAbout('root', 'export_mcp_warehouse')).toBe(false); + // An agent the grant holds nothing for is not asked: it cannot call it at all. + expect(execution.asksAbout('stranger', 'query_mcp_warehouse')).toBe(false); + }); + it('loads none of the other tools when the owner allowed none', async () => { const fixture = await executionFixture('invoke', readTool, undefined, { tools: ['execute_code', 'web_search'], diff --git a/packages/api/src/schedules/authorization/execution.ts b/packages/api/src/schedules/authorization/execution.ts index b1afc16c3e..9180336ac7 100644 --- a/packages/api/src/schedules/authorization/execution.ts +++ b/packages/api/src/schedules/authorization/execution.ts @@ -265,17 +265,18 @@ export function createScheduleMCPExecution< const serverSpellings = [...grantedServers, ...serverAliases.keys()]; /** * Whether a run under the grant loads this MCP key for the agent. A key for one tool needs - * that tool listed. A key for every tool on a server names none of them, and the grant - * lists tools by name, so it is never loaded. A key for the server alone is kept only - * where the grant lists a tool on that server for the agent. + * that tool granted, by name or through a grant of the whole server. A key for every tool + * on a server needs the whole server granted. A key for the server alone is kept where + * the grant holds anything on that server for the agent. */ const isGrantedKey = (agentId: string, toolKey: string): boolean => { const [selectionName, spelling] = splitMCPToolKey(toolKey, serverSpellings); const serverName = spelling != null && granted.has(spelling) ? spelling : serverAliases.get(spelling ?? ''); const tools = serverName == null ? undefined : granted.get(serverName)?.get(agentId); - if (!tools || selectionName === Constants.mcp_all) return false; - return selectionName === Constants.mcp_server ? tools.size > 0 : tools.has(selectionName); + if (!tools) return false; + if (selectionName === Constants.mcp_server) return tools.size > 0; + return tools.has(selectionName) || tools.has(Constants.mcp_all); }; const approved = new Set(options.approvedToolCalls ?? []); /** Every spelling a run may call an ask tool by, per agent. A miss is refused, not run. */ @@ -297,10 +298,12 @@ export function createScheduleMCPExecution< spellings(tool).forEach((key) => askingAny.add(key)); for (const { agentId, tools } of consent.permittedTools) { const keys = asking.get(agentId) ?? new Set(); - for (const tool of tools) { - if (!consent.askTools?.includes(tool)) continue; - for (const key of spellings(tool)) keys.add(key); - } + // An agent granted the whole server has every tool there, so every tool the consent + // asks about is asked about for it too, named for it or not. + const asked = tools.includes(Constants.mcp_all) + ? (consent.askTools ?? []) + : tools.filter((tool) => consent.askTools?.includes(tool)); + for (const tool of asked) for (const key of spellings(tool)) keys.add(key); if (keys.size > 0) asking.set(agentId, keys); } } @@ -376,10 +379,15 @@ export function createScheduleMCPExecution< if (!observed.settled) throw new ScheduledMCPPolicyError('dependency_unavailable', ''); return observed.value; }, - grants: (agentId: string, serverName: string, selectionName: string) => - whole || - granted.get(serverName)?.get(agentId)?.has(selectionName) === true || - lists(agentId, serverName, selectionName), + grants: (agentId: string, serverName: string, selectionName: string) => { + const tools = granted.get(serverName)?.get(agentId); + return ( + whole || + tools?.has(selectionName) === true || + tools?.has(Constants.mcp_all) === true || + lists(agentId, serverName, selectionName) + ); + }, narrow: (agentId: string, toolKeys: readonly string[]) => enrolled ? toolKeys.filter((key) => loads(agentId, key)) : [...toolKeys], grantsTool: allows, diff --git a/packages/api/src/schedules/authorization/runtime.spec.ts b/packages/api/src/schedules/authorization/runtime.spec.ts index 97ec1f9b3a..2b3ee36d3c 100644 --- a/packages/api/src/schedules/authorization/runtime.spec.ts +++ b/packages/api/src/schedules/authorization/runtime.spec.ts @@ -1061,6 +1061,47 @@ describe('a grant that lists a tool on a server the operator did not declare', ( }); }); +describe('a grant that lists the whole of a declared server', () => { + it('offers the selection as one item, makes the server ready, loads it and calls its tools', async () => { + const f = await setup(); + f.snapshot.enrollment = null; + f.setCandidates(['sys__all__sys_mcp_warehouse', 'web_search']); + const offer = await f.host.consent.service.view(f.identity); + expect(offer.targets).toMatchObject([ + { + resource: { serverName: 'warehouse' }, + permittedTools: expect.arrayContaining([{ agentId: 'root', tools: ['sys__all__sys'] }]), + }, + ]); + await f.host.consent.service.confirm(f.identity, { + offerDigest: offer.offer!.digest, + expectedRevision: offer.revision, + lifetimeHours: 1, + allow: { warehouse: ['sys__all__sys'] }, + }); + f.row.mcpConsent = f.snapshot.enrollment!; + expect(f.row.mcpConsent).not.toHaveProperty('everything'); + f.connect.mockClear(); + await expect(f.check()).resolves.toEqual([{ server: 'warehouse', status: 'ready' }]); + expect(f.connect).toHaveBeenCalledWith(expect.objectContaining({ serverName: 'warehouse' })); + await f.host.prepare({ req: f.req, context: f.context }); + const keys = ['sys__all__sys_mcp_warehouse', 'web_search']; + // The server's tools load. The other tool was not ticked. + expect(getScheduleMCPExecution(f.context)!.narrow('root', keys)).toEqual([ + 'sys__all__sys_mcp_warehouse', + ]); + await expect( + bindScheduledMCPInvocation(f.context, 'root', 'query')!.authorize({ + user: f.user, + serverName: 'warehouse', + serverConfig: f.serverConfig, + toolName: 'query', + loadTools: async () => ({ tools: [readTool], complete: true }), + }), + ).resolves.toBeUndefined(); + }); +}); + describe('a schedule being created with its grant', () => { /** Nothing is stored for it yet: the grant comes with the readiness check. */ async function creating( diff --git a/packages/api/src/schedules/authorization/service.spec.ts b/packages/api/src/schedules/authorization/service.spec.ts index 20d115502d..86d7f72341 100644 --- a/packages/api/src/schedules/authorization/service.spec.ts +++ b/packages/api/src/schedules/authorization/service.spec.ts @@ -906,11 +906,11 @@ describe('a grant of the whole agent', () => { expect(await s.service.authority.authorize(call('anything'), {})).toMatchObject({ state: 'authorized', }); - // Nothing to tick is offered for it, and the grant is not stale. + // The grant is not stale, and the selection is on offer as one item for the server. expect(await s.service.view(identity)).toMatchObject({ state: 'active', everything: true, - targets: [], + targets: [{ permittedTools: [{ agentId: 'root', tools: ['sys__all__sys'] }] }], }); expect(await s.service.authority.lookupConsent(identity, target.resource, {})).toMatchObject({ state: 'found', @@ -926,23 +926,23 @@ describe('a grant of the whole agent', () => { }; const s = setup(); s.changeTarget(every); - // Nothing to tick is listed for it, and it is still part of the whole agent. - expect((await s.service.view(identity)).targets).toEqual([]); - expect(await whole(s)).toMatchObject({ state: 'active', everything: true, targets: [] }); + const offered = [{ permittedTools: [{ agentId: 'root', tools: ['sys__all__sys'] }] }]; + expect((await s.service.view(identity)).targets).toMatchObject(offered); + expect(await whole(s)).toMatchObject({ state: 'active', everything: true }); expect(s.snapshot.enrollment!.consents).toMatchObject([ { resource: { serverName: 'warehouse', audience: 'warehouse' } }, ]); expect(await s.service.authority.authorize(call('anything'), {})).toMatchObject({ state: 'authorized', }); - // It is not listed, and the view still notices when its recipient moves. + // The view notices when its recipient moves. s.changeTarget({ ...every, resource: { ...every.resource, audience: 'elsewhere' } }); expect((await s.service.view(identity)).state).toBe('changed'); s.changeTarget(every); expect((await s.service.view(identity)).state).toBe('active'); // The same for a schedule that is being created. const offer = await s.service.draft(identity); - expect(offer.targets).toEqual([]); + expect(offer.targets).toMatchObject(offered); const grant = await s.service.grant(identity, { offerDigest: offer.offer!.digest, lifetimeHours: 1, @@ -1046,7 +1046,164 @@ describe('a grant of the whole agent', () => { }), ).rejects.toMatchObject({ code: 'consent_invalid' }); }); +}); +describe('a selection of every tool on a declared server, in a grant that lists its tools', () => { + const marker = 'sys__all__sys'; + const every: ScheduledMCPTarget = { + ...target, + permittedTools: [{ agentId: 'root', tools: [marker] }], + policyRevision: 'p3', + }; + const call = (tool: string, agentId = 'root', digest = 'a'.repeat(64)) => ({ + ...request('invoke'), + selection: { agentId, tools: [tool] }, + definitions: { [tool]: digest }, + }); + const refused = (reason: string) => ({ state: 'denied', failure: { reason } }); + + it('is one item the owner may tick, and then stands for every tool there', async () => { + const s = setup(); + s.changeTarget(every); + expect((await s.service.view(identity)).targets[0].permittedTools).toEqual([ + { agentId: 'root', tools: [marker] }, + ]); + await s.enroll({ warehouse: [marker] }); + expect(s.snapshot.enrollment).not.toHaveProperty('everything'); + expect(await s.service.authority.authorize(call('query'), {})).toMatchObject({ + state: 'authorized', + }); + expect(await s.service.authority.authorize(call('anything'), {})).toMatchObject({ + state: 'authorized', + }); + // For the agent it was ticked for, and no other. + expect(await s.service.authority.authorize(call('query', 'child'), {})).toMatchObject( + refused('tool_policy_denied'), + ); + // A tool used under it is pinned like any other, and refused once it changes. + expect(s.snapshot.enrollment!.consents[0].definitions).toEqual( + expect.arrayContaining([expect.objectContaining({ tool: 'query' })]), + ); + expect( + await s.service.authority.authorize(call('query', 'root', 'b'.repeat(64)), {}), + ).toMatchObject(refused('binding_mismatch')); + }); + + it('still fits when the agents go back to naming their tools, and the reverse', async () => { + const s = setup(); + s.changeTarget(every); + await s.enroll({ warehouse: [marker] }); + // The owner allowed everything there: whatever the agent selects now is within it. + s.changeTarget(target); + expect((await s.service.view(identity)).state).toBe('active'); + expect(await s.service.authority.authorize(call('query'), {})).toMatchObject({ + state: 'authorized', + }); + // A grant of one named tool, once the agent selects the whole server: that tool, no more. + const named = setup(); + await named.enroll({ warehouse: ['query'] }); + named.changeTarget({ + ...every, + permittedTools: [ + { agentId: 'root', tools: [marker] }, + { agentId: 'child', tools: [marker] }, + ], + }); + expect((await named.service.view(identity)).state).toBe('active'); + expect(await named.service.authority.authorize(call('query'), {})).toMatchObject({ + state: 'authorized', + }); + expect(await named.service.authority.authorize(call('export'), {})).toMatchObject( + refused('tool_policy_denied'), + ); + }); + + it('keeps the pins of the tools used under it through a renewal, until their change is acknowledged', async () => { + const s = setup(); + s.changeTarget(every); + await s.enroll({ warehouse: [marker] }); + await s.service.authority.authorize(call('query'), {}); + const pinned = () => s.snapshot.enrollment!.consents[0]; + expect(pinned().definitions).toEqual([{ tool: 'query', digest: 'a'.repeat(64) }]); + // Renewed as it is: the tool is not named in the grant, and its pin is still kept. + await s.enroll({ warehouse: [marker] }); + expect(pinned().definitions).toEqual([{ tool: 'query', digest: 'a'.repeat(64) }]); + const changed = call('query', 'root', 'b'.repeat(64)); + expect(await s.service.authority.authorize(changed, {})).toMatchObject( + refused('binding_mismatch'), + ); + expect((await s.service.view(identity)).changed).toEqual({ warehouse: ['query'] }); + // Confirming again with the change in view is allowing the new definition. + await s.enroll({ warehouse: [marker] }); + expect(pinned()).not.toHaveProperty('definitions'); + expect(await s.service.authority.authorize(changed, {})).toMatchObject({ + state: 'authorized', + }); + }); + + it('keeps a question about a tool it still covers after the agent that named the tool drops it', async () => { + const both: ScheduledMCPTarget = { + ...target, + permittedTools: [ + { agentId: 'child', tools: ['query'] }, + { agentId: 'root', tools: [marker] }, + ], + policyRevision: 'p4', + }; + const s = setup(); + s.changeTarget(both); + // The owner approves each use of `query`, which the root reaches through the whole server. + await s.enroll({ warehouse: ['query', marker] }, { warehouse: ['query'] }); + // The child stops naming it. The root still has it. + s.changeTarget(every); + const view = await s.service.view(identity); + await s.service.confirm(identity, { + offerDigest: view.offer!.digest, + expectedRevision: view.revision, + lifetimeHours: 1, + allow: { warehouse: [marker] }, + }); + expect(s.snapshot.enrollment!.consents[0].askTools).toEqual(['query']); + expect(await s.service.authority.authorize(call('query'), {})).toMatchObject({ + state: 'authorized', + approvalRequired: true, + }); + // Without the whole server, a question about a tool that is no longer allowed is dropped. + const named = setup(); + named.changeTarget(both); + await named.enroll({ warehouse: ['query'] }, { warehouse: ['query'] }); + named.changeTarget({ + ...target, + permittedTools: [{ agentId: 'child', tools: ['export'] }], + policyRevision: 'p5', + }); + const next = await named.service.view(identity); + await named.service.confirm(identity, { + offerDigest: next.offer!.digest, + expectedRevision: next.revision, + lifetimeHours: 1, + allow: { warehouse: ['export'] }, + }); + expect(named.snapshot.enrollment!.consents[0]).not.toHaveProperty('askTools'); + }); + + it('cannot be asked about: it names no tool to pause for', async () => { + const s = setup(); + s.changeTarget(every); + const view = await s.service.view(identity); + await expect( + s.service.confirm(identity, { + offerDigest: view.offer!.digest, + expectedRevision: view.revision, + lifetimeHours: 1, + allow: { warehouse: [marker] }, + ask: { warehouse: [marker] }, + }), + ).rejects.toMatchObject({ code: 'consent_invalid' }); + }); +}); + +describe('a grant of the whole agent, where it cannot be made', () => { it('is not offered, and is refused, where a grant limits MCP tools only', async () => { const s = setup(); const service = createScheduleMCPConsentService({ diff --git a/packages/api/src/schedules/authorization/service.ts b/packages/api/src/schedules/authorization/service.ts index cf80c41306..238caa4e3f 100644 --- a/packages/api/src/schedules/authorization/service.ts +++ b/packages/api/src/schedules/authorization/service.ts @@ -201,14 +201,19 @@ function selectAsking( whole = false, ): Record { const allowed = allowedTools(chosen); - const covers = (serverName: string, tool: string): boolean => - whole ? allowed[serverName] != null : allowed[serverName]?.includes(tool) === true; + // The whole server is not something to ask about: it names no tool to pause for. A tool it + // covers is: allowed there by name, or through a grant of the whole server to some agent. + const askable = (serverName: string, tool: string): boolean => { + const tools = allowed[serverName]; + if (tool === Constants.mcp_all || tools == null) return false; + return whole || tools.includes(tool) || tools.includes(Constants.mcp_all); + }; if (ask == null) return Object.fromEntries( Object.entries(stored) .map(([serverName, tools]): [string, string[]] => [ serverName, - tools.filter((tool) => covers(serverName, tool)), + tools.filter((tool) => askable(serverName, tool)), ]) .filter(([, tools]) => tools.length > 0), ); @@ -216,7 +221,7 @@ function selectAsking( Object.entries(ask) .filter(([, tools]) => tools.length > 0) .map(([serverName, tools]) => { - if (tools.some((tool) => !covers(serverName, tool))) + if (tools.some((tool) => !askable(serverName, tool))) throw new ScheduleMCPConsentError('consent_invalid'); return [serverName, [...new Set(tools)].sort()]; }), @@ -235,32 +240,25 @@ function coversGrant( sameResource(target.resource, grant.resource) && grant.permittedTools.every(({ agentId, tools }) => { const current = target.permittedTools.find((selection) => selection.agentId === agentId); - return current != null && tools.every((tool) => current.tools.includes(tool)); + // A grant of the whole server fits whatever the agent selects there now. + return ( + current != null && + tools.every((tool) => tool === Constants.mcp_all || covers(current, tool)) + ); }) ); }); } /** - * What can be ticked. A selection of every tool on a server names none of them, so it is not - * on offer tool by tool; the resolver still reports it, which tells a run under a whole-agent - * grant that the server is in use and who its recipient is. + * Whether a per-agent selection covers a tool: it names the tool, or it is of the whole + * server (`mcp_all`), which stands for every tool there, named or not, now or later. */ -function listable(targets: readonly ScheduledMCPTarget[]): ScheduledMCPTarget[] { - return targets.flatMap((target) => { - const marked = target.permittedTools.some(({ tools }) => tools.includes(Constants.mcp_all)); - if (!marked) return [target]; - const permittedTools = target.permittedTools - .map(({ agentId, tools }) => ({ - agentId, - tools: tools.filter((tool) => tool !== Constants.mcp_all), - })) - .filter((selection) => selection.tools.length > 0); - if (permittedTools.length === 0) return []; - return [ - { ...target, permittedTools, policyRevision: getScheduledMCPPolicyRevision(permittedTools) }, - ]; - }); +function covers(selection: ScheduledMCPToolSelection | undefined, tool: string): boolean { + return ( + selection != null && + (selection.tools.includes(tool) || selection.tools.includes(Constants.mcp_all)) + ); } /** @@ -339,8 +337,12 @@ function carriedPins( 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); + // A grant of the whole server keeps the pin of every tool used under it: the tool is not + // named, but it is still allowed, and its pin is what refuses it once it changes. A tool + // marked as changed loses its pin either way: confirming again is allowing the new one. + const every = allowed.has(Constants.mcp_all); const definitions = prior.definitions.filter( - (pin) => allowed.has(pin.tool) && !marked.has(pin.tool), + (pin) => (every || allowed.has(pin.tool)) && !marked.has(pin.tool), ); return definitions.length ? { definitions } : {}; } @@ -525,7 +527,7 @@ export function createScheduleMCPConsentService< deps.resolveTools?.(identity, options) ?? [], deps.resolveServers?.(identity, options) ?? [], ]); - resolved = listable(servers); + resolved = servers; } catch (error) { if (!(error instanceof ScheduleMCPConsentError) || !enrollment) throw error; return { @@ -695,7 +697,7 @@ export function createScheduleMCPConsentService< deps.resolveTools?.(identity, options) ?? [], deps.resolveServers?.(identity, options) ?? [], ]); - const resolved = listable(servers); + const resolved = servers; if (resolved.length === 0 && others.length === 0 && !standing) return none; const targets = canonicalTargets(resolved, { empty: true }); const subject = { @@ -1026,13 +1028,12 @@ export function createScheduleMCPConsentService< (s) => s.agentId === request.selection.agentId, ); if (!request.selection.tools.length) return denial('tool_policy_denied'); + // Granted and still selected, each by name or through a selection of the whole server. if ( !whole && - (!selection || - !currentSelection || - request.selection.tools.some( - (tool) => !selection.tools.includes(tool) || !currentSelection.tools.includes(tool), - )) + request.selection.tools.some( + (tool) => !covers(selection, tool) || !covers(currentSelection, tool), + ) ) return denial('tool_policy_denied'); const live = Object.entries(request.definitions ?? {}).filter(([tool]) => diff --git a/packages/api/src/schedules/bearer.spec.ts b/packages/api/src/schedules/bearer.spec.ts index 0f832b861c..00d53e6ada 100644 --- a/packages/api/src/schedules/bearer.spec.ts +++ b/packages/api/src/schedules/bearer.spec.ts @@ -125,7 +125,7 @@ async function bearerFixture(serverConfig = config, everything = false, tools = expectedRevision: null, offerDigest: offer.offer!.digest, lifetimeHours: 1, - ...(everything ? { allow: {}, everything: true as const } : { allow: { Files: ['echo'] } }), + ...(everything ? { allow: {}, everything: true as const } : { allow: { Files: [...tools] } }), }); const resolveBearer = jest.fn( async ( @@ -309,6 +309,35 @@ it('admits a connection to a declared server the agents took up after the whole await expect(f.call()).rejects.toMatchObject({ failure: { reason: 'consent_revoked' } }); }); +it('admits a connection under a grant of the whole server, whatever the agents select there now', async () => { + // The owner ticked every tool on the server, in a grant that lists its tools. + const f = await bearerFixture(config, false, ['sys__all__sys']); + expect(f.snapshot.enrollment).not.toHaveProperty('everything'); + await expect(resolveScheduledMCPBearerConfig(f.input)).resolves.toMatchObject({ + headers: { Authorization: 'Bearer resource-only' }, + }); + // The agents go back to naming tools: all of them are within what was allowed. + for (const selection of f.target.permittedTools) selection.tools = ['read', 'write']; + await expect(resolveScheduledMCPBearerConfig(f.input)).resolves.toMatchObject({ + headers: { Authorization: 'Bearer resource-only' }, + }); + await expect(f.call('root', ['write'])).resolves.toMatchObject({ + headers: { Authorization: 'Bearer resource-only' }, + }); +}); + +it('admits a connection for a named tool once the agents select its server as a whole', async () => { + const f = await bearerFixture(); + for (const selection of f.target.permittedTools) selection.tools = ['sys__all__sys']; + await expect(resolveScheduledMCPBearerConfig(f.input)).resolves.toMatchObject({ + headers: { Authorization: 'Bearer resource-only' }, + }); + // Still only the tool the owner named. + await expect(f.call('root', ['write'])).rejects.toMatchObject({ + failure: { reason: 'tool_policy_denied' }, + }); +}); + it('renews after synthetic expiry without a session, retaining no login refresh credentials', async () => { const f = await bearerFixture(); await f.call(); diff --git a/packages/api/src/schedules/bearer.ts b/packages/api/src/schedules/bearer.ts index 2766eebb43..58b6e8da1e 100644 --- a/packages/api/src/schedules/bearer.ts +++ b/packages/api/src/schedules/bearer.ts @@ -1,4 +1,5 @@ import { + Constants, extractEnvVariable, scheduledMCPIdentitySchema, scheduledMCPTargetSchema, @@ -145,10 +146,18 @@ export function createScheduledMCPBearerHost(deps: { // With no grant for the server, authorizing the whole selection reports why. // Nor is a whole-agent grant limited to the tools its agents had when it was made. if (lookup.state !== 'found' || lookup.everything === true) return target.permittedTools; + // The whole server, granted or selected, is `mcp_all`: it stands for every tool there. + const every: string = Constants.mcp_all; return lookup.consent.permittedTools .map(({ agentId, tools }) => { - const current = target.permittedTools.find((item) => item.agentId === agentId); - return { agentId, tools: tools.filter((tool) => current?.tools.includes(tool)) }; + const current = target.permittedTools.find((item) => item.agentId === agentId)?.tools; + if (!current) return { agentId, tools: [] }; + return { + agentId, + tools: tools.includes(every) + ? current + : tools.filter((tool) => current.includes(tool) || current.includes(every)), + }; }) .filter((item) => item.tools.length > 0); };