LibreChat/api/server/services/Tools/mcp.spec.js
J.C. Bartle bf251b820f ♻️ refactor: Pass OBO upstream-token closure into MCP instead of req
Build the OpenID upstream-token provider at the request boundary and thread
only the closure through MCP handling, so the MCP service layer no longer
receives the raw Express request. The closure still reads/refreshes the live
session at tool-call time, preserving the walk-away recovery.

- Drop `req`/`capturedReq` from createMCPTools, createMCPTool, reconnectServer,
  createToolInstance, and reinitMCPServer; forward `upstreamTokenProvider`
  instead. Closure is constructed in loadTools, loadToolDefinitionsWrapper, and
  the reinitialize route, where req/res are in scope.
- OBO: fall back to user.federatedTokens when the provider yields no live
  session, so OIDC remote-agent calls (verified bearer, no session) still work.
- Inline refresh: mirror a rotated refresh token to the refreshToken cookie via
  a shared setRefreshTokenCookie helper, guarded by !res.headersSent (no-op on
  the streaming path; session copy stays authoritative).
- Single-flight: hydrate a joining request's own session from the resolved
  tokens so a later OBO call doesn't replay a rotated-away refresh token.

Addresses owner feedback and three review findings.
2026-06-23 11:59:01 -04:00

202 lines
6.2 KiB
JavaScript

