Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions api/server/routes/mcp.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const {
generateCheckAccess,
validateOAuthSession,
OAUTH_SESSION_COOKIE,
parseElicitationFlowId,
} = require('@librechat/api');
const {
createMCPServerController,
Expand Down Expand Up @@ -68,6 +69,24 @@ const canAccessOAuthFlow = (flowId, userId) => {
return parsed.userId === userId || parsed.userId === 'system';
};

/**
* Elicitation flow IDs embed the requesting userId directly (unlike OAuth flow
* IDs, which are one-per-server; elicitation flows are one-per-tool-invocation
* — see `generateElicitationFlowId` in `@librechat/api`). This enforces the
* same per-user ownership OAuth flow routes do, so one user can't complete or
* observe another user's pending elicitation via a guessed/observed flowId.
*/
const canAccessElicitationFlow = (flowId, userId) => {
const parsed = parseElicitationFlowId(flowId);
if (!parsed) {
return false;
}
if (parsed.tenantId && parsed.tenantId !== getTenantId()) {
return false;
}
return parsed.userId === userId;
};

const clearGetTokensFlow = async ({ flowManager, flowId, tokens }) => {
const state = await flowManager.getFlowState(flowId, 'mcp_get_tokens');
if (state?.type === 'mcp_get_tokens' && state.status === 'PENDING') {
Expand Down Expand Up @@ -658,6 +677,46 @@ router.post('/oauth/cancel/:serverName', requireJwtAuth, async (req, res) => {
}
});

/**
* Submit a response to an MCP elicitation request. Completes a pending
* elicitation flow so `MCPManager.callTool` can resume:
* - `action: 'accept' | 'decline' | 'cancel'` — form-mode `elicitation/create`
* response (spec 2025-06-18); `content` carries the submitted field values.
* - `action: 'complete' | 'cancel'` — URL-mode card (either a `mode: 'url'`
* `elicitation/create` request, or a -32042 URL-exception retry): `complete`
* means "I've authorized — continue", which resumes/retries the tool call.
*/
router.post('/elicitation/:flowId', requireJwtAuth, async (req, res) => {
try {
const { flowId } = req.params;
const { action, content } = req.body ?? {};
const user = req.user;

if (!user?.id) {
return res.status(401).json({ error: 'User not authenticated' });
}

if (!action || !['accept', 'decline', 'cancel', 'complete'].includes(action)) {
return res.status(400).json({ error: 'Invalid action' });
}

if (!canAccessElicitationFlow(flowId, user.id)) {
return res.status(403).json({ error: 'Forbidden' });
}

const flowsCache = getLogStores(CacheKeys.FLOWS);
const flowManager = getFlowStateManager(flowsCache);
const ok = await flowManager.completeFlow(flowId, 'mcp_elicit', { action, content });
if (!ok) {
return res.status(404).json({ error: 'Flow not found' });
}
return res.json({ ok: true });
} catch (error) {
logger.error('[MCP Elicitation] Failed to complete elicitation flow', error);
return res.status(500).json({ error: 'Failed to complete elicitation flow' });
}
});

/**
* Reinitialize MCP server
* This endpoint allows reinitializing a specific MCP server
Expand Down
33 changes: 33 additions & 0 deletions api/server/services/MCP.js
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,33 @@ function createOAuthCallback({ runStepEmitter, runStepDeltaEmitter }) {
};
}

/**
* Emits the `on_elicitation` SSE event so the chat UI can render an
* authorization/form card. Covers both wire mechanisms: a `mode: 'form'|'url'`
* `elicitation/create` request, and the -32042 URL-exception path (always
* `mode: 'url'`, no `requestedSchema`).
* @param {object} params
* @param {ServerResponse} params.res - The Express response object for sending events.
* @param {string} params.stepId - The ID of the step.
* @param {string | null} [params.streamId] - The stream ID for resumable mode.
* @returns {(params: { flowId: string; mode: 'form' | 'url'; message: string; serverName?: string; toolName?: string; requestedSchema?: object; url?: string }) => Promise<void>}
*/
function createElicitationStart({ res, stepId, streamId = null }) {
return async function ({ flowId, mode, message, serverName, toolName, requestedSchema, url }) {
const data = {
id: stepId,
runId: Constants.USE_PRELIM_RESPONSE_MESSAGE_ID,
elicitation: { flowId, mode, message, serverName, toolName, requestedSchema, url },
};
const eventData = { event: 'on_elicitation', data };
if (streamId) {
await GenerationJobManager.emitChunk(streamId, eventData);
} else {
sendEvent(res, eventData);
}
};
}

/**
* @param {Object} params
* @param {ServerResponse} params.res - The Express response object for sending events.
Expand Down Expand Up @@ -807,6 +834,11 @@ function createToolInstance({
toolCall,
streamId,
});
const elicitationStart = createElicitationStart({
res,
stepId,
streamId,
});

if (derivedSignal) {
const tenantId = config?.configurable?.user?.tenantId ?? getTenantId();
Expand Down Expand Up @@ -840,6 +872,7 @@ function createToolInstance({
},
oauthStart,
oauthEnd,
elicitationStart,
graphTokenResolver: getGraphApiToken,
oboTokenResolver: exchangeOboToken,
oboTrustChecker: createOboTrustChecker(),
Expand Down
Loading
Loading