From 3f9c398b31a1c02511039be7fab9abff14889130 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 13 Feb 2026 00:10:56 -0500 Subject: [PATCH] feat: MCP OAuth flow improvements (#123) Rewrite OAuth flow handle authentication entirely in web app with secure proxy - Add MCP OAuth proxy with origin validation and callback handling - Remove auto OAuth method from authentication flow - Fix TypeScript build errors - Add directory support for MCP OAuth flows and improve config manager UI - Reload session caches after MCP connection changes --- ROADMAP.md | 65 --- backend/src/index.ts | 16 +- backend/src/routes/mcp-oauth-proxy.ts | 324 +++++++++++ backend/src/routes/settings.ts | 6 +- backend/src/services/mcp-oauth-state.ts | 69 +++ backend/src/services/proxy.ts | 63 +++ frontend/src/api/mcp.ts | 23 +- frontend/src/api/oauth.ts | 2 +- .../src/components/model/ApiKeyDialog.tsx | 2 +- .../src/components/repo/RepoMcpDialog.tsx | 45 +- .../settings/AddMcpServerDialog.tsx | 20 +- .../src/components/settings/AgentDialog.tsx | 2 +- .../src/components/settings/CommandDialog.tsx | 2 +- .../settings/CreateConfigDialog.tsx | 2 +- .../settings/GitCredentialDialog.tsx | 3 +- .../src/components/settings/McpManager.tsx | 61 ++- .../components/settings/McpOAuthDialog.tsx | 505 ++++++++++++------ .../src/components/settings/McpServerCard.tsx | 10 +- .../settings/OAuthAuthorizeDialog.tsx | 17 +- .../settings/OAuthCallbackDialog.tsx | 127 ++--- .../settings/OpenCodeConfigEditor.tsx | 2 +- .../settings/OpenCodeConfigManager.tsx | 116 ++-- .../components/settings/SettingsDialog.tsx | 2 +- .../settings/VersionSelectDialog.tsx | 2 +- frontend/src/components/ui/combobox.tsx | 4 +- frontend/src/components/ui/delete-dialog.tsx | 2 +- frontend/src/components/ui/dialog.tsx | 2 +- frontend/src/components/ui/dropdown-menu.tsx | 4 +- frontend/src/components/ui/select.tsx | 2 +- frontend/src/hooks/useMcpServers.ts | 34 +- frontend/src/lib/oauthErrors.ts | 3 +- 31 files changed, 1054 insertions(+), 483 deletions(-) delete mode 100644 ROADMAP.md create mode 100644 backend/src/routes/mcp-oauth-proxy.ts create mode 100644 backend/src/services/mcp-oauth-state.ts diff --git a/ROADMAP.md b/ROADMAP.md deleted file mode 100644 index 29460f4f..00000000 --- a/ROADMAP.md +++ /dev/null @@ -1,65 +0,0 @@ -# Roadmap - -This document outlines planned features for OpenCode Manager. Items are subject to change based on community feedback and priorities. - -## Phase 1: Authentication (In Progress) - -Implementation of a flexible authentication system using [BetterAuth](https://better-auth.com/). - -### Planned Features - -- **OAuth Providers** - Google, GitHub, GitLab, and other social logins -- **Hardware Keys** - WebAuthn/FIDO2 support for security keys and passkeys -- **OIDC Support** - Custom OpenID Connect provider configuration -- **User-Configurable Auth** - Let users choose which auth methods to enable -- **Session Management** - Secure session handling with refresh tokens -- **Role-Based Access Control** - Foundation for future permission systems - -### Technical Scope - -- BetterAuth integration with Hono backend -- SQLite schema additions for auth tables -- Frontend auth flows (login, signup, settings) -- Auth middleware for protected routes - ---- - -## Phase 2: PWA & Push Notifications - -Installable PWA with real-time push notifications for background alerts. - -### Planned Features - -- **PWA Installability** - Add to Home Screen on mobile and desktop -- **Real-Time Push Notifications** - Get notified when tasks complete, errors occur, or sessions need attention (even when the app isn't open) -- **Cross-Platform Push** - Works on desktop browsers, Android, and iOS (16.4+) -- **Permission Management** - User-friendly opt-in flow -- **Notification Preferences** - Per-category notification settings - -### Use Cases - -Push notifications are valuable for long-running operations: -- Task completed or failed while you're in another app -- Session disconnected or requires input -- Background job status updates - -### iOS Support Note - -Push notifications are fully supported on iOS/iPadOS 16.4+ when the app is installed to the Home Screen: -- App must be added to Home Screen (not just browser) -- Uses standard Web Push API (no Apple Developer account needed) -- Notifications appear on Lock Screen, Notification Center, and Apple Watch - -### Technical Scope - -- Service Worker for push event handling -- Web Push Protocol implementation (VAPID keys) -- Push subscription storage per user/device -- App manifest for PWA installability - - ---- - -## Contributing - -Have ideas or feedback on the roadmap? Open an issue or discussion on GitHub. diff --git a/backend/src/index.ts b/backend/src/index.ts index 2010ee1e..268ccd2e 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -19,6 +19,7 @@ import { createTitleRoutes } from './routes/title' import { createSSERoutes } from './routes/sse' import { createSSHRoutes } from './routes/ssh' import { createNotificationRoutes } from './routes/notifications' +import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy' import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth' import { createAuth } from './auth' import { createAuthMiddleware } from './auth/middleware' @@ -27,7 +28,7 @@ import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } import { SettingsService } from './services/settings' import { opencodeServerManager } from './services/opencode-single-server' import { cleanupOrphanedDirectories } from './services/repo' -import { proxyRequest } from './services/proxy' +import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy' import { NotificationService } from './services/notification' import { logger } from './utils/logger' import { @@ -229,6 +230,7 @@ app.route('/api/auth', createAuthRoutes(auth)) app.route('/api/auth-info', createAuthInfoRoutes(auth, db)) app.route('/api/health', createHealthRoutes(db)) +app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth)) const protectedApi = new Hono() protectedApi.use('/*', requireAuth) @@ -247,6 +249,18 @@ protectedApi.route('/notifications', createNotificationRoutes(notificationServic app.route('/api', protectedApi) +app.post('/api/opencode/mcp/:name/auth', requireAuth, async (c) => { + const serverName = c.req.param('name') + const directory = c.req.query('directory') + return proxyMcpAuthStart(serverName, directory) +}) + +app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => { + const serverName = c.req.param('name') + const directory = c.req.query('directory') + return proxyMcpAuthAuthenticate(serverName, directory) +}) + app.all('/api/opencode/*', requireAuth, async (c) => { const request = c.req.raw return proxyRequest(request) diff --git a/backend/src/routes/mcp-oauth-proxy.ts b/backend/src/routes/mcp-oauth-proxy.ts new file mode 100644 index 00000000..e7a1ea37 --- /dev/null +++ b/backend/src/routes/mcp-oauth-proxy.ts @@ -0,0 +1,324 @@ +import { Hono } from 'hono' +import { z } from 'zod' +import crypto from 'crypto' +import path from 'path' +import { readFile, writeFile, mkdir } from 'fs/promises' +import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state' +import { logger } from '../utils/logger' +import { getWorkspacePath, ENV } from '@opencode-manager/shared/config/env' + +const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` + +const StartSchema = z.object({ + serverName: z.string(), + serverUrl: z.string().url(), + scope: z.string().optional(), + clientId: z.string().optional(), + clientSecret: z.string().optional(), + directory: z.string().optional(), +}) + +function getMcpAuthPath(): string { + return path.join(getWorkspacePath(), '.opencode/state/opencode/mcp-auth.json') +} + +async function readMcpAuth(): Promise> { + try { + const content = await readFile(getMcpAuthPath(), 'utf-8') + return JSON.parse(content) as Record + } catch { + return {} + } +} + +async function writeMcpAuth(data: Record): Promise { + const filePath = getMcpAuthPath() + await mkdir(path.dirname(filePath), { recursive: true }) + await writeFile(filePath, JSON.stringify(data, null, 2), { mode: 0o600 }) +} + +function generateState(): string { + return crypto.randomBytes(32).toString('hex') +} + +function generateCodeVerifier(): string { + return crypto.randomBytes(32).toString('base64url') +} + +async function generateCodeChallenge(verifier: string): Promise { + const hash = crypto.createHash('sha256').update(verifier).digest() + return hash.toString('base64url') +} + +function escapeHtml(unsafe: string): string { + return unsafe + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +function renderPage(heading: string, message: string, isSuccess: boolean): string { + const color = isSuccess ? '#4ade80' : '#f87171' + return ` + + + ${escapeHtml(heading)} + + ${isSuccess ? '' : ''} + + +
+

${escapeHtml(heading)}

+

${escapeHtml(message)}

+
+ +` +} + +async function discoverOAuthMetadata(serverUrl: string): Promise<{ + authorization_endpoint: string + token_endpoint: string + registration_endpoint?: string +} | undefined> { + const url = new URL('/.well-known/oauth-authorization-server', serverUrl) + try { + const response = await fetch(url.toString(), { + headers: { 'MCP-Protocol-Version': '2025-03-26' }, + }) + if (!response.ok) return undefined + return await response.json() as { + authorization_endpoint: string + token_endpoint: string + registration_endpoint?: string + } + } catch { + return undefined + } +} + +async function registerClient( + serverUrl: string, + registrationEndpoint: string | undefined, + callbackUrl: string, + clientSecret?: string, +): Promise<{ client_id: string; client_secret?: string }> { + const regUrl = registrationEndpoint || new URL('/register', serverUrl).toString() + + const response = await fetch(regUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + redirect_uris: [callbackUrl], + client_name: 'OpenCode Manager', + client_uri: 'https://opencode.ai', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: clientSecret ? 'client_secret_post' : 'none', + }), + }) + + if (!response.ok) { + const text = await response.text() + throw new Error(`Dynamic client registration failed: ${response.status} ${text}`) + } + + const result = await response.json() as { client_id: string; client_secret?: string } + return result +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function createMcpOauthProxyRoutes(requireAuth?: any) { + const app = new Hono() + + if (requireAuth) { + app.use('/start', requireAuth) + app.use('/status/*', requireAuth) + } + + app.post('/start', async (c) => { + try { + const body = await c.req.json() + const { serverName, serverUrl, scope, clientId, clientSecret, directory } = StartSchema.parse(body) + + const origin = c.req.header('x-forwarded-proto') && c.req.header('host') + ? `${c.req.header('x-forwarded-proto')}://${c.req.header('host')}` + : c.req.header('origin') || `http://${c.req.header('host') || 'localhost:5003'}` + const callbackUrl = `${origin}/api/mcp-oauth-proxy/callback` + + const metadata = await discoverOAuthMetadata(serverUrl) + if (!metadata) { + return c.json({ error: 'OAuth metadata discovery failed for this MCP server' }, 400) + } + + let resolvedClientId = clientId + let resolvedClientSecret = clientSecret + + if (!resolvedClientId) { + if (!metadata.registration_endpoint) { + return c.json({ error: 'Server does not support dynamic client registration and no clientId provided' }, 400) + } + const registered = await registerClient(serverUrl, metadata.registration_endpoint, callbackUrl, clientSecret) + resolvedClientId = registered.client_id + resolvedClientSecret = registered.client_secret + logger.info(`Registered OAuth client for ${serverName}: ${resolvedClientId}`) + } + + const state = generateState() + const codeVerifier = generateCodeVerifier() + const codeChallenge = await generateCodeChallenge(codeVerifier) + + storeMcpOAuthFlow(state, { + serverName, + serverUrl, + codeVerifier, + clientId: resolvedClientId, + clientSecret: resolvedClientSecret, + callbackUrl, + tokenEndpoint: metadata.token_endpoint, + directory, + }) + + const authUrl = new URL(metadata.authorization_endpoint) + authUrl.searchParams.set('response_type', 'code') + authUrl.searchParams.set('client_id', resolvedClientId) + authUrl.searchParams.set('redirect_uri', callbackUrl) + authUrl.searchParams.set('state', state) + authUrl.searchParams.set('code_challenge', codeChallenge) + authUrl.searchParams.set('code_challenge_method', 'S256') + if (scope) { + authUrl.searchParams.set('scope', scope) + } + + return c.json({ authorizationUrl: authUrl.toString(), flowId: state }) + } catch (error) { + logger.error('MCP OAuth start failed:', error) + const message = error instanceof Error ? error.message : 'Failed to start OAuth flow' + return c.json({ error: message }, 500) + } + }) + + app.get('/status/:flowId', async (c) => { + const flowId = c.req.param('flowId') + const result = getMcpOAuthFlowResult(flowId) + if (!result) { + return c.json({ status: 'unknown' }) + } + return c.json(result) + }) + + app.get('/callback', async (c) => { + const code = c.req.query('code') + const state = c.req.query('state') + const error = c.req.query('error') + const errorDescription = c.req.query('error_description') + + if (!state) { + return c.html(renderPage('Missing State', 'No state parameter. Please try again.', false), 400) + } + + if (error) { + markMcpOAuthFlowFailed(state, errorDescription || error) + deleteMcpOAuthFlow(state) + return c.html(renderPage('Authorization Failed', errorDescription || error, false), 400) + } + + if (!code) { + markMcpOAuthFlowFailed(state, 'No authorization code received') + deleteMcpOAuthFlow(state) + return c.html(renderPage('Missing Code', 'No authorization code. Please try again.', false), 400) + } + + const flow = consumeMcpOAuthFlow(state) + if (!flow) { + return c.html(renderPage('Session Expired', 'Authorization session expired. Please try again.', false), 400) + } + + try { + const params = new URLSearchParams({ + grant_type: 'authorization_code', + client_id: flow.clientId, + code, + code_verifier: flow.codeVerifier, + redirect_uri: flow.callbackUrl, + }) + if (flow.clientSecret) { + params.set('client_secret', flow.clientSecret) + } + + const tokenResponse = await fetch(flow.tokenEndpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: params, + }) + + if (!tokenResponse.ok) { + const errText = await tokenResponse.text() + logger.error(`Token exchange failed for ${flow.serverName}: ${tokenResponse.status} ${errText}`) + markMcpOAuthFlowFailed(state, 'Token exchange failed') + return c.html(renderPage('Token Exchange Failed', 'Failed to exchange code for tokens. Please try again.', false), 500) + } + + const tokens = await tokenResponse.json() as { + access_token: string + refresh_token?: string + expires_in?: number + scope?: string + token_type?: string + } + + const authData = await readMcpAuth() + authData[flow.serverName] = { + ...(authData[flow.serverName] as Record || {}), + serverUrl: flow.serverUrl, + tokens: { + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresAt: tokens.expires_in ? Math.floor(Date.now() / 1000) + tokens.expires_in : undefined, + scope: tokens.scope, + }, + clientInfo: { + clientId: flow.clientId, + clientSecret: flow.clientSecret, + }, + } + await writeMcpAuth(authData) + logger.info(`Wrote OAuth tokens to mcp-auth.json for ${flow.serverName}`) + markMcpOAuthFlowCompleted(state, flow.serverName) + + try { + let reconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect` + if (flow.directory) { + const url = new URL(reconnectUrl) + url.searchParams.set('directory', flow.directory) + reconnectUrl = url.toString() + } + await fetch(reconnectUrl, { + method: 'POST', + }) + if (flow.directory) { + const globalReconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect` + await fetch(globalReconnectUrl, { + method: 'POST', + }) + } + } catch { + logger.warn(`Failed to trigger reconnect for ${flow.serverName}, may need manual reconnect`) + } + + return c.html(renderPage('Authentication Successful', 'You can close this window now.', true)) + } catch (err) { + logger.error('MCP OAuth callback failed:', err) + markMcpOAuthFlowFailed(state, 'Unexpected error during token exchange') + return c.html(renderPage('Unexpected Error', 'An error occurred. Please try again.', false), 500) + } + }) + + return app +} diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index b2909d74..91a843c1 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -125,6 +125,8 @@ const ConnectMcpDirectorySchema = z.object({ directory: z.string().min(1), }) +const McpAuthDirectorySchema = ConnectMcpDirectorySchema + const TestSSHConnectionSchema = z.object({ host: z.string().min(1), sshPrivateKey: z.string().min(1), @@ -1006,12 +1008,12 @@ export function createSettingsRoutes(db: Database) { try { const serverName = c.req.param('name') const body = await c.req.json() - const { directory } = ConnectMcpDirectorySchema.parse(body) + const { directory } = McpAuthDirectorySchema.parse(body) const response = await proxyToOpenCodeWithDirectory( `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`, 'POST', - directory + directory, ) if (!response.ok) { diff --git a/backend/src/services/mcp-oauth-state.ts b/backend/src/services/mcp-oauth-state.ts new file mode 100644 index 00000000..9a5830d8 --- /dev/null +++ b/backend/src/services/mcp-oauth-state.ts @@ -0,0 +1,69 @@ +export interface McpOAuthFlowState { + serverName: string + serverUrl: string + codeVerifier: string + clientId: string + clientSecret?: string + callbackUrl: string + tokenEndpoint: string + timestamp: number + directory?: string +} + +export type McpOAuthFlowResult = + | { status: 'pending' } + | { status: 'completed'; serverName: string } + | { status: 'failed'; error: string } + +const flowStore = new Map() +const resultStore = new Map() +const STATE_TTL_MS = 10 * 60 * 1000 +const RESULT_TTL_MS = 5 * 60 * 1000 +const CLEANUP_INTERVAL_MS = 60 * 1000 + +setInterval(() => { + const now = Date.now() + for (const [key, value] of flowStore) { + if (now - value.timestamp > STATE_TTL_MS) { + flowStore.delete(key) + } + } + for (const [key, value] of resultStore) { + if (now - value.timestamp > RESULT_TTL_MS) { + resultStore.delete(key) + } + } +}, CLEANUP_INTERVAL_MS) + +export function storeMcpOAuthFlow(state: string, data: Omit): void { + flowStore.set(state, { ...data, timestamp: Date.now() }) + resultStore.set(state, { status: 'pending', timestamp: Date.now() }) +} + +export function consumeMcpOAuthFlow(state: string): McpOAuthFlowState | undefined { + const data = flowStore.get(state) + if (data) { + flowStore.delete(state) + } + return data +} + +export function deleteMcpOAuthFlow(state: string): void { + flowStore.delete(state) +} + +export function markMcpOAuthFlowCompleted(state: string, serverName: string): void { + resultStore.set(state, { status: 'completed', serverName, timestamp: Date.now() }) +} + +export function markMcpOAuthFlowFailed(state: string, error: string): void { + resultStore.set(state, { status: 'failed', error, timestamp: Date.now() }) +} + +export function getMcpOAuthFlowResult(state: string): McpOAuthFlowResult | undefined { + const entry = resultStore.get(state) + if (!entry) return undefined + if (entry.status === 'completed') return { status: entry.status, serverName: entry.serverName } + if (entry.status === 'failed') return { status: entry.status, error: entry.error } + return { status: entry.status } +} diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index 54daae55..354f13ff 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -178,3 +178,66 @@ export async function proxyToOpenCodeWithDirectory( }) } } + +export async function proxyMcpAuthStart( + serverName: string, + directory: string | undefined, +): Promise { + const path = `/mcp/${encodeURIComponent(serverName)}/auth` + const url = new URL(`${OPENCODE_SERVER_URL}${path}`) + + if (directory) { + url.searchParams.set('directory', directory) + } + + try { + const response = await fetch(url.toString(), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) + + const responseBody = await response.text() + return new Response(responseBody, { + status: response.status, + headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' }, + }) + } catch (error) { + logger.error(`MCP auth start failed for ${serverName}:`, error) + return new Response(JSON.stringify({ error: 'MCP auth start failed' }), { + status: 502, + headers: { 'Content-Type': 'application/json' }, + }) + } +} + +export async function proxyMcpAuthAuthenticate( + serverName: string, + directory: string | undefined, +): Promise { + const path = `/mcp/${encodeURIComponent(serverName)}/auth/authenticate` + const url = new URL(`${OPENCODE_SERVER_URL}${path}`) + + if (directory) { + url.searchParams.set('directory', directory) + } + + try { + const response = await fetch(url.toString(), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) + + const responseBody = await response.text() + return new Response(responseBody, { + status: response.status, + headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' }, + }) + } catch (error) { + logger.error(`MCP auth authenticate failed for ${serverName}:`, error) + return new Response(JSON.stringify({ error: 'MCP auth authenticate failed' }), { + status: 502, + headers: { 'Content-Type': 'application/json' }, + }) + } +} + diff --git a/frontend/src/api/mcp.ts b/frontend/src/api/mcp.ts index 4ed714a9..7ae948ea 100644 --- a/frontend/src/api/mcp.ts +++ b/frontend/src/api/mcp.ts @@ -33,8 +33,15 @@ export interface AddMcpServerRequest { export interface McpAuthStartResponse { authorizationUrl: string + flowId: string } +export type McpOAuthFlowStatus = + | { status: 'pending' } + | { status: 'completed'; serverName: string } + | { status: 'failed'; error: string } + | { status: 'unknown' } + export const mcpApi = { async getStatus(): Promise { const response = await fetch(`${API_BASE}/api/opencode/mcp`) @@ -79,9 +86,11 @@ export const mcpApi = { return response.json() }, - async startAuth(name: string): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth`, { + async startAuth(name: string, serverUrl: string, scope?: string, clientId?: string, clientSecret?: string, directory?: string): Promise { + const response = await fetch(`${API_BASE}/api/mcp-oauth-proxy/start`, { method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ serverName: name, serverUrl, scope, clientId, clientSecret, directory }), }) if (!response.ok) { const error = await response.json().catch(() => ({ error: response.statusText })) @@ -90,6 +99,14 @@ export const mcpApi = { return response.json() }, + async checkFlowStatus(flowId: string): Promise { + const response = await fetch(`${API_BASE}/api/mcp-oauth-proxy/status/${encodeURIComponent(flowId)}`) + if (!response.ok) { + return { status: 'unknown' } + } + return response.json() + }, + async completeAuth(name: string, code: string): Promise { const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth/callback`, { method: 'POST', @@ -106,6 +123,8 @@ export const mcpApi = { async authenticate(name: string): Promise { const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth/authenticate`, { method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), }) if (!response.ok) { const error = await response.json().catch(() => ({ error: response.statusText })) diff --git a/frontend/src/api/oauth.ts b/frontend/src/api/oauth.ts index d45e7168..66a25632 100644 --- a/frontend/src/api/oauth.ts +++ b/frontend/src/api/oauth.ts @@ -3,7 +3,7 @@ import { fetchWrapper, FetchError } from "./fetchWrapper" export interface OAuthAuthorizeResponse { url: string - method: "auto" | "code" + method: "code" instructions: string } diff --git a/frontend/src/components/model/ApiKeyDialog.tsx b/frontend/src/components/model/ApiKeyDialog.tsx index 8ee71eb4..3eafd2d5 100644 --- a/frontend/src/components/model/ApiKeyDialog.tsx +++ b/frontend/src/components/model/ApiKeyDialog.tsx @@ -64,7 +64,7 @@ export function ApiKeyDialog({ return ( - + diff --git a/frontend/src/components/repo/RepoMcpDialog.tsx b/frontend/src/components/repo/RepoMcpDialog.tsx index c429f2ae..a5d94580 100644 --- a/frontend/src/components/repo/RepoMcpDialog.tsx +++ b/frontend/src/components/repo/RepoMcpDialog.tsx @@ -9,7 +9,8 @@ import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu' import { Loader2, XCircle, AlertCircle, Plug, Shield, MoreVertical, Key, RefreshCw } from 'lucide-react' import { McpOAuthDialog } from '@/components/settings/McpOAuthDialog' import { mcpApi, type McpStatus, type McpServerConfig, type McpAuthStartResponse } from '@/api/mcp' -import { useMutation } from '@tanstack/react-query' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { invalidateSessionCaches } from '@/lib/queryInvalidation' import { showToast } from '@/lib/toast' interface RepoMcpDialogProps { @@ -22,6 +23,7 @@ interface RepoMcpDialogProps { } export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcpDialogProps) { + const queryClient = useQueryClient() const [localStatus, setLocalStatus] = useState>({}) const [isLoadingStatus, setIsLoadingStatus] = useState(false) const [removeAuthConfirmServer, setRemoveAuthConfirmServer] = useState(null) @@ -61,6 +63,7 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp onSuccess: async () => { showToast.success('MCP server updated for this location') await fetchStatus() + invalidateSessionCaches(queryClient) }, onError: (error) => { showToast.error(error instanceof Error ? error.message : 'Failed to update MCP server') @@ -76,30 +79,51 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp showToast.success('Authentication removed for this location') setRemoveAuthConfirmServer(null) await fetchStatus() + invalidateSessionCaches(queryClient) }, onError: (error) => { showToast.error(error instanceof Error ? error.message : 'Failed to remove authentication') }, }) - const handleOAuthAutoAuth = async () => { - if (!authDialogServerId || !directory) return - await mcpApi.authenticateDirectory(authDialogServerId, directory) - await fetchStatus() - setAuthDialogServerId(null) - } - const handleOAuthStartAuth = async (): Promise => { if (!authDialogServerId) throw new Error('No server ID') - return await mcpApi.startAuth(authDialogServerId) + const serverConfig = mcpServers[authDialogServerId] + if (!serverConfig?.url) throw new Error('Server URL not found') + const oauthConfig = typeof serverConfig.oauth === 'object' ? serverConfig.oauth : undefined + return await mcpApi.startAuth( + authDialogServerId, + serverConfig.url, + oauthConfig?.scope, + oauthConfig?.clientId, + oauthConfig?.clientSecret, + directory, + ) } const handleOAuthCompleteAuth = async (code: string) => { if (!authDialogServerId) return await mcpApi.completeAuth(authDialogServerId, code) await fetchStatus() + invalidateSessionCaches(queryClient) setAuthDialogServerId(null) } + + const handleOAuthCheckStatus = async (): Promise => { + if (!authDialogServerId || !directory) return false + const status = await mcpApi.getStatusFor(directory) + const serverStatus = status[authDialogServerId] + if (serverStatus?.status === 'connected') { + setLocalStatus(status) + return true + } + return false + } + + const handleOAuthSuccess = () => { + fetchStatus() + invalidateSessionCaches(queryClient) + } useEffect(() => { if (open && directory) { @@ -308,9 +332,10 @@ export function RepoMcpDialog({ open, onOpenChange, config, directory }: RepoMcp open={!!authDialogServerId} onOpenChange={(o) => !o && setAuthDialogServerId(null)} serverName={authDialogServerId || ''} - onAutoAuth={handleOAuthAutoAuth} onStartAuth={handleOAuthStartAuth} onCompleteAuth={handleOAuthCompleteAuth} + onCheckStatus={handleOAuthCheckStatus} + onSuccess={handleOAuthSuccess} directory={directory} /> diff --git a/frontend/src/components/settings/AddMcpServerDialog.tsx b/frontend/src/components/settings/AddMcpServerDialog.tsx index 572a071d..a8426655 100644 --- a/frontend/src/components/settings/AddMcpServerDialog.tsx +++ b/frontend/src/components/settings/AddMcpServerDialog.tsx @@ -179,14 +179,14 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe return ( - + Add MCP Server
-
+
-
+
) : ( -
+
Leave fields blank to use the server's default OAuth discovery

-
+
-
+
-
+
+
- -
+ {step === 'loading' && ( +
+ + Preparing authentication...
)} - {step === 'auto' && ( -
-
- -

- Waiting for browser authorization... -

-
-
- )} - - {step === 'manual' && authUrl && ( + {step === 'ready' && authUrl && (

- Open the authorization link in your browser to begin the flow. Then paste the code below. + Click below to open the authorization page. After you approve access, this dialog will update automatically.

- +
)} - {step === 'enter_code' && ( -
+ {step === 'waiting' && ( +
+
+ + Waiting for authorization... +
+

+ Complete the authorization in the popup window. This dialog will update automatically. +

+ + {authUrl && ( + + )} + + +
+ )} + + {step === 'popup_closed' && ( +
+
+ + Checking authentication status... +

- Paste the authorization code from the browser: + If authorization was completed, this will update shortly. Otherwise, paste the code parameter from the redirect URL below.

- setAuthCode(e.target.value)} - placeholder="Paste code here..." - disabled={loading} - /> +
+ setAuthCode(e.target.value)} + placeholder="Paste code here..." + disabled={loading} + className="text-sm" + /> + +
+ {authUrl && ( + + )} +
+ )} + + {step === 'success' && ( +
+ +

Authentication successful

+
+ )} + + {step === 'error' && !error && ( +
+ +

Something went wrong

)}
- - {step === 'enter_code' && ( - <> - - - + + {step === 'error' && ( + )} - {(step === 'method' || step === 'manual') && ( + {step !== 'success' && (
) } + +function ManualCodeEntry({ + showManualEntry, + setShowManualEntry, + authCode, + setAuthCode, + loading, + onSubmit, +}: { + showManualEntry: boolean + setShowManualEntry: (show: boolean) => void + authCode: string + setAuthCode: (code: string) => void + loading: boolean + onSubmit: () => void +}) { + return ( +
+ + + {showManualEntry && ( +
+

+ After authorizing, copy the code parameter from the redirect URL in your browser. +

+ +
+ setAuthCode(e.target.value)} + placeholder="Paste code here..." + disabled={loading} + className="text-sm" + /> + +
+
+ )} +
+ ) +} diff --git a/frontend/src/components/settings/McpServerCard.tsx b/frontend/src/components/settings/McpServerCard.tsx index 044381e3..d2dd0a5a 100644 --- a/frontend/src/components/settings/McpServerCard.tsx +++ b/frontend/src/components/settings/McpServerCard.tsx @@ -152,20 +152,20 @@ export function McpServerCard({ {showAuthButton && onAuthenticate && ( - onAuthenticate(serverId)}> + setTimeout(() => onAuthenticate(serverId), 0)}> Authenticate )} {connectedWithOAuth && onAuthenticate && ( - onAuthenticate(serverId)}> + setTimeout(() => onAuthenticate(serverId), 0)}> Re-authenticate )} {connectedWithOAuth && onRemoveAuth && ( onRemoveAuth(serverId)} + onSelect={() => setTimeout(() => onRemoveAuth(serverId), 0)} disabled={isRemovingAuth} > @@ -174,7 +174,9 @@ export function McpServerCard({ )} {(showAuthButton || connectedWithOAuth) && } onDeleteServer(serverId, displayName)} + onSelect={() => { + setTimeout(() => onDeleteServer(serverId, displayName), 0) + }} className="text-red-600" > diff --git a/frontend/src/components/settings/OAuthAuthorizeDialog.tsx b/frontend/src/components/settings/OAuthAuthorizeDialog.tsx index 08fe8d76..882871a2 100644 --- a/frontend/src/components/settings/OAuthAuthorizeDialog.tsx +++ b/frontend/src/components/settings/OAuthAuthorizeDialog.tsx @@ -1,7 +1,7 @@ import { useState } from 'react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' -import { ExternalLink, Copy } from 'lucide-react' +import { Copy } from 'lucide-react' import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth' import { mapOAuthError, OAuthMethod } from '@/lib/oauthErrors' @@ -45,11 +45,11 @@ export function OAuthAuthorizeDialog({ return ( - + Connect to {providerName} - Choose an authentication method to connect your {providerName} account. + Connect your {providerName} account using authorization code. @@ -60,16 +60,6 @@ export function OAuthAuthorizeDialog({ )}
- -
-

• "Open Authorization Page" will open a browser window for you to sign in

• "Use Authorization Code" will give you a code to manually enter

diff --git a/frontend/src/components/settings/OAuthCallbackDialog.tsx b/frontend/src/components/settings/OAuthCallbackDialog.tsx index 5dc81fbc..46b17595 100644 --- a/frontend/src/components/settings/OAuthCallbackDialog.tsx +++ b/frontend/src/components/settings/OAuthCallbackDialog.tsx @@ -29,24 +29,6 @@ export function OAuthCallbackDialog({ const [authCode, setAuthCode] = useState('') const [error, setError] = useState(null) - const handleAutoCallback = async () => { - setIsLoading(true) - setLoadingMessage('Completing authentication...') - setError(null) - - try { - setLoadingMessage('Restarting server with new credentials...') - await oauthApi.callback(providerId, { method: OAuthMethod.AUTO }) - onSuccess() - } catch (err) { - setError(mapOAuthError(err, 'callback')) - console.error('OAuth callback error:', err) - } finally { - setIsLoading(false) - setLoadingMessage('') - } - } - const handleCodeCallback = async () => { if (!authCode.trim()) { setError('Please enter the authorization code') @@ -82,14 +64,11 @@ export function OAuthCallbackDialog({ return ( - + Complete {providerName} Authentication - {authResponse.method === 'auto' - ? 'Follow the instructions to complete authentication.' - : 'Enter the authorization code from the provider.' - } + Enter the authorization code from the provider. @@ -100,86 +79,50 @@ export function OAuthCallbackDialog({ )}
- {authResponse.method === 'auto' ? ( -
-
-

{authResponse.instructions}

-
- +
+
+

{authResponse.instructions}

+
- + />
- ) : ( -
-
-

{authResponse.instructions}

- -
-
- - setAuthCode(e.target.value)} - placeholder="Enter the authorization code..." - className="bg-background border-border" - disabled={isLoading} - /> -
- - -
- )} + +
diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index 3a3639c4..662a1ee5 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -70,7 +70,7 @@ export function OpenCodeConfigEditor({ return ( !open && onClose()}> - + {`Edit Config: ${config.name}`} diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 8a7390ee..a385fb8a 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -1,5 +1,5 @@ import { useState, useEffect, useRef } from 'react' -import { Loader2, Plus, Trash2, Edit, Star, StarOff, Download, RotateCcw, FileText, ArrowUpCircle, History } from 'lucide-react' +import { Loader2, Plus, Trash2, Edit, StarOff, Download, RotateCcw, FileText, ArrowUpCircle, History } from 'lucide-react' import { Button } from '@/components/ui/button' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Label } from '@/components/ui/label' @@ -434,64 +434,66 @@ export function OpenCodeConfigManager() { ) : (
- {configs.map((config) => ( - - -
-
- {config.name} - {config.isDefault && ( - - - - )} -
-
- - - - +
+
+ + + + +
-
- - -
-

Updated: {new Date(config.updatedAt).toLocaleString()}

-

Created: {new Date(config.createdAt).toLocaleString()}

-
-
- - ))} + + +
+

Updated: {new Date(config.updatedAt).toLocaleString()}

+

Created: {new Date(config.createdAt).toLocaleString()}

+
+
+ + ))} )} diff --git a/frontend/src/components/settings/SettingsDialog.tsx b/frontend/src/components/settings/SettingsDialog.tsx index 65d65041..82fc15ae 100644 --- a/frontend/src/components/settings/SettingsDialog.tsx +++ b/frontend/src/components/settings/SettingsDialog.tsx @@ -69,7 +69,7 @@ export function SettingsDialog() { diff --git a/frontend/src/components/settings/VersionSelectDialog.tsx b/frontend/src/components/settings/VersionSelectDialog.tsx index 2c4a52f3..d34c0cae 100644 --- a/frontend/src/components/settings/VersionSelectDialog.tsx +++ b/frontend/src/components/settings/VersionSelectDialog.tsx @@ -80,7 +80,7 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP return ( - + Select OpenCode Version diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx index c7f3e80a..6fcdc9da 100644 --- a/frontend/src/components/ui/combobox.tsx +++ b/frontend/src/components/ui/combobox.tsx @@ -199,7 +199,7 @@ export function Combobox({ {isOpen && flatFilteredOptions.length > 0 && (
{Object.entries(groupedOptions).map(([group, groupOptions]) => (
@@ -237,7 +237,7 @@ export function Combobox({ )} {isOpen && flatFilteredOptions.length === 0 && inputValue && allowCustomValue && ( -
+
Press Enter to use "{inputValue}"
diff --git a/frontend/src/components/ui/delete-dialog.tsx b/frontend/src/components/ui/delete-dialog.tsx index 682b19da..b2c05db2 100644 --- a/frontend/src/components/ui/delete-dialog.tsx +++ b/frontend/src/components/ui/delete-dialog.tsx @@ -26,7 +26,7 @@ export function DeleteDialog({ }: DeleteDialogProps) { return ( - + {title} diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index a5a0a91d..4fa44fc2 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -48,7 +48,7 @@ const DialogContent = React.forwardRef< ref={ref} aria-describedby={undefined} className={cn( - "fixed z-50 grid gap-4 border bg-background shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", + "fixed z-50 grid gap-4 border-0 sm:border bg-background shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", fullscreen ? "inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none" : mobileFullscreen diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsx index c56c7416..073ec7a3 100644 --- a/frontend/src/components/ui/dropdown-menu.tsx +++ b/frontend/src/components/ui/dropdown-menu.tsx @@ -42,7 +42,7 @@ const DropdownMenuSubContent = React.forwardRef< mcpApi.startAuth(name), + mutationFn: ({ name, serverUrl, scope, clientId, clientSecret, directory }: { name: string; serverUrl: string; scope?: string; clientId?: string; clientSecret?: string; directory?: string }) => + mcpApi.startAuth(name, serverUrl, scope, clientId, clientSecret, directory), onError: (error: Error) => { toast.error(`Failed to start authentication: ${error.message}`) }, @@ -69,18 +70,6 @@ export function useMcpServers() { }, }) - const authenticateMutation = useMutation({ - mutationFn: (name: string) => mcpApi.authenticate(name), - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['mcp-status'] }) - queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') }) - toast.success('Authentication completed') - }, - onError: (error: Error) => { - toast.error(`Failed to authenticate: ${error.message}`) - }, - }) - const removeAuthMutation = useMutation({ mutationFn: (name: string) => mcpApi.removeAuth(name), onSuccess: () => { @@ -93,16 +82,6 @@ export function useMcpServers() { }, }) - const toggleServer = async (name: string, currentStatus: McpStatus) => { - if (currentStatus.status === 'connected') { - return disconnectMutation.mutateAsync(name) - } else if (currentStatus.status === 'disabled') { - return connectMutation.mutateAsync(name) - } else if (currentStatus.status === 'needs_auth') { - return authenticateMutation.mutateAsync(name) - } - } - return { status: statusQuery.data as McpStatusMap | undefined, isLoading: statusQuery.isLoading, @@ -122,9 +101,6 @@ export function useMcpServers() { disconnectAsync: disconnectMutation.mutateAsync, isDisconnecting: disconnectMutation.isPending, - toggleServer, - isToggling: connectMutation.isPending || disconnectMutation.isPending || authenticateMutation.isPending, - startAuth: startAuthMutation.mutate, startAuthAsync: startAuthMutation.mutateAsync, isStartingAuth: startAuthMutation.isPending, @@ -133,10 +109,6 @@ export function useMcpServers() { completeAuthAsync: completeAuthMutation.mutateAsync, isCompletingAuth: completeAuthMutation.isPending, - authenticate: authenticateMutation.mutate, - authenticateAsync: authenticateMutation.mutateAsync, - isAuthenticating: authenticateMutation.isPending, - removeAuth: removeAuthMutation.mutate, removeAuthAsync: removeAuthMutation.mutateAsync, isRemovingAuth: removeAuthMutation.isPending, diff --git a/frontend/src/lib/oauthErrors.ts b/frontend/src/lib/oauthErrors.ts index 093cd466..8d4e6bc4 100644 --- a/frontend/src/lib/oauthErrors.ts +++ b/frontend/src/lib/oauthErrors.ts @@ -1,6 +1,5 @@ export const OAuthMethod = { - AUTO: 0, - CODE: 1, + CODE: 0, } as const export type OAuthMethodType = (typeof OAuthMethod)[keyof typeof OAuthMethod]