'use client'; import { PageShell } from '@/components/layout/PageShell'; import { useVconRole } from '@/components/layout/VconShell'; import { Button } from '@/components/ui/Button'; import { CodeBlock } from '@/components/ui/CodeBlock'; import { FormSwitch } from '@/components/ui/Form'; import { Input } from '@/components/ui/Input'; import { Modal } from '@/components/ui/Modal'; import { Panel } from '@/components/ui/Panel'; import { SettingsField, SettingsFooter, SettingsGroup, SettingsPanel, SettingsTabs, } from '@/components/ui/SettingsLayout'; import { StatStrip } from '@/components/ui/StatStrip'; import { useToast } from '@/components/ui/Toast'; import { applyCategoryPermissionToggle, applyMcpPermissionPreset, buildMcpClientConfigSnippet, buildMcpEndpointUrl, buildMcpSavePayload, countEnabledMcpPermissions, DEFAULT_PUBLIC_MCP_SETTINGS, describeMcpBridgeSync, groupMcpPermissionsByCategory, isMcpDraftDirty, MCP_CLIENT_TARGETS, type McpBridgeSyncView, type McpClientTargetId, type McpDraftState, type McpPermissionDefinitionView, type PublicMcpSettingsView, } from '@/lib/mcpUiHelpers'; import { getCached, setCached } from '@/lib/vconCache'; import { getVconRoleCapabilities } from '@/lib/vconUiHelpers'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; const MCP_TABS = [ { id: 'connection', label: 'Connection & Token' }, { id: 'permissions', label: 'Permissions (17)' }, { id: 'clients', label: 'AI Client Setup' }, { id: 'coolify', label: 'Build Logs (Coolify)' }, ]; type McpTabId = (typeof MCP_TABS)[number]['id']; function settingsToDraft(settings: PublicMcpSettingsView): McpDraftState { return { enabled: Boolean(settings.enabled), allowedIps: String(settings.allowedIps || ''), permissions: { ...(settings.permissions || {}) }, coolifyUrl: String(settings.coolifyUrl || ''), coolifyTokenInput: '', clearCoolifyToken: false, coolifyAppUuid: String(settings.coolifyAppUuid || ''), }; } export function McpWorkspace() { const currentRole = useVconRole(); const { isOwner } = getVconRoleCapabilities(currentRole); const { success, warning, error } = useToast(); const [saved, setSaved] = useState(() => getCached('vcon:mcp-settings', DEFAULT_PUBLIC_MCP_SETTINGS), ); const [draft, setDraft] = useState(() => settingsToDraft( getCached('vcon:mcp-settings', DEFAULT_PUBLIC_MCP_SETTINGS), ), ); const [definitions, setDefinitions] = useState(() => getCached('vcon:mcp-defs', []), ); const [bridgeSync, setBridgeSync] = useState(() => getCached('vcon:mcp-bridge', null), ); // Security: one-time token stays strictly in component state (never cached globally). const [issuedToken, setIssuedToken] = useState(''); const tokenBannerRef = useRef(null); const [activeTab, setActiveTab] = useState('connection'); const [selectedClientTarget, setSelectedClientTarget] = useState('claude'); const [origin, setOrigin] = useState(''); const [loading, setLoading] = useState( () => isOwner && !getCached('vcon:mcp-loaded', false), ); const [saving, setSaving] = useState(false); const [tokenBusy, setTokenBusy] = useState(false); const [rotateConfirmOpen, setRotateConfirmOpen] = useState(false); const [revokeConfirmOpen, setRevokeConfirmOpen] = useState(false); const loadMcpSettings = useCallback(async () => { if (!isOwner) { setLoading(false); return; } setLoading(true); try { const response = await fetch('/api/mcp', { credentials: 'include', cache: 'no-store', }); if (response.status === 401) { window.location.assign('/vcon/login'); return; } const data = await response.json(); if (!response.ok) { throw new Error(data?.error || 'Unable to load MCP settings.'); } const nextSettings = (data.settings ?? DEFAULT_PUBLIC_MCP_SETTINGS) as PublicMcpSettingsView; const nextDefs = Array.isArray(data.permissionDefinitions) ? (data.permissionDefinitions as McpPermissionDefinitionView[]) : []; const nextBridge = (data.bridgeSync ?? null) as McpBridgeSyncView | null; setCached('vcon:mcp-settings', nextSettings); setCached('vcon:mcp-defs', nextDefs); setCached('vcon:mcp-bridge', nextBridge); setCached('vcon:mcp-loaded', true); setSaved(nextSettings); setDraft(settingsToDraft(nextSettings)); setDefinitions(nextDefs); setBridgeSync(nextBridge); } catch (err: unknown) { error( 'Failed to load MCP settings', err instanceof Error ? err.message : 'Unable to fetch /api/mcp', ); } finally { setLoading(false); } }, [isOwner, error]); useEffect(() => { setOrigin(window.location.origin); void loadMcpSettings(); }, [loadMcpSettings]); const applyPostResult = (data: { settings?: PublicMcpSettingsView; issuedToken?: string; bridgeSync?: McpBridgeSyncView | null; }) => { if (data.settings) { setCached('vcon:mcp-settings', data.settings); setSaved(data.settings); setDraft(settingsToDraft(data.settings)); } if (data.bridgeSync !== undefined) { setCached('vcon:mcp-bridge', data.bridgeSync); setBridgeSync(data.bridgeSync); } if (data.issuedToken) { setIssuedToken(data.issuedToken); requestAnimationFrame(() => { tokenBannerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest', }); }); } }; const notifySyncOutcome = ( nextBridge: McpBridgeSyncView | null | undefined, successTitle: string, successDetail: string, ) => { const syncInfo = describeMcpBridgeSync(nextBridge); if (syncInfo.level === 'error') { error(syncInfo.title, syncInfo.detail); } else if (syncInfo.level === 'warning') { warning(syncInfo.title, syncInfo.detail); } else { success(successTitle, successDetail); } }; const isDirty = useMemo( () => isMcpDraftDirty(draft, saved, definitions), [draft, saved, definitions], ); const permCounts = useMemo( () => countEnabledMcpPermissions(draft.permissions, definitions), [draft.permissions, definitions], ); const groupedPermissions = useMemo( () => groupMcpPermissionsByCategory(definitions, draft.permissions), [definitions, draft.permissions], ); const endpointUrl = useMemo( () => buildMcpEndpointUrl(origin, saved.endpointPath || '/mcp'), [origin, saved.endpointPath], ); const activeClientMeta = useMemo( () => MCP_CLIENT_TARGETS.find((item) => item.id === selectedClientTarget) ?? MCP_CLIENT_TARGETS[0], [selectedClientTarget], ); const clientConfigJson = useMemo( () => buildMcpClientConfigSnippet(selectedClientTarget, { endpointUrl, token: issuedToken, }), [selectedClientTarget, endpointUrl, issuedToken], ); const copyText = async (value: string, label: string) => { try { if (!navigator?.clipboard?.writeText) { throw new Error('Clipboard API unavailable in this browser context'); } await navigator.clipboard.writeText(value); success('Copied', `${label} copied to clipboard.`); } catch (copyErr: unknown) { error( 'Copy failed', copyErr instanceof Error ? copyErr.message : 'Unable to copy to clipboard.', ); } }; const handleSave = async (event: React.FormEvent) => { event.preventDefault(); if (!isOwner) return; const payload = buildMcpSavePayload(draft, saved, definitions); if (Object.keys(payload).length === 0) { return; } setSaving(true); try { const response = await fetch('/api/mcp', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); if (response.status === 401) { window.location.assign('/vcon/login'); return; } const data = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(data?.error || 'Failed to save MCP settings.'); } applyPostResult(data); notifySyncOutcome( data.bridgeSync, data.issuedToken ? 'MCP enabled & token issued' : 'MCP settings saved', data.issuedToken ? 'Bearer token revealed at the top of MCP Server — copy it into your AI client config.' : 'Configuration synced to live Port 4000 MCP server.', ); } catch (saveErr: unknown) { error( 'Save failed', saveErr instanceof Error ? saveErr.message : 'Unable to save MCP settings.', ); } finally { setSaving(false); } }; const handleTokenAction = async (mode: 'rotate' | 'revoke') => { if (!isOwner) return; setTokenBusy(true); try { const body = mode === 'rotate' ? { rotateToken: true } : { revokeToken: true }; const response = await fetch('/api/mcp', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (response.status === 401) { window.location.assign('/vcon/login'); return; } const data = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(data?.error || `Unable to ${mode} MCP token.`); } if (mode === 'revoke') { setIssuedToken(''); } applyPostResult(data); setRotateConfirmOpen(false); setRevokeConfirmOpen(false); notifySyncOutcome( data.bridgeSync, mode === 'rotate' ? 'MCP token rotated' : 'MCP access revoked', mode === 'rotate' ? 'New one-time Bearer token generated below; old token invalidated.' : 'Bearer token cleared and Streamable HTTP /mcp endpoint disabled.', ); } catch (tokErr: unknown) { error( mode === 'rotate' ? 'Token rotation failed' : 'Token revocation failed', tokErr instanceof Error ? tokErr.message : 'MCP token operation failed.', ); } finally { setTokenBusy(false); } }; const bridgeSummary = describeMcpBridgeSync(bridgeSync); return ( void loadMcpSettings()} > Refresh ) : undefined } > {!isOwner ? (
Owner-only workspace ({currentRole}) — MCP configuration, Bearer tokens, and AI agent permissions are restricted to Owner accounts.
) : (
{issuedToken && (
One-Time MCP Bearer Token (copy now — hidden after page reload)
{issuedToken}
)} tab.id === 'permissions' ? { ...tab, label: `Permissions (${permCounts.enabled}/${permCounts.total || 17})`, } : tab, )} value={activeTab} onChange={(tab) => setActiveTab(tab as McpTabId)} />
{activeTab === 'connection' && ( <> setDraft((prev) => ({ ...prev, enabled: checked })) } />
setDraft((prev) => ({ ...prev, allowedIps: e.target.value })) } className="font-mono text-[11.5px]" />
{saved.hasToken ? saved.tokenPreview || 'Provisioned (dsmcp_...)' : 'Not provisioned (auto-mints on enable)'}
{saved.hasToken && ( )}
)} {activeTab === 'permissions' && ( <>
{permCounts.enabled} of {permCounts.total || 17} MCP tools enabled
{groupedPermissions.length === 0 ? (
{loading ? 'Loading MCP tool permissions...' : 'No MCP permission definitions available.'}
) : ( groupedPermissions.map((group) => ( } > {group.items.map((def) => (
setDraft((prev) => ({ ...prev, permissions: { ...prev.permissions, [def.key]: checked, }, })) } /> {def.description}
))}
)) )} )} {activeTab === 'clients' && (
{MCP_CLIENT_TARGETS.map((target) => ( ))}
{activeClientMeta.configPath}
void copyText( clientConfigJson, `${activeClientMeta.label} MCP JSON`, ) } > Copy JSON } > {clientConfigJson} {!issuedToken && (
Replace YOUR_MCP_BEARER_TOKEN{' '} with your saved dsmcp_ token, or rotate the token under Connection & Token to populate it here automatically.
)}
)} {activeTab === 'coolify' && ( setDraft((prev) => ({ ...prev, coolifyUrl: e.target.value })) } className="font-mono text-[11.5px]" />
setDraft((prev) => ({ ...prev, coolifyTokenInput: e.target.value, clearCoolifyToken: false, })) } className="font-mono text-[11.5px]" /> {saved.hasCoolifyToken && ( setDraft((prev) => ({ ...prev, clearCoolifyToken: checked, ...(checked ? { coolifyTokenInput: '' } : {}), })) } /> )}
setDraft((prev) => ({ ...prev, coolifyAppUuid: e.target.value, })) } className="font-mono text-[11.5px]" />
)} {isDirty && ( )}
)} { if (!tokenBusy) setRotateConfirmOpen(false); }} title="Rotate MCP Bearer Token" maxWidth="sm" footer={ <> } >

Generating a new dsmcp_{' '} Bearer token immediately invalidates the previous token across Port 4000{' '} /mcp sessions. Update connected AI clients with the new token shown afterward.

{ if (!tokenBusy) setRevokeConfirmOpen(false); }} title="Revoke MCP Token & Disable Server" maxWidth="sm" footer={ <> } >

Revoking deletes the active Bearer token and sets the{' '} /mcp server to Disabled (503 MCP_DISABLED).

); } export default McpWorkspace;