Skip to content
Open
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
159 changes: 159 additions & 0 deletions apps/sim/app/api/mcp/oauth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
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 {
assertSafeOauthServerUrl,
clearState,
clearVerifier,
loadOauthRowByState,
loadPreregisteredClient,
type McpOauthCallbackReason,
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, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}

function jsonLiteral(value: string | undefined): string {
if (value === undefined) return 'undefined'
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
}

function htmlClose(
message: string,
ok: boolean,
reason: McpOauthCallbackReason,
serverId?: string
): NextResponse {
const safeMessage = escapeHtml(message)
const title = ok ? 'Connected' : 'Connection failed'
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: ${jsonLiteral(serverId)}, reason: ${jsonLiteral(reason)} }, window.location.origin) } catch (e) {}
setTimeout(function () { window.close() }, 800)
</script></body></html>`
Comment thread
waleedlatif1 marked this conversation as resolved.
Comment thread
waleedlatif1 marked this conversation as resolved.
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, 'provider_error')
}
if (!state || !code) {
return htmlClose('Missing state or code in callback URL.', false, 'missing_params')
}

let serverId: string | undefined
try {
const session = await getSession()
if (!session?.user?.id) {
return htmlClose('You must be signed in to complete authorization.', false, 'unauthenticated')
}

const row = await loadOauthRowByState(state)
if (!row) {
return htmlClose('Invalid or expired authorization state.', false, 'invalid_state')
}
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,
'user_mismatch',
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, 'server_gone', serverId)
}
if (server.workspaceId !== row.workspaceId) {
return htmlClose(
'Workspace mismatch on authorization callback.',
false,
'invalid_state',
serverId
)
}
try {
assertSafeOauthServerUrl(server.url)
} catch {
return htmlClose(
'MCP OAuth requires https (or http://localhost for development).',
false,
'insecure_url',
serverId
)
}
Comment thread
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 })
let result: Awaited<ReturnType<typeof mcpAuth>>
try {
result = await mcpAuth(provider, {
serverUrl: server.url,
authorizationCode: code,
})
} catch (e) {
logger.error('Token exchange failed during MCP OAuth callback', e)
return htmlClose(
'Token exchange failed. Please try again.',
false,
'token_exchange_failed',
server.id
)
} finally {
await clearVerifier(row.id)
}

if (result !== 'AUTHORIZED') {
return htmlClose('Authorization did not complete.', false, 'token_exchange_failed', server.id)
}

try {
await mcpService.clearCache(server.workspaceId)
await mcpService.discoverServerTools(session.user.id, 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, 'authorized', server.id)
} catch (error) {
logger.error('MCP OAuth callback failed', error)
return htmlClose('Authorization failed. Please try again.', false, 'unknown', serverId)
}
Comment thread
waleedlatif1 marked this conversation as resolved.
})
135 changes: 135 additions & 0 deletions apps/sim/app/api/mcp/oauth/start/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* @vitest-environment node
*/
import {
dbChainMock,
dbChainMockFns,
hybridAuthMock,
hybridAuthMockFns,
McpOauthRedirectRequiredMock,
mcpOauthMock,
mcpOauthMockFns,
permissionsMock,
permissionsMockFns,
resetDbChainMock,
schemaMock,
} from '@sim/testing'
import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { mockMcpAuth } = vi.hoisted(() => ({
mockMcpAuth: vi.fn(),
}))

vi.mock('@sim/db', () => dbChainMock)
vi.mock('@sim/db/schema', () => schemaMock)
vi.mock('drizzle-orm', () => ({
and: vi.fn(),
eq: vi.fn(),
isNull: vi.fn(),
}))
vi.mock('@modelcontextprotocol/sdk/client/auth.js', () => ({
auth: mockMcpAuth,
}))
vi.mock('@/lib/auth/hybrid', () => hybridAuthMock)
vi.mock('@/lib/workspaces/permissions/utils', () => permissionsMock)
vi.mock('@/lib/mcp/oauth', () => mcpOauthMock)

import { GET } from './route'

describe('MCP OAuth start route', () => {
beforeEach(() => {
vi.clearAllMocks()
resetDbChainMock()
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({
success: true,
userId: 'user-2',
userName: 'User Two',
userEmail: 'user2@example.com',
authType: 'session',
})
permissionsMockFns.mockGetUserEntityPermissions.mockResolvedValue('write')
dbChainMockFns.limit.mockResolvedValue([
{
id: 'server-1',
name: 'Exa',
url: 'https://mcp.exa.ai/mcp',
workspaceId: 'workspace-1',
authType: 'oauth',
deletedAt: null,
},
])
mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValue({
id: 'oauth-row-1',
mcpServerId: 'server-1',
userId: 'user-1',
workspaceId: 'workspace-1',
clientInformation: null,
tokens: null,
codeVerifier: null,
state: null,
updatedAt: new Date(),
})
mcpOauthMockFns.mockLoadPreregisteredClient.mockResolvedValue(undefined)
mockMcpAuth.mockRejectedValue(new McpOauthRedirectRequiredMock('https://mcp.exa.ai/authorize'))
})

it('requires workspace write permission via MCP auth middleware', async () => {
const request = new NextRequest(
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
)

await GET(request)

expect(permissionsMockFns.mockGetUserEntityPermissions).toHaveBeenCalledWith(
'user-2',
'workspace',
'workspace-1'
)
})

it('uses a workspace-scoped OAuth row and stamps the latest authorizing user', async () => {
const request = new NextRequest(
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
)

const response = await GET(request)
const body = await response.json()

expect(response.status).toBe(200)
expect(body).toEqual({
status: 'redirect',
authorizationUrl: 'https://mcp.exa.ai/authorize',
})
expect(mcpOauthMockFns.mockGetOrCreateOauthRow).toHaveBeenCalledWith({
mcpServerId: 'server-1',
userId: 'user-2',
workspaceId: 'workspace-1',
})
expect(mcpOauthMockFns.mockSetOauthRowUser).toHaveBeenCalledWith('oauth-row-1', 'user-2')
})

it('rejects a second user starting OAuth while another authorization is active', async () => {
mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValueOnce({
id: 'oauth-row-1',
mcpServerId: 'server-1',
userId: 'user-1',
workspaceId: 'workspace-1',
clientInformation: null,
tokens: null,
codeVerifier: null,
state: 'hashed-active-state',
updatedAt: new Date(),
})
const request = new NextRequest(
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
)

const response = await GET(request)
const body = await response.json()

expect(response.status).toBe(409)
expect(body.error).toBe('OAuth authorization already in progress for this server')
expect(mockMcpAuth).not.toHaveBeenCalled()
})
})
Loading
Loading