Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔌 fix: Preserve MCP `serverInstructions` Declaration Through Inspection (#14815)
Danny Avila0654efb7edef
diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.tsindex 162cc32277..6741ded3aa 100644--- a/packages/api/src/mcp/MCPManager.ts+++ b/packages/api/src/mcp/MCPManager.ts@@ -18,6 +18,7 @@ import {requiresEphemeralUserConnection,requiresOAuthMachinery,requiresUserScopedConnection,+ resolveServerInstructions,} from './utils';import { getMCPAppToolsPublicationGeneration, getMCPToolsChangedGeneration } from './toolsChanged';import { MCPServersInitializer } from './registry/MCPServersInitializer';@@ -528,8 +529,9 @@ export class MCPManager extends UserConnectionManager {configServers,);for (const [serverName, config] of Object.entries(configs)) {- if (config.serverInstructions != null) {- instructions[serverName] = config.serverInstructions as string;+ const resolved = resolveServerInstructions(config);+ if (resolved != null) {+ instructions[serverName] = resolved;}}if (!serverNames) return instructions;diff --git a/packages/api/src/mcp/registry/MCPServerInspector.ts b/packages/api/src/mcp/registry/MCPServerInspector.tsindex f191bc230e..3281cdf6be 100644--- a/packages/api/src/mcp/registry/MCPServerInspector.ts+++ b/packages/api/src/mcp/registry/MCPServerInspector.ts@@ -150,7 +150,7 @@ export class MCPServerInspector {private async fetchServerInstructions(): Promise<void> {if (isEnabled(this.config.serverInstructions)) {- this.config.serverInstructions = this.connection!.client.getInstructions();+ this.config.resolvedInstructions = this.connection!.client.getInstructions();}}diff --git a/packages/api/src/mcp/registry/MCPServersInitializer.ts b/packages/api/src/mcp/registry/MCPServersInitializer.tsindex b4595a74d4..4cdd148383 100644--- a/packages/api/src/mcp/registry/MCPServersInitializer.ts+++ b/packages/api/src/mcp/registry/MCPServersInitializer.ts@@ -2,8 +2,8 @@ import { createHash } from 'crypto';import { logger } from '@librechat/data-schemas';import type * as t from '~/mcp/types';import { registryStatusCache as statusCache } from './cache/RegistryStatusCache';+import { resolveServerInstructions, sanitizeUrlForLogging } from '~/mcp/utils';import { MCPServersRegistry } from './MCPServersRegistry';-import { sanitizeUrlForLogging } from '~/mcp/utils';import { withTimeout } from '~/utils';import { isLeader } from '~/cluster';@@ -20,9 +20,11 @@ const DEFAULT_FOLLOWER_RETRY_MS = 3000;* Without it, a rolling restart on a Redis-backed cluster leaves the persisted* `INITIALIZED_CONFIG_HASH` matching the unchanged config, so replacement* followers short-circuit on the stale status and never re-tag entries written- * by the previous version. Bumped to 2 for plugin-provenance preservation.+ * by the previous version. Bumped to 3 so cached entries whose `serverInstructions` still holds+ * inspector-fetched text are rewritten with the declaration preserved and the text moved to+ * `resolvedInstructions`.*/-const REGISTRY_STORAGE_SCHEMA_VERSION = 2;+const REGISTRY_STORAGE_SCHEMA_VERSION = 3;const parseDurationMs = (value: string | undefined,@@ -175,22 +177,18 @@ export class MCPServersInitializer {logger.info(`${prefix} Tools: ${config.tools}`);logger.info(`${prefix} Server Instructions: ${MCPServersInitializer.formatInstructionsForLogging(- config.serverInstructions,+ resolveServerInstructions(config),)}`,);logger.info(`${prefix} Initialized in: ${config.initDuration ?? 'N/A'}ms`);logger.info(`${prefix} -------------------------------------------------┘`);}- private static formatInstructionsForLogging(instructions?: string | boolean): string {+ private static formatInstructionsForLogging(instructions?: string): string {if (!instructions) {return 'N/A';}- if (typeof instructions !== 'string') {- return 'configured';- }-return `configured (${instructions.length} chars)`;}diff --git a/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.tsindex 7b5d62d03f..b3f6aaf1f4 100644--- a/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts+++ b/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts@@ -41,7 +41,8 @@ describe('MCPServerInspector', () => {type: 'stdio',command: 'node',args: ['server.js'],- serverInstructions: 'instructions for test_server',+ serverInstructions: true,+ resolvedInstructions: 'instructions for test_server',requiresOAuth: false,capabilities:'{"tools":{"listChanged":true},"resources":{"listChanged":true},"prompts":{"get":"getPrompts for test_server"}}',@@ -268,6 +269,8 @@ describe('MCPServerInspector', () => {});});+ /** The declaration is preserved verbatim: overwriting it in place made a re-inspected+ * config compare unequal to its own YAML cache entry (issue #14798). */it('should handle serverInstructions as string "true" and fetch from server', async () => {const rawConfig: t.MCPOptions = {type: 'stdio',@@ -287,7 +290,8 @@ describe('MCPServerInspector', () => {type: 'stdio',command: 'node',args: ['server.js'],- serverInstructions: 'instructions for test_server',+ serverInstructions: 'true',+ resolvedInstructions: 'instructions for test_server',requiresOAuth: false,capabilities:'{"tools":{"listChanged":true},"resources":{"listChanged":true},"prompts":{"get":"getPrompts for test_server"}}',@@ -463,7 +467,8 @@ describe('MCPServerInspector', () => {type: 'stdio',command: 'node',args: ['server.js'],- serverInstructions: 'instructions for test_server',+ serverInstructions: true,+ resolvedInstructions: 'instructions for test_server',requiresOAuth: false,capabilities:'{"tools":{"listChanged":true},"resources":{"listChanged":true},"prompts":{"get":"getPrompts for test_server"}}',diff --git a/packages/api/src/mcp/registry/__tests__/serverInstructionsReinspection.test.ts b/packages/api/src/mcp/registry/__tests__/serverInstructionsReinspection.test.tsnew file mode 100644index 0000000000..5e8a502a98--- /dev/null+++ b/packages/api/src/mcp/registry/__tests__/serverInstructionsReinspection.test.ts@@ -0,0 +1,143 @@+import type * as t from '~/mcp/types';+import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';+import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';+import { resolveServerInstructions } from '~/mcp/utils';++jest.mock('~/mcp/registry/MCPServerInspector');+jest.mock('~/mcp/registry/db/ServerConfigsDB', () => ({+ ServerConfigsDB: jest.fn().mockImplementation(() => ({+ get: jest.fn().mockResolvedValue(undefined),+ getAll: jest.fn().mockResolvedValue({}),+ add: jest.fn().mockResolvedValue(undefined),+ update: jest.fn().mockResolvedValue(undefined),+ upsert: jest.fn().mockResolvedValue(undefined),+ remove: jest.fn().mockResolvedValue(undefined),+ reset: jest.fn().mockResolvedValue(undefined),+ })),+}));++const mockMongoose = {} as typeof import('mongoose');+const INSTRUCTIONS = 'Use these tools to do the thing.';++const yamlConfig: t.MCPOptions = {+ type: 'stdio',+ command: 'node',+ args: ['tools.js'],+ serverInstructions: true,+};++/** Mirrors MCPServerInspector: an enabled `serverInstructions` resolves to the text the+ * server advertises, while the declaration itself is left untouched. */+function inspectLikeProduction(rawConfig: t.MCPOptions): t.ParsedServerConfig {+ const parsed = {+ ...rawConfig,+ tools: 'tool_a, tool_b',+ capabilities: '{}',+ } as t.ParsedServerConfig;+ if (parsed.serverInstructions === true || parsed.serverInstructions === 'true') {+ parsed.resolvedInstructions = INSTRUCTIONS;+ }+ return parsed;+}++describe('MCPServersRegistry — YAML servers declaring serverInstructions', () => {+ let registry: MCPServersRegistry;+ let inspectSpy: jest.SpyInstance;++ beforeEach(async () => {+ (MCPServersRegistry as unknown as { instance: undefined }).instance = undefined;+ MCPServersRegistry.createInstance(mockMongoose);+ registry = MCPServersRegistry.getInstance();++ inspectSpy = jest+ .spyOn(MCPServerInspector, 'inspect')+ .mockImplementation(async (_serverName: string, rawConfig: t.MCPOptions) =>+ inspectLikeProduction(rawConfig),+ );++ await registry.reset();+ });++ afterEach(() => {+ inspectSpy.mockClear();+ });++ /** Regression: the inspector used to overwrite `serverInstructions` with the fetched text,+ * so the unmodified-YAML guard compared `true` against a string, re-inspected the server,+ * and produced a second config the live app connection then measured as stale. */+ it('should not re-inspect an unmodified YAML server that declares serverInstructions', async () => {+ await registry.addServer('instr', yamlConfig, 'CACHE');+ inspectSpy.mockClear();++ const result = await registry.ensureConfigServers({ instr: yamlConfig });++ expect(inspectSpy).not.toHaveBeenCalled();+ expect(result).not.toHaveProperty('instr');+ });++ it('should keep the effective config app-eligible for a user-scoped resolve', async () => {+ await registry.addServer('instr', yamlConfig, 'CACHE');++ const configServers = await registry.ensureConfigServers({ instr: yamlConfig });+ const effective = await registry.getServerConfig('instr', 'user-1', configServers);++ expect(effective).toBeDefined();+ expect(await registry.isAppServerConfig('instr', effective!)).toBe(true);+ });++ it('should preserve the operator declaration and expose the fetched text separately', async () => {+ const { config } = await registry.addServer('instr', yamlConfig, 'CACHE');++ expect(config.serverInstructions).toBe(true);+ expect(config.resolvedInstructions).toBe(INSTRUCTIONS);+ expect(resolveServerInstructions(config)).toBe(INSTRUCTIONS);+ });++ it('should still detect a genuine admin override of serverInstructions', async () => {+ await registry.addServer('instr', yamlConfig, 'CACHE');+ inspectSpy.mockClear();++ const overridden: t.MCPOptions = { ...yamlConfig, serverInstructions: 'Custom instructions' };+ const result = await registry.ensureConfigServers({ instr: overridden });++ expect(inspectSpy).toHaveBeenCalledTimes(1);+ expect(result).toHaveProperty('instr');+ });+});++describe('resolveServerInstructions', () => {+ const base = { type: 'stdio', command: 'node' } as t.ParsedServerConfig;++ it('should resolve an enabled declaration to the fetched text', () => {+ expect(+ resolveServerInstructions({+ ...base,+ serverInstructions: true,+ resolvedInstructions: INSTRUCTIONS,+ }),+ ).toBe(INSTRUCTIONS);+ });++ it('should resolve the string "true" to the fetched text', () => {+ expect(+ resolveServerInstructions({+ ...base,+ serverInstructions: 'true',+ resolvedInstructions: INSTRUCTIONS,+ }),+ ).toBe(INSTRUCTIONS);+ });++ it('should use an operator-authored string verbatim', () => {+ expect(resolveServerInstructions({ ...base, serverInstructions: 'Custom' })).toBe('Custom');+ });++ it('should yield nothing when enabled but the server advertised none', () => {+ expect(resolveServerInstructions({ ...base, serverInstructions: true })).toBeUndefined();+ });++ it('should yield nothing when disabled or unset', () => {+ expect(resolveServerInstructions({ ...base, serverInstructions: false })).toBeUndefined();+ expect(resolveServerInstructions(base)).toBeUndefined();+ });+});diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.tsindex f544984fe5..4585ac1bd6 100644--- a/packages/api/src/mcp/types/index.ts+++ b/packages/api/src/mcp/types/index.ts@@ -168,6 +168,13 @@ export type ParsedServerConfig = MCPOptions & {capabilities?: string;tools?: string;toolFunctions?: LCAvailableTools;+ /**+ * Instructions advertised by the server, fetched during inspection when+ * `serverInstructions` is enabled. Held separately so `serverInstructions`+ * always keeps the operator's declaration: overwriting it in place made a+ * re-inspected config compare unequal to its own YAML entry.+ */+ resolvedInstructions?: string;initDuration?: number;updatedAt?: number;dbId?: string;diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.tsindex 5327365272..a715a1df09 100644--- a/packages/api/src/mcp/utils.ts+++ b/packages/api/src/mcp/utils.ts@@ -9,6 +9,7 @@ import type { AgentToolOptions } from 'librechat-data-provider';import type { ParsedServerConfig } from '~/mcp/types';import type { RequestBody } from '~/types';import { ALLOWED_BODY_FIELDS, isPluginSourced } from '~/utils/env';+import { isEnabled } from '~/utils/common';export const mcpToolPattern: RegExp = new RegExp(`^.+${Constants.mcp_delimiter}.+$`);@@ -440,6 +441,17 @@ export function isUserSourced(config: Pick<ParsedServerConfig, 'source' | 'dbId'return config.source != null ? config.source === 'user' : !!config.dbId;}+/**+ * Resolves the instructions text for a server, mirroring how the inspector fills them:+ * an enabled flag resolves to the text fetched from the server, while an operator-authored+ * string is used verbatim. Anything else (`false`, unset) yields no instructions.+ */+export function resolveServerInstructions(config: ParsedServerConfig): string | undefined {+ const declared = config.serverInstructions;+ if (isEnabled(declared)) return config.resolvedInstructions;+ return typeof declared === 'string' ? declared : undefined;+}+export type RedactedServerConfig = Partial<ParsedServerConfig> & {/** True when this config needs chat request fields before it can connect. */requestScoped?: boolean;