Skip to content

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

🪢 fix: Bind Preserved MCP API Keys to Server Configuration (#16136)

Danny Avila1e0076376cd0
diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.js
index 657c13220f..5287f81be6 100644
--- a/api/server/controllers/mcp.js
+++ b/api/server/controllers/mcp.js
@@ -13,7 +13,6 @@ const {
isUserSourced,
createAuthIdentityContext,
MCPConnection,
- MCPErrorCodes,
MCPCatalogCapacityError,
splitMCPToolKey,
normalizeServerName,
@@ -21,9 +20,7 @@ const {
redactServerSecrets,
sanitizeMcpIconPath,
redactAllServerSecrets,
- isMCPDomainNotAllowedError,
- isMCPInspectionFailedError,
- isMCPOAuthSecretReentryRequiredError,
+ getMCPErrorResponse,
prepareMCPServerOAuthDeletion,
cleanupDeletedMCPServerOAuthUsers,
} = require('@librechat/api');
@@ -61,50 +58,8 @@ const db = require('~/models');
* @returns {import('express').Response | null} Response if handled, null if not an MCP error
*/
function handleMCPError(error, res) {
- if (isMCPDomainNotAllowedError(error)) {
- return res.status(error.statusCode).json({
- error: error.code,
- message: error.message,
- });
- }
-
- if (isMCPInspectionFailedError(error)) {
- return res.status(error.statusCode).json({
- error: error.code,
- message: error.message,
- });
- }
-
- if (isMCPOAuthSecretReentryRequiredError(error)) {
- return res.status(error.statusCode).json({
- error: error.code,
- message: error.message,
- });
- }
-
- // Fallback for legacy string-based error handling (backwards compatibility)
- if (error.message?.startsWith(MCPErrorCodes.DOMAIN_NOT_ALLOWED)) {
- return res.status(403).json({
- error: MCPErrorCodes.DOMAIN_NOT_ALLOWED,
- message: error.message.replace(/^MCP_DOMAIN_NOT_ALLOWED\s*:\s*/i, ''),
- });
- }
-
- if (error.message?.startsWith(MCPErrorCodes.INSPECTION_FAILED)) {
- return res.status(400).json({
- error: MCPErrorCodes.INSPECTION_FAILED,
- message: error.message,
- });
- }
-
- if (error.message?.startsWith(MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED)) {
- return res.status(400).json({
- error: MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED,
- message: error.message,
- });
- }
-
- return null;
+ const response = getMCPErrorResponse(error);
+ return response ? res.status(response.statusCode).json(response.body) : null;
}
/** Disposes a stale local connection after its DB-backed config has changed. */
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js
index bc3fe779b5..974560068d 100644
--- a/api/server/routes/__tests__/mcp.spec.js
+++ b/api/server/routes/__tests__/mcp.spec.js
@@ -3,7 +3,12 @@ const express = require('express');
const request = require('supertest');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
-const { getBasePath, PENDING_STALE_MS } = require('@librechat/api');
+const {
+ getBasePath,
+ PENDING_STALE_MS,
+ MCPApiKeyReentryRequiredError,
+ MCPOAuthSecretReentryRequiredError,
+} = require('@librechat/api');
const { MongoMemoryServer } = require('mongodb-memory-server');
function generateTestCsrfToken(flowId) {
@@ -88,16 +93,6 @@ jest.mock('@librechat/api', () => {
MCPServersRegistry: {
getInstance: () => mockRegistryInstance,
},
- // Error handling utilities (from @librechat/api mcp/errors)
- isMCPDomainNotAllowedError: (error) => error?.code === 'MCP_DOMAIN_NOT_ALLOWED',
- isMCPInspectionFailedError: (error) => error?.code === 'MCP_INSPECTION_FAILED',
- isMCPOAuthSecretReentryRequiredError: (error) =>
- error?.code === 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
- MCPErrorCodes: {
- DOMAIN_NOT_ALLOWED: 'MCP_DOMAIN_NOT_ALLOWED',
- INSPECTION_FAILED: 'MCP_INSPECTION_FAILED',
- OAUTH_SECRET_REENTRY_REQUIRED: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
- },
};
});
@@ -4446,15 +4441,7 @@ describe('MCP Routes', () => {
});
it('should require secret re-entry when OAuth credential bindings change', async () => {
- const error = Object.assign(
- new Error(
- 'Re-enter oauth.client_secret when changing OAuth credential binding fields: oauth.token_url',
- ),
- {
- code: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
- statusCode: 400,
- },
- );
+ const error = new MCPOAuthSecretReentryRequiredError(['oauth.token_url']);
mockRegistryInstance.inspectServerUpdate.mockRejectedValue(error);
const response = await request(app)
@@ -4479,6 +4466,30 @@ describe('MCP Routes', () => {
});
});
+ it('should require API key re-entry when its credential binding changes', async () => {
+ const error = new MCPApiKeyReentryRequiredError(['url']);
+ mockRegistryInstance.inspectServerUpdate.mockRejectedValue(error);
+
+ const response = await request(app)
+ .patch('/api/mcp/servers/test-server')
+ .send({
+ config: {
+ type: 'sse',
+ url: 'https://attacker.example.com/sse',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ },
+ },
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.body).toEqual({
+ error: 'MCP_API_KEY_REENTRY_REQUIRED',
+ message: 'Re-enter apiKey.key when changing API key credential binding fields: url',
+ });
+ });
+
it('should return 400 for invalid configuration', async () => {
const invalidConfig = {
type: 'sse',
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts
index 6eb70924cd..ce372d7d20 100644
--- a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts
+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.spec.ts
@@ -6,6 +6,7 @@ const localize = (key: TranslationKeys): string => `localized:${key}`;
describe('getMCPServerErrorMessage', () => {
it.each([
+ ['MCP_API_KEY_REENTRY_REQUIRED', 'com_ui_mcp_api_key_reentry_required'],
['MCP_INSPECTION_FAILED', 'com_ui_mcp_server_connection_failed'],
['MCP_DOMAIN_NOT_ALLOWED', 'com_ui_mcp_domain_not_allowed'],
['MCP_OAUTH_SECRET_REENTRY_REQUIRED', 'com_ui_mcp_oauth_secret_reentry_required'],
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts
index 6eadc6374e..88d2973bf5 100644
--- a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts
+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/utils/error.ts
@@ -3,6 +3,7 @@ import type { TranslationKeys } from '~/hooks';
type Localize = (key: TranslationKeys) => string;
const MCP_ERROR_MESSAGE_KEYS: Record<string, TranslationKeys> = {
+ MCP_API_KEY_REENTRY_REQUIRED: 'com_ui_mcp_api_key_reentry_required',
MCP_INSPECTION_FAILED: 'com_ui_mcp_server_connection_failed',
MCP_DOMAIN_NOT_ALLOWED: 'com_ui_mcp_domain_not_allowed',
MCP_OAUTH_SECRET_REENTRY_REQUIRED: 'com_ui_mcp_oauth_secret_reentry_required',
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index f3d8c6eef8..a97a9bdcd7 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1687,6 +1687,7 @@
"com_ui_max_favorites_reached_items": "Maximum favorites reached ({{0}}). Remove a favorite to add more.",
"com_ui_max_tags": "Maximum number allowed is {{0}}, using latest values.",
"com_ui_mcp_authenticated_success": "MCP server '{{0}}' authenticated successfully",
+ "com_ui_mcp_api_key_reentry_required": "Connection settings changed. Re-enter the API key to save this MCP server.",
"com_ui_mcp_background": "Background",
"com_ui_mcp_background_all": "Mark all as background",
"com_ui_mcp_click_to_background": "Runs this tool in the background: it returns immediately and the agent polls for the result, so it can keep working while the tool runs.",
diff --git a/packages/api/src/mcp/errors.spec.ts b/packages/api/src/mcp/errors.spec.ts
index 175d001061..db26a1fda0 100644
--- a/packages/api/src/mcp/errors.spec.ts
+++ b/packages/api/src/mcp/errors.spec.ts
@@ -4,6 +4,8 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import {
+ MCPApiKeyReentryRequiredError,
+ getMCPErrorResponse,
isMCPTransportAuthenticationError,
MCPTransportAuthenticationError,
isMCPInitializationError,
@@ -52,3 +54,29 @@ describe('direct bearer transport rejection classification', () => {
expect(isMCPTransportAuthenticationError(error)).toBe(false);
});
});
+
+describe('MCP HTTP error response mapping', () => {
+ it('maps API key rebinding errors without exposing credential material', () => {
+ expect(getMCPErrorResponse(new MCPApiKeyReentryRequiredError(['url']))).toEqual({
+ statusCode: 400,
+ body: {
+ error: 'MCP_API_KEY_REENTRY_REQUIRED',
+ message: 'Re-enter apiKey.key when changing API key credential binding fields: url',
+ },
+ });
+ });
+
+ it('preserves legacy domain error behavior', () => {
+ expect(getMCPErrorResponse(new Error('MCP_DOMAIN_NOT_ALLOWED: blocked.example.com'))).toEqual({
+ statusCode: 403,
+ body: {
+ error: 'MCP_DOMAIN_NOT_ALLOWED',
+ message: 'blocked.example.com',
+ },
+ });
+ });
+
+ it('ignores unrelated errors', () => {
+ expect(getMCPErrorResponse(new Error('unrelated'))).toBeNull();
+ });
+});
diff --git a/packages/api/src/mcp/errors.ts b/packages/api/src/mcp/errors.ts
index 50c652de77..2835ba228a 100644
--- a/packages/api/src/mcp/errors.ts
+++ b/packages/api/src/mcp/errors.ts
@@ -24,6 +24,7 @@ export const MCPErrorCodes = {
DOMAIN_NOT_ALLOWED: 'MCP_DOMAIN_NOT_ALLOWED',
INSPECTION_FAILED: 'MCP_INSPECTION_FAILED',
OAUTH_SECRET_REENTRY_REQUIRED: 'MCP_OAUTH_SECRET_REENTRY_REQUIRED',
+ API_KEY_REENTRY_REQUIRED: 'MCP_API_KEY_REENTRY_REQUIRED',
AUTHENTICATION_REJECTED: 'MCP_AUTHENTICATION_REJECTED',
AUTHENTICATION_REFRESH_FAILED: 'MCP_AUTHENTICATION_REFRESH_FAILED',
} as const;
@@ -327,6 +328,23 @@ export class MCPOAuthSecretReentryRequiredError extends Error {
}
}
+/** Raised when an update would move a retained admin API key across request boundaries. */
+export class MCPApiKeyReentryRequiredError extends Error {
+ public readonly code: 'MCP_API_KEY_REENTRY_REQUIRED' = MCPErrorCodes.API_KEY_REENTRY_REQUIRED;
+
+ public readonly statusCode = 400;
+ public readonly changedFields: readonly string[];
+
+ constructor(changedFields: readonly string[]) {
+ super(
+ `Re-enter apiKey.key when changing API key credential binding fields: ${changedFields.join(', ')}`,
+ );
+ this.name = 'MCPApiKeyReentryRequiredError';
+ this.changedFields = changedFields;
+ Object.setPrototypeOf(this, MCPApiKeyReentryRequiredError.prototype);
+ }
+}
+
/**
* A tool invocation was rejected before LibreChat could know whether the MCP
* server executed it. Recovery may prepare a later deliberate retry, but this
@@ -390,3 +408,70 @@ export function isMCPOAuthSecretReentryRequiredError(
): error is MCPOAuthSecretReentryRequiredError {
return error instanceof MCPOAuthSecretReentryRequiredError;
}
+
+/** Type guard for admin API-key binding violations. */
+export function isMCPApiKeyReentryRequiredError(
+ error: unknown,
+): error is MCPApiKeyReentryRequiredError {
+ return error instanceof MCPApiKeyReentryRequiredError;
+}
+
+export type MCPErrorResponse = {
+ statusCode: number;
+ body: {
+ error: MCPErrorCode;
+ message: string;
+ };
+};
+
+/** Maps MCP errors to their public HTTP response without exposing attached causes or secrets. */
+export function getMCPErrorResponse(error: unknown): MCPErrorResponse | null {
+ if (
+ isMCPDomainNotAllowedError(error) ||
+ isMCPInspectionFailedError(error) ||
+ isMCPOAuthSecretReentryRequiredError(error) ||
+ isMCPApiKeyReentryRequiredError(error)
+ ) {
+ return {
+ statusCode: error.statusCode,
+ body: { error: error.code, message: error.message },
+ };
+ }
+
+ const message =
+ typeof error === 'object' &&
+ error !== null &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ ? error.message
+ : undefined;
+ if (!message) {
+ return null;
+ }
+
+ if (message.startsWith(MCPErrorCodes.DOMAIN_NOT_ALLOWED)) {
+ return {
+ statusCode: 403,
+ body: {
+ error: MCPErrorCodes.DOMAIN_NOT_ALLOWED,
+ message: message.replace(/^MCP_DOMAIN_NOT_ALLOWED\s*:\s*/i, ''),
+ },
+ };
+ }
+
+ if (message.startsWith(MCPErrorCodes.INSPECTION_FAILED)) {
+ return {
+ statusCode: 400,
+ body: { error: MCPErrorCodes.INSPECTION_FAILED, message },
+ };
+ }
+
+ if (message.startsWith(MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED)) {
+ return {
+ statusCode: 400,
+ body: { error: MCPErrorCodes.OAUTH_SECRET_REENTRY_REQUIRED, message },
+ };
+ }
+
+ return null;
+}
diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.ts
index a8e51c3014..90372d76ec 100644
--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts
+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts
@@ -13,6 +13,7 @@ import { MCPInspectionFailedError, isMCPDomainNotAllowedError } from '~/mcp/erro
import { canBackfillSharedServerInstructions, isUserSourced } from '~/mcp/utils';
import { ReadThroughAllCache } from './cache/ReadThroughAllCache';
import { isPluginSourced, MCP_PLUGIN_SOURCE } from '~/utils/env';
+import { requireApiKeyReentryForRebinding } from './binding';
import { ReadThroughCache } from './cache/ReadThroughCache';
import { MCPServerInspector } from './MCPServerInspector';
import { ServerConfigsDB } from './db/ServerConfigsDB';
@@ -930,11 +931,12 @@ export class MCPServersRegistry {
const configRepo = this.getConfigRepository(storageLocation);
const source = resolveServerSource(config, storageLocation === 'CACHE' ? 'yaml' : 'user');
- // Merge existing admin API key if not provided in update (needed for inspection)
+ // Merge an equivalent update's existing admin API key for inspection.
let configForInspection = { ...config };
if (config.apiKey?.source === 'admin' && !config.apiKey?.key) {
const existingConfig = await configRepo.get(serverName, userId);
if (existingConfig?.apiKey?.key) {
+ requireApiKeyReentryForRebinding(existingConfig, config);
configForInspection = {
...configForInspection,
apiKey: {
diff --git a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts
index 6b6f153080..ce15ea4430 100644
--- a/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/MCPServersRegistry.test.ts
@@ -732,6 +732,142 @@ describe('MCPServersRegistry', () => {
});
});
+ describe('admin API key update binding', () => {
+ const bearerConfig: t.MCPOptions = {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ proxy: 'http://proxy.example.com/',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'bearer',
+ key: 'owner-secret',
+ },
+ };
+ const customHeaderConfig: t.MCPOptions = {
+ ...bearerConfig,
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'custom',
+ custom_header: 'X-Owner-Key',
+ key: 'owner-secret',
+ },
+ };
+ const rebindingCases: Array<[string, t.MCPOptions, t.MCPOptions, string[]]> = [
+ [
+ 'URL',
+ bearerConfig,
+ {
+ ...bearerConfig,
+ url: 'https://attacker.example.com/mcp',
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ },
+ ['url'],
+ ],
+ [
+ 'transport',
+ bearerConfig,
+ {
+ ...bearerConfig,
+ type: 'sse',
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ },
+ ['type'],
+ ],
+ [
+ 'proxy',
+ bearerConfig,
+ {
+ ...bearerConfig,
+ proxy: 'http://attacker.example.com/',
+ apiKey: { source: 'admin', authorization_type: 'bearer' },
+ },
+ ['proxy'],
+ ],
+ [
+ 'authorization type',
+ bearerConfig,
+ {
+ ...bearerConfig,
+ apiKey: { source: 'admin', authorization_type: 'basic' },
+ },
+ ['apiKey.authorization_type'],
+ ],
+ [
+ 'custom-header binding',
+ customHeaderConfig,
+ {
+ ...customHeaderConfig,
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'custom',
+ custom_header: 'X-Attacker-Key',
+ },
+ },
+ ['apiKey.custom_header'],
+ ],
+ ];
+
+ it.each(rebindingCases)(
+ 'rejects an omitted-key %s rebinding before outbound inspection',
+ async (_label, existingConfig, update, changedFields) => {
+ jest.spyOn(registry['dbConfigsRepo'], 'get').mockResolvedValue(existingConfig);
+ const inspectSpy = jest.mocked(MCPServerInspector.inspect);
+ inspectSpy.mockClear();
+
+ await expect(
+ registry.inspectServerUpdate('shared-server', update, 'DB', 'editor-user'),
+ ).rejects.toMatchObject({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ changedFields,
+ });
+
+ expect(inspectSpy).not.toHaveBeenCalled();
+ },
+ );
+
+ it('preserves the omitted key for an equivalent request boundary', async () => {
+ const existingConfig: t.MCPOptions = {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ proxy: 'http://proxy.example.com/',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'custom',
+ custom_header: 'X-Api-Key',
+ key: 'owner-secret',
+ },
+ };
+ const equivalentUpdate: t.MCPOptions = {
+ ...existingConfig,
+ type: 'http',
+ url: 'https://MCP.EXAMPLE.COM:443/mcp',
+ proxy: 'http://PROXY.EXAMPLE.COM:80/',
+ description: 'Updated description',
+ apiKey: {
+ source: 'admin',
+ authorization_type: 'custom',
+ custom_header: 'x-api-key',
+ },
+ };
+ jest.spyOn(registry['dbConfigsRepo'], 'get').mockResolvedValue(existingConfig);
+ const inspectSpy = jest.mocked(MCPServerInspector.inspect);
+ inspectSpy.mockClear();
+
+ await registry.inspectServerUpdate('shared-server', equivalentUpdate, 'DB', 'editor-user');
+
+ expect(inspectSpy).toHaveBeenCalledTimes(1);
+ expect(inspectSpy).toHaveBeenCalledWith(
+ 'shared-server',
+ expect.objectContaining({
+ apiKey: expect.objectContaining({ key: 'owner-secret' }),
+ }),
+ undefined,
+ undefined,
+ undefined,
+ );
+ });
+ });
+
describe('reinspectServer', () => {
const stubOptions: t.MCPOptions = {
type: 'streamable-http',
diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
index 8b36ef6437..4d8917f406 100644
--- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
@@ -664,7 +664,7 @@ describe('ServerConfigsDB', () => {
expect(retrieved?.apiKey?.key).toBe('new-api-key');
});
- it('should preserve apiKey.key when authorization_type changes (bearer to custom)', async () => {
+ it('should require apiKey.key when authorization_type changes', async () => {
const config: ParsedServerConfig = {
type: 'sse',
url: 'https://example.com/mcp',
@@ -686,16 +686,19 @@ describe('ServerConfigsDB', () => {
source: 'admin',
authorization_type: 'custom',
custom_header: 'X-My-Api-Key',
- // key not provided - should be preserved
},
};
- await serverConfigsDB.update(created.serverName, updatedConfig, userId);
+ await expect(
+ serverConfigsDB.update(created.serverName, updatedConfig, userId),
+ ).rejects.toMatchObject({
+ code: 'MCP_API_KEY_REENTRY_REQUIRED',
+ changedFields: ['apiKey.authorization_type', 'apiKey.custom_header'],
+ });
- // Verify the key is preserved and authorization_type/custom_header updated
const retrieved = await serverConfigsDB.get(created.serverName, userId);
expect(retrieved?.apiKey?.key).toBe('my-api-key');
- expect(retrieved?.apiKey?.authorization_type).toBe('custom');
- expect(retrieved?.apiKey?.custom_header).toBe('X-My-Api-Key');
+ expect(retrieved?.apiKey?.authorization_type).toBe('bearer');
+ expect(retrieved?.apiKey?.custom_header).toBeUndefined();
});
it('should NOT preserve apiKey.key when switching from admin to user source', async () => {
diff --git a/packages/api/src/mcp/registry/binding.ts b/packages/api/src/mcp/registry/binding.ts
new file mode 100644
index 0000000000..b589c1a1ca
--- /dev/null
+++ b/packages/api/src/mcp/registry/binding.ts
@@ -0,0 +1,80 @@
+import type { MCPOptions } from '~/mcp/types';
+import { MCPApiKeyReentryRequiredError } from '~/mcp/errors';
+
+function getUrl(config: MCPOptions): string | undefined {
+ return 'url' in config ? config.url : undefined;
+}
+
+function getProxy(config: MCPOptions): string | undefined {
+ return 'proxy' in config ? config.proxy : undefined;
+}
+
+function normalizeUrl(value?: string): string | undefined {
+ if (!value) {
+ return value;
+ }
+
+ try {
+ return new URL(value).href;
+ } catch {
+ return value;
+ }
+}
+
+function normalizeTransport(type: MCPOptions['type']): string {
+ return type === 'http' ? 'streamable-http' : type;
+}
+
+function normalizeCustomHeader(apiKey: MCPOptions['apiKey']): string | undefined {
+ if (apiKey?.authorization_type !== 'custom') {
+ return undefined;
+ }
+ return (apiKey.custom_header || 'X-Api-Key').toLowerCase();
+}
+
+/** Returns fields that would move an omitted, stored admin key to a new request boundary. */
+export function getChangedApiKeyBindingFields(
+ existingConfig: MCPOptions,
+ updatedConfig: MCPOptions,
+): string[] {
+ const existingApiKey = existingConfig.apiKey;
+ const updatedApiKey = updatedConfig.apiKey;
+ const preservesStoredKey =
+ existingApiKey?.source === 'admin' &&
+ !!existingApiKey.key &&
+ updatedApiKey?.source === 'admin' &&
+ !updatedApiKey.key;
+
+ if (!preservesStoredKey) {
+ return [];
+ }
+
+ const fields = [
+ ['url', normalizeUrl(getUrl(existingConfig)), normalizeUrl(getUrl(updatedConfig))],
+ ['type', normalizeTransport(existingConfig.type), normalizeTransport(updatedConfig.type)],
+ ['proxy', normalizeUrl(getProxy(existingConfig)), normalizeUrl(getProxy(updatedConfig))],
+ [
+ 'apiKey.authorization_type',
+ existingApiKey.authorization_type,
+ updatedApiKey.authorization_type,
+ ],
+ [
+ 'apiKey.custom_header',
+ normalizeCustomHeader(existingApiKey),
+ normalizeCustomHeader(updatedApiKey),
+ ],
+ ] as const;
+
+ return fields.filter(([, existing, updated]) => existing !== updated).map(([field]) => field);
+}
+
+/** Requires a replacement key before a stored admin credential can cross request boundaries. */
+export function requireApiKeyReentryForRebinding(
+ existingConfig: MCPOptions,
+ updatedConfig: MCPOptions,
+): void {
+ const changedFields = getChangedApiKeyBindingFields(existingConfig, updatedConfig);
+ if (changedFields.length > 0) {
+ throw new MCPApiKeyReentryRequiredError(changedFields);
+ }
+}
diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
index f439eb2186..383b6a654b 100644
--- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
+++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
@@ -7,10 +7,10 @@ import {
PermissionBits,
} from 'librechat-data-provider';
import type { AllMethods, MCPServerDocument, IAgent } from '@librechat/data-schemas';
-
import type { IServerConfigsRepositoryInterface } from '~/mcp/registry/ServerConfigsRepositoryInterface';
import type { ParsedServerConfig, AddServerResult } from '~/mcp/types';
import type { ResolvedPrincipal } from '~/types/principal';
+import { requireApiKeyReentryForRebinding } from '~/mcp/registry/binding';
import { MCPOAuthSecretReentryRequiredError } from '~/mcp/errors';
import { AccessControlService } from '~/acl/accessControlService';
@@ -362,6 +362,10 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {
const existingServer = await this._dbMethods.findMCPServerByServerName(serverName);
+ if (existingServer) {
+ requireApiKeyReentryForRebinding(existingServer.config, config);
+ }
+
let configToSave: ParsedServerConfig = sanitizeUserManagedOAuthConfig({
...config,
...sanitizeConfigHeaderMaps(config),