🪹 fix: Attach Ready OAuth MCP Servers With Empty Catalogs (#15727)

This commit is contained in:
Danny Avila 2026-09-08 07:14:13 -04:00 • committed by GitHub
parent 1b51ec49ee
commit 1dfefc3037
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 245 additions and 131 deletions

View file

@ -8,6 +8,7 @@ const mockSetValue = jest.fn();
const mockGetValues = jest.fn((): string[] => []);
const mockGetToolOptions = jest.fn((): Record<string, object> | undefined => undefined);
const mockMcpServersMap = jest.fn((): Map<string, object> => new Map());
let mockMcpToolsLoading = false;
const mockGetServerStatusIconProps = jest.fn((): object | null => null);
const mockInitializeServer = jest.fn();
const mockIsConnectionDeferred = jest.fn((): boolean => false);
@ -42,7 +43,10 @@ jest.mock('react-hook-form', () => ({
const mockCodeInterpreterSelected = jest.fn((): boolean => false);
jest.mock('~/Providers', () => ({
useAgentPanelContext: () => ({ mcpServersMap: mockMcpServersMap() }),
useAgentPanelContext: () => ({
mcpServersMap: mockMcpServersMap(),
mcpToolsLoading: mockMcpToolsLoading,
}),
}));
jest.mock('~/components/ui', () => ({
@ -189,6 +193,7 @@ describe('McpSection', () => {
mockGetToolOptions.mockReturnValue(undefined);
mockMcpServersMap.mockReset();
mockMcpServersMap.mockReturnValue(new Map());
mockMcpToolsLoading = false;
mockGetServerStatusIconProps.mockReset();
mockGetServerStatusIconProps.mockReturnValue(null);
mockLocalize.mockClear();
@ -308,75 +313,152 @@ describe('McpSection', () => {
expect(screen.getByText('com_ui_tools_mcp_no_tools')).toBeInTheDocument();
});
test('lets a ready request-scoped server attach its runtime tools', () => {
const runtimeItem: McpItem = {
test.each([true, false])(
'lets a ready server attach runtime tools (requestScoped=%s)',
(requestScoped) => {
const runtimeItem: McpItem = {
...item,
server: {
...item.server,
tools: [],
isConnected: !requestScoped,
isReadyForAgent: true,
requestScoped,
} as never,
toolCount: 0,
};
render(<McpSection item={runtimeItem} />);
expect(screen.getByText('com_ui_tools_mcp_runtime_tools_available')).toBeInTheDocument();
expect(mockSetValue).not.toHaveBeenCalled();
fireEvent.click(screen.getByLabelText('com_ui_tools_mcp_select_all'));
expect(mockSetValue).toHaveBeenCalledWith(
'tools',
['sys__server__sys_mcp_srv', 'sys__all__sys_mcp_srv'],
{ shouldDirty: true },
);
},
);
test.each([true, false])(
'detaches runtime tools without affecting unrelated tools (requestScoped=%s)',
(requestScoped) => {
mockGetValues.mockReturnValue([
'sys__server__sys_mcp_srv',
'sys__all__sys_mcp_srv',
'search_mcp_srv',
'dalle',
]);
const runtimeItem: McpItem = {
...item,
server: {
...item.server,
tools: [],
isConnected: true,
isReadyForAgent: true,
requestScoped,
} as never,
toolCount: 0,
};
render(<McpSection item={runtimeItem} />);
expect(screen.getByText('com_ui_tools_mcp_runtime_tools')).toBeInTheDocument();
fireEvent.click(screen.getByLabelText('com_ui_tools_mcp_deselect_all'));
expect(mockSetValue).toHaveBeenCalledWith('tools', ['dalle'], { shouldDirty: true });
},
);
test.each([true, false])(
'does not offer runtime attachment before readiness (requestScoped=%s)',
(requestScoped) => {
const disconnectedRuntimeItem: McpItem = {
...item,
server: {
...item.server,
tools: [],
isConnected: false,
requestScoped,
} as never,
toolCount: 0,
};
render(<McpSection item={disconnectedRuntimeItem} />);
expect(screen.queryByLabelText('com_ui_tools_mcp_select_all')).not.toBeInTheDocument();
expect(
screen.queryByText('com_ui_tools_mcp_runtime_tools_available'),
).not.toBeInTheDocument();
expect(screen.getByText('com_ui_tools_mcp_no_tools')).toBeInTheDocument();
expect(mockSetValue).not.toHaveBeenCalled();
},
);
test('attaches after OAuth succeeds with an empty catalog, but waits for catalog loading', async () => {
const empty: McpItem = {
...item,
server: {
...item.server,
tools: [],
isConnected: false,
isReadyForAgent: true,
requestScoped: true,
} as never,
server: { ...item.server, tools: [], isReadyForAgent: false, requestScoped: false },
toolCount: 0,
};
render(<McpSection item={runtimeItem} />);
expect(screen.getByText('com_ui_tools_mcp_runtime_tools_available')).toBeInTheDocument();
mockInitializeServer.mockResolvedValue({
success: true,
oauthRequired: true,
oauthUrl: 'https://oauth.example/authorize',
});
const { rerender } = render(<McpSection item={empty} />);
fireEvent.click(screen.getByText('com_nav_mcp_connect_server'));
expect(await screen.findByTestId('oauth-dialog')).toBeInTheDocument();
expect(mockSetValue).not.toHaveBeenCalled();
fireEvent.click(screen.getByLabelText('com_ui_tools_mcp_select_all'));
expect(mockSetValue).toHaveBeenCalledWith(
'tools',
['sys__server__sys_mcp_srv', 'sys__all__sys_mcp_srv'],
{ shouldDirty: true },
mockMcpServersMap.mockReturnValue(
new Map([
[
'srv',
{
...empty.server,
isConnected: true,
isReadyForAgent: true,
},
],
]),
);
mockMcpToolsLoading = true;
rerender(<McpSection item={empty} />);
expect(screen.queryByTestId('oauth-dialog')).not.toBeInTheDocument();
expect(screen.queryByLabelText('com_ui_tools_mcp_select_all')).not.toBeInTheDocument();
expect(mockSetValue).not.toHaveBeenCalled();
mockMcpToolsLoading = false;
rerender(<McpSection item={empty} />);
await waitFor(() =>
expect(mockSetValue).toHaveBeenCalledWith(
'tools',
['sys__server__sys_mcp_srv', 'sys__all__sys_mcp_srv'],
{ shouldDirty: true },
),
);
rerender(<McpSection item={empty} />);
expect(mockSetValue).toHaveBeenCalledTimes(1);
});
test('an explicitly unready server cannot attach despite a stale connected flag', () => {
render(
<McpSection
item={{
...item,
toolCount: 0,
server: {
...item.server,
tools: [],
isConnected: true,
isReadyForAgent: false,
},
}}
/>,
);
});
test('detaches every token for a request-scoped server while preserving unrelated tools', () => {
mockGetValues.mockReturnValue([
'sys__server__sys_mcp_srv',
'sys__all__sys_mcp_srv',
'search_mcp_srv',
'dalle',
]);
const runtimeItem: McpItem = {
...item,
server: {
...item.server,
tools: [],
isConnected: true,
isReadyForAgent: true,
requestScoped: true,
} as never,
toolCount: 0,
};
render(<McpSection item={runtimeItem} />);
expect(screen.getByText('com_ui_tools_mcp_runtime_tools')).toBeInTheDocument();
fireEvent.click(screen.getByLabelText('com_ui_tools_mcp_deselect_all'));
expect(mockSetValue).toHaveBeenCalledWith('tools', ['dalle'], { shouldDirty: true });
});
test('does not offer runtime attachment before a request-scoped server is connected', () => {
const disconnectedRuntimeItem: McpItem = {
...item,
server: {
...item.server,
tools: [],
isConnected: false,
requestScoped: true,
} as never,
toolCount: 0,
};
render(<McpSection item={disconnectedRuntimeItem} />);
expect(screen.queryByLabelText('com_ui_tools_mcp_select_all')).not.toBeInTheDocument();
expect(screen.queryByText('com_ui_tools_mcp_runtime_tools_available')).not.toBeInTheDocument();
expect(screen.getByText('com_ui_tools_mcp_no_tools')).toBeInTheDocument();
expect(mockSetValue).not.toHaveBeenCalled();
});

View file

@ -122,8 +122,8 @@ export default function McpSection({ item }: Props) {
/** Subscribe to the tools field so selection toggles re-render this section.
* `getValues` is a non-reactive read and left the checkboxes visually stale. */
const formTools = (useWatch({ control, name: 'tools' }) ?? []) as string[];
/** Attached via the server-wide `mcp_all` wildcard — used by request-scoped
* servers whose tools resolve at chat-turn time and can't be listed here. */
/** Attached via the server-wide `mcp_all` wildcard when tools resolve at
* chat-turn time rather than from the instance catalog. */
const isWildcardAttached = formTools.includes(serverAllToken);
/**
@ -284,9 +284,8 @@ export default function McpSection({ item }: Props) {
[getValues, isServerSelection, serverToken, setValue],
);
/** Request-scoped servers have no per-tool catalog outside a chat turn. Their
* sole meaningful selection is the runtime wildcard, so clearing it detaches
* the whole server instead of leaving behind an unusable server-only pin. */
/** Servers without a visible per-tool catalog attach through the runtime wildcard.
* Clearing it detaches the server instead of leaving an unusable server-only pin. */
const toggleRuntimeTools = useCallback(
(checked: boolean) => {
const current = (getValues('tools') ?? []) as string[];
@ -362,17 +361,12 @@ export default function McpSection({ item }: Props) {
* connects, polling for OAuth), select them all — an effect because both
* signals come from external systems, not from anything rendered here.
*
* Request-scoped servers (runtime `{{LIBRECHAT_BODY_*}}` placeholders) defer
* their connection to the next chat turn, so no tool list will ever arrive —
* attach the whole server via the `mcp_all` wildcard instead; the backend
* resolves it into the server's full tool set at turn time. Keying on the
* manager's init state (not the awaited response) also covers connects that
* happen behind the customUserVars config dialog, which this component does
* not await. */
* A ready server can still have an empty instance catalog when discovery needs
* user credentials or chat fields. Attach its runtime wildcard once loading
* settles. Deferred init also covers connects behind the customUserVars dialog. */
const initConnectionDeferred = isConnectionDeferred(serverName);
const requestScoped = liveServer.requestScoped === true;
const runtimeToolsAvailable =
!hasTools && !toolsLoading && (isWildcardAttached || (requestScoped && isReadyForAgent));
!hasTools && !toolsLoading && (isWildcardAttached || isReadyForAgent);
const runtimeToolsMessage = isWildcardAttached
? 'com_ui_tools_mcp_runtime_tools'
: 'com_ui_tools_mcp_runtime_tools_available';
@ -380,7 +374,7 @@ export default function McpSection({ item }: Props) {
if (!autoSelectPending) {
return;
}
if (initConnectionDeferred && !hasTools) {
if (!hasTools && (initConnectionDeferred || (!toolsLoading && isReadyForAgent))) {
setAutoSelectPending(false);
if (!isWildcardAttached) {
toggleRuntimeTools(true);
@ -395,6 +389,8 @@ export default function McpSection({ item }: Props) {
}, [
autoSelectPending,
initConnectionDeferred,
toolsLoading,
isReadyForAgent,
isConnected,
hasTools,
tools,

View file

@ -148,9 +148,10 @@ export default function ToolsMarketplaceDialog({
}
case 'mcp-add': {
if (item.kind !== 'mcp') break;
const toolIds = item.server.requestScoped
? [mcpAllToken(item.id)]
: (item.server.tools ?? []).map((t) => t.tool_id);
const toolIds =
item.server.requestScoped || !item.server.tools?.length
? [mcpAllToken(item.id)]
: (item.server.tools ?? []).map((t) => t.tool_id);
const current = (getValues('tools') ?? []) as string[];
setValue(
'tools',
@ -190,14 +191,14 @@ export default function ToolsMarketplaceDialog({
return;
}
const wasSelected = selectedIds.has(itemKey(item));
/** An unselected, toolless MCP server normally needs its setup dialog.
* An authorized request-scoped server is already ready and attaches via
* its runtime wildcard; a selected toolless server must remain removable. */
/** Ready servers can resolve their tools with user credentials at runtime,
* even when the instance catalog is empty. Unready servers still need setup;
* a selected toolless server must remain removable. */
if (
item.kind === 'mcp' &&
item.toolCount === 0 &&
!wasSelected &&
!(item.server.requestScoped === true && item.server.isReadyForAgent === true)
!(item.server.isReadyForAgent ?? item.server.isConnected)
) {
setDetailItem(item);
return;

View file

@ -249,70 +249,105 @@ describe('ToolsMarketplaceDialog', () => {
);
});
test('clicking a ready request-scoped zero-tool server attaches its runtime wildcard', () => {
test.each([
[true, false, true],
[false, true, true],
[false, true, undefined],
])(
'attaches a ready empty catalog (requestScoped=%s, connected=%s, ready=%s)',
(requestScoped, isConnected, isReadyForAgent) => {
mockMcpServersMap = new Map([
[
'runtime',
{
serverName: 'runtime',
tools: [],
isConfigured: true,
isConnected,
isReadyForAgent,
requestScoped,
metadata: { name: 'runtime', pluginKey: 'runtime', description: '' },
},
],
]);
render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);
fireEvent.click(screen.getByRole('button', { name: /runtime/ }));
expect(screen.queryByTestId('item-dialog')).not.toBeInTheDocument();
expect(mockSetValue).toHaveBeenCalledWith(
'tools',
['sys__server__sys_mcp_runtime', 'sys__all__sys_mcp_runtime'],
{ shouldDirty: true },
);
},
);
test('keeps concrete tool selection for an ordinary server with a populated catalog', () => {
mockMcpServersMap = new Map([
[
'runtime',
'enumerated',
{
serverName: 'runtime',
tools: [],
serverName: 'enumerated',
tools: [{ tool_id: 'search_mcp_enumerated' }, { tool_id: 'read_mcp_enumerated' }],
isConfigured: true,
isConnected: false,
isConnected: true,
isReadyForAgent: true,
requestScoped: true,
metadata: { name: 'runtime', pluginKey: 'runtime', description: '' },
requestScoped: false,
metadata: { name: 'enumerated', description: '' },
},
],
]);
render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);
fireEvent.click(screen.getByRole('button', { name: /runtime/ }));
expect(screen.queryByTestId('item-dialog')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /enumerated/ }));
expect(mockSetValue).toHaveBeenCalledWith(
'tools',
['sys__server__sys_mcp_runtime', 'sys__all__sys_mcp_runtime'],
['sys__server__sys_mcp_enumerated', 'search_mcp_enumerated', 'read_mcp_enumerated'],
{ shouldDirty: true },
);
});
test('clicking a selected zero-tool server removes all of its tokens directly', () => {
const selectedTools = [
'sys__server__sys_mcp_runtime',
'sys__all__sys_mcp_runtime',
'search_mcp_runtime',
'dalle',
];
mockWatchedTools = selectedTools;
mockGetValues.mockReturnValue(selectedTools);
mockMcpServersMap = new Map([
[
'runtime',
{
serverName: 'runtime',
tools: [],
isConfigured: true,
isConnected: true,
isReadyForAgent: true,
requestScoped: true,
metadata: { name: 'runtime', pluginKey: 'runtime', description: '' },
},
],
]);
test.each([true, false])(
'removes a selected zero-tool server (requestScoped=%s)',
(requestScoped) => {
const selectedTools = [
'sys__server__sys_mcp_runtime',
'sys__all__sys_mcp_runtime',
'search_mcp_runtime',
'dalle',
];
mockWatchedTools = selectedTools;
mockGetValues.mockReturnValue(selectedTools);
mockMcpServersMap = new Map([
[
'runtime',
{
serverName: 'runtime',
tools: [],
isConfigured: true,
isConnected: true,
isReadyForAgent: true,
requestScoped,
metadata: { name: 'runtime', pluginKey: 'runtime', description: '' },
},
],
]);
render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);
fireEvent.click(screen.getByRole('button', { name: /runtime/ }));
render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);
fireEvent.click(screen.getByRole('button', { name: /runtime/ }));
expect(screen.queryByTestId('item-dialog')).not.toBeInTheDocument();
expect(mockSetValue).toHaveBeenCalledWith('tools', ['dalle'], { shouldDirty: true });
});
expect(screen.queryByTestId('item-dialog')).not.toBeInTheDocument();
expect(mockSetValue).toHaveBeenCalledWith('tools', ['dalle'], { shouldDirty: true });
},
);
test.each([
['an ordinary connected', false, true],
['a disconnected request-scoped', true, false],
['an ordinary disconnected', false, false, undefined],
['a disconnected request-scoped', true, false, undefined],
['an explicitly unready connected', false, true, false],
])(
'clicking %s zero-tool server opens setup without changing the form',
(_description, requestScoped, isConnected) => {
(_description, requestScoped, isConnected, isReadyForAgent) => {
mockMcpServersMap = new Map([
[
'setup-required',
@ -322,6 +357,7 @@ describe('ToolsMarketplaceDialog', () => {
isConfigured: true,
isConnected,
requestScoped,
isReadyForAgent,
metadata: {
name: 'setup-required',
pluginKey: 'setup-required',

View file

@ -77,9 +77,8 @@ export function mcpServerToken(serverName: string): string {
* Server-wide wildcard token (`sys__all__sys_mcp_<serverName>`). Unlike the
* UI-only `mcp_server` placeholder (skipped at runtime), `mcp_all` is resolved
* by the backend into ALL of the server's tools at chat-turn time. Used for
* request-scoped servers (runtime `{{LIBRECHAT_BODY_*}}` placeholders) whose
* tools cannot be enumerated outside a chat turn, so per-tool selection is
* impossible and the server must be attached as a whole.
* ready servers whose catalog is unavailable without user credentials or chat
* fields. Per-tool selection is unavailable, so the server attaches as a whole.
*/
export function mcpAllToken(serverName: string): string {
return `${Constants.mcp_all}${Constants.mcp_delimiter}${serverName}`;