mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-19 06:23:32 +00:00
* fix: enforce FILE_SEARCH role permission server-side
The FILE_SEARCH role permission is stored, served by GET /api/roles/:name and
settable through the admin API, but nothing ever checks it.
PermissionTypes.FILE_SEARCH occurs zero times under api/server; the three
occurrences in @librechat/api are all in the interface-to-role sync, which
writes the permission rather than checking it.
Measured on v0.8.8-rc1 and confirmed unchanged in rc2: a user whose role has
FILE_SEARCH.USE = false can still upload a document with
tool_resource=file_search and gets 200 with "embedded": true. The same user
calling execute_code correctly gets 403.
Two gates, both mirroring toolAccessPermType in ~/server/controllers/tools.js:
* Upload (api/server/routes/files/files.js): a tool-resource-to-permission map
checked before any branching, so it also covers the assistants path. Returns
403 with the same log line as the RUN_CODE gate. execute_code is included
because it had the same hole: the tool CALL was gated, the upload was not.
* Tool loading (api/app/clients/tools/util/handleTools.js): checked outside the
lazy loader so a denied user never gets the tool equipped, rather than one
that fails when called. Fails closed if the permission check itself throws.
All four required imports were already present in that file, next to an
existing FILE_CITATIONS check.
Both changes live in /api (JavaScript) rather than /packages/api (TypeScript)
as CLAUDE.md prefers for new backend code: each mirrors an existing pattern in
exactly these files, and a second permission gate in another language and
package would be harder to keep in step with the first.
Tests: api/app/clients/tools/util/handleTools.fileSearchPermission.test.js
covers permit, deny, the log line, and the fail-closed path.
* fixup! fix: enforce FILE_SEARCH role permission server-side
* 🔐 fix: Gate `file_search` and `execute_code` on Role Permissions
The `FILE_SEARCH` gate added in the previous commit lives in
`handleTools.loadTools`, which `loadAgentTools` only reaches when
`definitionsOnly` is false. That default is false on the chat path
(`Endpoints/agents/initialize.js`) but true on the responses and
OpenAI-compatible controllers, so on those paths a denied user still got
the tool definition advertised to the model and their files primed by
`primeSearchFiles`, and the call failed later in `loadToolsForExecution` —
the "gets one that fails when called" outcome the gate set out to avoid.
Move the decision to the capability filters that both loaders already run,
mirroring how `canUseMCP` resolves the `MCP_SERVERS` permission ahead of the
synchronous filter. `AgentCapabilities` stays the instance-wide deployment
switch; the role grant is a second condition a tool has to clear. Because
`hasFileSearch`/`hasExecuteCode` derive from the filtered list, priming is
skipped for a denied user too.
`RUN_CODE` had the same hole: `toolAccessPermType` in
`~/server/controllers/tools.js` gates only `POST /tools/:toolId/call`, not
the agent run, so a role without `RUN_CODE.USE` could still execute code
through an agent. Both tools go through the same map.
Checks use `checkAccessWithRequestCache` and run only for tools whose
capability is already enabled, so a run costs at most one role read. A check
that throws denies the tool.
Also formats the test file added in the previous commit, which Prettier
rejects as-is.
* 🔐 fix: Close the Remaining `RUN_CODE` and `FILE_SEARCH` Bypasses
Codex review of the previous commit found four ways past the gates. All four
share a cause: the permission map was copied per call site, so every boundary
that was not copied into stayed open.
Moves the maps and the check into `packages/api/src/tools/rolePermissions.ts`,
per CLAUDE.md ("all new backend code must be TypeScript in `/packages/api`",
"keep `/api` changes to the absolute minimum"), and points the four `/api`
boundaries at it.
- `handleTools.loadTools` now gates every tool in `toolRolePermissions`, not
just `file_search`. It is the shared boundary the Assistants required-action
flow crosses via `processRequiredActions`, which never passes the agent
capability filter — so a legacy Assistant with a raw function named
`execute_code` ran arbitrary code for a role denied `RUN_CODE`.
- The check is now request-cached (`checkAccessWithRequestCache`). The previous
`checkAccess` call omitted `req`, so the agent path resolved the same grant
twice and issued a second serial `getRoleByName` during chat startup, against
the rule in AGENTS.md.
- `codeExecutionEnabled` is gated by the role result at all three loaders, not
only the `execute_code` entry in the filtered list. It drives tool
classification and the programmatic bash tool, so an agent pairing
`execute_code` with an MCP `code_execution` tool still advertised and
instantiated `run_tools_with_bash` for a denied role.
- The upload map covers `EToolResources.code_interpreter`, which the Assistants
builder posts instead of `execute_code`, and native `code_interpreter` /
`file_search` tools are dropped when an assistant is created or updated.
Those run inside the provider and reach neither loader, so configuration time
is the only place they can be gated.
Renames `handleTools.fileSearchPermission.test.js` to
`handleTools.rolePermissions.test.js` — it now covers both tools.
* 🔐 fix: Gate the Image Upload Route and the v1 Assistant Writers
Second Codex round found the same shape again: boundaries the map had not been
wired into. Adds two shared helpers next to the maps in
`packages/api/src/tools/rolePermissions.ts` so a new upload handler or assistant
writer gets the check by calling one function.
- `/files/images` accepts `tool_resource` and routes agent uploads to
`processAgentFileUpload` on its own. The Code Files UI sends images there, so
every image was a way around the upload boundary for a role denied
`RUN_CODE`. Both upload routes now call
`checkToolResourceUploadPermission`.
- That helper passes `req`, so the role read joins the request cache. The
previous `checkAccess` call omitted it, and an allowed Assistants upload goes
on to `processFileUpload` → `addResourceFileId` → `updateAssistant`, whose own
check does pass `req` — two serial lookups per upload, against AGENTS.md.
- `/assistants/v1` is still mounted and its `createAssistant` / `patchAssistant`
write native tools straight to the provider. Both now filter through
`resolveAssistantToolPermissions`, which v2 also uses in place of its local
copy.
Run-time enforcement for native assistant tools is deliberately not here: it
means overriding `body.tools` at `createRun` in both chat controllers, which
changes run semantics, and is better argued on its own.
* 🔐 fix: Gate Legacy `retrieval` and the Code-Environment File Tools
Third Codex round, same shape twice more.
- The v1 assistant builder submits `{ type: 'retrieval' }` where v2 submits
`file_search` (`AssistantPanel.tsx:203`). Only the v2 spelling was mapped, so
`resolveAssistantToolPermissions` treated legacy retrieval as ungated and both
v1 writers preserved it for a role denied `FILE_SEARCH`. Both spellings now
answer to the same grant.
- `codeEnvAvailable` in the agent initializer was capability-only, and
`initializeAgent` rebuilds `bash_tool`, `read_file` and the workspace file
tools from it — after the tool loader has already dropped `execute_code` for a
denied role. The bash gate stops command execution, but those handlers still
read, search, create and edit files in an attached code environment. The flag
now carries the role grant, and short-circuits before the role read when the
deployment has the capability off.
* 🔐 fix: Resolve Tool Grants Once Per Request and Pair Every Capability Gate
Four review rounds found thirteen issues, all one class: a boundary the
permission check had not been copied into. Rounds 2 and 3 each found gaps
created by the previous round's fix, and a manual sweep of tool constructors
and upload routes still missed the `codeEnvAvailable` family entirely — because
the thing worth enumerating is not "paths that reach a tool" but "reads of the
capability".
There are 28 such reads. This replaces per-site permission checks with one
resolution per request, pairs every read that is a gate, and pins the list so a
new one cannot be added silently.
- `resolveToolRoleGrants` resolves `RUN_CODE` and `FILE_SEARCH` together and
memoizes on the request. Both perf findings disappear by construction: gates
share one role read instead of each issuing its own.
- Newly paired gates: `codeEnvAvailable` in the OpenAI-compatible, Responses and
memory-agent initializers (`initializeAgent` rebuilds `bash_tool`, `read_file`
and the workspace file tools from it, and hands their handlers the code
environment); the capability checks in agent upload processing and in
agent-management upload purposes; and the library chat-completion service,
behind an optional `getRoleByName` dependency so embedders are not broken.
- The v1 Knowledge upload posts `assistant_id` with no `tool_resource`, so there
is no resource to authorize. It now reads the assistant's own native tools and
requires their grants, instead of treating a missing resource as unrestricted.
- The startup role read moved off the critical path into the existing
`Promise.all`, and the direct tool-call check passes `req` so the shared
loader gate reuses its result rather than repeating the lookup.
- `toolCapabilityGates.spec.js` pins every file that reads either capability
with a count and a reason. A new read fails the suite until it is classified,
so the next boundary announces itself instead of waiting for a reviewer.
* 🔐 fix: Abort Assistant Writes on Role-Lookup Failure, Authorize Legacy Uploads First
Round 5 found no missed boundary — the inventory held. All three findings are
about how the gates behave.
- Failing closed is right where a denial blocks the operation, and wrong where a
denial instead filters a payload the caller persists. A transient role-store
outage during an assistant create or patch was silently stripping
`code_interpreter` / `file_search` / `retrieval` and saving the result, turning
a momentary failure into permanent config loss. `checkToolRolePermission`
gains `throwOnError`, and `resolveAssistantToolPermissions` uses it: every one
of its callers either persists the filtered list or rejects the request, so a
lookup failure has to propagate.
- The legacy-assistant upload gate ran after `sanitizedUploadFn` had already
pushed the file to the provider, so a denied role left an untracked remote file
and got a 500 for what is a 403. Moved to the route, next to the tool-resource
gate, before any bytes are sent.
- `resendFiles` hydration derived its resource set from unfiltered `agent.tools`,
so a denied role still paid the thread walk and code-file reads for a tool
about to be dropped. The `execute_code` half now keys off
`effectiveCodeEnvAvailable`, which already carries the grant.
The `file_search` half of that last one needs the grant threaded into
`initializeAgent`, which is plumbing in the most delicate file here for a latency
win on an already-correct path — deliberately left for a follow-up.
* 🧪 fix: Declare `resolveToolRoleGrants` in the Upload Spec's Module Stub
`Tests: api (shard 2/3)` failed on `a0b38c3`: `process.spec.js` stubs
`@librechat/api` wholesale, so the `resolveToolRoleGrants` call added to the
upload gate resolved to undefined and threw. Five failures in
`processAgentFileUpload`, plus one cascading `processFileURL` assertion from the
same suite.
The gate was verified through its own spec and the routes above it, but not
through the spec of the file it lives in — `process.spec.js` was never run
locally. Every spec belonging to a file this PR touches now has been, and the
mongodb-backed ones that still cannot run here were checked statically for the
same stub shape: all but `process.integration.spec.js` spread `requireActual`,
and that one never reaches these paths.
* ⚡ fix: Skip the Role Lookup When Code Execution Is Disabled
The browser initializer already guards this; the OpenAI-compatible and Responses
controllers did not, so every request on those endpoints issued a role read whose
result the capability short-circuit then discarded. Both now start the lookup
only when the deployment has `execute_code` enabled, matching the third.
* ⚡ fix: Drop Three Redundant Reads on the Gated Paths
- The memory initializer resolved grants unconditionally, so a deployment
without `execute_code` paid a role read for a flag that could only be false.
Guarded like the three chat initializers.
- Agent-management upload purposes resolved grants before `checkCapability`, so
a purpose the deployment has switched off paid a role read on the way to being
rejected. Capability first, then the grant.
- The legacy-assistant preflight builds an OpenAI client to read the assistant's
tools, and `processFileUpload` then built a second one — re-reading the user's
key expiry and values. The preflight now hands its client on, and processing
builds one only when it wasn't given one.
---------
Co-authored-by: Paul <200737214+SSIG-IT@users.noreply.github.com>
731 lines
26 KiB
JavaScript
731 lines
26 KiB
JavaScript
const { logger, getTenantId } = require('@librechat/data-schemas');
|
|
const { Calculator, createSearchTool, createCodeExecutionTool } = require('@librechat/agents');
|
|
const {
|
|
checkAccess,
|
|
toolkitParent,
|
|
toolRolePermissions,
|
|
checkToolRolePermission,
|
|
createSafeUser,
|
|
createAuthIdentityContext,
|
|
mcpToolPattern,
|
|
loadWebSearchAuth,
|
|
splitMCPToolKey,
|
|
buildServerNameAliases,
|
|
findShadowedServerNames,
|
|
isNormalizationSensitiveName,
|
|
buildInlineMemoryTool,
|
|
getCodeApiAuthHeaders,
|
|
buildImageToolContext,
|
|
SET_MEMORY_TOOL_NAME,
|
|
buildWebSearchContext,
|
|
DELETE_MEMORY_TOOL_NAME,
|
|
createAskUserQuestionTool,
|
|
ASK_USER_QUESTION_TOOL_NAME,
|
|
resolveWebSearchSSRFAgents,
|
|
buildWebSearchDynamicContext,
|
|
codeExecutionAuthHeaders,
|
|
resolveCodeExecutionContext,
|
|
} = require('@librechat/api');
|
|
const {
|
|
AuthType,
|
|
Tools,
|
|
Constants,
|
|
Permissions,
|
|
EToolResources,
|
|
PermissionTypes,
|
|
AgentCapabilities,
|
|
} = require('librechat-data-provider');
|
|
const {
|
|
availableTools,
|
|
manifestToolMap,
|
|
// Basic Tools
|
|
GoogleSearchAPI,
|
|
// Structured Tools
|
|
DALLE3,
|
|
FluxAPI,
|
|
OpenWeather,
|
|
StructuredSD,
|
|
StructuredACS,
|
|
TraversaalSearch,
|
|
StructuredWolfram,
|
|
TavilySearchResults,
|
|
createGeminiImageTool,
|
|
createOpenAIImageTools,
|
|
} = require('../');
|
|
const {
|
|
createMCPTool,
|
|
createMCPTools,
|
|
createMCPPermissionContext,
|
|
resolveMcpServerContext,
|
|
resolveCollisionAuditNames,
|
|
} = require('~/server/services/MCP');
|
|
const { getMCPRequestContext } = require('~/server/services/MCPRequestContext');
|
|
const { createOpenIDSessionTokenProvider } = require('~/server/services/OpenIDSessionRefresh');
|
|
const { createFileSearchTool, primeFiles: primeSearchFiles } = require('./fileSearch');
|
|
const { primeFiles: primeCodeFiles } = require('~/server/services/Files/Code/process');
|
|
const { getUserPluginAuthValue } = require('~/server/services/PluginService');
|
|
const { loadAuthValues } = require('~/server/services/Tools/credentials');
|
|
const { getMCPServerTools, checkCapability } = require('~/server/services/Config');
|
|
const { getMCPServersRegistry } = require('~/config');
|
|
const { getRoleByName, setMemory, deleteMemory, getFormattedMemories } = require('~/models');
|
|
|
|
/**
|
|
* Validates the availability and authentication of tools for a user based on environment variables or user-specific plugin authentication values.
|
|
* Tools without required authentication or with valid authentication are considered valid.
|
|
*
|
|
* @param {Object} user The user object for whom to validate tool access.
|
|
* @param {Array<string>} tools An array of tool identifiers to validate. Defaults to an empty array.
|
|
* @returns {Promise<Array<string>>} A promise that resolves to an array of valid tool identifiers.
|
|
*/
|
|
const validateTools = async (user, tools = []) => {
|
|
try {
|
|
const validToolsSet = new Set(tools);
|
|
const availableToolsToValidate = availableTools.filter((tool) =>
|
|
validToolsSet.has(tool.pluginKey),
|
|
);
|
|
|
|
/**
|
|
* Validates the credentials for a given auth field or set of alternate auth fields for a tool.
|
|
* If valid admin or user authentication is found, the function returns early. Otherwise, it removes the tool from the set of valid tools.
|
|
*
|
|
* @param {string} authField The authentication field or fields (separated by "||" for alternates) to validate.
|
|
* @param {string} toolName The identifier of the tool being validated.
|
|
*/
|
|
const validateCredentials = async (authField, toolName) => {
|
|
const fields = authField.split('||');
|
|
for (const field of fields) {
|
|
const adminAuth = process.env[field];
|
|
if (adminAuth && adminAuth.length > 0) {
|
|
return;
|
|
}
|
|
|
|
let userAuth = null;
|
|
try {
|
|
userAuth = await getUserPluginAuthValue(user, field);
|
|
} catch (err) {
|
|
if (field === fields[fields.length - 1] && !userAuth) {
|
|
throw err;
|
|
}
|
|
}
|
|
if (userAuth && userAuth.length > 0) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
validToolsSet.delete(toolName);
|
|
};
|
|
|
|
for (const tool of availableToolsToValidate) {
|
|
if (!tool.authConfig || tool.authConfig.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
for (const auth of tool.authConfig) {
|
|
await validateCredentials(auth.authField, tool.pluginKey);
|
|
}
|
|
}
|
|
|
|
return Array.from(validToolsSet.values());
|
|
} catch (err) {
|
|
logger.error('[validateTools] There was a problem validating tools', err);
|
|
throw new Error(err);
|
|
}
|
|
};
|
|
|
|
/** @typedef {typeof import('@librechat/agents/langchain/tools').Tool} ToolConstructor */
|
|
/** @typedef {import('@librechat/agents/langchain/tools').Tool} Tool */
|
|
|
|
/**
|
|
* Initializes a tool with authentication values for the given user, supporting alternate authentication fields.
|
|
* Authentication fields can have alternates separated by "||", and the first defined variable will be used.
|
|
*
|
|
* @param {string} userId The user ID for which the tool is being loaded.
|
|
* @param {Array<string>} authFields Array of strings representing the authentication fields. Supports alternate fields delimited by "||".
|
|
* @param {ToolConstructor} ToolConstructor The constructor function for the tool to be initialized.
|
|
* @param {Object} options Optional parameters to be passed to the tool constructor alongside authentication values.
|
|
* @returns {() => Promise<Tool>} An Async function that, when called, asynchronously initializes and returns an instance of the tool with authentication.
|
|
*/
|
|
const loadToolWithAuth = (userId, authFields, ToolConstructor, options = {}) => {
|
|
return async function () {
|
|
const authValues = await loadAuthValues({ userId, authFields });
|
|
const userProvidedAuthFields = new Set(
|
|
authFields
|
|
.flatMap((authField) => authField.split('||'))
|
|
.filter((authField) => {
|
|
const value = process.env[authField];
|
|
return !value || value.trim() === '' || value === AuthType.USER_PROVIDED;
|
|
}),
|
|
);
|
|
return new ToolConstructor({
|
|
...options,
|
|
...authValues,
|
|
userId,
|
|
userProvidedAuthFields,
|
|
});
|
|
};
|
|
};
|
|
|
|
/**
|
|
* @param {string} toolKey
|
|
* @returns {Array<string>}
|
|
*/
|
|
const getAuthFields = (toolKey) => {
|
|
return manifestToolMap[toolKey]?.authConfig.map((auth) => auth.authField) ?? [];
|
|
};
|
|
|
|
/**
|
|
*
|
|
* @param {object} params
|
|
* @param {string} params.user
|
|
* @param {Record<string, Record<string, string>>} [object.userMCPAuthMap]
|
|
* @param {AbortSignal} [object.signal]
|
|
* @param {Pick<Agent, 'id' | 'provider' | 'model'>} [params.agent]
|
|
* @param {string} [params.model]
|
|
* @param {EModelEndpoint} [params.endpoint]
|
|
* @param {LoadToolOptions} [params.options]
|
|
* @param {boolean} [params.useSpecs]
|
|
* @param {Array<string>} params.tools
|
|
* @param {boolean} [params.functions]
|
|
* @param {boolean} [params.returnMap]
|
|
* @param {AppConfig['webSearch']} [params.webSearch]
|
|
* @param {AppConfig['fileStrategy']} [params.fileStrategy]
|
|
* @param {AppConfig['imageOutputType']} [params.imageOutputType]
|
|
* @returns {Promise<{ loadedTools: Tool[], toolContextMap: Object<string, any>, dynamicToolContextMap?: Object<string, any> } | Record<string,Tool>>}
|
|
*/
|
|
const loadTools = async ({
|
|
user,
|
|
agent,
|
|
model,
|
|
signal,
|
|
endpoint,
|
|
userMCPAuthMap,
|
|
tools = [],
|
|
options = {},
|
|
functions = true,
|
|
returnMap = false,
|
|
webSearch,
|
|
fileStrategy,
|
|
imageOutputType,
|
|
}) => {
|
|
const toolConstructors = {
|
|
flux: FluxAPI,
|
|
calculator: Calculator,
|
|
google: GoogleSearchAPI,
|
|
open_weather: OpenWeather,
|
|
wolfram: StructuredWolfram,
|
|
'stable-diffusion': StructuredSD,
|
|
'azure-ai-search': StructuredACS,
|
|
traversaal_search: TraversaalSearch,
|
|
tavily_search_results_json: TavilySearchResults,
|
|
};
|
|
|
|
const customConstructors = {
|
|
image_gen_oai: async (_toolContextMap, dynamicToolContextMap) => {
|
|
const authFields = getAuthFields('image_gen_oai');
|
|
const authValues = await loadAuthValues({ userId: user, authFields });
|
|
const imageFiles = options.tool_resources?.[EToolResources.image_edit]?.files ?? [];
|
|
const toolContext = buildImageToolContext({
|
|
imageFiles,
|
|
toolName: `${EToolResources.image_edit}_oai`,
|
|
contextDescription: 'image editing',
|
|
});
|
|
if (toolContext) {
|
|
dynamicToolContextMap.image_edit_oai = toolContext;
|
|
}
|
|
return createOpenAIImageTools({
|
|
...authValues,
|
|
isAgent: !!agent,
|
|
req: options.req,
|
|
imageOutputType,
|
|
fileStrategy,
|
|
imageFiles,
|
|
});
|
|
},
|
|
gemini_image_gen: async (_toolContextMap, dynamicToolContextMap) => {
|
|
const authFields = getAuthFields('gemini_image_gen');
|
|
const authValues = await loadAuthValues({ userId: user, authFields, throwError: false });
|
|
const imageFiles = options.tool_resources?.[EToolResources.image_edit]?.files ?? [];
|
|
const toolContext = buildImageToolContext({
|
|
imageFiles,
|
|
toolName: 'gemini_image_gen',
|
|
contextDescription: 'image context',
|
|
});
|
|
if (toolContext) {
|
|
dynamicToolContextMap.gemini_image_gen = toolContext;
|
|
}
|
|
return createGeminiImageTool({
|
|
...authValues,
|
|
isAgent: !!agent,
|
|
req: options.req,
|
|
imageFiles,
|
|
userId: user,
|
|
fileStrategy,
|
|
});
|
|
},
|
|
};
|
|
|
|
const requestedTools = {};
|
|
const hasMCPTools = tools.some((toolName) => toolName && mcpToolPattern.test(toolName));
|
|
const mcpPermissionContext =
|
|
options.mcpPermissionContext ?? createMCPPermissionContext(options.req);
|
|
const canUseMCP = hasMCPTools
|
|
? await mcpPermissionContext.canUseServers(options.req?.user)
|
|
: true;
|
|
let loggedMCPDenied = false;
|
|
|
|
if (functions === true) {
|
|
toolConstructors.dalle = DALLE3;
|
|
}
|
|
|
|
/** @type {ImageGenOptions} */
|
|
const imageGenOptions = {
|
|
isAgent: !!agent,
|
|
req: options.req,
|
|
fileStrategy,
|
|
processFileURL: options.processFileURL,
|
|
returnMetadata: options.returnMetadata,
|
|
uploadImageBuffer: options.uploadImageBuffer,
|
|
};
|
|
|
|
const toolOptions = {
|
|
flux: imageGenOptions,
|
|
dalle: imageGenOptions,
|
|
'stable-diffusion': imageGenOptions,
|
|
gemini_image_gen: imageGenOptions,
|
|
};
|
|
|
|
/** @type {Record<string, string>} */
|
|
const toolContextMap = {};
|
|
/** @type {Record<string, string>} */
|
|
const dynamicToolContextMap = {};
|
|
/**
|
|
* @type {import('@librechat/agents').CodeEnvFile[] | undefined}
|
|
* Captured by the `execute_code` factory when files are primed. Surfaced
|
|
* out of `loadTools` so client.js can seed `Graph.sessions[EXECUTE_CODE]`
|
|
* before run start — without that seed, the first `execute_code` /
|
|
* `bash_tool` call lands with empty `_injected_files` and the sandbox
|
|
* can't see the prior turn's generated artifacts.
|
|
*/
|
|
let primedCodeFiles;
|
|
const requestedMCPTools = {};
|
|
|
|
/** Resolve config-source servers for the current user/tenant context */
|
|
let configServers;
|
|
/** All configured names, in the normalized form tool keys carry */
|
|
let mcpServerNames = [];
|
|
/** All configured names in raw config form, for normalized→raw resolution */
|
|
let mcpRawServerNames = [];
|
|
if (hasMCPTools && canUseMCP) {
|
|
/** Reuse the caller's context when it already resolved one, so the chat
|
|
* startup path reads the request app config once. */
|
|
({
|
|
configServers,
|
|
serverNames: mcpServerNames,
|
|
rawServerNames: mcpRawServerNames = [],
|
|
} = options.mcpServerContext ?? (await resolveMcpServerContext(options.req)));
|
|
}
|
|
/**
|
|
* Collision guards need the FULL accessible set (operator + user DB): a
|
|
* cross-tier collision (DB `foo` vs operator `foo!`) is invisible to the
|
|
* operator-config names alone. The caller's heal may have already fetched
|
|
* it (threaded via `mcpServerContext.accessibleServerNames`); otherwise it
|
|
* is fetched ONLY when a configured name actually needs normalizing. When
|
|
* the full set was needed but unavailable, normalization-sensitive
|
|
* references FAIL CLOSED below rather than auditing operator names alone.
|
|
*/
|
|
const collisionAudit = hasMCPTools
|
|
? await resolveCollisionAuditNames({
|
|
rawServerNames: mcpRawServerNames,
|
|
/** Load-time callers thread the audit inside `mcpServerContext`;
|
|
* deferred execution threads initialization's snapshot as a bare
|
|
* `accessibleMcpServerNames` (it resolves no server context). */
|
|
accessibleServerNames:
|
|
options.mcpServerContext?.accessibleServerNames ?? options.accessibleMcpServerNames,
|
|
userId: user,
|
|
role: options.req?.user?.role,
|
|
})
|
|
: { names: [], complete: true };
|
|
const serverNameAliases = buildServerNameAliases(collisionAudit.names);
|
|
const shadowedServers = findShadowedServerNames(collisionAudit.names);
|
|
|
|
for (const tool of tools) {
|
|
/** `loadTools` is the shared boundary for every runtime that equips these
|
|
* tools — agents, and the Assistants required-action flow via
|
|
* `processRequiredActions`, which never passes through the agent capability
|
|
* filter. Gate here so a denied role cannot reach the sandbox or the search
|
|
* index down any of them. The check is request-cached, so the agent path
|
|
* that already resolved this grant pays nothing for the second look. */
|
|
const rolePermission = toolRolePermissions[tool];
|
|
if (rolePermission != null && options.req?.user != null) {
|
|
const allowed = await checkToolRolePermission({
|
|
req: options.req,
|
|
user: options.req.user,
|
|
permissionType: rolePermission,
|
|
getRoleByName,
|
|
context: 'handleTools',
|
|
});
|
|
if (!allowed) {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (tool === Tools.execute_code) {
|
|
requestedTools[tool] = async () => {
|
|
const statefulSessions =
|
|
agent?.stateful_code_sessions === true &&
|
|
(await checkCapability(options.req, AgentCapabilities.stateful_code_sessions));
|
|
const codeExecutionContext =
|
|
options.codeExecutionContext ??
|
|
resolveCodeExecutionContext({
|
|
statefulSessions,
|
|
environment: agent?.stateful_code_environment,
|
|
environmentId: agent?.code_environment_id,
|
|
environments:
|
|
options.req?.config?.endpoints?.agents?.statefulCodeSessions?.environments,
|
|
userId: user,
|
|
agentId: agent?.id,
|
|
conversationId: options.req?.body?.conversationId,
|
|
});
|
|
const { files, toolContext } = await primeCodeFiles({
|
|
...options,
|
|
agentId: agent?.id,
|
|
codeApiBaseUrl: codeExecutionContext.baseUrl,
|
|
executionProfile: codeExecutionContext.executionProfile,
|
|
executionRouteKey: codeExecutionContext.executionRouteKey,
|
|
bridgeWorkerId: codeExecutionContext.bridgeWorkerId,
|
|
});
|
|
if (toolContext) {
|
|
dynamicToolContextMap[tool] = toolContext;
|
|
}
|
|
if (files?.length) {
|
|
primedCodeFiles = files;
|
|
}
|
|
return createCodeExecutionTool({
|
|
user_id: user,
|
|
files,
|
|
authHeaders: () =>
|
|
codeExecutionAuthHeaders(
|
|
(bridgeWorkerId) => getCodeApiAuthHeaders(options.req, bridgeWorkerId),
|
|
codeExecutionContext,
|
|
),
|
|
...codeExecutionContext,
|
|
});
|
|
};
|
|
continue;
|
|
} else if (tool === Tools.file_search) {
|
|
requestedTools[tool] = async () => {
|
|
const { files, toolContext } = await primeSearchFiles({
|
|
...options,
|
|
agentId: agent?.id,
|
|
});
|
|
if (toolContext) {
|
|
dynamicToolContextMap[tool] = toolContext;
|
|
}
|
|
|
|
/** @type {boolean | undefined} Check if user has FILE_CITATIONS permission */
|
|
let fileCitations;
|
|
if (fileCitations == null && options.req?.user != null) {
|
|
try {
|
|
fileCitations = await checkAccess({
|
|
user: options.req.user,
|
|
permissionType: PermissionTypes.FILE_CITATIONS,
|
|
permissions: [Permissions.USE],
|
|
getRoleByName,
|
|
});
|
|
} catch (error) {
|
|
logger.error('[handleTools] FILE_CITATIONS permission check failed:', error);
|
|
fileCitations = false;
|
|
}
|
|
}
|
|
|
|
return createFileSearchTool({
|
|
appConfig: options.req.config,
|
|
userId: user,
|
|
files,
|
|
entity_id: agent?.id,
|
|
fileCitations,
|
|
});
|
|
};
|
|
continue;
|
|
} else if (tool === Tools.web_search) {
|
|
const result = await loadWebSearchAuth({
|
|
userId: user,
|
|
loadAuthValues,
|
|
webSearchConfig: webSearch,
|
|
});
|
|
if (!result.authenticated) {
|
|
logger.warn('[handleTools] Skipping web search because authentication is incomplete.');
|
|
continue;
|
|
}
|
|
const { onSearchResults, onGetHighlights } = options?.[Tools.web_search] ?? {};
|
|
const { httpAgent, httpsAgent } = resolveWebSearchSSRFAgents(
|
|
result.authResult,
|
|
webSearch?.allowedAddresses,
|
|
);
|
|
requestedTools[tool] = async () => {
|
|
toolContextMap[tool] = buildWebSearchContext();
|
|
dynamicToolContextMap[tool] = buildWebSearchDynamicContext(options.req?.turnStartedAt);
|
|
return createSearchTool({
|
|
...result.authResult,
|
|
httpAgent,
|
|
httpsAgent,
|
|
onSearchResults,
|
|
onGetHighlights,
|
|
logger,
|
|
});
|
|
};
|
|
continue;
|
|
} else if (tool === ASK_USER_QUESTION_TOOL_NAME) {
|
|
requestedTools[tool] = async () => createAskUserQuestionTool();
|
|
continue;
|
|
} else if (tool === SET_MEMORY_TOOL_NAME || tool === DELETE_MEMORY_TOOL_NAME) {
|
|
requestedTools[tool] = () =>
|
|
buildInlineMemoryTool({
|
|
toolName: tool,
|
|
req: options.req,
|
|
agent,
|
|
userId: user,
|
|
memoryMethods: { setMemory, deleteMemory, getFormattedMemories },
|
|
getRoleByName,
|
|
});
|
|
continue;
|
|
} else if (tool && mcpToolPattern.test(tool)) {
|
|
if (!canUseMCP) {
|
|
if (!loggedMCPDenied) {
|
|
logger.warn(
|
|
`[handleTools] User ${options.req?.user?.id} lacks MCP server use permission`,
|
|
);
|
|
loggedMCPDenied = true;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
/** Keys carry the normalized server name (raw in pre-normalization data),
|
|
* so both spellings resolve the boundary; everything downstream — the
|
|
* registry, config maps, cache, and auth rows — is keyed by the RAW name. */
|
|
const [toolName, parsedServerName] = splitMCPToolKey(tool, [
|
|
...mcpServerNames,
|
|
...serverNameAliases.values(),
|
|
]);
|
|
if (toolName === Constants.mcp_server) {
|
|
/** Placeholder used for UI purposes */
|
|
continue;
|
|
}
|
|
/** DIRECT-FIRST: a server resolving under the parsed name as-is wins
|
|
* (a user-DB server may be named exactly like an operator server's
|
|
* normalized form); only when nothing resolves is the parsed name
|
|
* treated as a normalized spelling of a raw config name. */
|
|
let serverName = parsedServerName;
|
|
let serverConfig = serverName
|
|
? await getMCPServersRegistry().getServerConfig(serverName, user, configServers)
|
|
: null;
|
|
if (!serverConfig && serverName != null) {
|
|
const aliasedName = serverNameAliases.get(serverName);
|
|
if (aliasedName != null && aliasedName !== serverName) {
|
|
serverConfig = await getMCPServersRegistry().getServerConfig(
|
|
aliasedName,
|
|
user,
|
|
configServers,
|
|
);
|
|
if (serverConfig) {
|
|
serverName = aliasedName;
|
|
}
|
|
}
|
|
}
|
|
/** A shadowed server's instances (wildcard-expanded or single) get the
|
|
* SAME normalized names as the winning server's — in-run dispatch
|
|
* could execute either. Fail closed at execution too, since legacy
|
|
* raw keys and `mcp_all` tokens bypass catalog filtering. Under an
|
|
* incomplete audit, any normalization-sensitive reference is
|
|
* potentially shadowed and fails closed the same way. */
|
|
if (
|
|
serverName != null &&
|
|
(shadowedServers.has(serverName) ||
|
|
(!collisionAudit.complete && isNormalizationSensitiveName(serverName, mcpRawServerNames)))
|
|
) {
|
|
logger.warn(
|
|
`[handleTools] Skipping MCP tool "${tool}": server "${serverName}" is shadowed by a name collision (or the collision audit is unavailable); rename one server or retry.`,
|
|
);
|
|
continue;
|
|
}
|
|
if (!serverConfig) {
|
|
logger.warn(
|
|
`MCP server "${serverName}" for "${toolName}" tool is not configured${agent?.id != null && agent.id ? ` but attached to "${agent.id}"` : ''}`,
|
|
);
|
|
continue;
|
|
}
|
|
if (toolName === Constants.mcp_all) {
|
|
requestedMCPTools[serverName] = [
|
|
{
|
|
type: 'all',
|
|
serverName,
|
|
config: serverConfig,
|
|
},
|
|
];
|
|
continue;
|
|
}
|
|
|
|
requestedMCPTools[serverName] = requestedMCPTools[serverName] || [];
|
|
requestedMCPTools[serverName].push({
|
|
type: 'single',
|
|
toolKey: tool,
|
|
serverName,
|
|
config: serverConfig,
|
|
});
|
|
continue;
|
|
}
|
|
|
|
const toolKey = customConstructors[tool] ? tool : toolkitParent[tool];
|
|
if (toolKey && customConstructors[toolKey]) {
|
|
if (!requestedTools[toolKey]) {
|
|
let cached;
|
|
requestedTools[toolKey] = async () => {
|
|
cached ??= customConstructors[toolKey](toolContextMap, dynamicToolContextMap);
|
|
return cached;
|
|
};
|
|
}
|
|
requestedTools[tool] = requestedTools[toolKey];
|
|
continue;
|
|
}
|
|
|
|
if (toolConstructors[tool]) {
|
|
const options = toolOptions[tool] || {};
|
|
const toolInstance = loadToolWithAuth(
|
|
user,
|
|
getAuthFields(tool),
|
|
toolConstructors[tool],
|
|
options,
|
|
);
|
|
requestedTools[tool] = toolInstance;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (returnMap) {
|
|
return requestedTools;
|
|
}
|
|
|
|
const toolPromises = [];
|
|
for (const tool of tools) {
|
|
const validTool = requestedTools[tool];
|
|
if (validTool) {
|
|
toolPromises.push(
|
|
validTool().catch((error) => {
|
|
logger.error(`Error loading tool ${tool}:`, error);
|
|
return null;
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
const loadedTools = (await Promise.all(toolPromises)).flatMap((plugin) => plugin || []);
|
|
const mcpToolPromises = [];
|
|
/** MCP server tools are initialized sequentially by server */
|
|
let index = -1;
|
|
const failedMCPServers = new Set();
|
|
const safeUser = createSafeUser(options.req?.user);
|
|
const requestScopedConnections =
|
|
options.requestScopedConnections ?? getMCPRequestContext(options.req, options.res);
|
|
/**
|
|
* Build the OBO upstream-token closure once at the request boundary (where
|
|
* `req`/`res` are in scope) and thread the function into MCP handling, so the
|
|
* MCP layer never receives the raw Express request. The closure reads/refreshes
|
|
* the live `req.session.openidTokens` at tool-call time and mirrors rotations
|
|
* to the `refreshToken` cookie when the response is still writable.
|
|
*/
|
|
const oboIdentityContext = createAuthIdentityContext({
|
|
user: options.req?.user,
|
|
tenantId: getTenantId(),
|
|
});
|
|
const upstreamTokenProvider = createOpenIDSessionTokenProvider({
|
|
req: options.req,
|
|
res: options.res,
|
|
user: options.req?.user,
|
|
identityContext: oboIdentityContext,
|
|
tokenPreference: 'access_token',
|
|
});
|
|
|
|
for (const [serverName, toolConfigs] of Object.entries(requestedMCPTools)) {
|
|
index++;
|
|
/** @type {LCAvailableTools} */
|
|
let availableTools = options.mcpAvailableTools?.[serverName];
|
|
for (const config of toolConfigs) {
|
|
try {
|
|
if (failedMCPServers.has(serverName)) {
|
|
continue;
|
|
}
|
|
const mcpParams = {
|
|
mcpPermissionContext,
|
|
index,
|
|
signal,
|
|
user: safeUser,
|
|
userMCPAuthMap,
|
|
configServers,
|
|
requestBody: options.requestBody ?? options.req?.body,
|
|
requestScopedConnections,
|
|
res: options.res,
|
|
upstreamTokenProvider,
|
|
oboIdentityContext,
|
|
streamId: options.req?._resumableStreamId || null,
|
|
jobCreatedAt: options.jobCreatedAt,
|
|
model: agent?.model ?? model,
|
|
serverName: config.serverName,
|
|
provider: agent?.provider ?? endpoint,
|
|
config: config.config,
|
|
};
|
|
|
|
if (config.type === 'all' && toolConfigs.length === 1) {
|
|
/** Handle async loading for single 'all' tool config */
|
|
mcpToolPromises.push(
|
|
createMCPTools(mcpParams).catch((error) => {
|
|
logger.error(`Error loading ${serverName} tools:`, error);
|
|
return null;
|
|
}),
|
|
);
|
|
continue;
|
|
}
|
|
if (!availableTools) {
|
|
try {
|
|
availableTools = await getMCPServerTools(safeUser.id, serverName, config.config);
|
|
} catch (error) {
|
|
logger.error(`Error fetching available tools for MCP server ${serverName}:`, error);
|
|
}
|
|
}
|
|
|
|
/** Handle synchronous loading */
|
|
const mcpTool =
|
|
config.type === 'all'
|
|
? await createMCPTools(mcpParams)
|
|
: await createMCPTool({
|
|
...mcpParams,
|
|
availableTools,
|
|
toolKey: config.toolKey,
|
|
onAvailableTools: (tools) => {
|
|
availableTools = tools;
|
|
},
|
|
});
|
|
|
|
if (Array.isArray(mcpTool)) {
|
|
loadedTools.push(...mcpTool);
|
|
} else if (mcpTool) {
|
|
loadedTools.push(mcpTool);
|
|
} else {
|
|
failedMCPServers.add(serverName);
|
|
logger.warn(
|
|
`MCP tool creation failed for "${config.toolKey}", server may be unavailable or unauthenticated.`,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
logger.error(`Error loading MCP tool for server ${serverName}:`, error);
|
|
}
|
|
}
|
|
}
|
|
loadedTools.push(...(await Promise.all(mcpToolPromises)).flatMap((plugin) => plugin || []));
|
|
return { loadedTools, toolContextMap, dynamicToolContextMap, primedCodeFiles };
|
|
};
|
|
|
|
module.exports = {
|
|
loadToolWithAuth,
|
|
validateTools,
|
|
loadTools,
|
|
};
|