+ )}
{canConfirm && data.offer && (
<>
diff --git a/client/src/components/Nav/SettingsTabs/ApiKeys/__tests__/KeyGrant.spec.tsx b/client/src/components/Nav/SettingsTabs/ApiKeys/__tests__/KeyGrant.spec.tsx
index 1e48b415f4..f72f2306f0 100644
--- a/client/src/components/Nav/SettingsTabs/ApiKeys/__tests__/KeyGrant.spec.tsx
+++ b/client/src/components/Nav/SettingsTabs/ApiKeys/__tests__/KeyGrant.spec.tsx
@@ -50,6 +50,7 @@ const view = (tools: string[]): ScheduleMCPConsentView => ({
allowed: {},
changed: {},
asking: {},
+ tools: { offered: [], allowed: [] },
approval: false,
required: false,
requireAfterMs: null,
diff --git a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx
index d7f9e1af63..4eb8bb0dea 100644
--- a/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx
+++ b/client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx
@@ -1,8 +1,8 @@
import { createRef } from 'react';
import userEvent from '@testing-library/user-event';
import { dataService } from 'librechat-data-provider';
-import { render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { render, screen, cleanup, waitFor } from '@testing-library/react';
import type { ScheduleMCPConsentView } from 'librechat-data-provider';
import Consent from '../Consent';
@@ -47,6 +47,7 @@ const view: ScheduleMCPConsentView = {
allowed: {},
changed: {},
asking: {},
+ tools: { offered: [], allowed: [] },
approval: false,
required: false,
requireAfterMs: null,
@@ -106,6 +107,7 @@ it('confirms the offer reference, lifetime and only the tools the owner ticked,
lifetimeHours: 1,
allow: { warehouse: ['query'] },
ask: {},
+ tools: [],
}),
);
expect(await screen.findByText('com_ui_schedule_consent_active')).toBeVisible();
@@ -278,6 +280,76 @@ it('unticks a tool the owner accepted once it is marked again under a later gran
),
);
});
+it("lists each of the agent's other tools as its own item, and sends the ones the owner ticks", async () => {
+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
+ ...view,
+ tools: { offered: ['execute_code', 'send_action_mail.example', 'web_search'], allowed: [] },
+ });
+ jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view);
+ display();
+ // Built-in tools go by name; anything else, such as an action, by its key.
+ const code = await screen.findByRole('checkbox', { name: 'com_ui_schedule_consent_tool_code' });
+ const search = screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_tool_web' });
+ const action = screen.getByRole('checkbox', { name: 'send_action_mail.example' });
+ for (const box of [code, search, action]) expect(box).not.toBeChecked();
+ await userEvent.click(screen.getByRole('checkbox', { name: 'query' }));
+ await userEvent.click(code);
+ await userEvent.click(action);
+ await userEvent.click(action);
+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_schedule_consent_confirm' }));
+ await waitFor(() =>
+ expect(dataService.confirmScheduleMCPConsent).toHaveBeenCalledWith(
+ 'schedule',
+ expect.objectContaining({ allow: { warehouse: ['query'] }, tools: ['execute_code'] }),
+ ),
+ );
+});
+it('allows every server, tool and other tool in one click', async () => {
+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({
+ ...view,
+ tools: { offered: ['execute_code', 'web_search'], allowed: [] },
+ });
+ jest.mocked(dataService.confirmScheduleMCPConsent).mockResolvedValue(view);
+ display();
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'com_ui_schedule_consent_allow_all' }),
+ );
+ for (const box of screen.getAllByRole('checkbox')) expect(box).toBeChecked();
+ 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'] },
+ tools: ['execute_code', 'web_search'],
+ }),
+ ),
+ );
+});
+it('starts from the other tools the stored grant allows, and names them when there is nothing to confirm', async () => {
+ const granted = {
+ ...view,
+ state: 'active' as const,
+ revision: 'grant',
+ expiresAtMs: Date.now() + 60_000,
+ allowed: { warehouse: ['query'] },
+ tools: { offered: ['execute_code', 'web_search'], allowed: ['web_search'] },
+ };
+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue(granted);
+ const first = display();
+ expect(
+ await screen.findByRole('checkbox', { name: 'com_ui_schedule_consent_tool_web' }),
+ ).toBeChecked();
+ expect(
+ screen.getByRole('checkbox', { name: 'com_ui_schedule_consent_tool_code' }),
+ ).not.toBeChecked();
+ first.clear();
+ cleanup();
+ jest.mocked(dataService.getScheduleMCPConsent).mockResolvedValue({ ...granted, offer: null });
+ display();
+ expect(await screen.findByText('com_ui_schedule_consent_other_allowed')).toBeVisible();
+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
+});
it('names the changed tools 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 b323c9004a..6ae6e9fdd9 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -3936,6 +3936,12 @@
"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_allow_all": "Allow everything",
+ "com_ui_schedule_consent_other_tools": "Other tools",
+ "com_ui_schedule_consent_other_allowed": "Other tools allowed: {{tools}}",
+ "com_ui_schedule_consent_tool_code": "Code execution",
+ "com_ui_schedule_consent_tool_web": "Web search",
+ "com_ui_schedule_consent_tool_files": "File search",
"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}}",
diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.ts
index 2910e5dd40..e4a3cd3c46 100644
--- a/packages/api/src/agents/__tests__/initialize.test.ts
+++ b/packages/api/src/agents/__tests__/initialize.test.ts
@@ -7764,6 +7764,7 @@ describe("initializeAgent: under a schedule's grant", () => {
'export_mcp_warehouse',
'purge_mcp_archive',
Tools.web_search,
+ Tools.execute_code,
];
async function initialize(attach: boolean) {
const { agent, req, res, loadTools, db } = createMocks();
@@ -7772,8 +7773,11 @@ describe("initializeAgent: under a schedule's grant", () => {
loadTools.mockResolvedValue({ toolDefinitions: [] });
if (attach) {
// The agents select `query` and `export` on the warehouse; the owner allowed `query`.
+ // Of the agent's other tools the owner allowed web search and left code execution out.
const fixture = await executionFixture('invoke', readTool, undefined, {
offered: ['export'],
+ tools: [Tools.execute_code, Tools.web_search],
+ allowTools: [Tools.web_search],
});
await fixture.factory.attach(getMCPRequestContext(req, res)!, fixture.identity, 'invoke');
}
@@ -7792,16 +7796,54 @@ describe("initializeAgent: under a schedule's grant", () => {
return loadTools.mock.calls.map(([call]) => call.tools as string[]);
}
- it('loads only the MCP tools the owner allowed, and nothing from a server left out', async () => {
+ it('loads only the tools the owner allowed, MCP or not, and nothing from a server left out', async () => {
const [tools, ...retries] = await initialize(true);
expect(retries).toEqual([]);
expect(tools).toContain('query_mcp_warehouse');
expect(tools).toContain(Tools.web_search);
+ expect(tools).not.toContain(Tools.execute_code);
expect(tools).not.toContain('export_mcp_warehouse');
// The loader is never asked about the archive server, so it is never connected to.
expect(tools).not.toContain('purge_mcp_archive');
});
+ it('sets up code execution and memory for the model only where the owner allowed them', async () => {
+ const defined = async (allowTools: string[]) => {
+ const { agent, req, res, loadTools, db } = createMocks();
+ agent.id = 'root';
+ agent.tools = ['query_mcp_warehouse', Tools.execute_code, Tools.memory];
+ loadTools.mockResolvedValue({ toolDefinitions: [] });
+ const fixture = await executionFixture('invoke', readTool, undefined, {
+ tools: [Tools.execute_code, Tools.memory],
+ allowTools,
+ });
+ await fixture.factory.attach(getMCPRequestContext(req, res)!, fixture.identity, 'invoke');
+ const result = await initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([agent.provider]),
+ isInitialAgent: true,
+ codeEnvAvailable: true,
+ memoryAvailable: true,
+ },
+ db,
+ );
+ return (result.toolDefinitions ?? []).map((tool) => tool.name);
+ };
+ // The markers on the agent's tool list set these up, not the loader: left out, they must
+ // not be read there either, or the model is shown a tool that is then refused.
+ const all = await defined([Tools.execute_code, Tools.memory]);
+ expect(all).toEqual(expect.arrayContaining(['bash_tool', 'set_memory', 'delete_memory']));
+ const none = await defined([]);
+ expect(none).not.toContain('bash_tool');
+ expect(none).not.toContain('set_memory');
+ expect(none).not.toContain('delete_memory');
+ });
+
it('loads everything the agent selects for a request with no grant', async () => {
const [tools] = await initialize(false);
expect(tools).toEqual(expect.arrayContaining(selected));
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index 613f26e09f..a5953f8016 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -1240,7 +1240,19 @@ export async function initializeAgent(
useChatProjectContext ?? params.req?.chatProjectContextEnabled === true;
assertToolOptionsWithinLimits(suppliedAgent.tool_options);
const inputAgent = restoreAgentInferenceInput(suppliedAgent);
- const agent = shouldUseChatProjectContext ? { ...inputAgent } : inputAgent;
+ /**
+ * Under a schedule's grant an agent has only the tools its owner allowed. Narrowed here, at
+ * the one list everything below reads: the loader, and the markers that set up code
+ * execution and memory, so a tool the owner left out is not defined for the model at all.
+ */
+ const grantedTools =
+ inputAgent.tools == null
+ ? inputAgent.tools
+ : narrowScheduledMCPTools(params.req, inputAgent.id, inputAgent.tools);
+ const agent =
+ shouldUseChatProjectContext || grantedTools !== inputAgent.tools
+ ? { ...inputAgent, tools: grantedTools }
+ : inputAgent;
const { user, appConfig } = runtime;
const requestFileOwnerId = user?.id;
const requestFileOwnerScope: FileOwnerScope | undefined = requestFileOwnerId
diff --git a/packages/api/src/schedules/README.md b/packages/api/src/schedules/README.md
index 328eee5106..e89b3e6870 100644
--- a/packages/api/src/schedules/README.md
+++ b/packages/api/src/schedules/README.md
@@ -69,6 +69,28 @@ agent still selects it. Anything else is refused with `tool_policy_denied`.
The operator-declared `mcpConsent.readOnlyPolicy` list is retired. The loader warns when the key
is still present and ignores it.
+### Tools that are not MCP tools
+
+An agent's other tools (code execution, web search, file search, each action, any other tool it
+carries) are offered too, each as its own item, and the dialog has one control that allows
+every server and tool at once. The grant stores them per agent (`tools`). Under a grant:
+
+- One the owner allowed loads and runs. The code environment's tools go by several names and
+ are all allowed by code execution.
+- One the owner left out is not loaded for the run, like a left-out MCP tool, and does not keep
+ the schedule from running.
+- A tool that reaches the run without having been offered, or the SDK's own controls aside, is
+ still refused with `tool_policy_denied`.
+- A grant made before these tools could be chosen lists none, so none of them loads until the
+ owner confirms again.
+- Nothing checks these tools against the stored grant when they are called, as an MCP call is
+ checked. The run holds them to the grant it read when it started: they stop at the grant's
+ deadline, and a grant that was already revoked allows none. A revocation made while a run is
+ under way stops its MCP calls at once and its other tools from the next run.
+
+A grant still needs at least one MCP tool: a schedule whose agents use no MCP server has
+nothing to authorize and runs as before. An API key's grant limits MCP tools only.
+
### 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
diff --git a/packages/api/src/schedules/authorization/enrollment.spec.ts b/packages/api/src/schedules/authorization/enrollment.spec.ts
index f40c498537..6229fcf8f1 100644
--- a/packages/api/src/schedules/authorization/enrollment.spec.ts
+++ b/packages/api/src/schedules/authorization/enrollment.spec.ts
@@ -5,7 +5,7 @@ import type { IUser, AppConfig, AgentGraphAccessContext } from '@librechat/data-
import type { ScheduledMCPIdentity } from 'librechat-data-provider';
import type { ScheduleMCPEnrollmentDeps } from './enrollment';
import type { ParsedServerConfig } from '~/mcp/types';
-import { createScheduleMCPEnrollmentResolver } from './enrollment';
+import { createScheduleMCPEnrollmentResolver, createScheduleMCPOffer } from './enrollment';
import { allowOffered, pinStorage } from './execution.helper';
import { createScheduleMCPConsentService } from './service';
import { createResolveAgentFireAccess } from '../access';
@@ -101,6 +101,41 @@ it('requires operator-declared recipient metadata, not a successful login or too
} as AppConfig);
expect(await resolve(identity, {})).toEqual([]);
});
+it("offers the agents' other tools beside their MCP tools, from one walk of the agent graph", async () => {
+ const { deps } = setup();
+ jest.mocked(deps.getNodes).mockImplementation(async (ids) =>
+ ids.map((id) => ({
+ id,
+ provider: 'test',
+ model: 'test',
+ tools:
+ id === 'root'
+ ? ['query_mcp_warehouse', 'web_search', 'execute_code', 'send_action_mail.example']
+ : ['query_mcp_warehouse', 'web_search', 'tool_search'],
+ agent_ids: id === 'root' ? ['child'] : [],
+ })),
+ );
+ const offer = createScheduleMCPOffer(deps);
+ const [targets, tools] = await Promise.all([
+ offer.targets(identity, {}),
+ offer.tools(identity, {}),
+ ]);
+ // An agent with other tools is offered a grant like any other: they no longer rule it out.
+ expect(targets[0].permittedTools).toEqual([
+ { agentId: 'child', tools: ['query'] },
+ { agentId: 'root', tools: ['query'] },
+ ]);
+ // Each is its own item, per agent. The SDK's own controls are not the owner's to allow.
+ expect(tools).toEqual([
+ { agentId: 'child', tools: ['web_search'] },
+ { agentId: 'root', tools: ['execute_code', 'send_action_mail.example', 'web_search'] },
+ ]);
+ expect(deps.findUser).toHaveBeenCalledTimes(1);
+ expect(deps.getServers).toHaveBeenCalledTimes(1);
+ // A grant that limits MCP tools only, as an API key's does, offers none of them.
+ const limited = createScheduleMCPOffer(deps, { otherTools: 'ignore' });
+ expect(await limited.tools(identity, {})).toEqual([]);
+});
it('denies a changed resource URL even if the configured server name is unchanged', async () => {
const { deps, resolve } = setup();
jest.mocked(deps.getServers).mockResolvedValue({
diff --git a/packages/api/src/schedules/authorization/enrollment.ts b/packages/api/src/schedules/authorization/enrollment.ts
index 6ab2acb5ca..cb61cdcb03 100644
--- a/packages/api/src/schedules/authorization/enrollment.ts
+++ b/packages/api/src/schedules/authorization/enrollment.ts
@@ -9,6 +9,7 @@ import type {
MCPGrantIdentity,
ScheduledMCPTarget,
ScheduledMCPIdentity,
+ ScheduledMCPToolSelection,
ScheduledMCPResourceBinding,
} from 'librechat-data-provider';
import type {
@@ -17,10 +18,10 @@ import type {
IUser,
AppConfig,
} from '@librechat/data-schemas';
-import type { ScheduleMCPEnrollmentResolver } from './service';
+import type { ScheduleMCPEnrollmentResolver, ScheduleToolsResolver } from './service';
import type { GetAppConfigOptions } from '~/app/service';
import type { ParsedServerConfig } from '~/mcp/types';
-import { getScheduledMCPPolicyRevision, isScheduledMCPCandidate } from './policy';
+import { getScheduledMCPPolicyRevision, isScheduledToolItem } from './policy';
import { getScheduledMCPConfigurationRevision } from './configuration';
import { resolveScheduledMCPRequirements } from '../requirements';
import { getAppConfigOptionsFromUser } from '~/app/service';
@@ -39,6 +40,23 @@ export interface ScheduleMCPEnrollmentDeps {
) => Promise>;
}
+interface OfferOptions {
+ /** Where the operator declared the servers this kind of grant may cover. */
+ resources?: (
+ appConfig: AppConfig | undefined,
+ ) => Record | undefined;
+ /**
+ * A schedule's grant covers the whole run, so the agents' other tools are offered too, each
+ * to be allowed or left out. A grant that only limits MCP use leaves them alone.
+ */
+ otherTools?: 'offer' | 'ignore';
+}
+
+interface Offer {
+ targets: ScheduledMCPTarget[];
+ tools: ScheduledMCPToolSelection[];
+}
+
/**
* 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.
@@ -47,25 +65,38 @@ export function createScheduleMCPEnrollmentResolver<
Identity extends MCPGrantIdentity = ScheduledMCPIdentity,
>(
deps: ScheduleMCPEnrollmentDeps,
- options: {
- /** Where the operator declared the servers this kind of grant may cover. */
- resources?: (
- appConfig: AppConfig | undefined,
- ) => Record | undefined;
- /**
- * A schedule's grant covers the whole run, so an agent with any other kind of tool cannot
- * be offered one. A grant that only limits MCP use leaves the agent's other tools alone.
- */
- otherTools?: 'refuse' | 'ignore';
- } = {},
+ options: OfferOptions = {},
): ScheduleMCPEnrollmentResolver {
+ return createScheduleMCPOffer(deps, options).targets;
+}
+
+/**
+ * Both halves of an offer, read once: the MCP tools on declared servers, and the agents'
+ * other tools. Asked for together, as the consent view does, they share one walk of the
+ * agent graph.
+ */
+export function createScheduleMCPOffer(
+ deps: ScheduleMCPEnrollmentDeps,
+ options: OfferOptions = {},
+): { targets: ScheduleMCPEnrollmentResolver; tools: ScheduleToolsResolver } {
+ const pending = new Map }>();
+ const resolve = (identity: Identity, signal?: AbortSignal): Promise => {
+ const key = JSON.stringify(identity);
+ const shared = pending.get(key);
+ if (shared && shared.signal === signal) return shared.offer;
+ const offer = load(identity, signal).finally(() => {
+ if (pending.get(key)?.offer === offer) pending.delete(key);
+ });
+ pending.set(key, { signal, offer });
+ return offer;
+ };
const declared =
options.resources ??
((appConfig: AppConfig | undefined) => {
const schedules = appConfig?.interfaceConfig?.schedules;
return typeof schedules === 'object' ? schedules?.mcpConsent?.resources : undefined;
});
- return async (identity, { signal }) => {
+ const load = async (identity: Identity, signal?: AbortSignal): Promise => {
signal?.throwIfAborted();
const user = await deps.findUser(identity.ownerId);
if (!user || (user.tenantId ?? null) !== identity.tenantId)
@@ -78,7 +109,7 @@ export function createScheduleMCPEnrollmentResolver<
failClosed: true,
});
const bindings = declared(appConfig);
- if (!bindings || !Object.keys(bindings).length) return [];
+ if (!bindings || !Object.keys(bindings).length) return { targets: [], tools: [] };
const [servers, { tools, candidates: candidateTools }] = await Promise.all([
deps.getServers(user, (appConfig?.mcpConfig ?? {}) as Record),
resolveScheduledMCPRequirements(
@@ -96,11 +127,15 @@ export function createScheduleMCPEnrollmentResolver<
const names = Object.keys(servers);
const aliases = buildServerNameAliases(names);
const candidates = [...names, ...aliases.keys()];
- if (
- options.otherTools !== 'ignore' &&
- candidateTools.some(({ name }) => !isScheduledMCPCandidate(name))
- )
- throw new ScheduleMCPConsentError('consent_unavailable');
+ const others = new Map>();
+ if (options.otherTools !== 'ignore') {
+ for (const { name, agentId } of candidateTools) {
+ if (!isScheduledToolItem(name)) continue;
+ const names_ = others.get(agentId) ?? new Set();
+ names_.add(name);
+ others.set(agentId, names_);
+ }
+ }
const selected = new Map>>();
for (const { name: key, agentId } of tools) {
if (
@@ -153,6 +188,15 @@ export function createScheduleMCPEnrollmentResolver<
target.permittedTools.sort((a, b) => a.agentId.localeCompare(b.agentId));
target.policyRevision = getScheduledMCPPolicyRevision(target.permittedTools);
}
- return [...targets.values()];
+ return {
+ targets: [...targets.values()],
+ tools: [...others]
+ .map(([agentId, selected]) => ({ agentId, tools: [...selected].sort() }))
+ .sort((a, b) => a.agentId.localeCompare(b.agentId)),
+ };
+ };
+ return {
+ targets: async (identity, { signal }) => (await resolve(identity, signal)).targets,
+ tools: async (identity, { signal }) => (await resolve(identity, signal)).tools,
};
}
diff --git a/packages/api/src/schedules/authorization/execution.helper.ts b/packages/api/src/schedules/authorization/execution.helper.ts
index a30a6770cf..50e43fde97 100644
--- a/packages/api/src/schedules/authorization/execution.helper.ts
+++ b/packages/api/src/schedules/authorization/execution.helper.ts
@@ -99,13 +99,18 @@ export async function executionFixture(
/**
* `offered` adds tools the agents select; `allow` is what the owner picks (default: `tool`);
* `ask` are the allowed tools the owner approves call by call; `approvedToolCalls` are the
- * calls the owner approved in the request that resumed the run.
+ * calls the owner approved in the request that resumed the run. `tools` are the agents' tools
+ * that are not MCP tools, and `allowTools` the ones of those the owner picks (default: none).
+ * `coversTools: false` is a grant that limits MCP tools only, as an API key's does.
*/
choice: {
offered?: string[];
allow?: string[];
ask?: string[];
approvedToolCalls?: string[];
+ tools?: string[];
+ allowTools?: string[];
+ coversTools?: boolean;
} = {},
) {
let time = 1000;
@@ -177,6 +182,10 @@ export async function executionFixture(
const service = createScheduleMCPConsentService({
storage,
resolveEnrollment,
+ resolveTools: async () =>
+ choice.tools?.length
+ ? ['child', 'root'].map((agentId) => ({ agentId, tools: [...choice.tools!].sort() }))
+ : [],
getLimits: async () => ({ enabled: true, maxLifetimeHours: 24 }),
canUse: async () => allowed,
canPause: async () => true,
@@ -189,9 +198,15 @@ export async function executionFixture(
lifetimeHours: 1,
allow: { warehouse: choice.allow ?? [tool.name] },
...(choice.ask && { ask: { warehouse: choice.ask } }),
+ ...(choice.allowTools && { tools: choice.allowTools }),
});
const loadAuthorization = jest.fn(async () => ({ authority: service.authority }));
- const factory = createScheduleMCPExecution({ storage, loadAuthorization });
+ const factory = createScheduleMCPExecution({
+ storage,
+ loadAuthorization,
+ coversTools: choice.coversTools ?? true,
+ now: () => time,
+ });
const execution = (await factory.resolve(identity, stage, {
approvedToolCalls: choice.approvedToolCalls,
}))!;
diff --git a/packages/api/src/schedules/authorization/execution.spec.ts b/packages/api/src/schedules/authorization/execution.spec.ts
index e7ba5e4374..8db93bdd85 100644
--- a/packages/api/src/schedules/authorization/execution.spec.ts
+++ b/packages/api/src/schedules/authorization/execution.spec.ts
@@ -1,6 +1,7 @@
import { Constants } from '@librechat/agents';
import { SCHEDULE_APPROVAL_REASON } from 'librechat-data-provider';
import type { Tool } from '@modelcontextprotocol/sdk/types.js';
+import type { HookCallback } from '@librechat/agents';
import {
scheduleAsksEveryUse,
narrowScheduledMCPTools,
@@ -347,6 +348,47 @@ it('installs an independent ceiling for root, child, handoff, and lazy tools wit
).toEqual({});
});
+it('lets a run use the other tools its owner allowed, and code tools only with code execution', async () => {
+ const f = await executionFixture('invoke', readTool, undefined, {
+ tools: ['execute_code', 'send_action_mail.example', 'web_search'],
+ allowTools: ['execute_code', 'web_search'],
+ });
+ const mcp = [{ name: 'query_mcp_warehouse', serverName: 'warehouse', toolType: 'mcp' }];
+ const decide = (execution: typeof f.execution, toolName: string, executingAgentId = 'root') =>
+ createScheduledMCPRunPolicy(execution, [
+ { id: 'root', toolDefinitions: mcp },
+ { id: 'child', toolDefinitions: mcp },
+ ]).hook(
+ { toolName, toolInput: {}, executingAgentId } as Parameters>[0],
+ new AbortController().signal,
+ );
+ const refused = { decision: 'deny', reason: expect.any(String) };
+ expect(await decide(f.execution, 'web_search')).toEqual({});
+ expect(await decide(f.execution, 'web_search', 'child')).toEqual({});
+ // The code environment's tools go by several names; code execution allows them all.
+ expect(await decide(f.execution, 'execute_code')).toEqual({});
+ expect(await decide(f.execution, 'bash_tool')).toEqual({});
+ // Left out by the owner, or not something the owner was offered at all.
+ expect(await decide(f.execution, 'send_action_mail.example')).toEqual(refused);
+ expect(await decide(f.execution, 'memory')).toEqual(refused);
+
+ // Memory runs as two tools of other names, both allowed by the one item.
+ const remembers = await executionFixture('invoke', readTool, undefined, {
+ tools: ['memory', 'web_search'],
+ allowTools: ['memory'],
+ });
+ expect(await decide(remembers.execution, 'set_memory')).toEqual({});
+ expect(await decide(remembers.execution, 'delete_memory')).toEqual({});
+ expect(await decide(f.execution, 'set_memory')).toEqual(refused);
+
+ const without = await executionFixture('invoke', readTool, undefined, {
+ tools: ['execute_code', 'web_search'],
+ allowTools: ['web_search'],
+ });
+ expect(await decide(without.execution, 'bash_tool')).toEqual(refused);
+ expect(await decide(without.execution, 'web_search')).toEqual({});
+});
+
it('refuses a consent deadline crossed while the final database admission is in flight', async () => {
const f = await executionFixture();
jest.mocked(f.storage.admitScheduleMCPConsent).mockImplementationOnce(async () => {
@@ -490,41 +532,89 @@ it.each(['consent_revoked', 'rbac_denied', 'binding_mismatch'] as const)(
);
describe('the tools a run loads under a grant', () => {
- it('keeps what the owner allowed and every tool that is not an MCP tool', async () => {
- const fixture = await executionFixture('invoke', readTool, undefined, { offered: ['export'] });
- const keys = [
+ const keys = [
+ 'query_mcp_warehouse',
+ 'export_mcp_warehouse',
+ 'purge_mcp_archive',
+ 'web_search',
+ 'execute_code',
+ 'send_action_mail.example',
+ // The SDK's own controls are not the owner's to allow: they always load.
+ 'tool_search',
+ ];
+
+ it('keeps the MCP tools and the other tools the owner allowed, each on its own', async () => {
+ const fixture = await executionFixture('invoke', readTool, undefined, {
+ offered: ['export'],
+ tools: ['execute_code', 'send_action_mail.example', 'web_search'],
+ allowTools: ['send_action_mail.example', 'web_search'],
+ });
+ expect(fixture.execution.narrow('root', keys)).toEqual([
'query_mcp_warehouse',
- 'export_mcp_warehouse',
- 'purge_mcp_archive',
'web_search',
- 'execute_code',
- ];
+ 'send_action_mail.example',
+ 'tool_search',
+ ]);
+ expect(fixture.execution.grantsTool('root', 'web_search')).toBe(true);
+ expect(fixture.execution.grantsTool('root', 'execute_code')).toBe(false);
+ // A grant is per agent: one it does not list keeps only the controls.
+ expect(fixture.execution.narrow('stranger', keys)).toEqual(['tool_search']);
+ expect(fixture.execution.grantsTool('stranger', 'web_search')).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'],
+ });
+ expect(fixture.execution.narrow('root', keys)).toEqual(['query_mcp_warehouse', 'tool_search']);
+ });
+
+ it('stops loading and allowing the other tools once the grant has run out or been revoked', async () => {
+ const choice = { tools: ['execute_code', 'web_search'], allowTools: ['web_search'] };
+ const fixture = await executionFixture('invoke', readTool, undefined, choice);
+ expect(fixture.execution.narrow('root', keys)).toContain('web_search');
+ // Nothing checks these tools at the call as an MCP call is checked, so the run does.
+ fixture.expire();
+ expect(fixture.execution.grantsTool('root', 'web_search')).toBe(false);
+ // The MCP tool still loads: its call is refused where it is made.
+ expect(fixture.execution.narrow('root', keys)).toEqual(['query_mcp_warehouse', 'tool_search']);
+
+ const revoked = await executionFixture('invoke', readTool, undefined, choice);
+ await revoked.revoke();
+ const next = (await revoked.factory.resolve(revoked.identity, 'invoke'))!;
+ expect(next.grantsTool('root', 'web_search')).toBe(false);
+ expect(next.narrow('root', keys)).not.toContain('web_search');
+ });
+
+ it('leaves the other tools alone under a grant that limits MCP tools only', async () => {
+ const fixture = await executionFixture('invoke', readTool, undefined, { coversTools: false });
expect(fixture.execution.narrow('root', keys)).toEqual([
'query_mcp_warehouse',
'web_search',
'execute_code',
+ 'send_action_mail.example',
+ 'tool_search',
]);
- // A grant is per agent: one it does not list keeps no MCP tool.
- expect(fixture.execution.narrow('stranger', keys)).toEqual(['web_search', 'execute_code']);
+ expect(fixture.execution.grantsTool('root', 'web_search')).toBe(false);
});
it('loads no key that stands for a whole server unless the grant lists a tool on it', async () => {
const fixture = await executionFixture('invoke', readTool, undefined, { offered: ['export'] });
- const keys = [
+ const wildcards = [
'query_mcp_warehouse',
'sys__all__sys_mcp_warehouse',
'sys__server__sys_mcp_warehouse',
'sys__all__sys_mcp_archive',
'sys__server__sys_mcp_archive',
- 'web_search',
+ 'tool_search',
];
// "Every tool" names none of them, so it would define what the owner left out.
- expect(fixture.execution.narrow('root', keys)).toEqual([
+ expect(fixture.execution.narrow('root', wildcards)).toEqual([
'query_mcp_warehouse',
'sys__server__sys_mcp_warehouse',
- 'web_search',
+ 'tool_search',
]);
- expect(fixture.execution.narrow('stranger', keys)).toEqual(['web_search']);
+ expect(fixture.execution.narrow('stranger', wildcards)).toEqual(['tool_search']);
});
it('leaves the tools of a schedule nobody authorized as they are', async () => {
diff --git a/packages/api/src/schedules/authorization/execution.ts b/packages/api/src/schedules/authorization/execution.ts
index fb3a4cee6c..d6a1c9e836 100644
--- a/packages/api/src/schedules/authorization/execution.ts
+++ b/packages/api/src/schedules/authorization/execution.ts
@@ -14,7 +14,11 @@ import type { ResolvedToolApprovalHook } from '~/agents/hitl/hooks';
import type { MCPToolsSnapshot } from '~/mcp/connection';
import type { ScheduledMCPAuthority } from './contract';
import type { ScheduledTokenContext } from '../context';
-import { getScheduledMCPToolDefinitionDigest, ScheduledMCPPolicyError } from './policy';
+import {
+ isScheduledToolItem,
+ ScheduledMCPPolicyError,
+ getScheduledMCPToolDefinitionDigest,
+} from './policy';
import { getScheduledMCPConfigurationRevision } from './configuration';
import { ScheduledMCPBearerError } from '~/mcp/errors';
import { findMCPRequestContext } from '~/mcp/request';
@@ -55,10 +59,16 @@ export interface ScheduleMCPExecution boolean;
/**
- * The agent's tool keys the run may load: every key that is not an MCP tool, and the MCP
- * tools the grant lists for the agent. A run that has no grant keeps them all.
+ * The agent's tool keys the run may load: the MCP tools the grant lists for the agent, and,
+ * where the grant covers the agent's other tools, the ones it lists of those. A run that has
+ * no grant keeps them all.
*/
readonly narrow: (agentId: string, toolKeys: readonly string[]) => string[];
+ /**
+ * Whether the grant lists this tool, one that is not an MCP tool, for the agent. Always
+ * false where the grant does not cover the agents' other tools.
+ */
+ readonly grantsTool: (agentId: string, toolKey: string) => boolean;
/** Whether the grant asks the owner about any tool, so this run may pause. */
readonly mayAsk: boolean;
/** Whether the owner approves each use of this tool, by the name the run calls it. */
@@ -141,6 +151,12 @@ export interface ScheduleMCPExecutionDeps<
}>;
/** Whether a subject with no grant may not use MCP tools. Absent, it always may. */
requiresGrant?: (identity: Identity) => Promise;
+ /**
+ * Whether a grant also decides which of the agents' other tools a run loads, so that one
+ * it does not list is left out. Absent, a grant limits MCP tools only.
+ */
+ coversTools?: boolean;
+ now?: () => number;
}
export interface ScheduleMCPExecutionOptions {
@@ -195,6 +211,22 @@ export function createScheduleMCPExecution<
new Map(permittedTools.map(({ agentId, tools }) => [agentId, new Set(tools)])),
]),
);
+ /**
+ * Until when the grant read for this run allows anything: its earliest deadline, or not at
+ * all once any part of it was revoked. An MCP call is checked against the stored grant when
+ * it is made; the agents' other tools have no such call, so they are held to this.
+ */
+ const consents = snapshot.enrollment?.consents ?? [];
+ const liveUntil = consents.some((consent) => consent.revokedAtMs != null)
+ ? 0
+ : Math.min(...consents.map((consent) => consent.absoluteExpiresAtMs));
+ const now = deps.now ?? Date.now;
+ /** The agents' tools that are not MCP tools, as the owner allowed them. */
+ const others = new Map>(
+ deps.coversTools === true
+ ? (snapshot.enrollment?.tools ?? []).map(({ agentId, tools }) => [agentId, new Set(tools)])
+ : [],
+ );
const grantedServers = [...granted.keys()];
const serverAliases = buildServerNameAliases(grantedServers);
const serverSpellings = [...grantedServers, ...serverAliases.keys()];
@@ -227,6 +259,13 @@ export function createScheduleMCPExecution<
if (keys.size > 0) asking.set(agentId, keys);
}
}
+ const allows = (agentId: string, toolKey: string): boolean =>
+ others.get(agentId)?.has(toolKey) === true && now() < liveUntil;
+ /** Whether a run under the grant loads this key of the agent's. */
+ const loads = (agentId: string, toolKey: string): boolean => {
+ if (toolKey.includes(Constants.mcp_delimiter)) return isGrantedKey(agentId, toolKey);
+ return deps.coversTools !== true || !isScheduledToolItem(toolKey) || allows(agentId, toolKey);
+ };
let fenced = false;
/** Asked at the first MCP call, so a run that uses none pays nothing. Kept for the run. */
let required: Promise | undefined;
@@ -266,11 +305,8 @@ export function createScheduleMCPExecution<
grants: (agentId: string, serverName: string, selectionName: string) =>
granted.get(serverName)?.get(agentId)?.has(selectionName) === true,
narrow: (agentId: string, toolKeys: readonly string[]) =>
- enrolled
- ? toolKeys.filter(
- (key) => !key.includes(Constants.mcp_delimiter) || isGrantedKey(agentId, key),
- )
- : [...toolKeys],
+ enrolled ? toolKeys.filter((key) => loads(agentId, key)) : [...toolKeys],
+ grantsTool: allows,
mayAsk: asking.size > 0,
asksAbout: (agentId: string, toolKey: string) => asking.get(agentId)?.has(toolKey) === true,
asksAboutAny: (toolKeys: readonly string[]) =>
diff --git a/packages/api/src/schedules/authorization/host.ts b/packages/api/src/schedules/authorization/host.ts
index 3c3b22410c..a2c428cab2 100644
--- a/packages/api/src/schedules/authorization/host.ts
+++ b/packages/api/src/schedules/authorization/host.ts
@@ -6,7 +6,11 @@ import {
} from 'librechat-data-provider';
import type { ScheduleMCPConsentStorage, AppConfig, IUser } from '@librechat/data-schemas';
import type { ScheduledMCPIdentity, TCheckpointerConfig } from 'librechat-data-provider';
-import type { ScheduleMCPEnrollmentResolver, ScheduleMCPConsentService } from './service';
+import type {
+ ScheduleToolsResolver,
+ ScheduleMCPConsentService,
+ ScheduleMCPEnrollmentResolver,
+} from './service';
import type { ScheduleMCPConsentHandlers } from './handlers';
import type { CheckAccessParams } from '~/middleware/access';
import type { GetAppConfigOptions } from '~/app/service';
@@ -42,6 +46,7 @@ export function createScheduleMCPConsentHost(deps: {
getRoleByName: CheckAccessParams['getRoleByName'];
canViewAgent: (agentId: string, user: IUser) => Promise;
resolveEnrollment?: ScheduleMCPEnrollmentResolver;
+ resolveTools?: ScheduleToolsResolver;
/** Whether a scheduled run of this owner can pause for approval. Absent, it cannot. */
canPauseRuns?: (user: IUser) => Promise;
}): { service: ScheduleMCPConsentService; handlers: ScheduleMCPConsentHandlers } {
@@ -99,6 +104,7 @@ export function createScheduleMCPConsentHost(deps: {
return permissions.every(Boolean) && (await deps.canViewAgent(identity.agentId, user));
},
resolveEnrollment: deps.resolveEnrollment,
+ resolveTools: deps.resolveTools,
canPause: async (identity) => {
const user = await loadPrincipal(identity);
return user != null && (await deps.canPauseRuns?.(user)) === true;
diff --git a/packages/api/src/schedules/authorization/policy.ts b/packages/api/src/schedules/authorization/policy.ts
index 31b1a3714d..f390a4e569 100644
--- a/packages/api/src/schedules/authorization/policy.ts
+++ b/packages/api/src/schedules/authorization/policy.ts
@@ -23,6 +23,15 @@ export function isScheduledMCPCandidate(name: string): boolean {
);
}
+/**
+ * A tool an agent carries that is neither an MCP tool nor one of the SDK's own controls:
+ * code execution, web search, file search, an action. Each is its own item for the owner to
+ * allow or leave out.
+ */
+export function isScheduledToolItem(name: string): boolean {
+ return !name.includes(Constants.mcp_delimiter) && !isScheduledMCPCandidate(name);
+}
+
/** Stable across object insertion order. Arrays retain their semantic order. */
function canonical(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonical);
diff --git a/packages/api/src/schedules/authorization/run.ts b/packages/api/src/schedules/authorization/run.ts
index ac2728cb45..6004dc9fd2 100644
--- a/packages/api/src/schedules/authorization/run.ts
+++ b/packages/api/src/schedules/authorization/run.ts
@@ -1,5 +1,6 @@
import { Constants } from '@librechat/agents';
import {
+ Tools,
normalizeServerName,
SCHEDULE_APPROVAL_REASON,
Constants as ProviderConstants,
@@ -7,8 +8,12 @@ import {
import type { HookCallback } from '@librechat/agents';
import type { ScheduleMCPExecution } from './execution';
import { ASK_USER_QUESTION_TOOL_NAME } from '~/agents/hitl/askUserQuestionTool';
+import { SET_MEMORY_TOOL_NAME, DELETE_MEMORY_TOOL_NAME } from '~/agents/memory';
+import { isStatefulCodeEnvironmentToolName } from '~/agents/hitl/byom';
import { ScheduledMCPPolicyError } from './policy';
+const MEMORY_TOOL_NAMES = new Set([SET_MEMORY_TOOL_NAME, DELETE_MEMORY_TOOL_NAME]);
+
interface HandoffEdge {
from: string | string[];
to: string | string[];
@@ -39,7 +44,10 @@ export interface ScheduledMCPPolicyAgent {
export const SCHEDULE_TOOL_NOT_ALLOWED =
'The owner of this schedule has not allowed this tool. Continue without it.';
-/** No direct actions, arbitrary code or unlisted tools in an enrolled run. */
+/**
+ * An enrolled run uses what its owner allowed: the MCP tools and the other tools the grant
+ * lists, the SDK's own controls, and nothing else.
+ */
export function createScheduledMCPRunPolicy(
execution: ScheduleMCPExecution,
agents: readonly ScheduledMCPPolicyAgent[],
@@ -143,6 +151,16 @@ export function createScheduledMCPRunPolicy(
Constants.TOOL_SEARCH,
ASK_USER_QUESTION_TOOL_NAME,
]);
+ /**
+ * Whether the grant lists this tool of the agent's, one that is not an MCP tool. Some items
+ * the owner allows run as tools of other names: the code environment's tools are all allowed
+ * by code execution, and the two memory tools by memory.
+ */
+ const allowsTool = (agentId: string, name: string): boolean =>
+ execution.grantsTool(agentId, name) ||
+ (isStatefulCodeEnvironmentToolName(name) &&
+ execution.grantsTool(agentId, Tools.execute_code)) ||
+ (MEMORY_TOOL_NAMES.has(name) && execution.grantsTool(agentId, Tools.memory));
const denied = (input: Parameters>[0]): boolean => {
const agentId = input.executingAgentId;
// Foreground delegation stays in this guarded run; detached continuations do not.
@@ -158,7 +176,8 @@ export function createScheduledMCPRunPolicy(
mcpTools.has(agentId) &&
(controls.has(input.toolName) ||
handoffs.get(agentId)?.has(input.toolName) === true ||
- mcpTools.get(agentId)!.has(input.toolName))
+ mcpTools.get(agentId)!.has(input.toolName) ||
+ allowsTool(agentId, input.toolName))
);
};
const decisions = new WeakMap