mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
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
This commit is contained in:
1 parent
7824d52fb8
commit
3f9c398b31
31 files changed
+1054
-483
No files matched your search
-65
@@ -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.
|
||||
+15
-1
@@ -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)
|
||||
|
||||
@@ -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<Record<string, unknown>> {
|
||||
try {
|
||||
const content = await readFile(getMcpAuthPath(), 'utf-8')
|
||||
return JSON.parse(content) as Record<string, unknown>
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
async function writeMcpAuth(data: Record<string, unknown>): Promise<void> {
|
||||
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<string> {
|
||||
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, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function renderPage(heading: string, message: string, isSuccess: boolean): string {
|
||||
const color = isSuccess ? '#4ade80' : '#f87171'
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>${escapeHtml(heading)}</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #0f172a; color: #e2e8f0; }
|
||||
.container { text-align: center; padding: 2rem; max-width: 400px; }
|
||||
h2 { color: ${color}; margin-bottom: 0.5rem; }
|
||||
p { color: #94a3b8; font-size: 0.9rem; }
|
||||
</style>
|
||||
${isSuccess ? '<script>setTimeout(() => window.close(), 2000);</script>' : ''}
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>${escapeHtml(heading)}</h2>
|
||||
<p>${escapeHtml(message)}</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
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<string, unknown> || {}),
|
||||
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
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<string, McpOAuthFlowState>()
|
||||
const resultStore = new Map<string, McpOAuthFlowResult & { timestamp: number }>()
|
||||
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<McpOAuthFlowState, 'timestamp'>): 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 }
|
||||
}
|
||||
@@ -178,3 +178,66 @@ export async function proxyToOpenCodeWithDirectory(
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyMcpAuthStart(
|
||||
serverName: string,
|
||||
directory: string | undefined,
|
||||
): Promise<Response> {
|
||||
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<Response> {
|
||||
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' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+21
-2
@@ -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<McpStatusMap> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp`)
|
||||
@@ -79,9 +86,11 @@ export const mcpApi = {
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async startAuth(name: string): Promise<McpAuthStartResponse> {
|
||||
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<McpAuthStartResponse> {
|
||||
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<McpOAuthFlowStatus> {
|
||||
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<McpStatus> {
|
||||
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<McpStatus> {
|
||||
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 }))
|
||||
|
||||
@@ -3,7 +3,7 @@ import { fetchWrapper, FetchError } from "./fetchWrapper"
|
||||
|
||||
export interface OAuthAuthorizeResponse {
|
||||
url: string
|
||||
method: "auto" | "code"
|
||||
method: "code"
|
||||
instructions: string
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ export function ApiKeyDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose} modal={false}>
|
||||
<DialogContent className="sm:max-w-md z-[100]">
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5" />
|
||||
|
||||
@@ -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<Record<string, McpStatus>>({})
|
||||
const [isLoadingStatus, setIsLoadingStatus] = useState(false)
|
||||
const [removeAuthConfirmServer, setRemoveAuthConfirmServer] = useState<string | null>(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<McpAuthStartResponse> => {
|
||||
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<boolean> => {
|
||||
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}
|
||||
/>
|
||||
</DialogContent>
|
||||
|
||||
@@ -179,14 +179,14 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
|
||||
<DialogTitle>Add MCP Server</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-2 sm:p-4">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="serverId">Server ID</Label>
|
||||
<Input
|
||||
id="serverId"
|
||||
@@ -200,7 +200,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="serverType">Server Type</Label>
|
||||
<Select value={serverType} onValueChange={(value: 'local' | 'remote') => setServerType(value)}>
|
||||
<SelectTrigger className="bg-background border-border">
|
||||
@@ -214,7 +214,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
</div>
|
||||
|
||||
{serverType === 'local' ? (
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="command">Command</Label>
|
||||
<Input
|
||||
id="command"
|
||||
@@ -228,7 +228,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="url">Server URL</Label>
|
||||
<Input
|
||||
id="url"
|
||||
@@ -258,7 +258,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Leave fields blank to use the server's default OAuth discovery
|
||||
</p>
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="oauthClientId">Client ID</Label>
|
||||
<Input
|
||||
id="oauthClientId"
|
||||
@@ -268,7 +268,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
className="bg-background border-border font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="oauthClientSecret">Client Secret</Label>
|
||||
<Input
|
||||
id="oauthClientSecret"
|
||||
@@ -279,7 +279,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
className="bg-background border-border font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="oauthScope">Scope</Label>
|
||||
<Input
|
||||
id="oauthScope"
|
||||
@@ -295,7 +295,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
)}
|
||||
|
||||
{serverType === 'local' && (
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Environment Variables</Label>
|
||||
<Button
|
||||
@@ -340,7 +340,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="timeout">Timeout (ms)</Label>
|
||||
<Input
|
||||
id="timeout"
|
||||
|
||||
@@ -176,7 +176,7 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
|
||||
<DialogTitle>{editingAgent ? 'Edit Agent' : 'Create Agent'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -99,7 +99,7 @@ export function CommandDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
|
||||
<DialogTitle>
|
||||
{editingCommand ? "Edit Command" : "Create Command"}
|
||||
|
||||
@@ -104,7 +104,7 @@ export function CreateConfigDialog({ isOpen, onOpenChange, onCreate, isUpdating
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[85vh] flex flex-col z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[85vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle>Create OpenCode Config</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -132,8 +132,7 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="max-w-lg z-[200] h-[90vh] sm:h-auto sm:max-h-[85vh] flex flex-col"
|
||||
overlayClassName="z-[200]">
|
||||
<DialogContent mobileFullscreen className="max-w-lg h-[90vh] sm:h-auto sm:max-h-[85vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0 px-4 sm:px-6 pt-4 sm:pt-6 pb-2 sm:pb-3">
|
||||
<DialogTitle>{credential ? 'Edit Git Credential' : 'Add Git Credential'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -12,6 +12,7 @@ import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import type { McpServerConfig } from '@/api/mcp'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
import type { McpAuthStartResponse } from '@/api/mcp'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
interface McpManagerProps {
|
||||
config: {
|
||||
@@ -38,16 +39,19 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
refetch: refetchStatus,
|
||||
connect,
|
||||
disconnect,
|
||||
authenticate,
|
||||
removeAuth,
|
||||
isRemovingAuth,
|
||||
isToggling
|
||||
removeAuthAsync,
|
||||
isRemovingAuth
|
||||
} = useMcpServers()
|
||||
|
||||
const deleteServerMutation = useMutation({
|
||||
mutationFn: async (serverId: string) => {
|
||||
if (!config) return
|
||||
|
||||
const currentStatus = mcpStatus?.[serverId]
|
||||
if (currentStatus?.status === 'connected') {
|
||||
await disconnect(serverId)
|
||||
}
|
||||
|
||||
const currentMcp = (config.content?.mcp as Record<string, McpServerConfig>) || {}
|
||||
const { [serverId]: _, ...rest } = currentMcp
|
||||
void _
|
||||
@@ -59,15 +63,19 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
|
||||
await onUpdate(updatedConfig)
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess: async () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
await refetchStatus()
|
||||
setDeleteConfirmServer(null)
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to delete MCP server')
|
||||
},
|
||||
})
|
||||
|
||||
const mcpServers = config?.content?.mcp as Record<string, McpServerConfig> || {}
|
||||
|
||||
const isAnyOperationPending = deleteServerMutation.isPending || togglingServerId !== null || isToggling
|
||||
const isAnyOperationPending = deleteServerMutation.isPending || togglingServerId !== null
|
||||
|
||||
const handleToggleServer = async (serverId: string) => {
|
||||
const currentStatus = mcpStatus?.[serverId]
|
||||
@@ -103,16 +111,18 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
setAuthDialogServerId(serverId)
|
||||
}
|
||||
|
||||
const handleOAuthAutoAuth = async () => {
|
||||
if (!authDialogServerId) return
|
||||
await authenticate(authDialogServerId)
|
||||
refetchStatus()
|
||||
setAuthDialogServerId(null)
|
||||
}
|
||||
|
||||
const handleOAuthStartAuth = async (): Promise<McpAuthStartResponse> => {
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
const handleOAuthCompleteAuth = async (code: string) => {
|
||||
@@ -122,14 +132,30 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
setAuthDialogServerId(null)
|
||||
}
|
||||
|
||||
const handleOAuthCheckStatus = async (): Promise<boolean> => {
|
||||
if (!authDialogServerId) return false
|
||||
const status = await mcpApi.getStatus()
|
||||
const serverStatus = status[authDialogServerId]
|
||||
if (serverStatus?.status === 'connected') {
|
||||
refetchStatus()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const handleOAuthSuccess = () => {
|
||||
refetchStatus()
|
||||
}
|
||||
|
||||
const handleRemoveAuth = (serverId: string) => {
|
||||
setRemoveAuthConfirmServer(serverId)
|
||||
}
|
||||
|
||||
const handleConfirmRemoveAuth = () => {
|
||||
const handleConfirmRemoveAuth = async () => {
|
||||
if (removeAuthConfirmServer) {
|
||||
removeAuth(removeAuthConfirmServer)
|
||||
await removeAuthAsync(removeAuthConfirmServer)
|
||||
setRemoveAuthConfirmServer(null)
|
||||
refetchStatus()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,9 +277,10 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
|
||||
open={!!authDialogServerId}
|
||||
onOpenChange={(open) => !open && setAuthDialogServerId(null)}
|
||||
serverName={authDialogServerId || ''}
|
||||
onAutoAuth={handleOAuthAutoAuth}
|
||||
onStartAuth={handleOAuthStartAuth}
|
||||
onCompleteAuth={handleOAuthCompleteAuth}
|
||||
onCheckStatus={handleOAuthCheckStatus}
|
||||
onSuccess={handleOAuthSuccess}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
|
||||
@@ -1,76 +1,205 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Loader2, ExternalLink, Key, XCircle } from 'lucide-react'
|
||||
import { Loader2, ExternalLink, Key, XCircle, ChevronDown, ChevronUp, CheckCircle } from 'lucide-react'
|
||||
import type { McpAuthStartResponse } from '@/api/mcp'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
|
||||
interface McpOAuthDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
serverName: string
|
||||
onAutoAuth: () => Promise<void>
|
||||
onStartAuth: () => Promise<McpAuthStartResponse>
|
||||
onCompleteAuth: (code: string) => Promise<void>
|
||||
onCheckStatus?: () => Promise<boolean>
|
||||
onSuccess?: () => void
|
||||
directory?: string
|
||||
}
|
||||
|
||||
type Step = 'loading' | 'ready' | 'waiting' | 'popup_closed' | 'success' | 'error'
|
||||
|
||||
export function McpOAuthDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
serverName,
|
||||
onAutoAuth,
|
||||
onStartAuth,
|
||||
onCompleteAuth,
|
||||
onCheckStatus,
|
||||
onSuccess,
|
||||
directory
|
||||
}: McpOAuthDialogProps) {
|
||||
const [step, setStep] = useState<'method' | 'auto' | 'manual' | 'enter_code'>('method')
|
||||
const [step, setStep] = useState<Step>('loading')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [authUrl, setAuthUrl] = useState<string | null>(null)
|
||||
const [authCode, setAuthCode] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showManualEntry, setShowManualEntry] = useState(false)
|
||||
const flowIdRef = useRef<string | null>(null)
|
||||
const flowPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const statusPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const popupPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const popupRef = useRef<Window | null>(null)
|
||||
const doneRef = useRef(false)
|
||||
|
||||
const handleAutoAuth = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
setStep('auto')
|
||||
try {
|
||||
await onAutoAuth()
|
||||
const scopes = directory ? 'this location' : 'globally'
|
||||
|
||||
const stopAllPolling = useCallback(() => {
|
||||
if (flowPollingRef.current) {
|
||||
clearInterval(flowPollingRef.current)
|
||||
flowPollingRef.current = null
|
||||
}
|
||||
if (statusPollingRef.current) {
|
||||
clearInterval(statusPollingRef.current)
|
||||
statusPollingRef.current = null
|
||||
}
|
||||
if (popupPollingRef.current) {
|
||||
clearInterval(popupPollingRef.current)
|
||||
popupPollingRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSuccess = useCallback(() => {
|
||||
if (doneRef.current) return
|
||||
doneRef.current = true
|
||||
stopAllPolling()
|
||||
if (popupRef.current && !popupRef.current.closed) {
|
||||
popupRef.current.close()
|
||||
}
|
||||
setStep('success')
|
||||
onSuccess?.()
|
||||
setTimeout(() => {
|
||||
onOpenChange(false)
|
||||
resetState()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to authenticate')
|
||||
setStep('method')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, 1500)
|
||||
}, [stopAllPolling, onOpenChange, onSuccess])
|
||||
|
||||
const handleStartManualAuth = async () => {
|
||||
setLoading(true)
|
||||
const resetState = useCallback(() => {
|
||||
setStep('loading')
|
||||
setAuthUrl(null)
|
||||
setAuthCode('')
|
||||
setError(null)
|
||||
try {
|
||||
const result = await onStartAuth()
|
||||
setAuthUrl(result.authorizationUrl)
|
||||
setStep('manual')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to start authentication')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setLoading(false)
|
||||
setShowManualEntry(false)
|
||||
stopAllPolling()
|
||||
doneRef.current = false
|
||||
flowIdRef.current = null
|
||||
if (popupRef.current && !popupRef.current.closed) {
|
||||
popupRef.current.close()
|
||||
}
|
||||
popupRef.current = null
|
||||
}, [stopAllPolling])
|
||||
|
||||
const startFlowPolling = useCallback(() => {
|
||||
if (flowPollingRef.current) return
|
||||
|
||||
flowPollingRef.current = setInterval(async () => {
|
||||
if (doneRef.current || !flowIdRef.current) return
|
||||
try {
|
||||
const result = await mcpApi.checkFlowStatus(flowIdRef.current)
|
||||
if (result.status === 'completed') {
|
||||
handleSuccess()
|
||||
} else if (result.status === 'failed') {
|
||||
stopAllPolling()
|
||||
setError('error' in result ? result.error : 'Authentication failed')
|
||||
setStep('error')
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, 1500)
|
||||
}, [handleSuccess, stopAllPolling])
|
||||
|
||||
const startStatusPolling = useCallback(() => {
|
||||
if (!onCheckStatus || statusPollingRef.current) return
|
||||
|
||||
statusPollingRef.current = setInterval(async () => {
|
||||
if (doneRef.current) return
|
||||
try {
|
||||
const isConnected = await onCheckStatus()
|
||||
if (isConnected) {
|
||||
handleSuccess()
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, 2000)
|
||||
}, [onCheckStatus, handleSuccess])
|
||||
|
||||
const startPopupPolling = useCallback(() => {
|
||||
if (popupPollingRef.current) return
|
||||
|
||||
popupPollingRef.current = setInterval(() => {
|
||||
const popup = popupRef.current
|
||||
if (!popup || doneRef.current) return
|
||||
|
||||
if (popup.closed) {
|
||||
if (popupPollingRef.current) {
|
||||
clearInterval(popupPollingRef.current)
|
||||
popupPollingRef.current = null
|
||||
}
|
||||
if (!doneRef.current) {
|
||||
setStep('popup_closed')
|
||||
startFlowPolling()
|
||||
startStatusPolling()
|
||||
}
|
||||
}
|
||||
}, 500)
|
||||
}, [startFlowPolling, startStatusPolling])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
resetState()
|
||||
|
||||
const initAuth = async () => {
|
||||
try {
|
||||
const result = await onStartAuth()
|
||||
setAuthUrl(result.authorizationUrl)
|
||||
flowIdRef.current = result.flowId
|
||||
setStep('ready')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to start authentication')
|
||||
setStep('error')
|
||||
}
|
||||
}
|
||||
|
||||
initAuth()
|
||||
}, [open]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopAllPolling()
|
||||
doneRef.current = false
|
||||
}
|
||||
}, [stopAllPolling])
|
||||
|
||||
const handleOpenAuthPage = () => {
|
||||
if (!authUrl) return
|
||||
const width = 600
|
||||
const height = 700
|
||||
const left = window.screenX + (window.outerWidth - width) / 2
|
||||
const top = window.screenY + (window.outerHeight - height) / 2
|
||||
popupRef.current = window.open(
|
||||
authUrl,
|
||||
'mcp-oauth',
|
||||
`width=${width},height=${height},left=${left},top=${top},popup=yes`
|
||||
)
|
||||
setStep('waiting')
|
||||
startPopupPolling()
|
||||
startFlowPolling()
|
||||
startStatusPolling()
|
||||
}
|
||||
|
||||
const handleCompleteAuth = async () => {
|
||||
const handleCompleteManualAuth = async () => {
|
||||
if (!authCode.trim()) return
|
||||
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
await onCompleteAuth(authCode.trim())
|
||||
onOpenChange(false)
|
||||
resetState()
|
||||
handleSuccess()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to complete authentication')
|
||||
} finally {
|
||||
@@ -78,21 +207,6 @@ export function McpOAuthDialog({
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenAuthUrl = () => {
|
||||
if (authUrl) {
|
||||
window.open(authUrl, '_blank')
|
||||
setStep('enter_code')
|
||||
}
|
||||
}
|
||||
|
||||
const resetState = () => {
|
||||
setStep('method')
|
||||
setAuthUrl(null)
|
||||
setAuthCode('')
|
||||
setError(null)
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!newOpen) {
|
||||
resetState()
|
||||
@@ -100,157 +214,175 @@ export function McpOAuthDialog({
|
||||
onOpenChange(newOpen)
|
||||
}
|
||||
|
||||
const scopes = directory ? 'this location' : 'global'
|
||||
const handleRetry = async () => {
|
||||
setError(null)
|
||||
setStep('loading')
|
||||
doneRef.current = false
|
||||
flowIdRef.current = null
|
||||
try {
|
||||
const result = await onStartAuth()
|
||||
setAuthUrl(result.authorizationUrl)
|
||||
flowIdRef.current = result.flowId
|
||||
setStep('ready')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to start authentication')
|
||||
setStep('error')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="w-[calc(100vw-2rem)] max-w-md h-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5" />
|
||||
Connect {serverName}
|
||||
<Key className="h-5 w-5 shrink-0" />
|
||||
<span className="truncate">Connect {serverName}</span>
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Authenticate to use this MCP server for {scopes}
|
||||
Authenticate to use this MCP server {scopes}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-4 py-2 min-w-0">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<XCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
<XCircle className="h-4 w-4 shrink-0" />
|
||||
<AlertDescription className="break-words">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{step === 'method' && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">Choose an authentication method:</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
onClick={handleAutoAuth}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="justify-start h-auto py-3"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Starting authentication...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2" />
|
||||
<div className="text-left">
|
||||
<div className="font-medium">Auto (Recommended)</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Opens browser, handles redirect automatically
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleStartManualAuth}
|
||||
disabled={loading}
|
||||
variant="outline"
|
||||
className="justify-start h-auto py-3"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Starting authentication...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
<div className="text-left">
|
||||
<div className="font-medium">Manual with Code</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Open URL, then paste the authorization code
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{step === 'loading' && (
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Preparing authentication...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'auto' && (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Waiting for browser authorization...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'manual' && authUrl && (
|
||||
{step === 'ready' && authUrl && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
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.
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleOpenAuthUrl}
|
||||
onClick={handleOpenAuthPage}
|
||||
className="w-full"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open Auth Page
|
||||
Open Authorization Page
|
||||
</Button>
|
||||
<div className="text-xs text-muted-foreground break-all bg-muted p-2 rounded">
|
||||
<a
|
||||
href={authUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block text-xs text-muted-foreground hover:text-foreground break-all transition-colors"
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
handleOpenAuthPage()
|
||||
}}
|
||||
>
|
||||
{authUrl}
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'enter_code' && (
|
||||
<div className="space-y-3">
|
||||
{step === 'waiting' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-blue-500" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Waiting for authorization...</span>
|
||||
</div>
|
||||
<p className="text-xs text-center text-muted-foreground">
|
||||
Complete the authorization in the popup window. This dialog will update automatically.
|
||||
</p>
|
||||
|
||||
{authUrl && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full text-xs text-muted-foreground"
|
||||
onClick={handleOpenAuthPage}
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
Re-open authorization popup
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<ManualCodeEntry
|
||||
showManualEntry={showManualEntry}
|
||||
setShowManualEntry={setShowManualEntry}
|
||||
authCode={authCode}
|
||||
setAuthCode={setAuthCode}
|
||||
loading={loading}
|
||||
onSubmit={handleCompleteManualAuth}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'popup_closed' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-blue-500" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Checking authentication status...</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Paste the authorization code from the browser:
|
||||
If authorization was completed, this will update shortly. Otherwise, paste the <code className="text-xs bg-muted px-1 py-0.5 rounded">code</code> parameter from the redirect URL below.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="auth-code">Authorization Code</Label>
|
||||
<Input
|
||||
id="auth-code"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Paste code here..."
|
||||
disabled={loading}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="auth-code"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Paste code here..."
|
||||
disabled={loading}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCompleteManualAuth}
|
||||
disabled={loading || !authCode.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Submit'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{authUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={handleOpenAuthPage}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Try Again
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'success' && (
|
||||
<div className="flex flex-col items-center justify-center py-6 gap-2">
|
||||
<CheckCircle className="h-8 w-8 text-green-500" />
|
||||
<p className="text-sm font-medium">Authentication successful</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'error' && !error && (
|
||||
<div className="flex flex-col items-center justify-center py-6 gap-2">
|
||||
<XCircle className="h-8 w-8 text-destructive" />
|
||||
<p className="text-sm text-muted-foreground">Something went wrong</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
{step === 'enter_code' && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setStep('method')}
|
||||
disabled={loading}
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleCompleteAuth}
|
||||
disabled={loading || !authCode.trim()}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Authenticating...
|
||||
</>
|
||||
) : (
|
||||
'Complete Authentication'
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
{step === 'error' && (
|
||||
<Button variant="outline" onClick={handleRetry}>
|
||||
Try Again
|
||||
</Button>
|
||||
)}
|
||||
{(step === 'method' || step === 'manual') && (
|
||||
{step !== 'success' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
@@ -264,3 +396,58 @@ export function McpOAuthDialog({
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="border-t border-border pt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowManualEntry(!showManualEntry)}
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors w-full"
|
||||
>
|
||||
{showManualEntry ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
Paste authorization code manually
|
||||
</button>
|
||||
|
||||
{showManualEntry && (
|
||||
<div className="space-y-2 mt-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
After authorizing, copy the <code className="bg-muted px-1 py-0.5 rounded">code</code> parameter from the redirect URL in your browser.
|
||||
</p>
|
||||
<Label htmlFor="auth-code" className="text-xs">Authorization Code</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="auth-code"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Paste code here..."
|
||||
disabled={loading}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button
|
||||
onClick={onSubmit}
|
||||
disabled={loading || !authCode.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Submit'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -152,20 +152,20 @@ export function McpServerCard({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{showAuthButton && onAuthenticate && (
|
||||
<DropdownMenuItem onClick={() => onAuthenticate(serverId)}>
|
||||
<DropdownMenuItem onSelect={() => setTimeout(() => onAuthenticate(serverId), 0)}>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && onAuthenticate && (
|
||||
<DropdownMenuItem onClick={() => onAuthenticate(serverId)}>
|
||||
<DropdownMenuItem onSelect={() => setTimeout(() => onAuthenticate(serverId), 0)}>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Re-authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && onRemoveAuth && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => onRemoveAuth(serverId)}
|
||||
onSelect={() => setTimeout(() => onRemoveAuth(serverId), 0)}
|
||||
disabled={isRemovingAuth}
|
||||
>
|
||||
<Shield className="h-4 w-4 mr-2" />
|
||||
@@ -174,7 +174,9 @@ export function McpServerCard({
|
||||
)}
|
||||
{(showAuthButton || connectedWithOAuth) && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem
|
||||
onClick={() => onDeleteServer(serverId, displayName)}
|
||||
onSelect={() => {
|
||||
setTimeout(() => onDeleteServer(serverId, displayName), 0)
|
||||
}}
|
||||
className="text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
|
||||
@@ -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 (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="bg-card border-border max-w-lg z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="bg-card border-border max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Connect to {providerName}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose an authentication method to connect your {providerName} account.
|
||||
Connect your {providerName} account using authorization code.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -60,16 +60,6 @@ export function OAuthAuthorizeDialog({
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={() => handleAuthorize(OAuthMethod.AUTO)}
|
||||
disabled={isLoading}
|
||||
className="w-full justify-start"
|
||||
variant="outline"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
{isLoading ? 'Authorizing...' : 'Open Authorization Page'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => handleAuthorize(OAuthMethod.CODE)}
|
||||
disabled={isLoading}
|
||||
@@ -82,7 +72,6 @@ export function OAuthAuthorizeDialog({
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p>• "Open Authorization Page" will open a browser window for you to sign in</p>
|
||||
<p>• "Use Authorization Code" will give you a code to manually enter</p>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
@@ -29,24 +29,6 @@ export function OAuthCallbackDialog({
|
||||
const [authCode, setAuthCode] = useState('')
|
||||
const [error, setError] = useState<string | null>(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 (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="bg-card border-border max-w-lg z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="bg-card border-border max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Complete {providerName} Authentication</DialogTitle>
|
||||
<DialogDescription>
|
||||
{authResponse.method === 'auto'
|
||||
? 'Follow the instructions to complete authentication.'
|
||||
: 'Enter the authorization code from the provider.'
|
||||
}
|
||||
Enter the authorization code from the provider.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -100,86 +79,50 @@ export function OAuthCallbackDialog({
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{authResponse.method === 'auto' ? (
|
||||
<div className="space-y-3">
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-sm">{authResponse.instructions}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-sm mb-2">{authResponse.instructions}</p>
|
||||
<Button
|
||||
onClick={handleOpenAuthUrl}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
disabled={isLoading}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open Authorization Page
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleAutoCallback}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="authCode">Authorization Code</Label>
|
||||
<Input
|
||||
id="authCode"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Enter the authorization code..."
|
||||
className="bg-background border-border"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{loadingMessage || 'Completing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
I Completed Authorization
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-sm mb-2">{authResponse.instructions}</p>
|
||||
<Button
|
||||
onClick={handleOpenAuthUrl}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open Authorization Page
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="authCode">Authorization Code</Label>
|
||||
<Input
|
||||
id="authCode"
|
||||
value={authCode}
|
||||
onChange={(e) => setAuthCode(e.target.value)}
|
||||
placeholder="Enter the authorization code..."
|
||||
className="bg-background border-border"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleCodeCallback}
|
||||
className="w-full"
|
||||
disabled={isLoading || !authCode.trim()}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{loadingMessage || 'Completing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
Complete Authentication
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={handleCodeCallback}
|
||||
className="w-full"
|
||||
disabled={isLoading || !authCode.trim()}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{loadingMessage || 'Completing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
Complete Authentication
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -70,7 +70,7 @@ export function OpenCodeConfigEditor({
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent mobileFullscreen className="gap-0 flex flex-col p-0 md:p-6 w-full min-w-0 sm:max-w-4xl max-h-[90vh] sm:max-h-[85vh] z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent mobileFullscreen className="gap-0 flex flex-col p-0 md:p-6 w-full min-w-0 sm:max-w-4xl max-h-[90vh] sm:max-h-[85vh]">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
|
||||
<DialogTitle className="text-lg sm:text-xl font-semibold">
|
||||
{`Edit Config: ${config.name}`}
|
||||
|
||||
@@ -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() {
|
||||
</Card>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4 md:grid md:grid-cols-2 lg:grid-cols">
|
||||
{configs.map((config) => (
|
||||
<Card key={config.id}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<CardTitle className="text-base">{config.name}</CardTitle>
|
||||
{config.isDefault && (
|
||||
<Badge variant="default" className="">
|
||||
<Star className="h-4 w-4" />
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => downloadConfig(config)}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => startEdit(config)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDefaultConfig(config)}
|
||||
disabled={config.isDefault || isUpdating}
|
||||
>
|
||||
{config.isDefault ? (
|
||||
<StarOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Star className="h-4 w-4" />
|
||||
{configs
|
||||
.sort((a, b) => {
|
||||
if (a.isDefault) return -1
|
||||
if (b.isDefault) return 1
|
||||
return 0
|
||||
})
|
||||
.map((config) => (
|
||||
<Card key={config.id} className={config.isDefault ? 'border-green-500' : ''}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<CardTitle className="text-base">{config.name}</CardTitle>
|
||||
{config.isDefault && (
|
||||
<Badge variant="default" className="text-green-500 bg-green-500/10">
|
||||
Current
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDeleteConfirmConfig(config)}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => downloadConfig(config)}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => startEdit(config)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDefaultConfig(config)}
|
||||
disabled={config.isDefault || isUpdating}
|
||||
>
|
||||
<StarOff className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDeleteConfirmConfig(config)}
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-sm text-muted-foreground break-words">
|
||||
<p className="truncate">Updated: {new Date(config.updatedAt).toLocaleString()}</p>
|
||||
<p className="truncate">Created: {new Date(config.createdAt).toLocaleString()}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-sm text-muted-foreground break-words">
|
||||
<p className="truncate">Updated: {new Date(config.updatedAt).toLocaleString()}</p>
|
||||
<p className="truncate">Created: {new Date(config.createdAt).toLocaleString()}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ export function SettingsDialog() {
|
||||
<Dialog open={isOpen} modal={false}>
|
||||
<DialogContent
|
||||
ref={contentRef}
|
||||
className="inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none bg-gradient-to-br from-background via-background to-background border-border overflow-hidden !flex !flex-col z-[100]"
|
||||
className="inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none bg-gradient-to-br from-background via-background to-background border-border overflow-hidden !flex !flex-col"
|
||||
style={swipeStyles}
|
||||
fullscreen
|
||||
>
|
||||
|
||||
@@ -80,7 +80,7 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md z-[200]" overlayClassName="z-[200]">
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Select OpenCode Version</DialogTitle>
|
||||
<DialogDescription>
|
||||
|
||||
@@ -199,7 +199,7 @@ export function Combobox({
|
||||
{isOpen && flatFilteredOptions.length > 0 && (
|
||||
<div
|
||||
ref={listRef}
|
||||
className="absolute z-50 mt-1 w-full bg-popover border border-border rounded-md shadow-lg max-h-60 overflow-y-auto"
|
||||
className="absolute z-[150] mt-1 w-full bg-popover border border-border rounded-md shadow-lg max-h-60 overflow-y-auto"
|
||||
>
|
||||
{Object.entries(groupedOptions).map(([group, groupOptions]) => (
|
||||
<div key={group || 'default'}>
|
||||
@@ -237,7 +237,7 @@ export function Combobox({
|
||||
)}
|
||||
|
||||
{isOpen && flatFilteredOptions.length === 0 && inputValue && allowCustomValue && (
|
||||
<div className="absolute z-50 mt-1 w-full bg-popover border border-border rounded-md shadow-lg p-3">
|
||||
<div className="absolute z-[150] mt-1 w-full bg-popover border border-border rounded-md shadow-lg p-3">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Press Enter to use "<span className="font-medium text-foreground">{inputValue}</span>"
|
||||
</div>
|
||||
|
||||
@@ -26,7 +26,7 @@ export function DeleteDialog({
|
||||
}: DeleteDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='max-w-[90%] sm:max-w-sm '>
|
||||
<DialogContent className='max-w-[90%] sm:max-w-sm'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -42,7 +42,7 @@ const DropdownMenuSubContent = React.forwardRef<
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
"z-[150] min-w-[8rem] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -60,7 +60,7 @@ const DropdownMenuContent = React.forwardRef<
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
"z-[150] min-w-[8rem] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -75,7 +75,7 @@ const SelectContent = React.forwardRef<
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border border-border bg-popover text-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
|
||||
"relative z-[150] max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border border-border bg-popover text-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
import type { McpStatusMap, McpServerConfig, McpStatus } from '@/api/mcp'
|
||||
import type { McpStatusMap, McpServerConfig } from '@/api/mcp'
|
||||
import { showToast as toast } from '@/lib/toast'
|
||||
|
||||
export function useMcpServers() {
|
||||
@@ -51,7 +51,8 @@ export function useMcpServers() {
|
||||
})
|
||||
|
||||
const startAuthMutation = useMutation({
|
||||
mutationFn: (name: string) => 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,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export const OAuthMethod = {
|
||||
AUTO: 0,
|
||||
CODE: 1,
|
||||
CODE: 0,
|
||||
} as const
|
||||
|
||||
export type OAuthMethodType = (typeof OAuthMethod)[keyof typeof OAuthMethod]
|
||||
|
||||
Reference in new issue
Block a user