mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-02 12:12:17 +00:00
* 🚧 fix: Narrow Chat MCP Selections to What the Picker May Offer The chat MCP picker offers a server only when the operator has not hidden it (`chatMenu: false`) and the user reaches it directly rather than through an agent (`consumeOnly`). Nothing enforced either condition on the request, so a stale client, a replayed body, or a hand-written one could name any server and get its tools — `consumeOnly` in particular is a permission the registry derives per user, so ignoring it let a user reach in plain chat a server they had only been granted through an agent. Narrow the picker's selection in the two ephemeral loaders, against the same predicate the client's `selectableServers` uses. The resolver is injected, so `packages/api` stays free of the registry and the loaders keep their existing `deps` shape. Provenance is why this lives in the loaders rather than at the tool-resolution chokepoint: only here is a server name known to have come from the picker. Servers a model spec pins are the operator's own choice and are added after the narrowing, so pinning a chat-hidden server to a spec keeps working. `chatMenu` only ever comes from the config tier, so the overlay settles it with no lookup at all. Lookups for the rest run concurrently and are cached per server and user. A name the registry cannot resolve — request-tier, declared on the body and never registered — is kept, as is one whose lookup fails: this narrows an already-authenticated selection and is not the authorization boundary. * 📝 docs: Say What chatMenu Now Bounds The schema still described `chatMenu` as dropdown visibility alone, which is misleading now that it also bars a server from the chat selection a request carries. Spell out both halves, and what it deliberately does not restrict: agents, and servers a model spec pins. * 🛡️ fix: Close Four Gaps in the Chat MCP Narrowing Dedupe before resolving. The selection is request-supplied and the loaders used to build a `Set` immediately; mapping the raw array first let one body repeat a name enough times to launch a resolver — registry, cache, and ACL reads, with no single-flight — per occurrence. Resolve names through the tool-loading aliases. A configured `private server` is addressable as `private_server` downstream, so an exact-key lookup let the normalized spelling walk past a `chatMenu: false` check and still load tools. Names are returned as sent; only the decision is canonicalized. Let the request overlay settle `chatMenu`. The config tier is where the flag lives and is what the picker itself was built from, so an overlay that re-enables a server now outranks the durable config the registry returns, which was silently dropping a valid selection. `consumeOnly` still comes from the registry. Narrow the request body, not just the loader's copy. `applyContextToAgent` reads `req.body.ephemeralAgent.mcp` directly and prefers it over the agent's tools, so a hidden server's `serverInstructions` reached the model context even after its tools were dropped. * 🧭 fix: Ask the Registry Which MCP Servers the Picker May Offer Three rounds of review found the same mistake in three disguises: this narrowing re-derived the registry's tier precedence instead of asking for it. A config entry was treated as authoritative over a user-DB or process-backed server of the same name; the alias map was built from config names only, so a DB server named `private_server` was misrouted to a config `private server`; and the overlay short-circuit ran before any of that could be consulted. Resolve the accessible set through `resolveAllMcpConfigs` instead — the same call behind `GET /api/mcp/servers`, so what the request may use and what the picker was offered come from one place and cannot drift. Precedence, cross-tier name collisions, and the config overlay are the registry's job again, and the selectability test is a single flag check over what it returns. The result is smaller: no overlay branch, no per-server lookups, one catalog read regardless of how long the selection is, and aliases built over the whole accessible set so an exact name always outranks another server's normalized form. Publish the servers actually in play back onto the request body, spec pins included. `applyContextToAgent` prefers that list over the agent's tools, so narrowing to the picker selection alone had started dropping a spec-pinned server's `serverInstructions` while suppressing a hidden one's.
248 lines
8.7 KiB
JavaScript
248 lines
8.7 KiB
JavaScript
const { logger } = require('@librechat/data-schemas');
|
|
const {
|
|
ADDED_AGENT_ID,
|
|
initializeAgent,
|
|
validateAgentModel,
|
|
resolveAgentScopedSkillIds,
|
|
resolveModelSpecSkillIds,
|
|
loadAddedAgent: loadAddedAgentFn,
|
|
} = require('@librechat/api');
|
|
const { isEphemeralAgentId } = require('librechat-data-provider');
|
|
const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');
|
|
const { getMCPServerTools } = require('~/server/services/Config');
|
|
const { getAccessibleMcpServerNames, getAccessibleMCPServers } = require('~/server/services/MCP');
|
|
const { isFatalAgentInitializationError } = require('~/server/services/ToolService');
|
|
const { getSkillDbMethods, canAuthorSkillFiles } = require('./skillDeps');
|
|
const db = require('~/models');
|
|
|
|
const loadAddedAgent = (params) =>
|
|
loadAddedAgentFn(params, {
|
|
getAgent: db.getAgent,
|
|
getMCPServerTools,
|
|
getAccessibleMCPServers,
|
|
});
|
|
|
|
/**
|
|
* Process addedConvo for parallel agent execution.
|
|
* Creates a parallel agent config from an added conversation.
|
|
*
|
|
* When an added agent has no incoming edges, it becomes a start node
|
|
* and runs in parallel with the primary agent automatically.
|
|
*
|
|
* Edge cases handled:
|
|
* - Primary agent has edges (handoffs): Added agent runs in parallel with primary,
|
|
* but doesn't participate in the primary's handoff graph
|
|
* - Primary agent has agent_ids (legacy chain): Added agent runs in parallel with primary,
|
|
* but doesn't participate in the chain
|
|
* - Primary agent has both: Added agent is independent, runs parallel from start
|
|
*
|
|
* @param {Object} params
|
|
* @param {import('express').Request} params.req
|
|
* @param {import('express').Response} params.res
|
|
* @param {Object} params.endpointOption - The endpoint option containing addedConvo
|
|
* @param {Object} params.modelsConfig - The models configuration
|
|
* @param {Function} params.logViolation - Function to log violations
|
|
* @param {Function} params.loadTools - Function to load agent tools
|
|
* @param {Array} params.requestFiles - Request files
|
|
* @param {string} params.conversationId - The conversation ID
|
|
* @param {string} [params.parentMessageId] - The parent message ID for thread filtering
|
|
* @param {import('@librechat/api').MCPRuntimeRequestBody} [params.requestBody]
|
|
* @param {Set} params.allowedProviders - Set of allowed providers
|
|
* @param {Map} params.agentConfigs - Map of agent configs to add to
|
|
* @param {string} params.primaryAgentId - The primary agent ID
|
|
* @param {Object|undefined} params.userMCPAuthMap - User MCP auth map to merge into
|
|
* @param {Array} [params.accessibleSkillIds] - Full VIEW-accessible skill IDs for the user
|
|
* @param {Array} [params.editableSkillIds] - Full EDIT-accessible skill IDs for the user
|
|
* @param {boolean} [params.skillsCapabilityEnabled] - Whether endpoint Skills are enabled
|
|
* @param {boolean} [params.ephemeralSkillsToggle] - Per-request ephemeral Skills badge state
|
|
* @param {boolean} [params.skillCreateAllowed] - Whether the user can create Skills
|
|
* @param {Record<string, boolean>} [params.skillStates] - Per-user Skill active overrides
|
|
* @param {boolean} [params.defaultActiveOnShare] - Default active state for shared Skills
|
|
* @param {boolean} [params.codeEnvAvailable] - `execute_code` capability flag;
|
|
* forwarded verbatim to the added agent's `initializeAgent`. @see
|
|
* InitializeAgentParams.codeEnvAvailable for full semantics.
|
|
* @param {boolean} [params.statefulSessionsAvailable] - `stateful_code_sessions`
|
|
* capability flag; forwarded verbatim alongside `codeEnvAvailable`.
|
|
* @returns {Promise<{userMCPAuthMap: Object|undefined}>} The updated userMCPAuthMap
|
|
*/
|
|
const processAddedConvo = async ({
|
|
req,
|
|
res,
|
|
endpointOption,
|
|
modelsConfig,
|
|
logViolation,
|
|
loadTools,
|
|
requestFiles,
|
|
conversationId,
|
|
parentMessageId,
|
|
requestBody,
|
|
allowedProviders,
|
|
agentConfigs,
|
|
primaryAgentId,
|
|
primaryAgent,
|
|
userMCPAuthMap,
|
|
accessibleSkillIds = [],
|
|
editableSkillIds = [],
|
|
skillsCapabilityEnabled = false,
|
|
ephemeralSkillsToggle = false,
|
|
skillCreateAllowed = false,
|
|
skillStates,
|
|
defaultActiveOnShare,
|
|
codeEnvAvailable,
|
|
backgroundToolsAvailable,
|
|
toolIntentsAvailable,
|
|
statefulSessionsAvailable,
|
|
memoryAvailable,
|
|
}) => {
|
|
const addedConvo = endpointOption.addedConvo;
|
|
if (addedConvo == null) {
|
|
return { userMCPAuthMap };
|
|
}
|
|
|
|
logger.debug('[processAddedConvo] Processing added conversation', {
|
|
model: addedConvo.model,
|
|
agentId: addedConvo.agent_id,
|
|
endpoint: addedConvo.endpoint,
|
|
});
|
|
|
|
try {
|
|
const skillDbMethods = getSkillDbMethods();
|
|
const addedAgent = await loadAddedAgent({ req, conversation: addedConvo, primaryAgent });
|
|
if (!addedAgent) {
|
|
return { userMCPAuthMap };
|
|
}
|
|
|
|
const addedValidation = await validateAgentModel({
|
|
req,
|
|
res,
|
|
modelsConfig,
|
|
logViolation,
|
|
agent: addedAgent,
|
|
});
|
|
|
|
if (!addedValidation.isValid) {
|
|
logger.warn(
|
|
`[processAddedConvo] Added agent validation failed: ${addedValidation.error?.message}`,
|
|
);
|
|
return { userMCPAuthMap };
|
|
}
|
|
|
|
const selectedModelSpec =
|
|
addedConvo.spec && Array.isArray(req.config?.modelSpecs?.list)
|
|
? req.config.modelSpecs.list.find((modelSpec) => modelSpec.name === addedConvo.spec)
|
|
: null;
|
|
|
|
if (
|
|
addedAgent &&
|
|
isEphemeralAgentId(addedAgent.id) &&
|
|
selectedModelSpec &&
|
|
Object.hasOwn(selectedModelSpec, 'skills')
|
|
) {
|
|
if (selectedModelSpec.skills === true) {
|
|
addedAgent.skills_enabled = true;
|
|
delete addedAgent.skills;
|
|
} else if (selectedModelSpec.skills === false) {
|
|
addedAgent.skills_enabled = false;
|
|
addedAgent.skills = [];
|
|
} else if (Array.isArray(selectedModelSpec.skills)) {
|
|
const resolvedSkillIds = await resolveModelSpecSkillIds({
|
|
names: selectedModelSpec.skills,
|
|
accessibleSkillIds,
|
|
getSkillByName: skillDbMethods.getSkillByName,
|
|
});
|
|
addedAgent.skills_enabled = true;
|
|
addedAgent.skills = resolvedSkillIds.map((id) => id.toString());
|
|
}
|
|
}
|
|
|
|
const scopedSkillIds = resolveAgentScopedSkillIds({
|
|
agent: addedAgent,
|
|
accessibleSkillIds,
|
|
skillsCapabilityEnabled,
|
|
ephemeralSkillsToggle,
|
|
});
|
|
const scopedEditableSkillIds = resolveAgentScopedSkillIds({
|
|
agent: addedAgent,
|
|
accessibleSkillIds: editableSkillIds,
|
|
skillsCapabilityEnabled,
|
|
ephemeralSkillsToggle,
|
|
});
|
|
|
|
const addedConfig = await initializeAgent(
|
|
{
|
|
req,
|
|
res,
|
|
loadTools,
|
|
requestFiles,
|
|
conversationId,
|
|
parentMessageId,
|
|
requestBody,
|
|
agent: addedAgent,
|
|
endpointOption,
|
|
allowedProviders,
|
|
accessibleSkillIds: scopedSkillIds,
|
|
skillAuthoringAvailable: canAuthorSkillFiles({
|
|
agent: addedAgent,
|
|
scopedEditableSkillIds,
|
|
skillCreateAllowed,
|
|
skillsCapabilityEnabled,
|
|
ephemeralSkillsToggle,
|
|
}),
|
|
codeEnvAvailable,
|
|
backgroundToolsAvailable,
|
|
toolIntentsAvailable,
|
|
statefulSessionsAvailable,
|
|
memoryAvailable,
|
|
skillStates,
|
|
defaultActiveOnShare,
|
|
},
|
|
{
|
|
getFiles: db.getFiles,
|
|
getUserKey: db.getUserKey,
|
|
getMessages: db.getMessages,
|
|
getConvoFiles: db.getConvoFiles,
|
|
getAccessibleMcpServerNames,
|
|
updateFilesUsage: db.updateFilesUsage,
|
|
getUserCodeFiles: db.getUserCodeFiles,
|
|
getUserKeyValues: db.getUserKeyValues,
|
|
getToolFilesByIds: db.getToolFilesByIds,
|
|
getCodeGeneratedFiles: db.getCodeGeneratedFiles,
|
|
filterFilesByAgentAccess,
|
|
listSkillsByAccess: skillDbMethods.listSkillsByAccess,
|
|
listAlwaysApplySkills: skillDbMethods.listAlwaysApplySkills,
|
|
getSkillByName: skillDbMethods.getSkillByName,
|
|
},
|
|
);
|
|
|
|
if (userMCPAuthMap != null) {
|
|
Object.assign(userMCPAuthMap, addedConfig.userMCPAuthMap ?? {});
|
|
} else {
|
|
userMCPAuthMap = addedConfig.userMCPAuthMap;
|
|
}
|
|
|
|
const addedAgentId = addedConfig.id || ADDED_AGENT_ID;
|
|
agentConfigs.set(addedAgentId, addedConfig);
|
|
|
|
// No edges needed - agent without incoming edges becomes a start node
|
|
// and runs in parallel with the primary agent automatically.
|
|
// This is independent of any edges/agent_ids the primary agent has.
|
|
|
|
logger.debug(
|
|
`[processAddedConvo] Added parallel agent: ${addedAgentId} (primary: ${primaryAgentId}, ` +
|
|
`primary has edges: ${!!endpointOption.edges}, primary has agent_ids: ${!!endpointOption.agent_ids})`,
|
|
);
|
|
|
|
return { userMCPAuthMap };
|
|
} catch (err) {
|
|
if (isFatalAgentInitializationError(err)) {
|
|
throw err;
|
|
}
|
|
logger.error('[processAddedConvo] Error processing addedConvo for parallel agent', err);
|
|
return { userMCPAuthMap };
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
processAddedConvo,
|
|
ADDED_AGENT_ID,
|
|
};
|