-
Notifications
You must be signed in to change notification settings - Fork 3.6k
feat(mcp): OAuth 2.1 + PKCE for outbound MCP servers #4441
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
waleedlatif1
wants to merge
32
commits into
staging
Choose a base branch
from
waleedlatif1/mcp-oauth
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+17,750
−495
Open
Changes from all commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
8832991
feat(mcp): OAuth 2.1 + PKCE for outbound MCP servers
waleedlatif1 316bbd5
fix(mcp): address PR review for OAuth feature
waleedlatif1 14e8b53
fix(mcp): promote authType + clear OAuth tokens on credential change
waleedlatif1 b6a5b52
fix(mcp): compare decrypted plaintext for OAuth client secret change
waleedlatif1 a7f7dc6
fix(mcp): trigger OAuth auto-detection probe for empty headers object
waleedlatif1 4926a41
fix(mcp): catch redirect-required error in execute + always test on save
waleedlatif1 7bbaa2d
fix(mcp): treat UnauthorizedError as disconnected in service discover…
waleedlatif1 8d82be3
fix(mcp): allow clearing OAuth credentials in edit + filter deleted s…
waleedlatif1 a27960f
fix(mcp): pass workspaceId to OAuth start + preserve client secret on…
waleedlatif1 5d7ae20
fix(mcp): pass workspaceId on auto-start OAuth after server create
waleedlatif1 2b62d86
fix(mcp): normalize empty/null when detecting OAuth client id change
waleedlatif1 e8f0c0b
fix(mcp): tighten 401 detection, hash OAuth state at rest
waleedlatif1 5136877
fix(mcp): allow OAuth flow for DCR-only servers; detect secret-only e…
waleedlatif1 95b5e69
fix(mcp): clear OAuth tokens on POST upsert; validate https; OAuthCli…
waleedlatif1 92bcd1c
fix(mcp): clear execution timeout to avoid timer leak; redact callbac…
waleedlatif1 570f886
fix(mcp): keep OAuth spinner until popup closes; remove dead comments
waleedlatif1 fb28537
fix(mcp): clear OAuth tokens on server revival; clear popup intervals…
waleedlatif1 87c4d59
chore(mcp): drop redundant useCallback from startOauthForServer
waleedlatif1 b8532e6
chore(mcp): align with React Query and design-token best practices
waleedlatif1 64cc3b8
chore(mcp): drop unobserved useCallback/useMemo, simplify state
waleedlatif1 1ab4ff3
fix(mcp): preserve custom headers for OAuth servers; atomic PATCH + t…
waleedlatif1 3f4196a
fix(mcp): wrap POST upsert delete+update in transaction
waleedlatif1 8714650
fix(mcp): preserve oauthClientSecret on POST upsert when not provided
waleedlatif1 9f37035
fix(mcp): include serverId in OAuth postMessage; honor stored secret …
waleedlatif1 cdd6e2a
fix(mcp): preserve authType on URL-unchanged upserts; fallback server…
waleedlatif1 155afe2
fix(mcp): mark OAuth-pending servers disconnected so reauth UI surfaces
waleedlatif1 f96119f
chore(mcp): cleanup pass; unique OAuth popup name per server
waleedlatif1 fc33e03
fix(mcp): forward serverId on callback failure; allow loopback http
waleedlatif1 b20f643
chore(db): drop OAuth migration; will regenerate post-rebase
waleedlatif1 0de4158
chore(db): regenerate MCP OAuth migration as 0205 post-rebase
waleedlatif1 4fd9cf3
refactor(mcp): cleanup pass — emcn buttons, derived state, OAuth head…
waleedlatif1 c45e164
chore(mcp): final audit pass — strip restated TSDoc and narration com…
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import { auth as mcpAuth } from '@modelcontextprotocol/sdk/client/auth.js' | ||
| import { db } from '@sim/db' | ||
| import { mcpServers } from '@sim/db/schema' | ||
| import { createLogger } from '@sim/logger' | ||
| import { toError } from '@sim/utils/errors' | ||
| import { and, eq, isNull } from 'drizzle-orm' | ||
| import type { NextRequest } from 'next/server' | ||
| import { NextResponse } from 'next/server' | ||
| import { getSession } from '@/lib/auth' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { | ||
| clearState, | ||
| clearVerifier, | ||
| loadOauthRowByState, | ||
| loadPreregisteredClient, | ||
| SimMcpOauthProvider, | ||
| } from '@/lib/mcp/oauth' | ||
| import { mcpService } from '@/lib/mcp/service' | ||
|
|
||
| const logger = createLogger('McpOauthCallbackAPI') | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| function escapeHtml(value: string): string { | ||
| return value | ||
| .replace(/&/g, '&') | ||
| .replace(/</g, '<') | ||
| .replace(/>/g, '>') | ||
| .replace(/"/g, '"') | ||
| .replace(/'/g, ''') | ||
| } | ||
|
|
||
| function htmlClose(message: string, ok: boolean, serverId?: string): NextResponse { | ||
| const safeMessage = escapeHtml(message) | ||
| const title = ok ? 'Connected' : 'Connection failed' | ||
| const serverIdLiteral = serverId ? JSON.stringify(serverId) : 'undefined' | ||
| const body = `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family: system-ui; padding: 24px"><p>${safeMessage}</p><script> | ||
| try { window.opener && window.opener.postMessage({ type: 'mcp-oauth', ok: ${ok ? 'true' : 'false'}, serverId: ${serverIdLiteral} }, window.location.origin) } catch (e) {} | ||
| setTimeout(function () { window.close() }, 800) | ||
| </script></body></html>` | ||
| return new NextResponse(body, { | ||
| headers: { 'Content-Type': 'text/html; charset=utf-8' }, | ||
| }) | ||
| } | ||
|
|
||
| export const GET = withRouteHandler(async (request: NextRequest) => { | ||
| const url = new URL(request.url) | ||
| const state = url.searchParams.get('state') | ||
| const code = url.searchParams.get('code') | ||
| const errorParam = url.searchParams.get('error') | ||
|
|
||
| if (errorParam) { | ||
| logger.warn(`MCP OAuth callback received error: ${errorParam}`) | ||
| return htmlClose(`Authorization failed: ${errorParam}`, false) | ||
| } | ||
| if (!state || !code) { | ||
| return htmlClose('Missing state or code in callback URL.', false) | ||
| } | ||
|
|
||
| let serverId: string | undefined | ||
| try { | ||
| const session = await getSession() | ||
| if (!session?.user?.id) { | ||
| return htmlClose('You must be signed in to complete authorization.', false) | ||
| } | ||
|
|
||
| const row = await loadOauthRowByState(state) | ||
| if (!row) { | ||
| return htmlClose('Invalid or expired authorization state.', false) | ||
| } | ||
| serverId = row.mcpServerId | ||
|
|
||
| if (session.user.id !== row.userId) { | ||
| return htmlClose( | ||
| 'You must be signed in as the same user that initiated the flow.', | ||
| false, | ||
| serverId | ||
| ) | ||
| } | ||
|
|
||
| const [server] = await db | ||
| .select({ id: mcpServers.id, url: mcpServers.url, workspaceId: mcpServers.workspaceId }) | ||
| .from(mcpServers) | ||
| .where(and(eq(mcpServers.id, row.mcpServerId), isNull(mcpServers.deletedAt))) | ||
| .limit(1) | ||
| if (!server || !server.url) { | ||
| return htmlClose('Server no longer exists.', false, serverId) | ||
| } | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
|
|
||
| // Burn state before token exchange so a replayed callback cannot reuse it. | ||
| await clearState(row.id) | ||
|
|
||
| const preregistered = await loadPreregisteredClient(server.id) | ||
| const provider = new SimMcpOauthProvider({ row, preregistered }) | ||
| const result = await mcpAuth(provider, { | ||
| serverUrl: server.url, | ||
| authorizationCode: code, | ||
| }) | ||
|
|
||
| await clearVerifier(row.id) | ||
|
|
||
| if (result !== 'AUTHORIZED') { | ||
| return htmlClose('Authorization did not complete.', false, server.id) | ||
| } | ||
|
|
||
| try { | ||
| await mcpService.clearCache(server.workspaceId) | ||
| await mcpService.discoverServerTools(row.userId, server.id, server.workspaceId) | ||
| } catch (e) { | ||
| logger.warn('Post-auth tools refresh failed', toError(e).message) | ||
| } | ||
|
|
||
| return htmlClose('Connected. You can close this window.', true, server.id) | ||
| } catch (error) { | ||
| logger.error('MCP OAuth callback failed', error) | ||
| return htmlClose('Authorization failed. Please try again.', false, serverId) | ||
| } | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { auth as mcpAuth } from '@modelcontextprotocol/sdk/client/auth.js' | ||
| import { db } from '@sim/db' | ||
| import { mcpServers } from '@sim/db/schema' | ||
| import { createLogger } from '@sim/logger' | ||
| import { toError } from '@sim/utils/errors' | ||
| import { and, eq, isNull } from 'drizzle-orm' | ||
| import type { NextRequest } from 'next/server' | ||
| import { NextResponse } from 'next/server' | ||
| import { startMcpOauthQuerySchema } from '@/lib/api/contracts/mcp' | ||
| import { validationErrorResponse } from '@/lib/api/server' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { withMcpAuth } from '@/lib/mcp/middleware' | ||
| import { | ||
| getOrCreateOauthRow, | ||
| loadPreregisteredClient, | ||
| McpOauthRedirectRequired, | ||
| SimMcpOauthProvider, | ||
| } from '@/lib/mcp/oauth' | ||
| import { createMcpErrorResponse } from '@/lib/mcp/utils' | ||
|
|
||
| const logger = createLogger('McpOauthStartAPI') | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export const GET = withRouteHandler( | ||
| withMcpAuth('write')(async (request: NextRequest, { userId, workspaceId, requestId }) => { | ||
| try { | ||
| const queryResult = startMcpOauthQuerySchema.safeParse( | ||
| Object.fromEntries(new URL(request.url).searchParams) | ||
| ) | ||
| if (!queryResult.success) { | ||
| return validationErrorResponse(queryResult.error) | ||
| } | ||
| const { serverId } = queryResult.data | ||
|
|
||
| const [server] = await db | ||
| .select() | ||
| .from(mcpServers) | ||
| .where( | ||
| and( | ||
| eq(mcpServers.id, serverId), | ||
| eq(mcpServers.workspaceId, workspaceId), | ||
| isNull(mcpServers.deletedAt) | ||
| ) | ||
| ) | ||
| .limit(1) | ||
|
|
||
| if (!server) { | ||
| return createMcpErrorResponse(new Error('Server not found'), 'Server not found', 404) | ||
| } | ||
| if (server.authType !== 'oauth') { | ||
| return createMcpErrorResponse( | ||
| new Error(`Server authType is "${server.authType}", not oauth`), | ||
| 'Server is not configured for OAuth', | ||
| 400 | ||
| ) | ||
| } | ||
| if (!server.url) { | ||
| return createMcpErrorResponse(new Error('Server has no URL'), 'Missing server URL', 400) | ||
| } | ||
|
|
||
| const row = await getOrCreateOauthRow({ | ||
| mcpServerId: server.id, | ||
| userId, | ||
| workspaceId, | ||
| }) | ||
| const preregistered = await loadPreregisteredClient(server.id) | ||
| const provider = new SimMcpOauthProvider({ row, preregistered }) | ||
|
|
||
| try { | ||
| const result = await mcpAuth(provider, { serverUrl: server.url }) | ||
| if (result === 'AUTHORIZED') { | ||
| return NextResponse.json({ status: 'already_authorized' }) | ||
| } | ||
| return createMcpErrorResponse( | ||
| new Error('Provider did not capture redirect URL'), | ||
| 'Failed to start OAuth flow', | ||
| 500 | ||
| ) | ||
| } catch (e) { | ||
| if (e instanceof McpOauthRedirectRequired) { | ||
| logger.info(`[${requestId}] OAuth redirect for server ${serverId}`) | ||
| return NextResponse.json({ | ||
| status: 'redirect', | ||
| authorizationUrl: e.authorizationUrl, | ||
| }) | ||
| } | ||
| throw e | ||
| } | ||
| } catch (error) { | ||
| logger.error(`[${requestId}] Error starting MCP OAuth flow:`, error) | ||
| return createMcpErrorResponse(toError(error), 'Failed to start OAuth flow', 500) | ||
| } | ||
| }) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.