const { Constants } = require('librechat-data-provider');
const mockGetConnection = jest.fn();
const mockDiscoverServerTools = jest.fn();
const mockGetGraphApiToken = jest.fn();
const mockUpdateMCPServerTools = jest.fn();
jest.mock('~/config', () => ({
getMCPManager: jest.fn(() => ({
getConnection: mockGetConnection,
discoverServerTools: mockDiscoverServerTools,
})),
getMCPServersRegistry: jest.fn(() => ({ getServerConfig: jest.fn() })),
getFlowStateManager: jest.fn(() => ({})),
}));
jest.mock('~/models', () => ({
findToken: jest.fn(),
createToken: jest.fn(),
updateToken: jest.fn(),
deleteTokens: jest.fn(),
}));
jest.mock('~/server/services/Config', () => ({
updateMCPServerTools: mockUpdateMCPServerTools,
}));
jest.mock('~/server/services/GraphTokenService', () => ({
getGraphApiToken: mockGetGraphApiToken,
}));
jest.mock('~/cache', () => ({
getLogStores: jest.fn(() => ({})),
}));
const { reinitMCPServer } = require('./mcp');
describe('reinitMCPServer — customUserVars gating (issue #10969)', () => {
const user = { id: 'user-123' };
const serverName = 'Thingy';
const serverConfig = {
type: 'streamable-http',
url: 'https://thingy.example.com/mcp',
customUserVars: {
THINGY_TOKEN: { title: 'Thingy Access Token', description: 'Create this in Thingy' },
},
};
beforeEach(() => {
jest.clearAllMocks();
mockUpdateMCPServerTools.mockResolvedValue({});
});
it('does not connect and exposes no tools when a required customUserVar is unset', async () => {
const result = await reinitMCPServer({
user,
serverName,
serverConfig,
userMCPAuthMap: undefined,
});
expect(mockGetConnection).not.toHaveBeenCalled();
expect(result).toMatchObject({
availableTools: null,
success: false,
tools: null,
oauthRequired: false,
serverName,
});
expect(result.message).toContain('THINGY_TOKEN');
});
it('does not connect when the stored value for a required customUserVar is empty', async () => {
const result = await reinitMCPServer({
user,
serverName,
serverConfig,
userMCPAuthMap: { [`${Constants.mcp_prefix}${serverName}`]: { THINGY_TOKEN: '' } },
});
expect(mockGetConnection).not.toHaveBeenCalled();
expect(result.success).toBe(false);
expect(result.availableTools).toBeNull();
});
it('proceeds to connect once every required customUserVar is provided', async () => {
mockGetConnection.mockResolvedValue({ fetchTools: jest.fn().mockResolvedValue([]) });
await reinitMCPServer({
user,
serverName,
serverConfig,
userMCPAuthMap: {
[`${Constants.mcp_prefix}${serverName}`]: { THINGY_TOKEN: 'secret-token' },
},
});
expect(mockGetConnection).toHaveBeenCalledTimes(1);
expect(mockGetConnection).toHaveBeenCalledWith(
expect.objectContaining({
serverName,
customUserVars: { THINGY_TOKEN: 'secret-token' },
}),
);
});
it('passes request body and Graph resolver into connection creation', async () => {
mockGetConnection.mockResolvedValue({ fetchTools: jest.fn().mockResolvedValue([]) });
const requestBody = { conversationId: 'conv-123', messageId: 'msg-123' };
await reinitMCPServer({
user,
serverName,
serverConfig: { type: 'streamable-http', url: 'https://thingy.example.com/mcp' },
requestBody,
userMCPAuthMap: undefined,
});
expect(mockGetConnection).toHaveBeenCalledWith(
expect.objectContaining({
requestBody,
graphTokenResolver: mockGetGraphApiToken,
}),
);
});
it('forwards the pre-built upstreamTokenProvider closure into connection creation', async () => {
mockGetConnection.mockResolvedValue({ fetchTools: jest.fn().mockResolvedValue([]) });
const upstreamTokenProvider = jest.fn().mockResolvedValue(null);
await reinitMCPServer({
user,
serverName,
serverConfig: { type: 'streamable-http', url: 'https://thingy.example.com/mcp' },
upstreamTokenProvider,
});
expect(mockGetConnection).toHaveBeenCalledWith(
expect.objectContaining({ upstreamTokenProvider }),
);
});
it('passes request body and Graph resolver into OAuth discovery fallback', async () => {
mockGetConnection.mockRejectedValue(new Error('OAuth authentication required'));
mockDiscoverServerTools.mockResolvedValue({ tools: [], oauthRequired: true, oauthUrl: null });
const requestBody = { conversationId: 'conv-456', messageId: 'msg-456' };
await reinitMCPServer({
user,
serverName,
serverConfig: { type: 'streamable-http', url: 'https://thingy.example.com/mcp' },
requestBody,
userMCPAuthMap: undefined,
});
expect(mockDiscoverServerTools).toHaveBeenCalledWith(
expect.objectContaining({
requestBody,
graphTokenResolver: mockGetGraphApiToken,
}),
);
});
it('disconnects ephemeral BODY-scoped connections after loading tools', async () => {
const disconnect = jest.fn().mockResolvedValue(undefined);
const tools = [{ name: 'search', inputSchema: { type: 'object', properties: {} } }];
const serverConfig = {
type: 'streamable-http',
url: 'https://thingy.example.com/messages/{{LIBRECHAT_BODY_MESSAGEID}}/mcp',
source: 'yaml',
};
mockGetConnection.mockResolvedValue({
disconnect,
fetchTools: jest.fn().mockResolvedValue(tools),
});
await reinitMCPServer({
user,
serverName,
serverConfig,
requestBody: { messageId: 'msg-789' },
userMCPAuthMap: undefined,
});
expect(disconnect).toHaveBeenCalledTimes(1);
expect(mockUpdateMCPServerTools).toHaveBeenCalledWith(
expect.objectContaining({
tools,
serverConfig,
}),
);
});
it('proceeds to connect when the server declares no customUserVars', async () => {
mockGetConnection.mockResolvedValue({ fetchTools: jest.fn().mockResolvedValue([]) });
await reinitMCPServer({
user,
serverName,
serverConfig: { type: 'streamable-http', url: 'https://thingy.example.com/mcp' },
userMCPAuthMap: undefined,
});
expect(mockGetConnection).toHaveBeenCalledTimes(1);
});
});