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: Allow Opting Out of the MCP OAuth `resource` Parameter (#15982)

lia-by-librechat[bot]8fa56b0b9ea8
diff --git a/packages/api/src/mcp/MCPConnectionFactory.ts b/packages/api/src/mcp/MCPConnectionFactory.ts
index 6c416ae65a..68a02d004d 100644
--- a/packages/api/src/mcp/MCPConnectionFactory.ts
+++ b/packages/api/src/mcp/MCPConnectionFactory.ts
@@ -1323,6 +1323,25 @@ export class MCPConnectionFactory {
return flowTenantId === this.tenantId;
}
+ /**
+ * A pending flow's authorization URL was already built with or without RFC 8707
+ * `resource`, so replaying it after the operator changed `send_resource_parameter`
+ * reissues the request they reconfigured away from.
+ *
+ * Deliberately separate from {@link isCurrentServerOAuthFlow}: that check also gates reuse
+ * of a recent COMPLETED flow's tokens, and this setting must never invalidate tokens that
+ * were already issued.
+ */
+ private isReplayablePendingOAuthFlow(meta: MCPOAuthFlowMetadata | undefined): boolean {
+ if (!MCPOAuthHandler.matchesResourceParameterDecision(meta, this.serverConfig.oauth)) {
+ logger.info(
+ `${this.logPrefix} Pending OAuth flow predates a send_resource_parameter change; starting a new flow`,
+ );
+ return false;
+ }
+ return this.isCurrentServerOAuthFlow(meta);
+ }
+
/** Prevents server-name keyed OAuth flow cache entries from crossing config bindings. */
private isCurrentServerOAuthFlow(meta: MCPOAuthFlowMetadata | undefined): boolean {
const currentServerUrl = (this.serverConfig as t.SSEOptions | t.StreamableHTTPOptions).url;
@@ -1603,7 +1622,7 @@ export class MCPConnectionFactory {
: Infinity;
const flowMeta = existingFlow.metadata as MCPOAuthFlowMetadata | undefined;
- if (pendingAge < PENDING_STALE_MS && this.isCurrentServerOAuthFlow(flowMeta)) {
+ if (pendingAge < PENDING_STALE_MS && this.isReplayablePendingOAuthFlow(flowMeta)) {
logger.debug(
`${this.logPrefix} Recent PENDING OAuth flow exists (${Math.round(pendingAge / 1000)}s old), skipping new initiation`,
);
@@ -2017,7 +2036,7 @@ export class MCPConnectionFactory {
? Date.now() - existingFlow.createdAt
: Infinity;
- if (pendingAge < PENDING_STALE_MS && this.isCurrentServerOAuthFlow(flowMeta)) {
+ if (pendingAge < PENDING_STALE_MS && this.isReplayablePendingOAuthFlow(flowMeta)) {
logger.debug(
`${this.logPrefix} Found recent PENDING OAuth flow (${Math.round(pendingAge / 1000)}s old), joining instead of creating new one`,
);
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
index ffe06f2773..b00df44d9d 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts
@@ -189,6 +189,13 @@ describe('MCPConnectionFactory', () => {
: undefined,
);
mockMCPOAuthHandler.assertStoredClientBinding.mockImplementation(() => undefined);
+ /**
+ * Automock returns `undefined` for a boolean predicate, which would read as
+ * "the flow's RFC 8707 decision no longer matches the config" and retire every
+ * pending flow. Default it to matching, the way the real implementation does when
+ * neither the flow nor the config opts out.
+ */
+ mockMCPOAuthHandler.matchesResourceParameterDecision.mockReturnValue(true);
mockMCPTokenStorage.isCurrentAccessToken.mockResolvedValue(true);
mockMCPTokenStorage.getClientInfoAndMetadata.mockResolvedValue({
clientInfo: { client_id: 'persisted-client' },
@@ -856,6 +863,93 @@ describe('MCPConnectionFactory', () => {
});
});
+ it('replaces a recent PENDING OAuth flow whose resource-parameter decision changed', async () => {
+ /**
+ * An operator sets `send_resource_parameter: false` to repair a failing Entra
+ * login. The pending flow's authorization URL still carries `resource`, so
+ * replaying it would reissue the request that just failed. The stored client
+ * binding is unchanged here, so the resource-parameter check is the only thing
+ * that can retire the flow.
+ */
+ const currentConfig = {
+ type: 'sse' as const,
+ url: 'https://server-a.example.com/mcp',
+ initTimeout: 5000,
+ oauth: { send_resource_parameter: false },
+ } as t.SSEOptions;
+ const staleMetadata = {
+ serverName: 'test-server',
+ userId: 'user123',
+ serverUrl: 'https://server-a.example.com/mcp',
+ state: 'stale-state',
+ authorizationUrl:
+ 'https://auth.example.com/old-authorize?resource=https%3A%2F%2Fserver-a.example.com%2Fmcp',
+ clientInfo: { client_id: 'dynamic-client' },
+ clientSource: 'dynamic' as const,
+ metadata: {
+ authorization_endpoint: 'https://auth.example.com/authorize',
+ token_endpoint: 'https://auth.example.com/token',
+ },
+ };
+ const freshTokens: MCPOAuthTokens = {
+ access_token: 'fresh-access-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ };
+ const oauthStart = jest.fn();
+
+ mockProcessMCPEnv.mockReturnValue(currentConfig);
+ mockMCPOAuthHandler.generateFlowId.mockReturnValue('flow123');
+ mockMCPOAuthHandler.matchesResourceParameterDecision.mockReturnValue(false);
+ mockFlowManager.getFlowState.mockResolvedValue({
+ status: 'PENDING',
+ type: 'mcp_oauth',
+ metadata: staleMetadata,
+ createdAt: Date.now(),
+ });
+ mockMCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
+ authorizationUrl: 'https://auth.example.com/fresh-authorize',
+ flowId: 'fresh-flow',
+ flowMetadata: {
+ ...staleMetadata,
+ state: 'fresh-state',
+ authorizationUrl: 'https://auth.example.com/fresh-authorize',
+ sendResourceParameter: false,
+ },
+ });
+ mockFlowManager.createFlow.mockResolvedValue(freshTokens);
+
+ const factory = new InspectableMCPConnectionFactory(
+ { serverName: 'test-server', serverConfig: currentConfig },
+ {
+ useOAuth: true,
+ user: mockUser,
+ flowManager: mockFlowManager,
+ oauthStart,
+ tokenMethods: {
+ findToken: jest.fn(),
+ createToken: jest.fn(),
+ updateToken: jest.fn(),
+ deleteTokens: jest.fn(),
+ },
+ },
+ );
+
+ const result = await factory.handleOAuthRequiredForTest();
+
+ expect(mockMCPOAuthHandler.matchesResourceParameterDecision).toHaveBeenCalledWith(
+ expect.objectContaining({ state: 'stale-state' }),
+ currentConfig.oauth,
+ );
+ expect(result?.tokens).toEqual(freshTokens);
+ expect(mockMCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalled();
+ expect(oauthStart).toHaveBeenCalledWith('https://auth.example.com/fresh-authorize');
+ expect(oauthStart).not.toHaveBeenCalledWith(
+ expect.stringContaining('resource='),
+ expect.anything(),
+ );
+ });
+
it.each(['PENDING', 'COMPLETED'] as const)(
'replaces a recent %s OAuth flow bound to another server URL',
async (status) => {
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthResourceEndpoints.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthResourceEndpoints.test.ts
new file mode 100644
index 0000000000..76dc65b032
--- /dev/null
+++ b/packages/api/src/mcp/__tests__/MCPOAuthResourceEndpoints.test.ts
@@ -0,0 +1,142 @@
+/**
+ * Covers a suppressed RFC 8707 `resource` that could still reach the provider through an
+ * endpoint URL which already carries it: the MCP SDK uses `token_endpoint` verbatim and the
+ * refresh paths post to the resolved token URL as-is, so gating only the parameters
+ * LibreChat *adds* leaves an inherited one in place.
+ *
+ * Verified against a real recorded request line rather than a mock, so it asserts what the
+ * authorization server would actually receive.
+ */
+
+import * as net from 'net';
+import * as http from 'http';
+import type { Socket } from 'net';
+import { MCPOAuthHandler } from '~/mcp/oauth';
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ },
+ getTenantId: jest.fn(),
+ SYSTEM_TENANT_ID: '__SYSTEM__',
+ encryptV2: jest.fn(async (val: string) => `enc:${val}`),
+ decryptV2: jest.fn(async (val: string) => val.replace(/^enc:/, '')),
+}));
+
+/** Bypass SSRF for local test endpoints. */
+jest.mock('~/auth', () => ({
+ ...jest.requireActual('~/auth'),
+ createSSRFSafeUndiciConnect: jest.fn(() => undefined),
+ isSSRFTarget: jest.fn(() => false),
+ resolveHostnameSSRF: jest.fn(async () => false),
+ isOAuthUrlAllowed: jest.fn(() => true),
+}));
+
+function getFreePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const srv = net.createServer();
+ srv.listen(0, '127.0.0.1', () => {
+ const addr = srv.address() as net.AddressInfo;
+ srv.close((err) => (err ? reject(err) : resolve(addr.port)));
+ });
+ });
+}
+
+/** Records the request line of every /token POST so the query string can be asserted. */
+async function startUrlRecordingTokenServer(): Promise<{
+ origin: string;
+ urls: string[];
+ close: () => Promise<void>;
+}> {
+ const urls: string[] = [];
+ const port = await getFreePort();
+ const sockets = new Set<Socket>();
+ const server = http.createServer((req, res) => {
+ urls.push(req.url ?? '');
+ req.on('data', () => undefined);
+ req.on('end', () => {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ access_token: 'new-access-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ }),
+ );
+ });
+ });
+ server.on('connection', (socket: Socket) => {
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ });
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+ return {
+ origin: `http://127.0.0.1:${port}`,
+ urls,
+ close: () =>
+ new Promise<void>((resolve) => {
+ for (const socket of sockets) {
+ socket.destroy();
+ }
+ sockets.clear();
+ server.close(() => resolve());
+ }),
+ };
+}
+
+describe('MCP OAuth resource inherited from endpoint URLs', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('strips an inherited resource from the token URL on refresh when opted out', async () => {
+ const { origin, urls, close } = await startUrlRecordingTokenServer();
+ try {
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'refresh-token-1',
+ { serverName: 'entra-server' },
+ {},
+ {
+ token_url: `${origin}/token?resource=${encodeURIComponent('https://stale.example.test/mcp')}&foo=bar`,
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ send_resource_parameter: false,
+ },
+ );
+
+ expect(urls).toHaveLength(1);
+ const received = new URL(urls[0], origin);
+ expect(received.searchParams.has('resource')).toBe(false);
+ /** Unrelated query parameters on the configured endpoint survive. */
+ expect(received.searchParams.get('foo')).toBe('bar');
+ } finally {
+ await close();
+ }
+ });
+
+ it('keeps an inherited resource on the token URL by default', async () => {
+ const { origin, urls, close } = await startUrlRecordingTokenServer();
+ try {
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'refresh-token-1',
+ { serverName: 'entra-server' },
+ {},
+ {
+ token_url: `${origin}/token?resource=${encodeURIComponent('https://stale.example.test/mcp')}`,
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ },
+ );
+
+ expect(urls).toHaveLength(1);
+ expect(new URL(urls[0], origin).searchParams.get('resource')).toBe(
+ 'https://stale.example.test/mcp',
+ );
+ } finally {
+ await close();
+ }
+ });
+});
diff --git a/packages/api/src/mcp/__tests__/MCPOAuthResourceParameter.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthResourceParameter.test.ts
new file mode 100644
index 0000000000..c0931e3c95
--- /dev/null
+++ b/packages/api/src/mcp/__tests__/MCPOAuthResourceParameter.test.ts
@@ -0,0 +1,333 @@
+/**
+ * Tests that `mcpServers.<name>.oauth.send_resource_parameter: false` suppresses the
+ * RFC 8707 `resource` parameter that Protected Resource Metadata discovery otherwise
+ * injects into:
+ * - the pre-configured authorize URL
+ * - the `refresh_token` grant body
+ *
+ * and that the decision is captured on the flow metadata the token exchange reads.
+ *
+ * A local HTTP server publishes RFC 9728 Protected Resource Metadata so discovery
+ * yields a real `resource` identifier bound to the MCP server URL. The refresh case
+ * is verified by recording the outbound /token POST body.
+ */
+
+import * as net from 'net';
+import * as http from 'http';
+import { TokenExchangeMethodEnum } from 'librechat-data-provider';
+import type { Socket } from 'net';
+import { MCPOAuthHandler } from '~/mcp/oauth';
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ },
+ getTenantId: jest.fn(),
+ SYSTEM_TENANT_ID: '__SYSTEM__',
+ encryptV2: jest.fn(async (val: string) => `enc:${val}`),
+ decryptV2: jest.fn(async (val: string) => val.replace(/^enc:/, '')),
+}));
+
+/** Bypass SSRF for local test endpoints. */
+jest.mock('~/auth', () => ({
+ ...jest.requireActual('~/auth'),
+ createSSRFSafeUndiciConnect: jest.fn(() => undefined),
+ isSSRFTarget: jest.fn(() => false),
+ resolveHostnameSSRF: jest.fn(async () => false),
+ isOAuthUrlAllowed: jest.fn(() => true),
+}));
+
+function getFreePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const srv = net.createServer();
+ srv.listen(0, '127.0.0.1', () => {
+ const addr = srv.address() as net.AddressInfo;
+ srv.close((err) => (err ? reject(err) : resolve(addr.port)));
+ });
+ });
+}
+
+function trackSockets(httpServer: http.Server): () => Promise<void> {
+ const sockets = new Set<Socket>();
+ httpServer.on('connection', (socket: Socket) => {
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ });
+ return () =>
+ new Promise<void>((resolve) => {
+ for (const socket of sockets) {
+ socket.destroy();
+ }
+ sockets.clear();
+ httpServer.close(() => resolve());
+ });
+}
+
+/** MCP server that publishes RFC 9728 metadata whose `resource` matches its own URL. */
+async function startProtectedResourceServer(): Promise<{
+ serverUrl: string;
+ close: () => Promise<void>;
+}> {
+ const port = await getFreePort();
+ const serverUrl = `http://127.0.0.1:${port}/mcp`;
+ const server = http.createServer((req, res) => {
+ if (req.url?.startsWith('/.well-known/oauth-protected-resource')) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ resource: serverUrl, scopes_supported: ['mcp.read'] }));
+ return;
+ }
+ res.writeHead(401, { 'WWW-Authenticate': 'Bearer' });
+ res.end();
+ });
+ const close = trackSockets(server);
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+ return { serverUrl, close };
+}
+
+/** Records every /token request body and answers with a valid token payload. */
+async function startRecordingTokenServer(): Promise<{
+ url: string;
+ bodies: URLSearchParams[];
+ close: () => Promise<void>;
+}> {
+ const bodies: URLSearchParams[] = [];
+ const port = await getFreePort();
+ const server = http.createServer((req, res) => {
+ if (req.method !== 'POST') {
+ res.writeHead(405);
+ res.end();
+ return;
+ }
+ let raw = '';
+ req.on('data', (chunk) => (raw += chunk));
+ req.on('end', () => {
+ bodies.push(new URLSearchParams(raw));
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ access_token: 'new-access-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ }),
+ );
+ });
+ });
+ const close = trackSockets(server);
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+ return { url: `http://127.0.0.1:${port}/`, bodies, close };
+}
+
+describe('MCP OAuth send_resource_parameter', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('pre-configured authorize URL', () => {
+ it('sends the discovered resource identifier by default', async () => {
+ const { serverUrl, close } = await startProtectedResourceServer();
+ try {
+ const { authorizationUrl, flowMetadata } = await MCPOAuthHandler.initiateOAuthFlow(
+ 'entra-server',
+ serverUrl,
+ 'user-1',
+ {},
+ {
+ authorization_url: 'https://login.microsoftonline.test/tenant/oauth2/v2.0/authorize',
+ token_url: 'https://login.microsoftonline.test/tenant/oauth2/v2.0/token',
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ scope: 'api://test-client/access_as_user openid offline_access',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ },
+ );
+
+ expect(new URL(authorizationUrl).searchParams.get('resource')).toBe(serverUrl);
+ expect(flowMetadata.sendResourceParameter).toBeUndefined();
+ expect(flowMetadata.resourceMetadata?.resource).toBe(serverUrl);
+ } finally {
+ await close();
+ }
+ });
+
+ it('omits the resource parameter when send_resource_parameter is false', async () => {
+ const { serverUrl, close } = await startProtectedResourceServer();
+ try {
+ const { authorizationUrl, flowMetadata } = await MCPOAuthHandler.initiateOAuthFlow(
+ 'entra-server',
+ serverUrl,
+ 'user-1',
+ {},
+ {
+ authorization_url: 'https://login.microsoftonline.test/tenant/oauth2/v2.0/authorize',
+ token_url: 'https://login.microsoftonline.test/tenant/oauth2/v2.0/token',
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ scope: 'api://test-client/access_as_user openid offline_access',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ send_resource_parameter: false,
+ },
+ );
+
+ const params = new URL(authorizationUrl).searchParams;
+ expect(params.has('resource')).toBe(false);
+ expect(params.get('scope')).toBe('api://test-client/access_as_user openid offline_access');
+ expect(flowMetadata.sendResourceParameter).toBe(false);
+ /** Capability discovery is untouched: the document is still validated and stored. */
+ expect(flowMetadata.resourceMetadata?.resource).toBe(serverUrl);
+ expect(flowMetadata.resourceMetadata?.scopes_supported).toEqual(['mcp.read']);
+ } finally {
+ await close();
+ }
+ });
+ });
+
+ describe('resource inherited from the authorization endpoint', () => {
+ const entraAuthorize = 'https://login.microsoftonline.test/tenant/oauth2/v2.0/authorize';
+
+ /**
+ * `startAuthorization` copies the configured endpoint's query string verbatim, so a
+ * `resource` left in `authorization_url` reaches the provider even though discovery
+ * never supplied it. Declining to add one is not enough; it has to be removed.
+ */
+ it('removes a resource parameter carried by the configured authorization_url', async () => {
+ const { serverUrl, close } = await startProtectedResourceServer();
+ try {
+ const { authorizationUrl } = await MCPOAuthHandler.initiateOAuthFlow(
+ 'entra-server',
+ serverUrl,
+ 'user-1',
+ {},
+ {
+ authorization_url: `${entraAuthorize}?resource=${encodeURIComponent('https://stale.example.test/mcp')}`,
+ token_url: 'https://login.microsoftonline.test/tenant/oauth2/v2.0/token',
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ scope: 'api://test-client/access_as_user openid offline_access',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ send_resource_parameter: false,
+ },
+ );
+
+ const params = new URL(authorizationUrl).searchParams;
+ expect(params.has('resource')).toBe(false);
+ /** Unrelated parameters on the configured URL survive. */
+ expect(params.get('scope')).toBe('api://test-client/access_as_user openid offline_access');
+ } finally {
+ await close();
+ }
+ });
+
+ it('replaces an inherited resource with the discovered identifier when enabled', async () => {
+ const { serverUrl, close } = await startProtectedResourceServer();
+ try {
+ const { authorizationUrl } = await MCPOAuthHandler.initiateOAuthFlow(
+ 'entra-server',
+ serverUrl,
+ 'user-1',
+ {},
+ {
+ authorization_url: `${entraAuthorize}?resource=${encodeURIComponent('https://stale.example.test/mcp')}`,
+ token_url: 'https://login.microsoftonline.test/tenant/oauth2/v2.0/token',
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ scope: 'api://test-client/access_as_user openid offline_access',
+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
+ },
+ );
+
+ expect(new URL(authorizationUrl).searchParams.get('resource')).toBe(serverUrl);
+ } finally {
+ await close();
+ }
+ });
+ });
+
+ /**
+ * Stored tokens intentionally survive a change to this setting, but a pending flow
+ * cannot: its authorization URL was already built, so replaying it would reissue the
+ * request the operator just reconfigured away from.
+ */
+ describe('matchesResourceParameterDecision', () => {
+ it('keeps a pending flow whose decision still matches the config', () => {
+ expect(MCPOAuthHandler.matchesResourceParameterDecision({}, {})).toBe(true);
+ expect(
+ MCPOAuthHandler.matchesResourceParameterDecision(
+ { sendResourceParameter: false },
+ { send_resource_parameter: false },
+ ),
+ ).toBe(true);
+ });
+
+ it('retires a pending flow that still sends resource after the opt-out', () => {
+ expect(
+ MCPOAuthHandler.matchesResourceParameterDecision({}, { send_resource_parameter: false }),
+ ).toBe(false);
+ });
+
+ it('retires a pending opted-out flow after the opt-out is withdrawn', () => {
+ expect(
+ MCPOAuthHandler.matchesResourceParameterDecision({ sendResourceParameter: false }, {}),
+ ).toBe(false);
+ });
+
+ it('treats a flow initiated before the field existed as sending resource', () => {
+ // No flag on stored metadata: the flow did send `resource`, so it stays valid
+ // only while the config still asks for it.
+ expect(MCPOAuthHandler.matchesResourceParameterDecision(undefined, undefined)).toBe(true);
+ expect(
+ MCPOAuthHandler.matchesResourceParameterDecision(undefined, {
+ send_resource_parameter: false,
+ }),
+ ).toBe(false);
+ });
+ });
+
+ describe('refresh_token grant', () => {
+ it('sends resource= by default', async () => {
+ const { url, bodies, close } = await startRecordingTokenServer();
+ try {
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'refresh-token-1',
+ { serverName: 'entra-server', resource: 'https://mcp.example.test/mcp' },
+ {},
+ {
+ token_url: url,
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ },
+ );
+
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0].get('resource')).toBe('https://mcp.example.test/mcp');
+ } finally {
+ await close();
+ }
+ });
+
+ it('omits resource= when send_resource_parameter is false', async () => {
+ const { url, bodies, close } = await startRecordingTokenServer();
+ try {
+ await MCPOAuthHandler.refreshOAuthTokens(
+ 'refresh-token-1',
+ { serverName: 'entra-server', resource: 'https://mcp.example.test/mcp' },
+ {},
+ {
+ token_url: url,
+ client_id: 'test-client',
+ client_secret: 'test-secret',
+ send_resource_parameter: false,
+ },
+ );
+
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0].has('resource')).toBe(false);
+ expect(bodies[0].get('grant_type')).toBe('refresh_token');
+ } finally {
+ await close();
+ }
+ });
+ });
+});
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.ts
index 8b9e822aeb..2b7aa4d6eb 100644
--- a/packages/api/src/mcp/__tests__/handler.test.ts
+++ b/packages/api/src/mcp/__tests__/handler.test.ts
@@ -3217,6 +3217,112 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
);
});
+ /**
+ * The `authorization_code` exchange must carry the same parameters as the
+ * `/authorize` request that produced the code, so the decision travels on flow
+ * metadata rather than being re-read from live config. Validation is unaffected:
+ * `assertResourceBoundToServer` runs on both paths before the exchange.
+ */
+ const exchangeFlowState = (sendResourceParameter?: boolean): FlowStateManager<MCPOAuthTokens> =>
+ ({
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: 123,
+ metadata: {
+ serverName: 'entra-server',
+ userId: 'user-123',
+ serverUrl: 'https://example.com/mcp',
+ state: 'abc',
+ codeVerifier: 'verifier',
+ clientInfo: { client_id: 'cid' },
+ metadata: {
+ authorization_endpoint: 'https://login.microsoftonline.test/authorize',
+ token_endpoint: 'https://login.microsoftonline.test/token',
+ },
+ resourceMetadata: { resource: 'https://example.com/mcp' },
+ ...(sendResourceParameter !== undefined && { sendResourceParameter }),
+ } as MCPOAuthFlowMetadata,
+ }),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
+ }) as unknown as FlowStateManager<MCPOAuthTokens>;
+
+ it('omits resource at token exchange when the flow opted out of the parameter', async () => {
+ mockExchangeAuthorization.mockResolvedValue({
+ access_token: 'access-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+
+ await MCPOAuthHandler.completeOAuthFlow('flow-id', 'auth-code', exchangeFlowState(false), {});
+
+ expect(mockExchangeAuthorization).toHaveBeenCalledTimes(1);
+ expect(mockExchangeAuthorization.mock.calls[0][1].resource).toBeUndefined();
+ });
+
+ it('strips an inherited resource from the token endpoint at exchange when opted out', async () => {
+ // The SDK builds the token request from `token_endpoint` verbatim, so a `resource`
+ // left in the configured `token_url` would survive the opt-out.
+ mockExchangeAuthorization.mockResolvedValue({
+ access_token: 'access-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+ const flowManager = {
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: 123,
+ metadata: {
+ serverName: 'entra-server',
+ userId: 'user-123',
+ serverUrl: 'https://example.com/mcp',
+ state: 'abc',
+ codeVerifier: 'verifier',
+ clientInfo: { client_id: 'cid' },
+ metadata: {
+ authorization_endpoint: 'https://login.microsoftonline.test/authorize',
+ token_endpoint:
+ 'https://login.microsoftonline.test/token?resource=https%3A%2F%2Fstale.example.test%2Fmcp&foo=bar',
+ },
+ resourceMetadata: { resource: 'https://example.com/mcp' },
+ sendResourceParameter: false,
+ } as MCPOAuthFlowMetadata,
+ }),
+ completeFlowIfCurrent: jest.fn().mockResolvedValue('updated'),
+ } as unknown as FlowStateManager<MCPOAuthTokens>;
+
+ await MCPOAuthHandler.completeOAuthFlow('flow-id', 'auth-code', flowManager, {});
+
+ const exchangedTokenEndpoint = mockExchangeAuthorization.mock.calls[0][1].metadata
+ ?.token_endpoint as string | undefined;
+ expect(exchangedTokenEndpoint).toBeDefined();
+ const tokenEndpoint = new URL(exchangedTokenEndpoint as string);
+ expect(tokenEndpoint.searchParams.has('resource')).toBe(false);
+ expect(tokenEndpoint.searchParams.get('foo')).toBe('bar');
+ expect(mockExchangeAuthorization.mock.calls[0][1].resource).toBeUndefined();
+ });
+
+ it('sends resource at token exchange for flows initiated before the opt-out existed', async () => {
+ // Mixed-version upgrade: flow state has a bounded TTL, so a flow started under
+ // older code carries no flag and must keep the previous behavior.
+ mockExchangeAuthorization.mockResolvedValue({
+ access_token: 'access-token',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+
+ await MCPOAuthHandler.completeOAuthFlow(
+ 'flow-id',
+ 'auth-code',
+ exchangeFlowState(undefined),
+ {},
+ );
+
+ expect(mockExchangeAuthorization).toHaveBeenCalledTimes(1);
+ expect(mockExchangeAuthorization.mock.calls[0][1].resource?.href).toBe(
+ 'https://example.com/mcp',
+ );
+ });
+
it('falls back to origin-based discovery when the well-known endpoint returns no metadata', async () => {
// A missing/404 PRM doc is different from a spoofed one: the SDK throws, we
// catch it, and proceed to discover the auth server from the MCP server URL.
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index 3bbf1d8214..83c2b568f2 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -589,8 +589,94 @@ export class MCPOAuthHandler {
}
}
- private static appendResourceParameter(body: URLSearchParams, resource?: string): void {
- if (!resource) {
+ /**
+ * RFC 8707 makes `resource` OPTIONAL, and authorization servers that reject it cannot
+ * complete a flow that sends it — Entra ID v2.0 answers `AADSTS9010010` when `resource`
+ * accompanies `scope`. Opting out suppresses the parameter without weakening the
+ * RFC 9728 §3.3 binding, which {@link discoverResourceMetadata} asserts at discovery and
+ * {@link completeOAuthFlow} re-asserts at token exchange regardless of this setting.
+ * See `OAuthOptionsSchema.send_resource_parameter`.
+ */
+ private static shouldSendResourceParameter(config?: MCPOptions['oauth']): boolean {
+ return config?.send_resource_parameter !== false;
+ }
+
+ /**
+ * Removes a `resource` parameter that came from the authorization endpoint itself.
+ * {@link startAuthorization} copies the endpoint's query string verbatim, so a `resource`
+ * an admin left in `authorization_url` — or one present on a discovered endpoint —
+ * survives into the generated request. Opting out has to delete it rather than merely
+ * decline to add one, or the parameter still reaches the provider that rejects it and
+ * the flow this option exists to repair keeps failing.
+ */
+ /**
+ * Returns `endpoint` without its `resource` query parameter.
+ *
+ * The MCP SDK uses `token_endpoint` verbatim and the refresh paths post to the resolved
+ * token URL as-is, so a `resource` an admin left in `token_url` — or one present on a
+ * discovered token endpoint — still reaches the provider even though every place
+ * LibreChat *adds* the parameter is gated. Only the outbound URL is rewritten: stored
+ * metadata keeps its configured form, so {@link assertStoredClientBinding} still matches
+ * and changing the option does not force re-authentication.
+ */
+ private static withoutResourceParameter(
+ endpoint: string | URL,
+ shouldSend: boolean,
+ serverName: string,
+ ): string | URL {
+ if (shouldSend) {
+ return endpoint;
+ }
+ try {
+ const url = new URL(typeof endpoint === 'string' ? endpoint : endpoint.href);
+ if (!url.searchParams.has('resource')) {
+ return endpoint;
+ }
+ url.searchParams.delete('resource');
+ logger.debug(
+ `[MCPOAuth] Removed inherited resource parameter from the token endpoint for ${serverName}; disabled by send_resource_parameter`,
+ );
+ return typeof endpoint === 'string' ? url.href : url;
+ } catch {
+ /** Endpoints are validated absolute URLs; never fail a refresh over sanitization. */
+ return endpoint;
+ }
+ }
+
+ private static stripInheritedResourceParameter(authorizationUrl: URL, serverName: string): void {
+ if (!authorizationUrl.searchParams.has('resource')) {
+ return;
+ }
+ authorizationUrl.searchParams.delete('resource');
+ logger.debug(
+ `[MCPOAuth] Removed inherited resource parameter from the authorization URL for ${serverName}; disabled by send_resource_parameter`,
+ );
+ }
+
+ /**
+ * Whether a pending flow's captured RFC 8707 decision still matches the live config.
+ *
+ * {@link assertStoredClientBinding} deliberately ignores this setting so that flipping it
+ * does not invalidate stored tokens. A pending flow cannot be treated the same way: its
+ * authorization URL was already built with or without `resource`, so replaying it would
+ * reissue exactly the request the operator just reconfigured away from. A flow initiated
+ * before this field existed carries no flag and reads as "sending", which is what it did.
+ */
+ public static matchesResourceParameterDecision(
+ flowMetadata: Pick<MCPOAuthFlowMetadata, 'sendResourceParameter'> | undefined,
+ config?: MCPOptions['oauth'],
+ ): boolean {
+ return (
+ (flowMetadata?.sendResourceParameter !== false) === this.shouldSendResourceParameter(config)
+ );
+ }
+
+ private static appendResourceParameter(
+ body: URLSearchParams,
+ resource?: string,
+ config?: MCPOptions['oauth'],
+ ): void {
+ if (!resource || !this.shouldSendResourceParameter(config)) {
return;
}
body.set('resource', resource);
@@ -730,6 +816,7 @@ export class MCPOAuthHandler {
try {
this.assertNoUnpinnedClientSecret(config);
+ const sendResourceParameter = this.shouldSendResourceParameter(config);
if (config?.authorization_url && config?.token_url && config?.client_id) {
logger.debug(`[MCPOAuth] Using pre-configured OAuth settings for ${serverName}`);
@@ -883,7 +970,12 @@ export class MCPOAuthHandler {
authorizationUrl.searchParams.set('state', state);
logger.debug(`[MCPOAuth] Added state parameter to authorization URL`);
- if (resourceMetadata?.resource) {
+ if (!sendResourceParameter) {
+ this.stripInheritedResourceParameter(authorizationUrl, serverName);
+ logger.debug(
+ `[MCPOAuth] Omitting resource parameter from pre-configured authorization URL for ${serverName}; disabled by send_resource_parameter`,
+ );
+ } else if (resourceMetadata?.resource) {
const canonicalResource = new URL(resourceMetadata.resource).href;
authorizationUrl.searchParams.set('resource', canonicalResource);
logger.debug(
@@ -911,6 +1003,7 @@ export class MCPOAuthHandler {
clientSource: 'configured',
metadata,
resourceMetadata,
+ ...(!sendResourceParameter && { sendResourceParameter: false }),
...(allowedDomains !== undefined && { allowedDomains }),
...(allowedAddresses !== undefined && { allowedAddresses }),
...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),
@@ -1067,7 +1160,12 @@ export class MCPOAuthHandler {
authorizationUrl.searchParams.set('state', state);
logger.debug(`[MCPOAuth] Added state parameter to authorization URL`);
- if (resourceMetadata?.resource) {
+ if (!sendResourceParameter) {
+ this.stripInheritedResourceParameter(authorizationUrl, serverName);
+ logger.debug(
+ `[MCPOAuth] Omitting resource parameter from authorization URL for ${serverName}; disabled by send_resource_parameter`,
+ );
+ } else if (resourceMetadata?.resource) {
/**
* `resource` was already canonicalized and bound to `serverUrl` inside
* {@link discoverMetadata} via {@link assertResourceBoundToServer}, so `new URL`
@@ -1117,6 +1215,7 @@ export class MCPOAuthHandler {
clientSource,
metadata,
resourceMetadata,
+ ...(!sendResourceParameter && { sendResourceParameter: false }),
...(allowedDomains !== undefined && { allowedDomains }),
...(allowedAddresses !== undefined && { allowedAddresses }),
...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),
@@ -1194,6 +1293,7 @@ export class MCPOAuthHandler {
}
let resource: URL | undefined;
+ const sendResourceParameter = metadata.sendResourceParameter !== false;
if (metadata.resourceMetadata) {
/**
* Defense-in-depth: re-assert the RFC 9728 §3.3 binding against the flow's stored
@@ -1203,15 +1303,31 @@ export class MCPOAuthHandler {
* teams to flush flow state on deploy (GHSA-gvpj-vm2f-2m23).
*/
this.assertResourceBoundToServer(metadata.serverUrl, metadata.resourceMetadata);
- if (metadata.resourceMetadata.resource) {
+ if (!sendResourceParameter) {
+ logger.debug(
+ `[MCPOAuth] Omitting resource parameter from token exchange for flow ${flowId}; disabled by send_resource_parameter`,
+ );
+ } else if (metadata.resourceMetadata.resource) {
resource = new URL(metadata.resourceMetadata.resource);
logger.debug(`[MCPOAuth] Resource URL for flow ${flowId}: ${resource.toString()}`);
}
}
+ const exchangeMetadata =
+ sendResourceParameter || typeof metadata.metadata.token_endpoint !== 'string'
+ ? metadata.metadata
+ : {
+ ...metadata.metadata,
+ token_endpoint: this.withoutResourceParameter(
+ metadata.metadata.token_endpoint,
+ false,
+ metadata.serverName,
+ ) as string,
+ };
+
const tokens = await exchangeAuthorization(metadata.serverUrl, {
redirectUri: metadata.clientInfo.redirect_uris?.[0] || this.getDefaultRedirectUri(),
- metadata: metadata.metadata as unknown as SDKOAuthMetadata,
+ metadata: exchangeMetadata as unknown as SDKOAuthMetadata,
clientInformation: metadata.clientInfo,
codeVerifier: metadata.codeVerifier,
authorizationCode,
@@ -1614,7 +1730,13 @@ export class MCPOAuthHandler {
body: URLSearchParams,
serverName: string,
signal?: AbortSignal,
+ config?: MCPOptions['oauth'],
): Promise<Response> {
+ tokenUrl = this.withoutResourceParameter(
+ tokenUrl,
+ this.shouldSendResourceParameter(config),
+ serverName,
+ );
const response = await oauthFetch(tokenUrl, { method: 'POST', headers, body, signal });
if (response.ok || !body.has('scope')) {
return response;
@@ -1819,7 +1941,7 @@ export class MCPOAuthHandler {
if (metadata.clientInfo.scope) {
body.append('scope', metadata.clientInfo.scope);
}
- this.appendResourceParameter(body, metadata.resource);
+ this.appendResourceParameter(body, metadata.resource, config);
/**
* Forward Auth0-style `audience` on refresh by default — Auth0 strips the
@@ -1892,6 +2014,7 @@ export class MCPOAuthHandler {
body,
metadata.serverName,
signal,
+ config,
);
if (!response.ok) {
@@ -1924,7 +2047,7 @@ export class MCPOAuthHandler {
if (config.scope) {
body.append('scope', config.scope);
}
- this.appendResourceParameter(body, metadata.resource);
+ this.appendResourceParameter(body, metadata.resource, config);
const headers: HeadersInit = {
Accept: 'application/json',
@@ -1980,6 +2103,7 @@ export class MCPOAuthHandler {
body,
metadata.serverName,
signal,
+ config,
);
if (!response.ok) {
@@ -2029,7 +2153,7 @@ export class MCPOAuthHandler {
grant_type: 'refresh_token',
refresh_token: refreshToken,
});
- this.appendResourceParameter(body, metadata.resource);
+ this.appendResourceParameter(body, metadata.resource, config);
const headers: HeadersInit = {
Accept: 'application/json',
@@ -2038,12 +2162,19 @@ export class MCPOAuthHandler {
};
const oauthFetch = createHardenedOAuthFetch({ allowedDomains, allowedAddresses });
- const response = await oauthFetch(tokenUrl, {
- method: 'POST',
- headers,
- body,
- signal,
- });
+ const response = await oauthFetch(
+ this.withoutResourceParameter(
+ tokenUrl,
+ this.shouldSendResourceParameter(config),
+ metadata.serverName,
+ ),
+ {
+ method: 'POST',
+ headers,
+ body,
+ signal,
+ },
+ );
if (!response.ok) {
const errorText = await response.text();
diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.ts
index e161a79e38..c16ac7c1c4 100644
--- a/packages/api/src/mcp/oauth/types.ts
+++ b/packages/api/src/mcp/oauth/types.ts
@@ -119,6 +119,12 @@ export interface MCPOAuthFlowMetadata extends FlowMetadata {
reusedClientCredentialSetId?: string;
/** Tenant context captured at flow initiation for callback replay (SameSite cookies unavailable on cross-origin redirects) */
tenantId?: string;
+ /**
+ * False when `oauth.send_resource_parameter` opted this server out of RFC 8707
+ * `resource`. Captured at flow initiation so the token exchange sends the same
+ * parameters as the authorization request that produced the code.
+ */
+ sendResourceParameter?: boolean;
}
export interface MCPOAuthTokens extends OAuthTokens {
diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
index b05a7d3f48..d5fd98d0f0 100644
--- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
+++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
@@ -80,6 +80,7 @@ function sanitizeUserManagedOAuthConfig(config: ParsedServerConfig): ParsedServe
const {
audience: _audience,
forward_audience_on_refresh: _forwardAudienceOnRefresh,
+ send_resource_parameter: _sendResourceParameter,
...oauth
} = config.oauth;
return {
diff --git a/packages/data-provider/specs/mcp.spec.ts b/packages/data-provider/specs/mcp.spec.ts
index 8f2511429a..5c9f756b97 100644
--- a/packages/data-provider/specs/mcp.spec.ts
+++ b/packages/data-provider/specs/mcp.spec.ts
@@ -586,6 +586,20 @@ describe('MCP schemas', () => {
expect(result.success).toBe(false);
});
+ it('should reject the RFC 8707 resource opt-out from user-managed OAuth configuration', () => {
+ // Stripping it silently would save the server while discarding the requested
+ // opt-out, so the flow would keep sending `resource` with nothing telling the user.
+ const result = MCPServerUserInputSchema.safeParse({
+ type: 'streamable-http',
+ url: 'https://mcp-server.com/http',
+ oauth: {
+ send_resource_parameter: false,
+ },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
it('should continue accepting non-audience OAuth fields from user-managed configuration', () => {
const result = MCPServerUserInputSchema.safeParse({
type: 'streamable-http',
@@ -735,6 +749,39 @@ describe('MCP schemas', () => {
expect(result.success).toBe(false);
});
+ it('should accept send_resource_parameter = false (Entra opt-out) from admin config', () => {
+ const result = MCPOptionsSchema.safeParse({
+ type: 'streamable-http',
+ url: 'https://mcp-server.com/http',
+ oauth: {
+ authorization_url: 'https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize',
+ token_url: 'https://login.microsoftonline.com/tenant/oauth2/v2.0/token',
+ client_id: 'app-id',
+ client_secret: 'secret',
+ scope: 'api://app-id/access_as_user openid offline_access',
+ send_resource_parameter: false,
+ },
+ });
+
+ expect(result.success).toBe(true);
+ if (result.success && result.data.oauth) {
+ expect(result.data.oauth.send_resource_parameter).toBe(false);
+ }
+ });
+
+ it('should default send_resource_parameter to undefined when omitted', () => {
+ const result = MCPOptionsSchema.safeParse({
+ type: 'streamable-http',
+ url: 'https://mcp-server.com/http',
+ oauth: { client_id: 'app-id' },
+ });
+
+ expect(result.success).toBe(true);
+ if (result.success && result.data.oauth) {
+ expect(result.data.oauth.send_resource_parameter).toBeUndefined();
+ }
+ });
+
it('should accept forward_audience_on_refresh = false (Cognito opt-out)', () => {
const result = MCPOptionsSchema.safeParse({
type: 'streamable-http',
diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.ts
index b39a4959ea..9072b4a223 100644
--- a/packages/data-provider/src/mcp.ts
+++ b/packages/data-provider/src/mcp.ts
@@ -109,6 +109,27 @@ const OAuthOptionsBaseSchema = z.object({
* Ignored when `audience` itself is not configured.
*/
forward_audience_on_refresh: z.boolean().optional(),
+ /**
+ * Whether to send the RFC 8707 `resource` parameter on `/authorize`, the
+ * `authorization_code` exchange and the `refresh_token` grant. The value is the
+ * canonical resource identifier from the MCP server's Protected Resource Metadata
+ * (RFC 9728), never an operator-supplied string.
+ *
+ * Default: `true`. RFC 8707 makes `resource` OPTIONAL, and authorization servers
+ * that reject it cannot complete a flow that sends it: Microsoft Entra ID v2.0
+ * fails an `/authorize` request carrying both `resource` and `scope` with
+ * `AADSTS9010010`. Set to `false` for those providers, and rely on `scope` (or
+ * `audience` above) to obtain an API-scoped token.
+ *
+ * Opting out suppresses the parameter only. Protected Resource Metadata is still
+ * discovered, still validated against the MCP server URL (RFC 9728 §3.3), and
+ * still recorded on the stored client binding, so scope discovery, authorization
+ * server discovery and re-authentication checks are unaffected.
+ *
+ * This field is only accepted from trusted/admin MCP configuration and is rejected
+ * from user-managed servers.
+ */
+ send_resource_parameter: z.boolean().optional(),
/** OAuth revocation endpoint (optional - can be auto-discovered) */
revocation_endpoint: z
.string()
@@ -145,6 +166,7 @@ const userOAuthEndpointUrlSchema = z
const UserOAuthOptionsSchema = OAuthOptionsBaseSchema.omit({
audience: true,
forward_audience_on_refresh: true,
+ send_resource_parameter: true,
})
.extend({
authorization_url: userOAuthEndpointUrlSchema.optional(),
@@ -153,6 +175,7 @@ const UserOAuthOptionsSchema = OAuthOptionsBaseSchema.omit({
revocation_endpoint: userOAuthEndpointUrlSchema.optional(),
audience: z.never().optional(),
forward_audience_on_refresh: z.never().optional(),
+ send_resource_parameter: z.never().optional(),
})
.superRefine(validateOAuthClientCredentials);