mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 06:51:59 +00:00
🔌 feat: Let a Schedule's Owner Allow Tools on an MCP Server the Operator Did Not Declare (#18550)
* 🔌 feat: Let a Schedule's Owner Allow Tools on an MCP Server the Operator Did Not Declare An owner who authorizes a schedule tool by tool could tick only tools on servers declared under mcpConsent.resources. A local server, one they added, or one the operator never declared was covered only by a grant of the whole agent. Its tools are now offered among the agent's other tools, each under its key, and a selection of the whole server as one item. * 🏷️ fix: Check Listed Tools at Creation and Label Them Against the Servers in Use Readiness for a schedule being created read only the grant's consents, so a tool listed on an undeclared server was set aside and its server never probed. The label for such a tool split its key at the last delimiter, which is wrong for a server name that contains one; the view now names the servers in use and the key is read against them.
This commit is contained in:
parent
447e377b0b
commit
969403a2c8
16 changed files with 426 additions and 29 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { useId, useState } from 'react';
|
||||
import { Label, Button, Checkbox } from '@librechat/client';
|
||||
import { Tools, AgentCapabilities } from 'librechat-data-provider';
|
||||
import { Tools, Constants, AgentCapabilities, normalizeServerName } from 'librechat-data-provider';
|
||||
import type {
|
||||
ScheduledMCPTarget,
|
||||
ScheduleMCPConsentView,
|
||||
|
|
@ -18,6 +18,35 @@ const toolKeys = new Map<string, TranslationKeys>([
|
|||
[AgentCapabilities.skills, 'com_ui_schedule_consent_tool_skills'],
|
||||
]);
|
||||
|
||||
/**
|
||||
* The tool and server an MCP key names. Either name may contain the delimiter, so the key is
|
||||
* read against the servers the agents use, longest first, by either spelling. Where none
|
||||
* fits, a selection of a whole server is still told by its marker, and anything else falls
|
||||
* back to the last delimiter.
|
||||
*/
|
||||
export function splitToolKey(
|
||||
key: string,
|
||||
servers: readonly string[],
|
||||
): { name: string; server: string } | undefined {
|
||||
const delimiter = Constants.mcp_delimiter;
|
||||
const known = [...servers]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.flatMap((server) =>
|
||||
[server, normalizeServerName(server)].map((spelling) => ({
|
||||
server,
|
||||
suffix: `${delimiter}${spelling}`,
|
||||
})),
|
||||
)
|
||||
.find(({ suffix }) => key.endsWith(suffix) && key.length > suffix.length);
|
||||
if (known) return { name: key.slice(0, -known.suffix.length), server: known.server };
|
||||
const whole = `${Constants.mcp_all}${delimiter}`;
|
||||
if (key.startsWith(whole) && key.length > whole.length)
|
||||
return { name: `${Constants.mcp_all}`, server: key.slice(whole.length) };
|
||||
const at = key.lastIndexOf(delimiter);
|
||||
if (at <= 0) return undefined;
|
||||
return { name: key.slice(0, at), server: key.slice(at + delimiter.length) };
|
||||
}
|
||||
|
||||
/** Every tool on offer for a server, whichever agents selected it. */
|
||||
function offeredTools(target: ScheduledMCPTarget): string[] {
|
||||
return [...new Set(target.permittedTools.flatMap((selection) => selection.tools))].sort();
|
||||
|
|
@ -280,9 +309,21 @@ export default function GrantTools({
|
|||
} = state;
|
||||
/** What the stored grant asks about, which a whole-agent confirmation keeps. */
|
||||
const kept = [...new Set(Object.values(data.asking).flat())].sort();
|
||||
/**
|
||||
* An MCP tool listed among the other tools is on a server the operator declared nothing
|
||||
* for, and comes as the key the agent has it by: its name and server, or every tool there.
|
||||
*/
|
||||
const toolLabel = (tool: string) => {
|
||||
const key = toolKeys.get(tool);
|
||||
return key ? localize(key) : tool;
|
||||
if (key) return localize(key);
|
||||
const part = splitToolKey(tool, data.tools.servers ?? []);
|
||||
if (!part) return tool;
|
||||
return part.name === Constants.mcp_all
|
||||
? localize('com_ui_schedule_consent_tools_on_server', { server: part.server })
|
||||
: localize('com_ui_schedule_consent_tool_on_server', {
|
||||
tool: part.name,
|
||||
server: part.server,
|
||||
});
|
||||
};
|
||||
return (
|
||||
<>
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { dataService } from 'librechat-data-provider';
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { render, screen, cleanup, waitFor } from '@testing-library/react';
|
||||
import type { ScheduleMCPConsentView } from 'librechat-data-provider';
|
||||
import { splitToolKey } from '~/components/MCP/GrantTools';
|
||||
import Consent from '../Consent';
|
||||
|
||||
jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
|
||||
|
|
@ -459,6 +460,59 @@ it('offers the skills of the agent as one item, by name, and sends it like any o
|
|||
),
|
||||
);
|
||||
});
|
||||
it('lists a tool on a server the operator did not declare by its name and server, and sends its key', async () => {
|
||||
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
|
||||
...view,
|
||||
targets: [],
|
||||
tools: {
|
||||
offered: ['lookup_mcp_notes', 'sys__all__sys_mcp_archive', 'web_search'],
|
||||
allowed: [],
|
||||
},
|
||||
});
|
||||
jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view);
|
||||
display();
|
||||
// One tool by name, and a selection of a whole server as one item.
|
||||
const tool = await screen.findByRole('checkbox', {
|
||||
name: 'com_ui_schedule_consent_tool_on_server',
|
||||
});
|
||||
const every = screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_tools_on_server' });
|
||||
expect(screen.queryByRole('checkbox', { name: 'lookup_mcp_notes' })).not.toBeInTheDocument();
|
||||
await userEvent.click(tool);
|
||||
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: {},
|
||||
tools: ['lookup_mcp_notes', 'sys__all__sys_mcp_archive'],
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
it('reads the tool and the server out of a key against the servers in use, not by position', () => {
|
||||
// A server name may contain the delimiter. So may a tool's.
|
||||
expect(splitToolKey('lookup_mcp_Finance_mcp_EU', ['Finance_mcp_EU', 'EU'])).toEqual({
|
||||
name: 'lookup',
|
||||
server: 'Finance_mcp_EU',
|
||||
});
|
||||
expect(splitToolKey('read_mcp_log_mcp_notes', ['notes'])).toEqual({
|
||||
name: 'read_mcp_log',
|
||||
server: 'notes',
|
||||
});
|
||||
// The agent may have the key under the normalized spelling of the server.
|
||||
expect(splitToolKey('lookup_mcp_My_Notes', ['My Notes'])).toEqual({
|
||||
name: 'lookup',
|
||||
server: 'My Notes',
|
||||
});
|
||||
// A selection of a whole server is told by its marker even with no server to match.
|
||||
expect(splitToolKey('sys__all__sys_mcp_Finance_mcp_EU', [])).toEqual({
|
||||
name: 'sys__all__sys',
|
||||
server: 'Finance_mcp_EU',
|
||||
});
|
||||
expect(splitToolKey('send_action_mail.example', ['notes'])).toBeUndefined();
|
||||
});
|
||||
|
||||
it('authorizes a schedule whose agent uses no MCP server, once one of its tools is ticked', async () => {
|
||||
jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
|
||||
...view,
|
||||
|
|
|
|||
|
|
@ -3958,6 +3958,8 @@
|
|||
"com_ui_schedule_consent_tool_web": "Web search",
|
||||
"com_ui_schedule_consent_tool_files": "File search",
|
||||
"com_ui_schedule_consent_tool_skills": "Skills",
|
||||
"com_ui_schedule_consent_tool_on_server": "{{tool}} on {{server}}",
|
||||
"com_ui_schedule_consent_tools_on_server": "All tools on {{server}}",
|
||||
"com_ui_schedule_consent_ask_first": "Ask me first",
|
||||
"com_ui_schedule_consent_ask_tool": "Ask me before each use of {{tool}}",
|
||||
"com_ui_schedule_consent_asking": "Asks you before each use: {{tools}}",
|
||||
|
|
|
|||
|
|
@ -144,6 +144,24 @@ 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.
|
||||
|
||||
### 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
|
||||
local `stdio` server, one the owner added, or one the operator simply never declared. Its
|
||||
tools are still the owner's to allow. Each one the agents select is offered among the other
|
||||
tools, under the key the agent has it by (`lookup_mcp_notes`), and a selection of the whole
|
||||
server is one such key (`sys__all__sys_mcp_notes`), which stands for every tool there.
|
||||
|
||||
- Allowed, the key loads for that agent, together with the key for its server alone, and
|
||||
the server is made ready.
|
||||
- A call is let through after `authority.standing` makes the live checks a consented server
|
||||
gets, and finds the tool listed for the calling agent. It is then made as the owner's own
|
||||
use would make it: with their ordinary credentials for that server.
|
||||
- There is no recipient to bind and no definition pin, and such a tool cannot be asked about
|
||||
call by call. An operator who wants those declares the server.
|
||||
- A grant that limits MCP tools only, as an API key's does, has no other tools to list them
|
||||
among, so it does not cover them.
|
||||
|
||||
### A tool the owner approves call by call
|
||||
|
||||
Beside allowing a tool, the owner can set it to "ask me first". The grant stores those tools
|
||||
|
|
|
|||
|
|
@ -76,6 +76,13 @@ export interface ScheduledMCPStandingRequest<
|
|||
readonly revision: string;
|
||||
readonly stage: 'activation' | 'invoke' | 'resume';
|
||||
readonly manual?: boolean;
|
||||
/**
|
||||
* For a grant that lists its tools: the agent calling, and every key the tool being called
|
||||
* could be listed under (either spelling of its server, and the selection of the whole
|
||||
* server). The grant must list one of them for that agent. Left out, only a grant of the
|
||||
* whole agent passes.
|
||||
*/
|
||||
readonly listed?: { readonly agentId: string; readonly keys: readonly string[] };
|
||||
}
|
||||
|
||||
export type ScheduledMCPStandingResult =
|
||||
|
|
@ -95,9 +102,10 @@ export interface ScheduledMCPAuthority<Identity extends MCPGrantIdentity = Sched
|
|||
options: { signal?: AbortSignal },
|
||||
) => Promise<ScheduledMCPAuthorizationResult>;
|
||||
/**
|
||||
* The live checks of `authorize` with no server to match: the stored grant is the whole-agent
|
||||
* one this run started under and still in force, and its owner may still use schedules, MCP
|
||||
* servers and the agent on a deployment that still runs them.
|
||||
* The live checks of `authorize` with no server to match, for a tool on a server the grant
|
||||
* holds no consent for: the stored grant is the one this run started under and still in
|
||||
* force, it is for the whole agent or lists that tool, and its owner may still use
|
||||
* schedules, MCP servers and the agent on a deployment that still runs them.
|
||||
*/
|
||||
readonly standing: (
|
||||
request: ScheduledMCPStandingRequest<Identity>,
|
||||
|
|
|
|||
|
|
@ -239,7 +239,18 @@ it('still offers the rest when one server the agents use cannot be offered', asy
|
|||
const targets = await offer.targets(identity, {});
|
||||
expect(targets.map((target) => target.resource.serverName)).toEqual(['warehouse']);
|
||||
expect(targets[0].permittedTools).toEqual([{ agentId: 'root', tools: ['query'] }]);
|
||||
expect(await offer.tools(identity, {})).toEqual([{ agentId: 'root', tools: ['web_search'] }]);
|
||||
// A server the operator declared nothing for has no recipient to bind: its tools are
|
||||
// offered among the other tools, under the key the agent has them by. A key that names no
|
||||
// server the owner can reach is not offered at all.
|
||||
expect(await offer.tools(identity, {})).toEqual([
|
||||
{ agentId: 'root', tools: ['lookup_mcp_notes', 'purge_mcp_archive', 'web_search'] },
|
||||
]);
|
||||
// A grant that limits MCP tools only has no such list to put them in.
|
||||
const limited = createScheduleMCPOffer(deps, { otherTools: 'ignore' });
|
||||
expect(await limited.tools(identity, {})).toEqual([]);
|
||||
expect((await limited.targets(identity, {})).map((t) => t.resource.serverName)).toEqual([
|
||||
'warehouse',
|
||||
]);
|
||||
// Every server in use is reported by name, offered or not, so a grant can tell a server
|
||||
// that lost its declaration from one the agents dropped.
|
||||
expect(await offer.servers(identity, {})).toEqual(['archive', 'notes', 'warehouse']);
|
||||
|
|
|
|||
|
|
@ -69,10 +69,13 @@ interface Offer {
|
|||
* Resolves what the owner can be offered: the MCP tools the agent graph selects, on servers
|
||||
* whose recipient the operator declared. Does not connect or mint.
|
||||
*
|
||||
* A server that cannot be offered is left out, and the rest is still offered: one the
|
||||
* operator did not declare, or one whose configuration no longer matches the declaration. A
|
||||
* grant that lists its tools then does not cover it. A grant of the whole agent does, as the
|
||||
* owner's own use would.
|
||||
* A server whose configuration no longer matches the operator's declaration is left out, and
|
||||
* the rest is still offered. A grant that lists its tools then does not cover it; a grant of
|
||||
* the whole agent does, as the owner's own use would.
|
||||
*
|
||||
* A server the operator declared nothing for is not a target either: there is no recipient
|
||||
* to bind. Its tools are offered among the agents' other tools (see `createScheduleMCPOffer`),
|
||||
* where the grant covers those.
|
||||
*/
|
||||
export function createScheduleMCPEnrollmentResolver<
|
||||
Identity extends MCPGrantIdentity = ScheduledMCPIdentity,
|
||||
|
|
@ -179,7 +182,19 @@ export function createScheduleMCPOffer<Identity extends MCPGrantIdentity = Sched
|
|||
const name = servers[alias] ? alias : aliases.get(alias);
|
||||
if (!name || !tool) continue;
|
||||
used.add(name);
|
||||
if (undeclared) continue;
|
||||
if (!mcp) continue;
|
||||
// A server the operator declared nothing for has no recipient to hold a consent for.
|
||||
// Where the grant covers the agents' other tools, each tool the agents select there is
|
||||
// offered among them, under the key the agent has it by: allowed, it is called as the
|
||||
// owner's own use would call it. A selection of the whole server is one such key.
|
||||
if (bindings[name] === undefined) {
|
||||
if (options.otherTools !== 'ignore') {
|
||||
const keys = others.get(agentId) ?? new Set<string>();
|
||||
keys.add(key);
|
||||
others.set(agentId, keys);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const agents = selected.get(name) ?? new Map<string, Set<string>>();
|
||||
const names_ = agents.get(agentId) ?? new Set<string>();
|
||||
names_.add(tool);
|
||||
|
|
|
|||
|
|
@ -685,6 +685,57 @@ describe('the tools a run loads under a grant', () => {
|
|||
expect(await decide(['skills'], 'execute_code')).toMatchObject({ decision: 'deny' });
|
||||
});
|
||||
|
||||
it('loads and calls a tool on a server the operator did not declare, once the owner listed it', async () => {
|
||||
const notes = { type: 'stdio' as const, command: 'notes', args: [] };
|
||||
const offered = ['lookup_mcp_notes', 'purge_mcp_notes', 'web_search'];
|
||||
const fixture = await executionFixture('invoke', readTool, undefined, {
|
||||
tools: offered,
|
||||
allowTools: ['lookup_mcp_notes'],
|
||||
});
|
||||
const call = (tool: string, execution = fixture.execution) =>
|
||||
execution.bind('root', tool).authorize({
|
||||
user: fixture.user,
|
||||
serverName: 'notes',
|
||||
serverConfig: notes as never,
|
||||
toolName: tool,
|
||||
loadTools: async () => ({ tools: [{ ...readTool, name: tool }], complete: true }),
|
||||
});
|
||||
// It loads under the key the agent has it by, and so does the key for its server alone.
|
||||
expect(
|
||||
fixture.execution.narrow('root', [...offered, 'sys__server__sys_mcp_notes', 'x_mcp_other']),
|
||||
).toEqual(['lookup_mcp_notes', 'sys__server__sys_mcp_notes']);
|
||||
expect(fixture.execution.grants('root', 'notes', 'lookup')).toBe(true);
|
||||
expect(fixture.execution.grants('root', 'notes', 'purge')).toBe(false);
|
||||
expect(fixture.execution.grants('stranger', 'notes', 'lookup')).toBe(false);
|
||||
await expect(call('lookup')).resolves.toBeUndefined();
|
||||
expect(fixture.loadAuthorization).toHaveBeenCalledTimes(1);
|
||||
await expect(call('purge')).rejects.toMatchObject({
|
||||
failure: { reason: 'tool_policy_denied' },
|
||||
});
|
||||
// Once the grant has run out it is not loaded, and a call says why.
|
||||
fixture.expire();
|
||||
expect(fixture.execution.narrow('root', offered)).toEqual([]);
|
||||
await expect(call('lookup')).rejects.toMatchObject({ failure: { reason: 'consent_expired' } });
|
||||
|
||||
// A selection of the whole server is one key, and stands for every tool there.
|
||||
const every = await executionFixture('invoke', readTool, undefined, {
|
||||
tools: ['sys__all__sys_mcp_notes'],
|
||||
allowTools: ['sys__all__sys_mcp_notes'],
|
||||
});
|
||||
expect(every.execution.narrow('root', ['sys__all__sys_mcp_notes'])).toEqual([
|
||||
'sys__all__sys_mcp_notes',
|
||||
]);
|
||||
expect(every.execution.grants('root', 'notes', 'anything')).toBe(true);
|
||||
await expect(call('anything', every.execution)).resolves.toBeUndefined();
|
||||
// A grant that limits MCP tools only has no other tools: nothing is listed there.
|
||||
const limited = await executionFixture('invoke', readTool, undefined, {
|
||||
tools: offered,
|
||||
allowTools: ['lookup_mcp_notes'],
|
||||
coversTools: false,
|
||||
});
|
||||
expect(limited.execution.grants('root', 'notes', 'lookup')).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'],
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import {
|
|||
isScheduledToolItem,
|
||||
ScheduledMCPPolicyError,
|
||||
getScheduledMCPToolDefinitionDigest,
|
||||
listedMCPKeys,
|
||||
} from './policy';
|
||||
import { getScheduledMCPConfigurationRevision } from './configuration';
|
||||
import { ScheduledMCPBearerError } from '~/mcp/errors';
|
||||
|
|
@ -284,10 +285,29 @@ export function createScheduleMCPExecution<
|
|||
}
|
||||
const allows = (agentId: string, toolKey: string): boolean =>
|
||||
(whole || others.get(agentId)?.has(toolKey) === true) && now() < liveUntil;
|
||||
/** Whether a run under the grant loads this key of the agent's. */
|
||||
/** An MCP tool the grant names for the agent among its other tools. */
|
||||
const names = (agentId: string, serverName: string, selectionName: string): boolean =>
|
||||
listedMCPKeys(serverName, selectionName).some(
|
||||
(key) => others.get(agentId)?.has(key) === true,
|
||||
);
|
||||
/** The same, while the grant lasts: what a run loads and is made ready for. */
|
||||
const lists = (agentId: string, serverName: string, selectionName: string): boolean =>
|
||||
names(agentId, serverName, selectionName) && now() < liveUntil;
|
||||
/**
|
||||
* Whether a run under the grant loads this key of the agent's. An MCP key loads when a
|
||||
* consent grants it, or when it is itself listed among the other tools. A key for a server
|
||||
* alone loads where anything on that server is listed.
|
||||
*/
|
||||
const loads = (agentId: string, toolKey: string): boolean => {
|
||||
if (toolKey.includes(Constants.mcp_delimiter)) return whole || isGrantedKey(agentId, toolKey);
|
||||
return deps.coversTools !== true || !isScheduledToolItem(toolKey) || allows(agentId, toolKey);
|
||||
if (!toolKey.includes(Constants.mcp_delimiter))
|
||||
return (
|
||||
deps.coversTools !== true || !isScheduledToolItem(toolKey) || allows(agentId, toolKey)
|
||||
);
|
||||
if (whole || isGrantedKey(agentId, toolKey) || allows(agentId, toolKey)) return true;
|
||||
const marker = `${Constants.mcp_server}${Constants.mcp_delimiter}`;
|
||||
if (!toolKey.startsWith(marker) || now() >= liveUntil) return false;
|
||||
const suffix = `${Constants.mcp_delimiter}${toolKey.slice(marker.length)}`;
|
||||
return [...(others.get(agentId) ?? [])].some((key) => key.endsWith(suffix));
|
||||
};
|
||||
let fenced = false;
|
||||
/** Asked at the first MCP call, so a run that uses none pays nothing. Kept for the run. */
|
||||
|
|
@ -334,7 +354,9 @@ export function createScheduleMCPExecution<
|
|||
return observed.value;
|
||||
},
|
||||
grants: (agentId: string, serverName: string, selectionName: string) =>
|
||||
whole || granted.get(serverName)?.get(agentId)?.has(selectionName) === true,
|
||||
whole ||
|
||||
granted.get(serverName)?.get(agentId)?.has(selectionName) === true ||
|
||||
lists(agentId, serverName, selectionName),
|
||||
narrow: (agentId: string, toolKeys: readonly string[]) =>
|
||||
enrolled ? toolKeys.filter((key) => loads(agentId, key)) : [...toolKeys],
|
||||
grantsTool: allows,
|
||||
|
|
@ -389,10 +411,12 @@ export function createScheduleMCPExecution<
|
|||
}
|
||||
// Only the recipient is captured. Authority re-resolves live graph/policy below.
|
||||
const resource = resources.get(serverName);
|
||||
// The whole-agent grant holds no consent for this server: one the operator did not
|
||||
// declare, or one the agents took up since. The call goes ahead as the owner's own
|
||||
// would, after the same live checks a call on a server with a consent gets.
|
||||
if (!resource && whole) {
|
||||
// The grant holds no consent for this server: one the operator did not declare, or,
|
||||
// under a grant of the whole agent, one the agents took up since. Where the grant
|
||||
// is for the whole agent or lists this tool for the agent, the call goes ahead as
|
||||
// the owner's own would, after the same live checks a consented server gets.
|
||||
// Whether it is still in force is for those checks to say, with the reason.
|
||||
if (!resource && (whole || names(agentId!, serverName, selectionName))) {
|
||||
try {
|
||||
const { authority } = await deps.loadAuthorization(capturedIdentity);
|
||||
const standing = await authority.standing(
|
||||
|
|
@ -401,6 +425,9 @@ export function createScheduleMCPExecution<
|
|||
revision: snapshot.enrollment!.revision,
|
||||
stage,
|
||||
...(manual && { manual: true }),
|
||||
...(!whole && {
|
||||
listed: { agentId: agentId!, keys: listedMCPKeys(serverName, selectionName) },
|
||||
}),
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { Constants as AgentConstants } from '@librechat/agents';
|
||||
import { Constants, isActionTool } from 'librechat-data-provider';
|
||||
import { Constants, isActionTool, normalizeServerName } from 'librechat-data-provider';
|
||||
import type {
|
||||
ScheduledMCPToolSelection,
|
||||
ScheduledMCPFailureReason,
|
||||
|
|
@ -32,6 +32,19 @@ export function isScheduledToolItem(name: string): boolean {
|
|||
return !name.includes(Constants.mcp_delimiter) && !isScheduledMCPCandidate(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every key a tool on a server could be listed under among an agent's other tools: by either
|
||||
* spelling of the server, by name or as part of a selection of the whole server. The tools of
|
||||
* a server the operator declared nothing for are listed that way. Built from the server's
|
||||
* own name, never by splitting a key: a server name may contain the delimiter.
|
||||
*/
|
||||
export function listedMCPKeys(serverName: string, selectionName: string): string[] {
|
||||
return [serverName, normalizeServerName(serverName)].flatMap((spelling) => [
|
||||
`${selectionName}${Constants.mcp_delimiter}${spelling}`,
|
||||
`${Constants.mcp_all}${Constants.mcp_delimiter}${spelling}`,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Stable across object insertion order. Arrays retain their semantic order. */
|
||||
function canonical(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(canonical);
|
||||
|
|
|
|||
|
|
@ -977,6 +977,90 @@ describe('a schedule being edited with a new grant', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('a grant that lists a tool on a server the operator did not declare', () => {
|
||||
it('offers it by its key, makes only that server ready, loads it and calls it', async () => {
|
||||
const f = await setup();
|
||||
const archive = { type: 'streamable-http' as const, url: 'https://archive.example/mcp' };
|
||||
f.servers.archive = archive;
|
||||
Object.assign(f.config.mcpConfig as object, { archive });
|
||||
f.snapshot.enrollment = null;
|
||||
f.setCandidates(['query_mcp_warehouse', 'query_mcp_archive']);
|
||||
const offer = await f.host.consent.service.view(f.identity);
|
||||
// The declared server is a target with a recipient. The other has none: it is a tool key.
|
||||
expect(offer.targets.map((target) => target.resource.serverName)).toEqual(['warehouse']);
|
||||
expect(offer.tools.offered).toEqual(['query_mcp_archive']);
|
||||
// With the servers in use, so the dialog can tell a tool's name from its server's.
|
||||
expect(offer.tools.servers).toEqual(['archive', 'warehouse']);
|
||||
await f.host.consent.service.confirm(f.identity, {
|
||||
offerDigest: offer.offer!.digest,
|
||||
expectedRevision: offer.revision,
|
||||
lifetimeHours: 1,
|
||||
allow: {},
|
||||
tools: ['query_mcp_archive'],
|
||||
});
|
||||
f.row.mcpConsent = f.snapshot.enrollment!;
|
||||
f.connect.mockClear();
|
||||
// Readiness is for what was allowed: the declared server was left out.
|
||||
await expect(f.check()).resolves.toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ server: 'archive', status: 'ready' })]),
|
||||
);
|
||||
expect(f.connect).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ serverName: 'warehouse' }),
|
||||
);
|
||||
await f.host.prepare({ req: f.req, context: f.context });
|
||||
expect(
|
||||
getScheduleMCPExecution(f.context)!.narrow('root', [
|
||||
'query_mcp_warehouse',
|
||||
'query_mcp_archive',
|
||||
]),
|
||||
).toEqual(['query_mcp_archive']);
|
||||
const call = (serverName: string, serverConfig: object) =>
|
||||
bindScheduledMCPInvocation(f.context, 'root', 'query')!.authorize({
|
||||
user: f.user,
|
||||
serverName,
|
||||
serverConfig: serverConfig as typeof f.serverConfig,
|
||||
toolName: 'query',
|
||||
loadTools: async () => ({ tools: [readTool], complete: true }),
|
||||
});
|
||||
await expect(call('archive', archive)).resolves.toBeUndefined();
|
||||
await expect(call('warehouse', f.serverConfig)).rejects.toMatchObject({
|
||||
failure: { reason: 'tool_policy_denied' },
|
||||
});
|
||||
// A schedule being created with such a grant has nothing stored yet: readiness is
|
||||
// handed the grant, and still reaches the listed server, so one that is down is reported.
|
||||
const grant = f.snapshot.enrollment!;
|
||||
const stored = jest.mocked(f.storage.readScheduleMCPConsent).getMockImplementation()!;
|
||||
jest.mocked(f.storage.readScheduleMCPConsent).mockResolvedValue(null);
|
||||
const creating = () =>
|
||||
f.preflight('root', f.user, {
|
||||
scheduleId: 'sched_new',
|
||||
stage: 'activation',
|
||||
concurrency: 3,
|
||||
grant,
|
||||
});
|
||||
f.connect.mockClear();
|
||||
await expect(creating()).resolves.toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ server: 'archive', status: 'ready' })]),
|
||||
);
|
||||
expect(f.connect).toHaveBeenCalledWith(expect.objectContaining({ serverName: 'archive' }));
|
||||
expect(f.connect).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ serverName: 'warehouse' }),
|
||||
);
|
||||
f.connect.mockRejectedValueOnce(new Error('down'));
|
||||
await expect(creating()).rejects.toMatchObject({ code: 'mcp_unavailable' });
|
||||
jest.mocked(f.storage.readScheduleMCPConsent).mockImplementation(stored);
|
||||
// The owner loses the right to use MCP servers: the listed tool goes with it.
|
||||
f.getRoleByName.mockResolvedValue({
|
||||
permissions: {
|
||||
[PermissionTypes.SCHEDULES]: { [Permissions.USE]: true, [Permissions.CREATE]: true },
|
||||
},
|
||||
} as IRole);
|
||||
await expect(call('archive', archive)).rejects.toMatchObject({
|
||||
failure: { reason: 'rbac_denied' },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('a schedule being created with its grant', () => {
|
||||
/** Nothing is stored for it yet: the grant comes with the readiness check. */
|
||||
async function creating(
|
||||
|
|
|
|||
|
|
@ -822,7 +822,48 @@ describe('a grant of the whole agent', () => {
|
|||
{ identity, revision: listed.snapshot.enrollment!.revision, stage: 'invoke' },
|
||||
{},
|
||||
),
|
||||
).toMatchObject(refused('binding_mismatch'));
|
||||
).toMatchObject(refused('tool_policy_denied'));
|
||||
});
|
||||
|
||||
it('passes that call under a grant that lists the tool for the agent, and no other', async () => {
|
||||
const s = setup();
|
||||
s.offerTools(
|
||||
{ agentId: 'root', tools: ['lookup_mcp_notes', 'web_search'] },
|
||||
{ agentId: 'child', tools: ['web_search'] },
|
||||
);
|
||||
await s.enroll({}, undefined, ['lookup_mcp_notes', 'web_search']);
|
||||
const standing = (agentId: string, keys: string[], over: Record<string, unknown> = {}) =>
|
||||
s.service.authority.standing(
|
||||
{
|
||||
identity,
|
||||
revision: s.snapshot.enrollment!.revision,
|
||||
stage: 'invoke' as const,
|
||||
listed: { agentId, keys },
|
||||
...over,
|
||||
},
|
||||
{},
|
||||
);
|
||||
const refused = (reason: string) => ({ state: 'denied', failure: { reason } });
|
||||
// Any of the keys the tool could be listed under.
|
||||
expect(await standing('root', ['lookup_mcp_Notes', 'lookup_mcp_notes'])).toEqual({
|
||||
state: 'authorized',
|
||||
});
|
||||
expect(await standing('root', ['purge_mcp_notes'])).toMatchObject(
|
||||
refused('tool_policy_denied'),
|
||||
);
|
||||
// Listed for one agent is not listed for another.
|
||||
expect(await standing('child', ['lookup_mcp_notes'])).toMatchObject(
|
||||
refused('tool_policy_denied'),
|
||||
);
|
||||
// The same live checks as for the whole agent.
|
||||
expect(await standing('root', ['lookup_mcp_notes'], { revision: 'earlier' })).toMatchObject(
|
||||
refused('binding_mismatch'),
|
||||
);
|
||||
s.setTime(1000 + 3_600_000);
|
||||
expect(await standing('root', ['lookup_mcp_notes'])).toMatchObject(refused('consent_expired'));
|
||||
s.setTime(1000);
|
||||
s.deny();
|
||||
expect(await standing('root', ['lookup_mcp_notes'])).toMatchObject(refused('rbac_denied'));
|
||||
});
|
||||
|
||||
it('is refused that call where the owner may no longer use MCP servers, or schedules are off', async () => {
|
||||
|
|
|
|||
|
|
@ -591,7 +591,11 @@ export function createScheduleMCPConsentService<
|
|||
allowed: allowedByServer,
|
||||
changed: changedByServer,
|
||||
asking: askingByServer,
|
||||
tools: { offered: toolNames(offeredOther), allowed: allowedOther },
|
||||
tools: {
|
||||
offered: toolNames(offeredOther),
|
||||
allowed: allowedOther,
|
||||
...(used.length > 0 && { servers: [...used] }),
|
||||
},
|
||||
everything: whole,
|
||||
approval,
|
||||
required,
|
||||
|
|
@ -686,9 +690,10 @@ export function createScheduleMCPConsentService<
|
|||
offer: null,
|
||||
};
|
||||
if (!limits.enabled || !deps.resolveEnrollment) return none;
|
||||
const [servers, others] = await Promise.all([
|
||||
const [servers, others, used] = await Promise.all([
|
||||
deps.resolveEnrollment(identity, options),
|
||||
deps.resolveTools?.(identity, options) ?? [],
|
||||
deps.resolveServers?.(identity, options) ?? [],
|
||||
]);
|
||||
const resolved = listable(servers);
|
||||
if (resolved.length === 0 && others.length === 0 && !standing) return none;
|
||||
|
|
@ -702,7 +707,11 @@ export function createScheduleMCPConsentService<
|
|||
...none,
|
||||
state: 'missing',
|
||||
targets,
|
||||
tools: { offered: toolNames(others), allowed: [] },
|
||||
tools: {
|
||||
offered: toolNames(others),
|
||||
allowed: [],
|
||||
...(used.length > 0 && { servers: [...used] }),
|
||||
},
|
||||
offer: {
|
||||
digest: offerDigest(subject, 0, targets, {}, others),
|
||||
maxLifetimeHours: limits.maxLifetimeHours,
|
||||
|
|
@ -930,8 +939,17 @@ export function createScheduleMCPConsentService<
|
|||
const lifetime = grantLifetime(enrollment);
|
||||
if (lifetime.revoked) return denial('consent_revoked');
|
||||
if (now() >= lifetime.expiresAtMs) return denial('consent_expired');
|
||||
/** The whole agent, or the tool listed for the agent among its other tools. */
|
||||
const covered =
|
||||
enrollment.everything === true ||
|
||||
(request.listed != null &&
|
||||
enrollment.tools?.some(
|
||||
({ agentId, tools }) =>
|
||||
agentId === request.listed!.agentId &&
|
||||
request.listed!.keys.some((key) => tools.includes(key)),
|
||||
) === true);
|
||||
if (!covered) return denial('tool_policy_denied');
|
||||
if (
|
||||
enrollment.everything !== true ||
|
||||
enrollment.revision !== request.revision ||
|
||||
(!snapshot!.enabled && request.stage !== 'activation' && request.manual !== true) ||
|
||||
snapshot!.agentId !== request.identity.agentId ||
|
||||
|
|
|
|||
|
|
@ -45,9 +45,9 @@ import {
|
|||
} from '../mcp/utils';
|
||||
import { MCPConfigInitializationCanceledError } from '../mcp/registry/MCPServersRegistry';
|
||||
import { createMCPRequestContext, cleanupMCPRequestContext } from '../mcp/request';
|
||||
import { ScheduledMCPPolicyError, listedMCPKeys } from './authorization/policy';
|
||||
import { attachScheduledMCPBearer, ScheduledMCPBearerError } from './bearer';
|
||||
import { toScheduledTokenContext } from '~/agents/authority/context';
|
||||
import { ScheduledMCPPolicyError } from './authorization/policy';
|
||||
import { resolveScheduledMCPRequirements } from './requirements';
|
||||
import { getAppConfigOptionsFromUser } from '../app/service';
|
||||
import { createConcurrencyLimiter } from '../utils/promise';
|
||||
|
|
@ -343,12 +343,17 @@ export function createScheduleMCPPreflight(deps: ScheduleMCPDeps): ScheduleMCPPr
|
|||
new Map(permittedTools.map(({ agentId: owner, tools }) => [owner, new Set(tools)])),
|
||||
]),
|
||||
);
|
||||
/** MCP tools the pending grant lists among the other tools: on a server with no consent. */
|
||||
const listed = new Map(
|
||||
(options.grant?.tools ?? []).map(({ agentId: owner, tools }) => [owner, new Set(tools)]),
|
||||
);
|
||||
const grants: ScheduleMCPExecution['grants'] | undefined = execution?.enrolled
|
||||
? execution.grants
|
||||
: pending &&
|
||||
((owner, server, tool) =>
|
||||
options.grant?.everything === true ||
|
||||
pending.get(server)?.get(owner)?.has(tool) === true);
|
||||
pending.get(server)?.get(owner)?.has(tool) === true ||
|
||||
listedMCPKeys(server, tool).some((key) => listed.get(owner)?.has(key) === true));
|
||||
// A run under a grant needs the permission only for the MCP tools the grant allows, so
|
||||
// it is held to it below, once the tools the owner left out are set aside.
|
||||
if (!permitted && !grants) refuse();
|
||||
|
|
|
|||
|
|
@ -369,7 +369,7 @@ export type ScheduleMCPPreflight = (
|
|||
* handed over: readiness then covers the MCP tools it allows, as for a stored grant, and
|
||||
* the grant the edit replaces is not consulted.
|
||||
*/
|
||||
grant?: Pick<ScheduledMCPEnrollment, 'consents' | 'everything'>;
|
||||
grant?: Pick<ScheduledMCPEnrollment, 'consents' | 'everything' | 'tools'>;
|
||||
},
|
||||
) => Promise<ScheduleMCPOutcome[]>;
|
||||
|
||||
|
|
|
|||
|
|
@ -323,7 +323,16 @@ export interface ScheduleMCPConsentView {
|
|||
* The agents' tools that are not MCP tools: every one the owner may choose from, and the
|
||||
* ones the stored grant allows.
|
||||
*/
|
||||
tools: { offered: string[]; allowed: string[] };
|
||||
tools: {
|
||||
offered: string[];
|
||||
allowed: string[];
|
||||
/**
|
||||
* The MCP servers the agents use, by name. An MCP tool listed in `offered` comes as the
|
||||
* key the agent has it by; these say where the tool's name ends and its server's begins,
|
||||
* which the key alone does not when a name contains the delimiter.
|
||||
*/
|
||||
servers?: string[];
|
||||
};
|
||||
/** Whether the stored grant is for the whole agent, including what is added to it later. */
|
||||
everything: boolean;
|
||||
/** Whether a scheduled run can pause for the owner's approval on this deployment. */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue