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
123 changes: 123 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,123 @@
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, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}

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).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
: '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>`
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)
}
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)
}
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,
})
} finally {
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(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, server.id)
} catch (error) {
logger.error('MCP OAuth callback failed', error)
return htmlClose('Authorization failed. Please try again.', false, serverId)
}
Comment thread
waleedlatif1 marked this conversation as resolved.
})
152 changes: 152 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,152 @@
/**
* @vitest-environment node
*/
import {
dbChainMock,
dbChainMockFns,
hybridAuthMock,
hybridAuthMockFns,
permissionsMock,
permissionsMockFns,
resetDbChainMock,
schemaMock,
} from '@sim/testing'
import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const {
mockMcpAuth,
mockGetOrCreateOauthRow,
mockLoadPreregisteredClient,
mockSetOauthRowUser,
MockMcpOauthRedirectRequired,
} = vi.hoisted(() => ({
mockMcpAuth: vi.fn(),
mockGetOrCreateOauthRow: vi.fn(),
mockLoadPreregisteredClient: vi.fn(),
mockSetOauthRowUser: vi.fn(),
MockMcpOauthRedirectRequired: class MockMcpOauthRedirectRequired extends Error {
constructor(public readonly authorizationUrl: string) {
super('redirect required')
}
},
}))

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', () => ({
getOrCreateOauthRow: mockGetOrCreateOauthRow,
loadPreregisteredClient: mockLoadPreregisteredClient,
McpOauthRedirectRequired: MockMcpOauthRedirectRequired,
setOauthRowUser: mockSetOauthRowUser,
SimMcpOauthProvider: vi.fn().mockImplementation((value) => value),
}))

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,
},
])
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(),
})
mockLoadPreregisteredClient.mockResolvedValue(undefined)
mockMcpAuth.mockRejectedValue(new MockMcpOauthRedirectRequired('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(mockGetOrCreateOauthRow).toHaveBeenCalledWith({
mcpServerId: 'server-1',
userId: 'user-2',
workspaceId: 'workspace-1',
})
expect(mockSetOauthRowUser).toHaveBeenCalledWith('oauth-row-1', 'user-2')
})

it('rejects a second user starting OAuth while another authorization is active', async () => {
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()
})
})
109 changes: 109 additions & 0 deletions apps/sim/app/api/mcp/oauth/start/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
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,
setOauthRowUser,
} from '@/lib/mcp/oauth'
import { createMcpErrorResponse } from '@/lib/mcp/utils'

const logger = createLogger('McpOauthStartAPI')
const OAUTH_START_TTL_MS = 10 * 60 * 1000

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 hasActiveFlow = !!row.state && row.updatedAt.getTime() > Date.now() - OAUTH_START_TTL_MS
if (hasActiveFlow && row.userId && row.userId !== userId) {
return createMcpErrorResponse(
new Error('OAuth authorization already in progress'),
'OAuth authorization already in progress for this server',
409
)
}
if (row.userId !== userId) {
await setOauthRowUser(row.id, userId)
row.userId = userId
}
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)
}
})
)
Loading
Loading