mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-09-01 19:41:32 +00:00
* 🔌 feat: Add Agent Plugins v1.0.0 Support Implements the Agent Plugins 1.0.0 specification so LibreChat can load portable plugin packages: a `plugin.json` manifest, `skills/` holding Agent Skills, `mcp.json` describing MCP servers, and reverse-domain extension directories. - Validate the closed `plugin.json` schema, selecting rules from `$schema` without retrieving it. Unknown top-level fields and a non-object `extensions` field are reported and ignored; every other violation rejects the plugin. - Enforce plugin-root containment through realpath, including for paths whose leaf does not exist, and apply the narrowest failure boundary per component. - Map `mcp.json` onto LibreChat MCP options across stdio, Streamable HTTP, and legacy HTTP+SSE, bypassing the config loader's `${VAR}` process-env expansion so plugin values never resolve against the server environment. - Expand only `${PLUGIN_ROOT}` and `${PLUGIN_DATA}`, once and non-recursively, in `args`, `env` values, and `cwd`; supply both variables to the subprocess after configured `env`, and reject entries that declare them. - Discover skills from the immediate children of `skills/` only, reusing the deployment skill loader so plugin skills are ordinary deployment skills with a distinct id namespace. - Read LibreChat's `ai.librechat` extension directory and hand `hooks/hooks.json` to the Claude hook compatibility layer. - Load operator-installed plugins from `DEPLOYMENT_PLUGINS_DIR` at startup, merging their skills into the deployment skill registry and their MCP servers into the app config. Plugins never displace a configured server or deployment skill. - Add `cwd` to the stdio MCP transport, which the specification requires and LibreChat did not previously support. Component failures stay isolated: a malformed `mcp.json`, an invalid skill, or a bad hooks document never prevents the rest of a plugin from loading. * 🔒 fix: Contain Agent Plugins config at the runtime boundary Review of #14704 surfaced that every real finding sat where the loader's output crosses into LibreChat's existing runtime, not in the specification logic. The loader deliberately left plugin placeholders literal, but downstream layers re-processed the same fields and undid it. - Mark plugin MCP configuration with `source: 'plugin'` and return it verbatim from `processMCPEnv`. Without this a remote plugin could declare `Authorization: Bearer ${OPENAI_API_KEY}` and receive host credentials at its own origin. The gate reads the configuration rather than a caller-supplied flag, so no future call site can reintroduce the leak by omitting it. - Skip `preProcessGraphTokens` for plugin configuration as well; it resolves placeholders into headers, url, and args on the same path. - Reject plugin server names that change under `normalizeServerName`. Tool keys embed the normalized name while request-time resolution uses the raw name, so an unstable name published tools that nothing could resolve. - Reject `__proto__`, `constructor`, and `prototype` as server names, and merge plugin servers with `Object.defineProperty` and an own-property conflict check, so a package cannot reach a prototype setter or collide with an inherited member. - Enforce manifest-name uniqueness before components are accepted; two packages sharing a name would share one `PLUGIN_DATA` directory. - Isolate a failed data-directory creation to the single plugin instead of rejecting the whole scan. - Prefix rejected-plugin diagnostics with the directory, which is the only identifier a package without a valid manifest has. - Type extension namespace contents as JSON rather than `unknown`, and correct the header field-value comment to name obs-text. Verified end to end from the built package: a plugin declaring an environment placeholder in a header reaches the transport with the placeholder intact while operator-authored configuration still resolves normally. * 🔇 fix: Report Agent Plugin hooks that will not run The loader reads `ai.librechat/hooks/hooks.json`, but nothing registers the resulting plan, and startup supplies no hook capabilities. A package declaring hooks was therefore accepted in silence, leaving an operator to believe the hooks ran. Detect the document when no capabilities are registered and report it as unsupported, so the limitation is visible in startup diagnostics rather than inferred from behavior that never happens. * 🧯 test: Restore MCP startup test mocks Carries the two mock additions from #14711 so this branch can prove itself green. `initializeMCPs` now calls `syncStaticTools`, which the server startup specs do not stub, so they fail on every branch that has not picked this up. Drops out of the rebase once #14711 lands. Co-authored-by: Danny Avila <danny@librechat.ai>
148 lines
5.1 KiB
JavaScript
148 lines
5.1 KiB
JavaScript
const mongoose = require('mongoose');
|
|
const { logger } = require('@librechat/data-schemas');
|
|
const {
|
|
registerShutdownTask,
|
|
setMCPToolsChangedHandler,
|
|
getDeploymentPluginMcpServers,
|
|
setMCPToolsChangedGenerationHandler,
|
|
setMCPToolsChangedGenerationRenewalHandler,
|
|
setMCPToolsChangedRevisionHandler,
|
|
} = require('@librechat/api');
|
|
const { syncStaticTools, mergeAppTools, getAppConfig } = require('./Config');
|
|
const {
|
|
getMCPToolsCacheGeneration,
|
|
renewMCPToolsCacheGeneration,
|
|
getNextAppToolsPublicationRevision,
|
|
updateMCPServerTools,
|
|
} = require('./Config/mcp');
|
|
const { createMCPServersRegistry, createMCPManager } = require('~/config');
|
|
|
|
/**
|
|
* Resolves the current request's effective MCP allowlists from the merged (tenant-scoped)
|
|
* config. The registry calls this per inspection/connection so admin-panel `mcpSettings`
|
|
* overrides are honored without a restart. Tenant comes from the ALS context inside
|
|
* `getAppConfig`; `userId`/`role` pick up user/role-scoped overrides when an actor exists.
|
|
* @param {{ userId?: string, role?: string }} [ctx]
|
|
*/
|
|
async function resolveMCPAllowlists(ctx) {
|
|
const appConfig = await getAppConfig({ role: ctx?.role, userId: ctx?.userId });
|
|
return {
|
|
allowedDomains: appConfig?.mcpSettings?.allowedDomains,
|
|
allowedAddresses: appConfig?.mcpSettings?.allowedAddresses,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Refreshes one server's tools after it reported `notifications/tools/list_changed`.
|
|
*
|
|
* A server that builds tools at runtime is the case this exists for: without it the tool list
|
|
* stayed frozen at connection time and only a restart picked up the change (#7117). The list is
|
|
* re-fetched from the live connection and written over that server's cache entry, so tools that
|
|
* disappeared stop being advertised too.
|
|
*/
|
|
async function refreshChangedServerTools({
|
|
serverName,
|
|
userId,
|
|
tools,
|
|
serverConfig,
|
|
publicationGeneration,
|
|
publicationRevision,
|
|
}) {
|
|
await updateMCPServerTools({
|
|
userId,
|
|
serverName,
|
|
tools,
|
|
serverConfig,
|
|
...(publicationGeneration && { publicationGeneration }),
|
|
...(publicationRevision && { publicationRevision }),
|
|
});
|
|
const toolCount = tools.length;
|
|
logger.info(
|
|
`[MCP][${serverName}] Tool list changed; refreshed ${toolCount} ${toolCount === 1 ? 'tool' : 'tools'}${userId ? ` for user ${userId}` : ''}`,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Merges Agent Plugins MCP servers under the configured servers. A plugin never
|
|
* displaces a server the operator declared in `librechat.yaml`.
|
|
*/
|
|
function withPluginServers(configured) {
|
|
const pluginServers = getDeploymentPluginMcpServers();
|
|
const names = Object.keys(pluginServers);
|
|
if (names.length === 0) {
|
|
return configured;
|
|
}
|
|
|
|
const merged = { ...configured };
|
|
for (const name of names) {
|
|
/** Own-property check: an inherited member like `toString` is not a conflict. */
|
|
if (Object.hasOwn(merged, name)) {
|
|
logger.warn(
|
|
`[MCP] Plugin server "${name}" conflicts with a configured server and was skipped.`,
|
|
);
|
|
continue;
|
|
}
|
|
/** Defined rather than assigned so a name like `__proto__` cannot reach a setter. */
|
|
Object.defineProperty(merged, name, {
|
|
value: pluginServers[name],
|
|
enumerable: true,
|
|
writable: true,
|
|
configurable: true,
|
|
});
|
|
}
|
|
return merged;
|
|
}
|
|
|
|
/**
|
|
* Initialize MCP servers
|
|
*/
|
|
async function initializeMCPs() {
|
|
const appConfig = await getAppConfig({ baseOnly: true });
|
|
const mcpServers = withPluginServers(appConfig.mcpConfig);
|
|
|
|
try {
|
|
createMCPServersRegistry(
|
|
mongoose,
|
|
appConfig?.mcpSettings?.allowedDomains,
|
|
appConfig?.mcpSettings?.allowedAddresses,
|
|
resolveMCPAllowlists,
|
|
);
|
|
} catch (error) {
|
|
logger.error('[MCP] Failed to initialize MCPServersRegistry:', error);
|
|
throw error;
|
|
}
|
|
|
|
try {
|
|
const mcpManager = await createMCPManager(mcpServers || {});
|
|
setMCPToolsChangedHandler(refreshChangedServerTools);
|
|
setMCPToolsChangedGenerationHandler(getMCPToolsCacheGeneration);
|
|
setMCPToolsChangedGenerationRenewalHandler(renewMCPToolsCacheGeneration);
|
|
setMCPToolsChangedRevisionHandler(({ serverName, configGeneration }) =>
|
|
getNextAppToolsPublicationRevision(serverName, configGeneration),
|
|
);
|
|
registerShutdownTask('MCP app connections', () => mcpManager.disconnectAppServers());
|
|
|
|
if (mcpServers && Object.keys(mcpServers).length > 0) {
|
|
const mcpTools = (await mcpManager.getAppToolFunctions()) || {};
|
|
try {
|
|
await mergeAppTools(mcpTools, appConfig.availableTools || {});
|
|
} finally {
|
|
await mcpManager.connectAppServers();
|
|
}
|
|
const serverCount = Object.keys(mcpServers).length;
|
|
const toolCount = Object.keys(mcpTools).length;
|
|
logger.info(
|
|
`[MCP] Initialized with ${serverCount} configured ${serverCount === 1 ? 'server' : 'servers'} and ${toolCount} ${toolCount === 1 ? 'tool' : 'tools'}.`,
|
|
);
|
|
} else {
|
|
await syncStaticTools(appConfig.availableTools || {});
|
|
logger.debug('[MCP] No servers configured. MCPManager ready for UI-based servers.');
|
|
}
|
|
} catch (error) {
|
|
logger.error('[MCP] Failed to initialize MCPManager:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
module.exports = initializeMCPs;
|
|
module.exports.refreshChangedServerTools = refreshChangedServerTools;
|