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
🔐 feat: Defer MCP OAuth Sign-In Until a Deferred Tool Is Used (#17225)
Marco Berettaf7b053789e4f
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 410d3d7e4a..3819777dcf 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -27,6 +27,7 @@ const {getCodeApiAuthHeaders,getReplayablePendingMCPOAuthStart,getMCPServerNamesFromTools,+ createMCPOAuthDeferral,buildMCPAuthToolCall,buildMCPAuthStepId,buildMCPAuthRunStepEvent,@@ -1166,6 +1167,16 @@ async function loadToolDefinitionsWrapper({* spellings itself (direct identity first, alias fallback), so this* closure must look up EXACTLY the name it is given. */const approvalMetadata = createMCPToolApprovalMetadata();+ const oauthDeferral = createMCPOAuthDeferral({+ tools: defsFilteredTools,+ toolOptions: agent.tool_options,+ deferredToolsEnabled,+ backgroundToolsEnabled: checkCapability(AgentCapabilities.run_in_background),+ knownServerNames: [...(mcpServerNames ?? []), ...mcpRawServerNames],+ pendingOAuthServers,+ pendingOAuthStarts,+ rememberAvailableTools: rememberMCPAvailableTools,+ });const getOrFetchMCPServerTools = async (userId, serverName) => {const addPendingOAuthServer = async () => {const pendingOAuthStart = await getReplayablePendingMCPOAuthStart({@@ -1226,12 +1237,17 @@ async function loadToolDefinitionsWrapper({const cached = await getMCPServerTools(userId, serverName, serverConfig, capabilityProfile);if (cached) {rememberMCPAvailableTools(serverName, cached);- await addPendingOAuthServer();+ await oauthDeferral.promptUnlessDeferred(+ serverName,+ serverConfig,+ cached,+ addPendingOAuthServer,+ );return cached;}if (await addPendingOAuthServer()) {- return null;+ return oauthDeferral.deferSignIn(serverName, serverConfig);}const oauthStart = async (authURL, options) => {@@ -1261,11 +1277,11 @@ async function loadToolDefinitionsWrapper({});rememberMCPAvailableTools(serverName, result?.availableTools);- return result?.availableTools || null;+ return oauthDeferral.resolveReconnectTools(serverName, serverConfig, result?.availableTools);};const refreshMCPServerTools = async (_userId, serverName) => {- if (pendingOAuthServers.has(serverName)) {+ if (oauthDeferral.hasSignInDecision(serverName)) {return null;}@@ -1402,7 +1418,7 @@ async function loadToolDefinitionsWrapper({/** OAuth discovery must not reconnect (or prompt for) a server whose* definitions the collision filter deliberately rejected. */for (const serverName of getMCPServerNamesFromTools(defsFilteredTools, mcpServerNames)) {- if (pendingOAuthServers.has(serverName)) {+ if (oauthDeferral.hasSignInDecision(serverName)) {continue;}diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.jsindex 5e5180e985..409481d835 100644--- a/api/server/services/__tests__/ToolService.spec.js+++ b/api/server/services/__tests__/ToolService.spec.js@@ -1802,6 +1802,166 @@ describe('ToolService - Action Capability Gating', () => {expect(mockLoadToolDefinitions).toHaveBeenCalledTimes(1);});+ describe('sign-in deferred to the first tool call', () => {+ const serverName = 'Sheets';+ const mcpTool = `read${Constants.mcp_delimiter}${serverName}`;+ const ownCatalog = {+ [mcpTool]: {+ type: 'function',+ function: { name: mcpTool, description: 'Read a sheet', parameters: {} },+ },+ };+ const declaredCatalog = {+ [mcpTool]: {+ type: 'function',+ function: {+ name: mcpTool,+ description: 'Read a sheet',+ parameters: { type: 'object', properties: {} },+ },+ },+ };+ const capabilities = [AgentCapabilities.tools, AgentCapabilities.deferred_tools];+ const deferredAgent = {+ id: 'agent_123',+ tools: [mcpTool],+ tool_options: { [mcpTool]: { defer_loading: true } },+ };++ const setUp = (serverConfig) => {+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));+ mockResolveConfigServers.mockResolvedValue({+ [serverName]: {+ type: 'streamable-http',+ url: 'https://mcp.example.com/sheets',+ requiresOAuth: true,+ oauthPrompt: 'on_use',+ oauthToolCatalog: [{ name: 'read', description: 'Read a sheet' }],+ ...serverConfig,+ },+ });+ mockGetMCPServerTools.mockResolvedValue(null);+ mockFlowManager.getFlowState.mockResolvedValue(null);+ mockLoadToolDefinitions.mockImplementation(async (params, deps) => {+ const fetched = await deps.getOrFetchMCPServerTools(params.userId, serverName);+ return {+ toolDefinitions: fetched ? [{ name: mcpTool }] : [],+ toolRegistry: new Map(),+ hasDeferredTools: fetched != null,+ mcpResolution: { resolvedToolCount: fetched ? 1 : 0 },+ };+ });+ reinitMCPServer.mockImplementation(async ({ returnOnOAuth, oauthStart }) => {+ if (returnOnOAuth === false) {+ return { availableTools: ownCatalog };+ }+ await oauthStart('https://auth.example.com/sheets');+ return { availableTools: null };+ });+ };++ const oauthEvents = () =>+ mockSendEvent.mock.calls.filter(([, event]) =>+ event.data?.stepDetails?.tool_calls?.some((call) => call.name?.startsWith('oauth')),+ );++ it('offers the declared catalog without prompting or waiting', async () => {+ setUp();++ const result = await loadAgentTools({+ req: createMockReq(capabilities),+ res: { writableEnded: false },+ agent: deferredAgent,+ definitionsOnly: true,+ });++ expect(result.toolDefinitions).toEqual([{ name: mcpTool }]);+ expect(result.mcpAvailableTools).toEqual({ [serverName]: declaredCatalog });+ expect(reinitMCPServer).toHaveBeenCalledTimes(1);+ expect(reinitMCPServer).not.toHaveBeenCalledWith(+ expect.objectContaining({ returnOnOAuth: false }),+ );+ expect(oauthEvents()).toHaveLength(0);+ });++ it('does not replay an earlier pending sign-in at turn start', async () => {+ setUp();+ mockFlowManager.getFlowState.mockResolvedValue({+ status: 'PENDING',+ createdAt: Date.now(),+ metadata: { authorizationUrl: 'https://auth.example.com/sheets' },+ });++ const result = await loadAgentTools({+ req: createMockReq(capabilities),+ res: { writableEnded: false },+ agent: deferredAgent,+ definitionsOnly: true,+ });++ expect(result.mcpAvailableTools).toEqual({ [serverName]: declaredCatalog });+ expect(reinitMCPServer).not.toHaveBeenCalled();+ expect(oauthEvents()).toHaveLength(0);+ });++ it("uses the user's own cached catalog without replaying a pending sign-in", async () => {+ setUp();+ mockGetMCPServerTools.mockResolvedValue(ownCatalog);+ mockFlowManager.getFlowState.mockResolvedValue({+ status: 'PENDING',+ createdAt: Date.now(),+ metadata: { authorizationUrl: 'https://auth.example.com/sheets' },+ });++ const result = await loadAgentTools({+ req: createMockReq(capabilities),+ res: { writableEnded: false },+ agent: deferredAgent,+ definitionsOnly: true,+ });++ expect(result.mcpAvailableTools).toEqual({ [serverName]: ownCatalog });+ expect(reinitMCPServer).not.toHaveBeenCalled();+ expect(oauthEvents()).toHaveLength(0);+ });++ it('signs in at turn start when the operator declared no catalog', async () => {+ setUp({ oauthToolCatalog: undefined });++ await loadAgentTools({+ req: createMockReq(capabilities),+ res: { writableEnded: false },+ agent: deferredAgent,+ definitionsOnly: true,+ });++ expect(reinitMCPServer).toHaveBeenCalledWith(+ expect.objectContaining({ serverName, returnOnOAuth: false }),+ );+ expect(oauthEvents()).toHaveLength(1);+ });++ it.each([+ ['the server keeps the default prompt', { oauthPrompt: undefined }, deferredAgent],+ [+ 'a selected tool is not deferred',+ {},+ { ...deferredAgent, tool_options: { [mcpTool]: { defer_loading: false } } },+ ],+ ])('signs in at turn start when %s', async (_label, serverConfig, agent) => {+ setUp(serverConfig);++ await loadAgentTools({+ req: createMockReq(capabilities),+ res: { writableEnded: false },+ agent,+ definitionsOnly: true,+ });++ expect(oauthEvents()).toHaveLength(1);+ });+ });+it('fences resumable MCP OAuth definition events to the owning job epoch', async () => {const req = createMockReq([AgentCapabilities.tools]);const res = { writableEnded: false };diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yamlindex 3feb03b109..b673ee1a45 100644--- a/e2e/config/librechat.e2e.yaml+++ b/e2e/config/librechat.e2e.yaml@@ -118,6 +118,29 @@ mcpServers:authorization_url: http://127.0.0.1:8767/authorizetoken_url: http://127.0.0.1:8767/tokenclient_id: e2e-oauth-client+ e2e-oauth-deferred:+ type: streamable-http+ url: http://127.0.0.1:8767/mcp+ startup: false+ title: E2E OAuth Deferred+ description: Protected MCP fixture whose sign-in waits for the first tool call.+ # Reached through agent tools only; kept out of the composer so palette specs keep their layout.+ chatMenu: false+ timeout: 30000+ requiresOAuth: true+ oauthPrompt: on_use+ oauthToolCatalog:+ - name: echo+ description: Echo the given text back.+ inputSchema:+ type: object+ properties:+ text: { type: string }+ required: [text]+ oauth:+ authorization_url: http://127.0.0.1:8767/authorize+ token_url: http://127.0.0.1:8767/token+ client_id: e2e-oauth-client# __E2E_DYNAMIC_MCP_NETWORK_SERVERS__# __E2E_MCP_APPS_SERVER__diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 9c3beb84ad..e324892d70 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -124,6 +124,7 @@ const TOOL_APPROVAL_BATCH_MARKER = 'E2E_TOOL_APPROVAL_BATCH:';const TOOL_APPROVAL_RESTRICTED_MARKER = 'E2E_TOOL_APPROVAL_RESTRICTED:';const TOOL_APPROVAL_REWRITE_MARKER = 'E2E_TOOL_APPROVAL_REWRITE:';const DEFERRED_HITL_MARKER = 'E2E_DEFERRED_HITL:';+const DEFERRED_OAUTH_MARKER = 'E2E_DEFERRED_OAUTH:';const HANDOFF_MARKER = 'E2E_HANDOFF:';const SUBAGENT_RESULT_MARKER = 'E2E_SUBAGENT_RESULT:';const SUBAGENT_CHILD_MARKER = 'E2E_SUBAGENT_CHILD:';@@ -186,6 +187,7 @@ const BACKGROUND_TOOL_NAME = 'slow_echo_mcp_e2e-memory';const DEFERRED_HITL_TOOL_NAME = BACKGROUND_TOOL_NAME;const DEFERRED_HITL_CONTROL_TOOL_NAME = 'recall_fact_mcp_e2e-memory';const TOOL_SEARCH_NAME = 'tool_search';+const DEFERRED_OAUTH_TOOL_NAME = 'echo_mcp_e2e-oauth-deferred';const ASK_USER_QUESTION_NAME = 'ask_user_question';const CHECK_BACKGROUND_TASK_TOOL_NAME = 'check_background_task';const APPROVAL_TOOL_NAME = 'approval_probe_mcp_e2e-memory';@@ -3083,6 +3085,59 @@ function deferredHitlInvocationResponse({ graph, messages, options, runManager }};}+/**+ * An `oauthPrompt: on_use` server must not hold the turn for sign-in: the model runs first,+ * discovers the server's deferred tool, and only its call asks the user to sign in.+ */+function deferredOAuthInvocationResponse(messages) {+ const label = getMarkerValue(getLatestUserText(messages), DEFERRED_OAUTH_MARKER);+ if (!label) {+ return null;+ }++ const searchCallId = `call_e2e_deferred_oauth_search_${label}`;+ const echoCallId = `call_e2e_deferred_oauth_echo_${label}`;+ const echoResult = findToolMessage(messages, echoCallId);+ if (echoResult) {+ return {+ response: `E2E deferred OAuth tool returned ${label}: ${getContentText(echoResult.content)}`,+ };+ }++ const searchResult = findToolMessage(messages, searchCallId);+ if (searchResult) {+ const searchOutput = getContentText(searchResult.content);+ if (!searchOutput.includes(DEFERRED_OAUTH_TOOL_NAME)) {+ return {+ response: `E2E deferred OAuth failed ${label}: ${TOOL_SEARCH_NAME} did not find ${DEFERRED_OAUTH_TOOL_NAME}`,+ };+ }+ return {+ response: '',+ toolCalls: [+ {+ id: echoCallId,+ name: DEFERRED_OAUTH_TOOL_NAME,+ args: { text: label },+ type: 'tool_call',+ },+ ],+ };+ }++ return {+ response: '',+ toolCalls: [+ {+ id: searchCallId,+ name: TOOL_SEARCH_NAME,+ args: { query: DEFERRED_OAUTH_TOOL_NAME, max_results: 1 },+ type: 'tool_call',+ },+ ],+ };+}+function validateHandoffTool(route, tool, toolName) {const failures = [];const expectedDescription = route.description ?? `Transfer control to agent '${route.to}'`;@@ -3834,6 +3889,7 @@ module.exports = function fakeModelHook(run, context) {options: streamOptions,runManager,}) ??+ deferredOAuthInvocationResponse(streamMessages) ??resolveInvocation?.(streamMessages, streamOptions, runManager) ??null,resolveOnStream: (streamMessages, streamOptions, runManager) =>diff --git a/e2e/specs/mock/scenarios/mcp-oauth-on-use.spec.ts b/e2e/specs/mock/scenarios/mcp-oauth-on-use.spec.tsnew file mode 100644index 0000000000..a9e253f393--- /dev/null+++ b/e2e/specs/mock/scenarios/mcp-oauth-on-use.spec.ts@@ -0,0 +1,118 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import type { Agents } from 'librechat-data-provider';+import type { AgentDetail } from '../agents.helpers';+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from '../agents.helpers';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ fetchJson,+ getAccessToken,+ requestJson,+ sendMessage,+} from '../helpers';++const PROMPT_MARKER = 'E2E_DEFERRED_OAUTH:';+const SIGN_IN_BUTTON = /Sign-in to 127\.0\.0\.1/i;++type GenerationStatus = {+ active?: boolean;+ resumeState?: {+ runSteps?: Agents.RunStep[];+ pendingOAuthPrompts?: Agents.PendingMCPOAuthPrompt[];+ };+};++/** The agent is picked in the builder side panel, which the mobile layout keeps in a drawer. */+test.use({ viewport: { width: 1280, height: 860 }, hasTouch: false, isMobile: false });++function toolCallNames(runSteps: Agents.RunStep[] = []): string[] {+ return runSteps.flatMap((step) => {+ const details = step.stepDetails as { tool_calls?: Array<{ name?: string }> };+ return (details.tool_calls ?? []).map((call) => call.name ?? '');+ });+}++/**+ * Sends a turn to an agent whose only tool is a deferred tool on a protected server, waits for+ * the sign-in prompt, and returns the tool calls the turn made before it.+ */+async function runUntilSignIn(page: Page, serverName: string) {+ const toolId = `echo_mcp_${serverName}`;+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ const token = await getAccessToken(page);+ const agentName = uniqueAgentName('E2E OAuth Prompt Agent');+ const agent = await requestJson<AgentDetail>(page, {+ path: '/api/agents',+ token,+ method: 'POST',+ body: {+ name: agentName,+ description: 'Verifies when MCP OAuth sign-in is requested for a deferred tool.',+ instructions: 'Discover the requested tool, then call it.',+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ tools: [toolId],+ tool_options: { [toolId]: { defer_loading: true } },+ },+ });++ try {+ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name: agentName }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(agentName);+ await form.getByRole('button', { name: 'Select Agent' }).click();++ const label = `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;+ const admission = await sendMessage(page, `${PROMPT_MARKER}${label}`);+ expect(admission.ok()).toBeTruthy();+ const { conversationId } = (await admission.json()) as { conversationId?: string };+ expect(conversationId).toBeTruthy();++ const signIn = page.getByRole('button', { name: SIGN_IN_BUTTON });+ await expect(signIn).toBeVisible({ timeout: 30000 });+ await expect(signIn).toHaveCount(1);++ const status = await fetchJson<GenerationStatus>(+ page,+ `/api/agents/chat/status/${encodeURIComponent(conversationId!)}`,+ token,+ );+ expect(status.active).toBe(true);+ return { toolId, status, calls: toolCallNames(status.resumeState?.runSteps) };+ } finally {+ const stop = page.getByRole('button', { name: 'Stop generating' });+ if (await stop.isVisible({ timeout: 1000 }).catch(() => false)) {+ await stop.click();+ await expect(stop).toBeHidden({ timeout: 10000 });+ }+ await cleanupAgent(page, agent.id);+ }+}++test('an on_use OAuth server asks to sign in when its deferred tool is called @scenario:mcp-oauth-on-use-signs-in-at-tool-call', async ({+ page,+}) => {+ test.setTimeout(120000);+ const serverName = 'e2e-oauth-deferred';+ const { toolId, status, calls } = await runUntilSignIn(page, serverName);++ /** A turn-start prompt holds the turn before the model runs, so neither call would exist. */+ expect(calls).toEqual(expect.arrayContaining(['tool_search', toolId]));+ expect(calls).not.toContain(`oauth_mcp_${serverName}`);+ expect(status.resumeState?.pendingOAuthPrompts ?? []).toHaveLength(0);+});++test('a default OAuth server still asks to sign in when the turn starts @scenario:mcp-oauth-default-signs-in-at-turn-start', async ({+ page,+}) => {+ test.setTimeout(120000);+ const serverName = 'e2e-oauth';+ const { status, calls } = await runUntilSignIn(page, serverName);++ expect(calls).toEqual([`oauth_mcp_${serverName}`]);+ expect(status.resumeState?.pendingOAuthPrompts).toEqual([+ expect.objectContaining({ toolName: `oauth_mcp_${serverName}` }),+ ]);+});diff --git a/librechat.example.yaml b/librechat.example.yamlindex a0ca0e585c..f39437a86f 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -685,6 +685,19 @@ actions:# oauthRefreshWaitTimeout: 15000# # Callback/adoption persistence wait; raise for longer publication budgets (max 840000 ms).# oauthPersistenceWaitTimeout: 15000+# # When to ask users to sign in. `on_start` (default) asks when the turn starts. `on_use`+# # waits for the agent's first call to one of this server's tools, but only when every tool+# # the agent selected from it is deferred. Until a user signs in, tool search offers the+# # tools listed in `oauthToolCatalog`; without one the turn-start prompt is kept.+# # oauthPrompt: on_use+# # oauthToolCatalog:+# # - name: read_sheet+# # description: Read the values in a spreadsheet range+# # inputSchema:+# # type: object+# # properties:+# # range: { type: string }+# # required: [range]# private-openid:# type: streamable-http# url: https://mcp.example.com/mcpdiff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex b3d9bd8dbf..7133de3499 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -25,6 +25,7 @@ export * from './mcp/registry/MCPServersRegistry';export * from './mcp/MCPManager';export * from './mcp/connection';export * from './mcp/toolsChanged';+export * from './mcp/defer';export * from './mcp/oauth';export * from './mcp/auth';export * from './mcp/zod';diff --git a/packages/api/src/mcp/defer.spec.ts b/packages/api/src/mcp/defer.spec.tsnew file mode 100644index 0000000000..bca6a4fcfe--- /dev/null+++ b/packages/api/src/mcp/defer.spec.ts@@ -0,0 +1,308 @@+import { Constants, normalizeServerName } from 'librechat-data-provider';+import type { AgentToolOptions } from 'librechat-data-provider';+import type { LCAvailableTools, LCFunctionTool, ParsedServerConfig } from '~/mcp/types';+import { createMCPOAuthDeferral, shouldDeferMCPOAuthSignIn } from './defer';++const key = (tool: string, server: string) => `${tool}${Constants.mcp_delimiter}${server}`;++const onUseConfig: ParsedServerConfig = {+ type: 'streamable-http',+ url: 'https://sheets.example.com/mcp',+ source: 'yaml',+ requiresOAuth: true,+ oauthPrompt: 'on_use',+ oauthToolCatalog: [+ { name: 'read', description: 'Read a sheet' },+ { name: 'write', description: 'Write a sheet' },+ ],+};++const sheetsTools = [key('read', 'sheets'), key('write', 'sheets')];+const deferredOptions: AgentToolOptions = {+ [key('read', 'sheets')]: { defer_loading: true },+ [key('write', 'sheets')]: { defer_loading: true },+};++const decide = (overrides: Partial<Parameters<typeof shouldDeferMCPOAuthSignIn>[0]> = {}) =>+ shouldDeferMCPOAuthSignIn({+ serverName: 'sheets',+ serverConfig: onUseConfig,+ tools: [...sheetsTools, key('list', 'drive')],+ toolOptions: deferredOptions,+ deferredToolsEnabled: true,+ knownServerNames: ['sheets', 'drive'],+ ...overrides,+ });++describe('shouldDeferMCPOAuthSignIn', () => {+ it('defers a server whose selected tools are all deferred', () => {+ expect(decide()).toBe(true);+ });++ it('ignores server pins and tools from other servers', () => {+ expect(+ decide({ tools: [...sheetsTools, key(Constants.mcp_server, 'sheets'), key('x', 'drive')] }),+ ).toBe(true);+ });++ it('keeps the turn-start prompt when any selected tool loads up front', () => {+ expect(decide({ toolOptions: { ...deferredOptions, [key('write', 'sheets')]: {} } })).toBe(+ false,+ );+ });++ it('keeps the turn-start prompt for a whole-server selection', () => {+ expect(decide({ tools: [key(Constants.mcp_all, 'sheets')] })).toBe(false);+ });++ it('keeps the turn-start prompt when only a pin attaches the server', () => {+ expect(decide({ tools: [key(Constants.mcp_server, 'sheets')] })).toBe(false);+ });++ it('keeps the turn-start prompt when deferred tools are disabled', () => {+ expect(decide({ deferredToolsEnabled: false })).toBe(false);+ });++ it('keeps the turn-start prompt unless the server opts in', () => {+ expect(decide({ serverConfig: { ...onUseConfig, oauthPrompt: undefined } })).toBe(false);+ expect(decide({ serverConfig: { ...onUseConfig, oauthPrompt: 'on_start' } })).toBe(false);+ });++ it('matches tools keyed by a normalized server name', () => {+ const serverName = 'Connector: Company';+ const tool = key('read', normalizeServerName(serverName));+ expect(+ decide({+ serverName,+ tools: [tool],+ toolOptions: { [tool]: { defer_loading: true } },+ knownServerNames: [serverName],+ }),+ ).toBe(true);+ });++ it('keeps the turn-start prompt when the offered catalog misses a selected tool', () => {+ const catalog = { [key('read', 'sheets')]: {} } as LCAvailableTools;+ expect(decide({ catalog })).toBe(false);+ });++ it('keeps the turn-start prompt when a selected tool may run in the background', () => {+ const toolOptions = {+ ...deferredOptions,+ [key('write', 'sheets')]: { defer_loading: true, run_in_background: true },+ };+ expect(decide({ toolOptions, backgroundToolsEnabled: true })).toBe(false);+ expect(decide({ toolOptions, backgroundToolsEnabled: false })).toBe(true);+ });++ it('keeps the turn-start prompt for a wildcard background opt-in', () => {+ const toolOptions = { ...deferredOptions, '*': { run_in_background: true } };+ expect(decide({ toolOptions, backgroundToolsEnabled: true })).toBe(false);+ });++ it('accepts a canonical key whose entry keeps the prefixed upstream name', () => {+ const catalog = {+ [key('read', 'sheets')]: { serverToolName: 'sheets_read' },+ [key('write', 'sheets')]: {},+ } as unknown as LCAvailableTools;+ expect(decide({ catalog })).toBe(true);+ });++ it('matches a stored pre-strip key against its catalog entry', () => {+ const stored = key('sheets_read', 'sheets');+ const catalog = {+ [key('read', 'sheets')]: { serverToolName: 'sheets_read' },+ } as unknown as LCAvailableTools;+ const options = { [stored]: { defer_loading: true } };+ expect(decide({ tools: [stored], toolOptions: options, catalog })).toBe(true);+ expect(+ decide({+ tools: [stored],+ toolOptions: options,+ catalog: { [key('read', 'sheets')]: {} } as LCAvailableTools,+ }),+ ).toBe(false);+ });++ it('reads options saved under the other spelling of a selected tool', () => {+ const stored = key('sheets_read', 'sheets');+ const current = key('read', 'sheets');+ const catalog = {+ [current]: { serverToolName: 'sheets_read' },+ } as unknown as LCAvailableTools;++ expect(+ decide({ tools: [stored], toolOptions: { [current]: { defer_loading: true } }, catalog }),+ ).toBe(true);+ expect(+ decide({ tools: [current], toolOptions: { [stored]: { defer_loading: true } }, catalog }),+ ).toBe(true);+ expect(+ decide({+ tools: [current],+ toolOptions: { [stored]: { defer_loading: true, run_in_background: true } },+ backgroundToolsEnabled: true,+ catalog,+ }),+ ).toBe(false);+ });++ it('prefers options saved under the selected spelling over its alias', () => {+ const stored = key('sheets_read', 'sheets');+ const current = key('read', 'sheets');+ const catalog = {+ [current]: { serverToolName: 'sheets_read' },+ } as unknown as LCAvailableTools;+ const toolOptions = { [stored]: { defer_loading: false }, [current]: { defer_loading: true } };++ expect(decide({ tools: [stored], toolOptions, catalog })).toBe(false);+ });++ it('does not alias options without a catalog proving the identity', () => {+ const stored = key('sheets_read', 'sheets');+ const toolOptions = { [key('read', 'sheets')]: { defer_loading: true } };++ expect(decide({ tools: [stored], toolOptions })).toBe(false);+ });++ it('does not require OAuth to be configured up front', () => {+ expect(decide({ serverConfig: { ...onUseConfig, requiresOAuth: false } })).toBe(true);+ });++ it('keeps the turn-start prompt without a declared catalog', () => {+ expect(decide({ serverConfig: { ...onUseConfig, oauthToolCatalog: undefined } })).toBe(false);+ expect(decide({ serverConfig: { ...onUseConfig, oauthToolCatalog: [] } })).toBe(false);+ });+});++describe('createMCPOAuthDeferral', () => {+ const declared = (name: string, description: string): LCFunctionTool => ({+ type: 'function',+ ['function']: {+ name: key(name, 'sheets'),+ description,+ parameters: { type: 'object', properties: {} },+ },+ });+ const declaredCatalog: LCAvailableTools = {+ [key('read', 'sheets')]: declared('read', 'Read a sheet'),+ [key('write', 'sheets')]: declared('write', 'Write a sheet'),+ };+ const ownCatalog = declaredCatalog;++ const create = () => {+ const pendingOAuthServers = new Set(['sheets']);+ const pendingOAuthStarts = new Map<string, unknown>([['sheets', { authURL: 'x' }]]);+ const rememberAvailableTools = jest.fn();+ const tracker = createMCPOAuthDeferral({+ tools: sheetsTools,+ toolOptions: deferredOptions,+ deferredToolsEnabled: true,+ knownServerNames: ['sheets'],+ pendingOAuthServers,+ pendingOAuthStarts,+ rememberAvailableTools,+ });+ return { tracker, pendingOAuthServers, pendingOAuthStarts, rememberAvailableTools };+ };++ it('withdraws the turn-start prompt and offers the declared catalog', () => {+ const { tracker, pendingOAuthServers, pendingOAuthStarts, rememberAvailableTools } = create();++ expect(tracker.deferSignIn('sheets', onUseConfig)).toEqual(declaredCatalog);+ expect(pendingOAuthServers.has('sheets')).toBe(false);+ expect(pendingOAuthStarts.has('sheets')).toBe(false);+ expect(rememberAvailableTools).toHaveBeenCalledWith('sheets', declaredCatalog);+ expect(tracker.hasSignInDecision('sheets')).toBe(true);+ });++ it('keeps the turn-start prompt for a server that does not qualify', () => {+ const { tracker, pendingOAuthServers, rememberAvailableTools } = create();+ const onStart = { ...onUseConfig, oauthPrompt: 'on_start' as const };++ expect(tracker.deferSignIn('sheets', onStart)).toBeNull();+ expect(pendingOAuthServers.has('sheets')).toBe(true);+ expect(rememberAvailableTools).not.toHaveBeenCalled();+ });++ it('keeps the turn-start prompt when the declared catalog misses a selected tool', () => {+ const { tracker, pendingOAuthServers } = create();+ const partial = { ...onUseConfig, oauthToolCatalog: [{ name: 'read' }] };++ expect(tracker.deferSignIn('sheets', partial)).toBeNull();+ expect(pendingOAuthServers.has('sheets')).toBe(true);+ expect(tracker.hasSignInDecision('sheets')).toBe(true);+ });++ it('defers after a reconnect that found no tools while sign-in is pending', () => {+ const { tracker } = create();++ expect(tracker.resolveReconnectTools('sheets', onUseConfig, {})).toEqual(declaredCatalog);+ });++ it('withdraws the prompt when discovery without a token finds the selected tools', () => {+ const { tracker, pendingOAuthServers, rememberAvailableTools } = create();++ expect(tracker.resolveReconnectTools('sheets', onUseConfig, ownCatalog)).toBe(ownCatalog);+ expect(pendingOAuthServers.has('sheets')).toBe(false);+ expect(rememberAvailableTools).toHaveBeenCalledWith('sheets', ownCatalog);+ });++ it('keeps the prompt when the tools a reconnect found do not qualify', () => {+ const { tracker, pendingOAuthServers } = create();+ const onStart = { ...onUseConfig, oauthPrompt: 'on_start' as const };++ expect(tracker.resolveReconnectTools('sheets', onStart, ownCatalog)).toBe(ownCatalog);+ expect(pendingOAuthServers.has('sheets')).toBe(true);+ });++ it('keeps the tools a reconnect found without a pending sign-in', () => {+ const { tracker, pendingOAuthServers } = create();+ pendingOAuthServers.delete('sheets');++ expect(tracker.resolveReconnectTools('sheets', onUseConfig, ownCatalog)).toBe(ownCatalog);+ expect(tracker.hasSignInDecision('sheets')).toBe(false);+ });++ it('does not defer a reconnect that failed without a pending sign-in', () => {+ const { tracker, pendingOAuthServers } = create();+ pendingOAuthServers.delete('sheets');++ expect(tracker.resolveReconnectTools('sheets', onUseConfig, null)).toBeNull();+ expect(tracker.hasSignInDecision('sheets')).toBe(false);+ });++ it('queues the turn-start prompt only for a server that does not defer', async () => {+ const { tracker } = create();+ const prompt = jest.fn().mockResolvedValue(true);++ await tracker.promptUnlessDeferred('sheets', onUseConfig, ownCatalog, prompt);+ expect(prompt).not.toHaveBeenCalled();++ const onStart = { ...onUseConfig, oauthPrompt: 'on_start' as const };+ await tracker.promptUnlessDeferred('sheets', onStart, ownCatalog, prompt);+ expect(prompt).toHaveBeenCalledTimes(1);++ const partial = { [key('read', 'sheets')]: ownCatalog[key('read', 'sheets')] };+ await tracker.promptUnlessDeferred('sheets', onUseConfig, partial, prompt);+ expect(prompt).toHaveBeenCalledTimes(2);+ });++ it('queues the turn-start prompt for a cached catalog without a declared one', async () => {+ const { tracker } = create();+ const prompt = jest.fn().mockResolvedValue(true);+ const undeclared = { ...onUseConfig, oauthToolCatalog: undefined };++ await tracker.promptUnlessDeferred('sheets', undeclared, ownCatalog, prompt);+ expect(prompt).toHaveBeenCalledTimes(1);+ expect(tracker.hasSignInDecision('sheets')).toBe(true);+ });++ it('records a server deferred with its own catalog', async () => {+ const { tracker, pendingOAuthServers } = create();+ pendingOAuthServers.delete('sheets');++ await tracker.promptUnlessDeferred('sheets', onUseConfig, ownCatalog, jest.fn());+ expect(tracker.hasSignInDecision('sheets')).toBe(true);+ });+});diff --git a/packages/api/src/mcp/defer.ts b/packages/api/src/mcp/defer.tsnew file mode 100644index 0000000000..8279fca4f8--- /dev/null+++ b/packages/api/src/mcp/defer.ts@@ -0,0 +1,247 @@+import {+ Constants,+ normalizeServerName,+ splitMCPToolKey,+ stripServerNamePrefix,+} from 'librechat-data-provider';+import type { AgentToolOptions } from 'librechat-data-provider';+import type { LCAvailableTools, ParsedServerConfig } from '~/mcp/types';+import { canDeferOAuthSignIn, isMCPAllPlaceholder } from '~/mcp/utils';+import { resolveToolOption } from '~/agents/selection';+import { formatMCPServerTools } from '~/mcp/tools';++const serverPinPrefix = `${Constants.mcp_server}${Constants.mcp_delimiter}`;++/**+ * The catalog key a selected tool resolves to, matching the definitions loader: the key itself,+ * or the server-prefix-stripped key whose entry keeps the stored spelling as `serverToolName`.+ */+function catalogKeyFor(+ catalog: LCAvailableTools,+ tool: string,+ toolPart: string,+ keyServerName: string,+): string | undefined {+ if (catalog[tool] != null) {+ return tool;+ }+ const strippedPart = stripServerNamePrefix(toolPart, keyServerName);+ if (strippedPart === toolPart) {+ return undefined;+ }+ const strippedKey = `${strippedPart}${Constants.mcp_delimiter}${keyServerName}`;+ return catalog[strippedKey]?.serverToolName === toolPart ? strippedKey : undefined;+}++/**+ * The tool's other spelling, from which the definitions loader's `aliasMCPToolOptions` heals+ * `tool_options`: the current catalog key for a stored pre-strip key, or the pre-strip name for+ * a current key whose entry keeps one.+ */+function optionsAliasFor(+ catalog: LCAvailableTools,+ tool: string,+ catalogKey: string,+ keyServerName: string,+): string | undefined {+ if (catalogKey !== tool) {+ return catalogKey;+ }+ const serverToolName = catalog[catalogKey]?.serverToolName;+ if (!serverToolName) {+ return undefined;+ }+ const alias = `${serverToolName}${Constants.mcp_delimiter}${keyServerName}`;+ return alias !== tool ? alias : undefined;+}++/** The options the loader reads for a tool, after aliasing them across its spellings. */+function withAliasedOptions(+ tool: string,+ aliasName: string | undefined,+ toolOptions: AgentToolOptions | undefined,+): AgentToolOptions | undefined {+ if (!toolOptions || toolOptions[tool] != null || !aliasName || toolOptions[aliasName] == null) {+ return toolOptions;+ }+ return { ...toolOptions, [tool]: toolOptions[aliasName] };+}++/**+ * Whether a turn may skip the up-front sign-in for a server and leave it to the server's+ * first tool call. That holds only when the server opts in with `oauthPrompt: on_use`, every+ * tool the agent selected from it is deferred, so the model can only reach those tools through+ * tool search and nothing in the turn needs them before it asks for one, and, when given, the+ * catalog offered in the meantime holds every one of them.+ */+export function shouldDeferMCPOAuthSignIn({+ serverName,+ serverConfig,+ tools,+ toolOptions,+ deferredToolsEnabled,+ backgroundToolsEnabled = false,+ knownServerNames,+ catalog,+}: {+ serverName: string;+ serverConfig: ParsedServerConfig;+ tools: readonly string[];+ toolOptions?: AgentToolOptions;+ deferredToolsEnabled: boolean;+ /** Whether the `run_in_background` capability lets opted-in tools run detached. */+ backgroundToolsEnabled?: boolean;+ knownServerNames?: readonly string[];+ catalog?: LCAvailableTools;+}): boolean {+ if (!deferredToolsEnabled || !canDeferOAuthSignIn(serverConfig)) {+ return false;+ }+ /** Tool keys carry the normalized server name; the loader may ask with the raw one. */+ const keyServerName = normalizeServerName(serverName);+ let selected = 0;+ for (const tool of tools) {+ if (tool.startsWith(serverPinPrefix)) {+ continue;+ }+ const [toolPart, toolServerName] = splitMCPToolKey(tool, knownServerNames);+ if (toolServerName !== serverName && toolServerName !== keyServerName) {+ continue;+ }+ if (isMCPAllPlaceholder(tool)) {+ return false;+ }+ const catalogKey = catalog && catalogKeyFor(catalog, tool, toolPart, keyServerName);+ if (catalog && !catalogKey) {+ return false;+ }+ const aliasName =+ catalog && catalogKey ? optionsAliasFor(catalog, tool, catalogKey, keyServerName) : undefined;+ const options = withAliasedOptions(tool, aliasName, toolOptions);+ /** A background call runs detached and could not pause for the sign-in it would trigger. */+ if (+ options?.[tool]?.defer_loading !== true ||+ (backgroundToolsEnabled &&+ resolveToolOption(tool, 'run_in_background', options)?.value === true)+ ) {+ return false;+ }+ selected++;+ }+ return selected > 0;+}++export interface MCPOAuthDeferral {+ /**+ * For a caller that already holds the user's own catalog: queues the turn-start sign-in+ * through `prompt` unless the server defers it and that catalog holds every selected tool.+ */+ promptUnlessDeferred: (+ serverName: string,+ serverConfig: ParsedServerConfig,+ catalog: LCAvailableTools,+ prompt: () => Promise<unknown>,+ ) => Promise<void>;+ /**+ * Defers a qualifying server that is waiting on sign-in, offering the tool catalog its+ * operator declared and withdrawing the turn-start prompt. Null keeps that prompt.+ */+ deferSignIn: (serverName: string, serverConfig: ParsedServerConfig) => LCAvailableTools | null;+ /**+ * The tools a reconnect attempt yields. While a sign-in this turn may defer is pending, the+ * prompt is withdrawn and the attempt's own tools, or the declared catalog when it found+ * none, are offered instead.+ */+ resolveReconnectTools: (+ serverName: string,+ serverConfig: ParsedServerConfig,+ tools: LCAvailableTools | null | undefined,+ ) => LCAvailableTools | null;+ /** Whether the server's sign-in is already settled this turn: prompted for, or deferred. */+ hasSignInDecision: (serverName: string) => boolean;+}++/** Tracks, for one turn's tool loading, which servers leave sign-in to the first tool call. */+export function createMCPOAuthDeferral({+ tools,+ toolOptions,+ deferredToolsEnabled,+ backgroundToolsEnabled,+ knownServerNames,+ pendingOAuthServers,+ pendingOAuthStarts,+ rememberAvailableTools,+}: {+ tools: readonly string[];+ toolOptions?: AgentToolOptions;+ deferredToolsEnabled: boolean;+ backgroundToolsEnabled?: boolean;+ knownServerNames?: readonly string[];+ /** Servers whose turn-start sign-in prompt is queued. */+ pendingOAuthServers: Pick<Set<string>, 'has' | 'delete'>;+ /** Queued turn-start sign-in prompts, by server. */+ pendingOAuthStarts: Pick<Map<string, unknown>, 'delete'>;+ rememberAvailableTools: (serverName: string, availableTools: LCAvailableTools) => void;+}): MCPOAuthDeferral {+ const deferred = new Set<string>();+ const qualifies = (+ serverName: string,+ serverConfig: ParsedServerConfig,+ catalog: LCAvailableTools,+ ): boolean =>+ shouldDeferMCPOAuthSignIn({+ serverName,+ serverConfig,+ tools,+ toolOptions,+ deferredToolsEnabled,+ backgroundToolsEnabled,+ knownServerNames,+ catalog,+ });+ /** Leaves the server's sign-in to its first tool call, withdrawing any turn-start prompt. */+ const withdrawPrompt = (serverName: string, catalog: LCAvailableTools): LCAvailableTools => {+ deferred.add(serverName);+ pendingOAuthServers.delete(serverName);+ pendingOAuthStarts.delete(serverName);+ rememberAvailableTools(serverName, catalog);+ return catalog;+ };+ const deferSignIn = (+ serverName: string,+ serverConfig: ParsedServerConfig,+ ): LCAvailableTools | null => {+ if (!serverConfig.oauthToolCatalog?.length) {+ return null;+ }+ const catalog = formatMCPServerTools(serverName, serverConfig.oauthToolCatalog);+ if (!qualifies(serverName, serverConfig, catalog)) {+ return null;+ }+ return withdrawPrompt(serverName, catalog);+ };+ return {+ promptUnlessDeferred: async (serverName, serverConfig, catalog, prompt) => {+ if (qualifies(serverName, serverConfig, catalog)) {+ deferred.add(serverName);+ return;+ }+ await prompt();+ },+ deferSignIn,+ resolveReconnectTools: (serverName, serverConfig, availableTools) => {+ if (!pendingOAuthServers.has(serverName)) {+ return availableTools || null;+ }+ if (availableTools == null || Object.keys(availableTools).length === 0) {+ return deferSignIn(serverName, serverConfig);+ }+ /** Discovery without a token can still list the tools; the call will need the sign-in. */+ return qualifies(serverName, serverConfig, availableTools)+ ? withdrawPrompt(serverName, availableTools)+ : availableTools;+ },+ hasSignInDecision: (serverName) =>+ pendingOAuthServers.has(serverName) || deferred.has(serverName),+ };+}diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.tsindex f593fe2c12..36af5aa283 100644--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts@@ -129,6 +129,8 @@ const ADMIN_CONFIGURABLE_FIELDS = ['requestHeaders','proxy','requiresOAuth',+ 'oauthPrompt',+ 'oauthToolCatalog','apiKey','oauth','oauth_headers',diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.tsindex 18e7a326e2..5ce89efe0f 100644--- a/packages/api/src/mcp/utils.ts+++ b/packages/api/src/mcp/utils.ts@@ -626,6 +626,27 @@ export function canUseAppConnection(config: UserScopedConnectionConfig): boolean);}+/**+ * Whether a server defers sign-in to its first tool call, offering a user who has not signed in+ * yet the tool catalog the operator declared. Limited to operator-owned servers whose tools+ * cannot vary by request or user input. OAuth itself is not required up front: it is often only+ * discovered when the connection is refused, and the caller only asks once a sign-in is pending.+ * The declared catalog is required even for a user who holds a cached one from an earlier+ * connection: one config then prompts every user at the same point, and a cache that may be stale+ * against the server never decides on its own whether sign-in waits.+ */+export function canDeferOAuthSignIn(config: ParsedServerConfig): boolean {+ return (+ config.oauthPrompt === 'on_use' &&+ (config.oauthToolCatalog?.length ?? 0) > 0 &&+ !isUserSourced(config) &&+ config.obo == null &&+ !hasCustomUserVars(config) &&+ !hasRuntimeContextPlaceholders(config) &&+ !hasChatOnlyHeaders(config)+ );+}+/*** Server instructions fetched from a connection are safe to retain in the* shared YAML registry only when the connection cannot vary by identity ordiff --git a/packages/data-provider/specs/mcp.spec.ts b/packages/data-provider/specs/mcp.spec.tsindex d80b59048c..20f62a7eb1 100644--- a/packages/data-provider/specs/mcp.spec.ts+++ b/packages/data-provider/specs/mcp.spec.ts@@ -882,6 +882,8 @@ describe('MCP_USER_INPUT_FIELDS', () => {expect(MCP_USER_INPUT_FIELDS.has('requiresOAuth')).toBe(false);expect(MCP_USER_INPUT_FIELDS.has('customUserVars')).toBe(false);expect(MCP_USER_INPUT_FIELDS.has('oauth_headers')).toBe(false);+ expect(MCP_USER_INPUT_FIELDS.has('oauthPrompt')).toBe(false);+ expect(MCP_USER_INPUT_FIELDS.has('oauthToolCatalog')).toBe(false);// Stdio is intentionally excluded from MCPServerUserInputSchema (security// posture), so its transport-only fields should not be in the set either.@@ -922,3 +924,72 @@ describe('OAuth coordination rollout configuration', () => {expect(user).not.toHaveProperty('oauthPersistenceWaitTimeout');});});++describe('oauthToolCatalog', () => {+ const server = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ oauthPrompt: 'on_use',+ };+ const catalog = [+ {+ name: 'read_sheet',+ description: 'Read the values in a spreadsheet range',+ inputSchema: {+ type: 'object',+ properties: { range: { type: 'string', enum: ['A1', 'B2'] } },+ required: ['range'],+ },+ },+ ];++ it('accepts an operator-declared catalog', () => {+ expect(+ MCPOptionsSchema.parse({ ...server, oauthToolCatalog: catalog }).oauthToolCatalog,+ ).toEqual(catalog);+ });++ it('rejects schema keywords it cannot carry instead of dropping them', () => {+ const nested = [+ {+ name: 'read_sheet',+ inputSchema: {+ type: 'object',+ properties: { range: { type: 'object', properties: { a1: { type: 'string' } } } },+ },+ },+ ];+ expect(MCPOptionsSchema.safeParse({ ...server, oauthToolCatalog: nested }).success).toBe(false);+ });++ it.each([+ ['an unknown type', { type: 'strng' }],+ ['an empty type list', { type: [] }],+ ['an empty enum', { type: 'string', enum: [] }],+ ])('rejects a property with %s', (_label, property) => {+ const invalid = [+ { name: 'read_sheet', inputSchema: { type: 'object', properties: { range: property } } },+ ];+ expect(MCPOptionsSchema.safeParse({ ...server, oauthToolCatalog: invalid }).success).toBe(+ false,+ );+ });++ it('rejects a misspelled catalog entry key', () => {+ const typo = [{ name: 'read_sheet', input_schema: { type: 'object' } }];+ expect(MCPOptionsSchema.safeParse({ ...server, oauthToolCatalog: typo }).success).toBe(false);+ });++ it('rejects an input schema that is not an object schema', () => {+ const invalid = [{ name: 'read_sheet', inputSchema: { type: 'string' } }];+ expect(MCPOptionsSchema.safeParse({ ...server, oauthToolCatalog: invalid }).success).toBe(+ false,+ );+ });++ it('is not part of the user-managed server schema', () => {+ const parsed = MCPServerUserInputSchema.parse({ ...server, oauthToolCatalog: catalog });+ expect(parsed).not.toHaveProperty('oauthToolCatalog');+ expect(parsed).not.toHaveProperty('oauthPrompt');+ });+});diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.tsindex 9742b9fdfb..faf5c52a0b 100644--- a/packages/data-provider/src/mcp.ts+++ b/packages/data-provider/src/mcp.ts@@ -194,6 +194,41 @@ export const MCP_SERVER_TITLE_PATTERN = new RegExp(export const MCP_SERVER_TITLE_ERROR ='Title must start with a letter or number and can include spaces, hyphens, and apostrophes';+const ToolSchemaScalarSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);+const ToolSchemaTypeSchema = z.enum([+ 'string',+ 'number',+ 'integer',+ 'boolean',+ 'object',+ 'array',+ 'null',+]);+const ToolSchemaTypesSchema = z.union([ToolSchemaTypeSchema, z.array(ToolSchemaTypeSchema).min(1)]);+const ToolSchemaEnumSchema = z.array(ToolSchemaScalarSchema).min(1);++/**+ * One input of a declared tool. Bounded rather than full JSON Schema: it only has to tell tool+ * search and the model what to pass, and the server validates the real call after sign-in.+ * Strict, so a keyword it cannot carry fails config validation instead of being dropped.+ */+const DeclaredToolPropertySchema = z+ .object({+ type: ToolSchemaTypesSchema.optional(),+ description: z.string().optional(),+ enum: ToolSchemaEnumSchema.optional(),+ default: ToolSchemaScalarSchema.optional(),+ items: z+ .object({+ type: ToolSchemaTypesSchema.optional(),+ description: z.string().optional(),+ enum: ToolSchemaEnumSchema.optional(),+ })+ .strict()+ .optional(),+ })+ .strict();+const BaseOptionsSchema = z.object({/** Display name for the MCP server */title: z.string().regex(MCP_SERVER_TITLE_PATTERN, MCP_SERVER_TITLE_ERROR).optional(),@@ -252,6 +287,36 @@ const BaseOptionsSchema = z.object({* If not specified, will be auto-detected during construction*/requiresOAuth: z.boolean().optional(),+ /**+ * When an OAuth server asks the user to sign in:+ * - `on_start` (default): when the conversation turn starts+ * - `on_use`: when the agent first calls one of the server's tools, as long as every+ * tool the agent selected from it is deferred (`defer_loading`) and the server declares+ * an `oauthToolCatalog`+ */+ oauthPrompt: z.enum(['on_start', 'on_use']).optional(),+ /**+ * Tools an `oauthPrompt: on_use` server offers to tool search before the user signs in.+ * Operator supplied, so no user's connection decides what other users' models read.+ */+ oauthToolCatalog: z+ .array(+ z+ .object({+ name: z.string().min(1),+ description: z.string().optional(),+ inputSchema: z+ .object({+ type: z.literal('object'),+ properties: z.record(z.string(), DeclaredToolPropertySchema).optional(),+ required: z.array(z.string()).optional(),+ })+ .strict()+ .optional(),+ })+ .strict(),+ )+ .optional(),/*** OAuth configuration for SSE and Streamable HTTP transports* - Optional: OAuth can be auto-discovered on 401 responses@@ -500,6 +565,8 @@ const omitServerManagedFields = <T extends z.ZodObject<z.ZodRawShape>>(schema: TchatMenu: true,serverInstructions: true,requiresOAuth: true,+ oauthPrompt: true,+ oauthToolCatalog: true,customUserVars: true,oauth_headers: true,});