LibreChat/packages/api/src/agents/context.ts
Danny Avila 67b7b441b2
🛂 feat: Filter Model-Bound Content by Source (#14425)
* feat: introduce optional content protection seam

* feat: enforce source-aware content filters

* feat: complete source-aware content enforcement

* test: activate skill file-text fail-close fixtures

* fix: harden source-aware content filters

* fix: harden model-bound content filtering

* fix: preserve legacy filters and generated files

* fix: inspect shared scalar metadata

* test: align mocks with current dev dependencies

* feat: add persisted content filter safeguards

* feat: complete source-aware content filter enforcement

* fix: move resume content preflight into TypeScript

* fix: close content inspection edge cases

* fix: harden content protection boundaries

* fix: complete content protection safeguards

* test: align persisted memory filter coverage

* fix: reconcile content protection with current dev

* fix: reconcile content protection with latest dev

* fix: close content protection review gaps

* fix: enforce source-aware provider boundaries

* fix: preserve legacy PII preflight semantics

* test: stabilize stored branch preflight fixture

* fix: defer agent writes until protected model admission

* perf: harden source-aware model-bound filtering

* fix: canonicalize provider lineage before validation

* fix: satisfy model-bound callback type checks

* perf: Bound content protection filtering work

* fix: Bound submission array traversal

* fix: Stabilize bounded content snapshots

* fix: Scope model-bound traversal overflows

* fix: Preserve scoped content inspection

* fix: Accumulate aggregate traversal scopes

* fix: centralize content policy boundaries

* test: align deferred tool policy context

* test: align controller policy mocks

* style: normalize content protection imports

* fix: close content policy review gaps

* fix: narrow active skill policy config

* fix: address content protection review boundaries

* fix: retain exact provenance overflow sentinel

* fix: preserve literal and scoped provenance updates

* fix: narrow persisted edit provenance

* fix: isolate exact overflow attribution

* fix: centralize stored prompt protection

* fix: fail closed on incomplete transcript evidence

* fix: align canonical transcript routing

* refactor: centralize content policy preflights

* fix: isolate upload policy error typing

* style: sort policy preflight imports

* refactor: centralize content policy boundaries
2026-08-21 22:43:32 -04:00

197 lines
6.2 KiB
TypeScript

import { Constants } from 'librechat-data-provider';
import { DynamicStructuredTool } from '@librechat/agents/langchain/tools';
import type { Agent, TEphemeralAgent } from 'librechat-data-provider';
import type { LCTool } from '@librechat/agents';
import type { Logger } from 'winston';
import type { ParsedServerConfig } from '~/mcp/types';
import type { MCPManager } from '~/mcp/MCPManager';
/**
* Agent type with optional tools array that can contain DynamicStructuredTool or string.
* For context operations, we only require id and instructions, other Agent fields are optional.
*/
export type AgentWithTools = Pick<Agent, 'id'> &
Partial<Omit<Agent, 'id' | 'tools'>> & {
tools?: Array<DynamicStructuredTool | string>;
/** Serializable tool definitions for event-driven mode */
toolDefinitions?: LCTool[];
};
/**
* Extracts unique MCP server names from an agent's tools or tool definitions.
* Supports both full tool instances (tools) and serializable definitions (toolDefinitions).
* @param agent - The agent with tools and/or tool definitions
* @returns Array of unique MCP server names
*/
export function extractMCPServers(agent: AgentWithTools): string[] {
const mcpServers = new Set<string>();
/** Check tool instances (non-event-driven mode) */
if (agent?.tools?.length) {
for (const tool of agent.tools) {
if (tool instanceof DynamicStructuredTool && tool.name.includes(Constants.mcp_delimiter)) {
const carried = (tool as { mcpRawServerName?: string }).mcpRawServerName;
const serverName = carried ?? tool.name.split(Constants.mcp_delimiter).pop();
if (serverName) {
mcpServers.add(serverName);
}
}
}
}
/** Check tool definitions (event-driven mode) */
if (agent?.toolDefinitions?.length) {
for (const toolDef of agent.toolDefinitions) {
if (toolDef.name?.includes(Constants.mcp_delimiter)) {
const serverName = toolDef.serverName ?? toolDef.name.split(Constants.mcp_delimiter).pop();
if (serverName) {
mcpServers.add(serverName);
}
}
}
}
return Array.from(mcpServers);
}
/**
* Fetches MCP instructions for the given server names.
* @param {string[]} mcpServers - Array of MCP server names
* @param {MCPManager} mcpManager - MCP manager instance
* @param {Logger} [logger] - Optional logger instance
* @returns {Promise<string>} MCP instructions string, empty if none
*/
export async function getMCPInstructionsForServers(
mcpServers: string[],
mcpManager: MCPManager,
logger?: Logger,
configServers?: Record<string, ParsedServerConfig>,
): Promise<string> {
if (!mcpServers.length) {
return '';
}
try {
const mcpInstructions = await mcpManager.formatInstructionsForContext(
mcpServers,
configServers,
);
if (mcpInstructions && logger) {
logger.debug('[AgentContext] Fetched MCP instructions', {
serverCount: mcpServers.length,
});
}
return mcpInstructions || '';
} catch {
if (logger) {
logger.error('[AgentContext] Failed to get MCP instructions');
}
return '';
}
}
/**
* Builds stable instructions for an agent by combining agent-specific context and MCP context.
* Order: baseInstructions -> mcpInstructions
*
* @param {Object} params
* @param {string} [params.baseInstructions] - Agent's base instructions
* @param {string} [params.mcpInstructions] - Agent's MCP server instructions
* @returns {string | undefined} Combined instructions, or undefined if empty
*/
export function buildAgentInstructions({
baseInstructions,
mcpInstructions,
}: {
baseInstructions?: string;
mcpInstructions?: string;
}): string | undefined {
const parts = [baseInstructions, mcpInstructions].filter(Boolean);
const combined = parts.join('\n\n').trim();
return combined || undefined;
}
/**
* Builds dynamic system-tail instructions for an agent.
* Order: existing additional instructions -> shared run context.
*/
export function buildAgentAdditionalInstructions({
additionalInstructions,
sharedRunContext,
}: {
additionalInstructions?: string;
sharedRunContext?: string;
}): string | undefined {
const parts = [additionalInstructions, sharedRunContext].filter(Boolean);
const combined = parts.join('\n\n').trim();
return combined || undefined;
}
/**
* Applies run context and MCP instructions to an agent's configuration.
* Mutates the agent object in place.
*
* @param {Object} params
* @param {Agent} params.agent - The agent to update
* @param {string} params.sharedRunContext - Run-level shared context
* @param {MCPManager} params.mcpManager - MCP manager instance
* @param {Object} [params.ephemeralAgent] - Ephemeral agent config (for MCP override)
* @param {string} [params.agentId] - Agent ID for logging
* @param {Logger} [params.logger] - Optional logger instance
* @returns {Promise<void>}
*/
export async function applyContextToAgent({
agent,
sharedRunContext,
mcpManager,
ephemeralAgent,
agentId,
logger,
configServers,
}: {
agent: AgentWithTools;
sharedRunContext: string;
mcpManager: MCPManager;
ephemeralAgent?: TEphemeralAgent;
agentId?: string;
logger?: Logger;
configServers?: Record<string, ParsedServerConfig>;
}): Promise<void> {
const baseInstructions = agent.instructions || '';
const additionalInstructions = agent.additional_instructions || '';
try {
const mcpServers = ephemeralAgent?.mcp?.length ? ephemeralAgent.mcp : extractMCPServers(agent);
const mcpInstructions = await getMCPInstructionsForServers(
mcpServers,
mcpManager,
logger,
configServers,
);
agent.instructions = buildAgentInstructions({
baseInstructions,
mcpInstructions,
});
agent.additional_instructions = buildAgentAdditionalInstructions({
additionalInstructions,
sharedRunContext,
});
if (agentId && logger) {
logger.debug('[AgentContext] Applied context to agent');
}
} catch {
agent.instructions = buildAgentInstructions({
baseInstructions,
mcpInstructions: '',
});
agent.additional_instructions = buildAgentAdditionalInstructions({
additionalInstructions,
sharedRunContext,
});
if (logger) {
logger.error('[AgentContext] Failed to apply context; using base instructions only');
}
}
}