From fea3c214af5d685c65565bea5660a6ac7340aef9 Mon Sep 17 00:00:00 2001 From: Chris Scott Date: Wed, 26 Nov 2025 23:43:19 -0500 Subject: [PATCH] Add MCP server management with auto-restart functionality --- backend/src/routes/settings.ts | 38 +++ .../src/services/opencode-single-server.ts | 7 + bun.lockb | Bin 0 -> 11390 bytes frontend/src/api/opencode.ts | 5 + frontend/src/api/settings.ts | 5 + .../session/SessionDetailHeader.tsx | 53 +++- .../settings/AddMcpServerDialog.tsx | 281 ++++++++++++++++++ .../src/components/settings/McpManager.tsx | 248 ++++++++++++++++ .../settings/OpenCodeConfigManager.tsx | 168 ++++++++--- frontend/src/hooks/useOpenCode.ts | 17 ++ frontend/src/lib/mcpServerTemplates.ts | 123 ++++++++ frontend/src/pages/SessionDetail.tsx | 10 +- frontend/src/pages/Settings.tsx | 16 +- 13 files changed, 916 insertions(+), 55 deletions(-) create mode 100755 bun.lockb create mode 100644 frontend/src/components/settings/AddMcpServerDialog.tsx create mode 100644 frontend/src/components/settings/McpManager.tsx create mode 100644 frontend/src/lib/mcpServerTemplates.ts diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index c6a9a53e..bd2ee7b5 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -10,6 +10,7 @@ import { OpenCodeConfigSchema, } from '../types/settings' import { logger } from '../utils/logger' +import { opencodeServerManager } from '../services/opencode-single-server' const UpdateSettingsSchema = z.object({ preferences: UserPreferencesSchema.partial(), @@ -26,6 +27,26 @@ const UpdateOpenCodeConfigSchema = z.object({ isDefault: z.boolean().optional(), }) +function hasMcpChanged(oldContent: Record, newContent: Record): boolean { + const oldMcp = oldContent.mcp as Record || {} + const newMcp = newContent.mcp as Record || {} + + const oldKeys = Object.keys(oldMcp).sort() + const newKeys = Object.keys(newMcp).sort() + + if (JSON.stringify(oldKeys) !== JSON.stringify(newKeys)) { + return true + } + + for (const key of oldKeys) { + if (JSON.stringify(oldMcp[key]) !== JSON.stringify(newMcp[key])) { + return true + } + } + + return false +} + const CreateCustomCommandSchema = z.object({ name: z.string().min(1).max(255), description: z.string().min(1).max(1000), @@ -126,6 +147,7 @@ export function createSettingsRoutes(db: Database) { const body = await c.req.json() const validated = UpdateOpenCodeConfigSchema.parse(body) + const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId) const config = settingsService.updateOpenCodeConfig(configName, validated, userId) if (!config) { return c.json({ error: 'Config not found' }, 404) @@ -138,6 +160,11 @@ export function createSettingsRoutes(db: Database) { logger.info(`Wrote default config to: ${configPath}`) await patchOpenCodeConfig(config.content) + + if (existingConfig && hasMcpChanged(existingConfig.content, config.content)) { + logger.info('MCP configuration changed, restarting OpenCode server') + await opencodeServerManager.restart() + } } return c.json(config) @@ -207,6 +234,17 @@ export function createSettingsRoutes(db: Database) { } }) + app.post('/opencode-restart', async (c) => { + try { + logger.info('Manual OpenCode server restart requested') + await opencodeServerManager.restart() + return c.json({ success: true, message: 'OpenCode server restarted successfully' }) + } catch (error) { + logger.error('Failed to restart OpenCode server:', error) + return c.json({ error: 'Failed to restart OpenCode server' }, 500) + } + }) + // Custom Commands routes app.get('/custom-commands', async (c) => { try { diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 2f3cc041..cb0bc155 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -120,6 +120,13 @@ class OpenCodeServerManager { this.isHealthy = false } + async restart(): Promise { + logger.info('Restarting OpenCode server') + await this.stop() + await new Promise(r => setTimeout(r, 1000)) + await this.start() + } + getPort(): number { return OPENCODE_SERVER_PORT } diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..fb513b36385ffad4d4e6c71d940f4dffae04c7f7 GIT binary patch literal 11390 zcmeHN2~<`_J3DCPn(j zNtWIoXqva+K6m2q=eEOQ4upKyyQxybtQ!G^APtlghU!N&Mv>PTq3BO>&&WY!_-0Q|KB^%2Eb9#7{UQuKBS>`&~BYOCj0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qXs>&TZ;X39&U(efOO8`5u}J>{%mY=~eX>u6wnP>z^HoE*wg^MEo<{#wKd z;&otKYoQh(A_0yB*7Hu9lx*!liV&*nY&$7WZBt1#B+wJgCeEtkPW#XsgXo7Zpbt9l jc(QE(`/session/${sessionID}/fork`, { messageID diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 7baad124..3a7698b7 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -97,4 +97,9 @@ export const settingsApi = { return null } }, + + restartOpenCodeServer: async (): Promise<{ success: boolean; message: string }> => { + const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-restart`) + return data + }, } diff --git a/frontend/src/components/session/SessionDetailHeader.tsx b/frontend/src/components/session/SessionDetailHeader.tsx index 2f1d56c7..007dabf7 100644 --- a/frontend/src/components/session/SessionDetailHeader.tsx +++ b/frontend/src/components/session/SessionDetailHeader.tsx @@ -3,6 +3,7 @@ import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicato import { BranchSwitcher } from "@/components/repo/BranchSwitcher"; import { Button } from "@/components/ui/button"; import { Loader2, Settings, FolderOpen } from "lucide-react"; +import { useState } from "react"; interface Repo { id: number; @@ -24,6 +25,7 @@ interface SessionDetailHeaderProps { repoDirectory: string | undefined; onFileBrowserOpen: () => void; onSettingsOpen: () => void; + onSessionTitleUpdate: (newTitle: string) => void; } export function SessionDetailHeader({ @@ -36,7 +38,10 @@ export function SessionDetailHeader({ repoDirectory, onFileBrowserOpen, onSettingsOpen, + onSessionTitleUpdate, }: SessionDetailHeaderProps) { + const [isEditing, setIsEditing] = useState(false); + const [editTitle, setEditTitle] = useState(sessionTitle); if (repo.cloneStatus !== 'ready') { return ( @@ -54,15 +59,61 @@ export function SessionDetailHeader({ const repoName = repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository"; const currentBranch = repo.currentBranch || "main"; + const handleTitleClick = () => { + setIsEditing(true); + setEditTitle(sessionTitle); + }; + + const handleTitleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (editTitle.trim() && editTitle !== sessionTitle) { + onSessionTitleUpdate(editTitle.trim()); + } + setIsEditing(false); + }; + + const handleTitleBlur = () => { + if (editTitle.trim() && editTitle !== sessionTitle) { + onSessionTitleUpdate(editTitle.trim()); + } + setIsEditing(false); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Escape') { + setEditTitle(sessionTitle); + setIsEditing(false); + } else if (e.key === 'Enter') { + handleTitleSubmit(e); + } + }; + return (
-

+ {isEditing ? ( +
+ setEditTitle(e.target.value)} + onBlur={handleTitleBlur} + onKeyDown={handleKeyDown} + className="text-xs sm:text-base font-semibold bg-background border border-border rounded px-1 outline-none w-full truncate focus:border-primary sm:max-w-[250px]" + autoFocus + /> +
+ ) : ( +

{sessionTitle}

+ )}

{repoName} diff --git a/frontend/src/components/settings/AddMcpServerDialog.tsx b/frontend/src/components/settings/AddMcpServerDialog.tsx new file mode 100644 index 00000000..213806a7 --- /dev/null +++ b/frontend/src/components/settings/AddMcpServerDialog.tsx @@ -0,0 +1,281 @@ +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { Loader2 } from 'lucide-react' +import { settingsApi } from '@/api/settings' +import { useMutation, useQueryClient } from '@tanstack/react-query' + +interface AddMcpServerDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + configName?: string + onUpdate?: (configName: string, content: Record) => Promise +} + +interface EnvironmentVariable { + key: string + value: string +} + +export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServerDialogProps) { + const [serverId, setServerId] = useState('') + const [serverType, setServerType] = useState<'local' | 'remote'>('local') + const [command, setCommand] = useState('') + const [url, setUrl] = useState('') + const [environment, setEnvironment] = useState([]) + const [timeout, setTimeout] = useState('') + const [enabled, setEnabled] = useState(true) + + const queryClient = useQueryClient() + + const addMcpServerMutation = useMutation({ + mutationFn: async () => { + const config = await settingsApi.getDefaultOpenCodeConfig() + if (!config) throw new Error('No default config found') + + const currentMcp = (config.content?.mcp as Record) || {} + + const mcpConfig: any = { + type: serverType, + enabled, + } + + if (serverType === 'local') { + const commandArray = command.split(' ').filter(arg => arg.trim()) + if (commandArray.length === 0) { + throw new Error('Command is required for local MCP servers') + } + mcpConfig.command = commandArray + + const envVars: Record = {} + environment.forEach(env => { + if (env.key.trim() && env.value.trim()) { + envVars[env.key.trim()] = env.value.trim() + } + }) + if (Object.keys(envVars).length > 0) { + mcpConfig.environment = envVars + } + } else { + if (!url.trim()) { + throw new Error('URL is required for remote MCP servers') + } + mcpConfig.url = url.trim() + } + + if (timeout && parseInt(timeout)) { + mcpConfig.timeout = parseInt(timeout) + } + + const updatedConfig = { + ...config.content, + mcp: { + ...currentMcp, + [serverId]: mcpConfig, + }, + } + + await settingsApi.updateOpenCodeConfig(config.name, { content: updatedConfig }) + }, +onSuccess: async () => { + if (onUpdate) { + const config = await settingsApi.getDefaultOpenCodeConfig() + if (config) { + await onUpdate(config.name, config.content) + } + } else { + queryClient.invalidateQueries({ queryKey: ['opencode-config'] }) + } + handleClose() + }, + }) + + const handleAddEnvironmentVar = () => { + setEnvironment([...environment, { key: '', value: '' }]) + } + + const handleRemoveEnvironmentVar = (index: number) => { + setEnvironment(environment.filter((_, i) => i !== index)) + } + + const handleUpdateEnvironmentVar = (index: number, field: 'key' | 'value', value: string) => { + const updated = [...environment] + updated[index][field] = value + setEnvironment(updated) + } + + const handleAdd = () => { + if (serverId) { + addMcpServerMutation.mutate() + } + } + + const handleClose = () => { + setServerId('') + setServerType('local') + setCommand('') + setUrl('') + setEnvironment([]) + setTimeout('') + setEnabled(true) + onOpenChange(false) + } + + return ( +

+ + + Add MCP Server + + Configure a new Model Context Protocol server for your OpenCode configuration + + + +
+
+ + setServerId(e.target.value)} + placeholder="e.g., filesystem, git, my-server" + className="bg-background border-border" + /> +

+ Unique identifier for this MCP server (lowercase, no spaces) +

+
+ +
+ + +
+ + {serverType === 'local' ? ( +
+ + setCommand(e.target.value)} + placeholder="npx @modelcontextprotocol/server-filesystem /tmp" + className="bg-background border-border font-mono" + /> +

+ Command and arguments to run the MCP server +

+
+ ) : ( +
+ + setUrl(e.target.value)} + placeholder="http://localhost:3000/mcp" + className="bg-background border-border font-mono" + /> +

+ URL of the remote MCP server +

+
+ )} + + {serverType === 'local' && ( +
+
+ + +
+ {environment.map((env, index) => ( +
+ handleUpdateEnvironmentVar(index, 'key', e.target.value)} + placeholder="API_KEY" + className="bg-background border-border font-mono" + /> + handleUpdateEnvironmentVar(index, 'value', e.target.value)} + placeholder="your-api-key-here" + className="bg-background border-border font-mono" + /> + {environment.length > 1 && ( + + )} +
+ ))} +

+ Environment variables to set when running the MCP server +

+
+ )} + +
+ + setTimeout(e.target.value)} + placeholder="5000" + className="bg-background border-border" + /> +

+ Timeout in milliseconds for fetching tools (default: 5000) +

+
+ +
+ setEnabled(e.target.checked)} + className="rounded" + /> + +
+
+ + + + + +
+
+ ) +} \ No newline at end of file diff --git a/frontend/src/components/settings/McpManager.tsx b/frontend/src/components/settings/McpManager.tsx new file mode 100644 index 00000000..baeec389 --- /dev/null +++ b/frontend/src/components/settings/McpManager.tsx @@ -0,0 +1,248 @@ +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Dialog, DialogTrigger } from '@/components/ui/dialog' +import { Badge } from '@/components/ui/badge' +import { Switch } from '@/components/ui/switch' +import { Plus, Trash2, Globe, Terminal, Loader2 } from 'lucide-react' +import { DeleteDialog } from '@/components/ui/delete-dialog' +import { AddMcpServerDialog } from './AddMcpServerDialog' +import { useMutation, useQueryClient } from '@tanstack/react-query' + +interface McpServerConfig { + type: 'local' | 'remote' + enabled: boolean + command?: string[] + url?: string + environment?: Record + timeout?: number +} + +interface McpManagerProps { + config: { + name: string + content: Record + } | null + onUpdate: (content: Record) => Promise + onConfigUpdate?: (configName: string, content: Record) => Promise +} + +export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps) { + const [isAddDialogOpen, setIsAddDialogOpen] = useState(false) + const [deleteConfirmServer, setDeleteConfirmServer] = useState<{ id: string; name: string } | null>(null) + const [togglingServerId, setTogglingServerId] = useState(null) + + const queryClient = useQueryClient() + + const toggleServerMutation = useMutation({ + mutationFn: async ({ serverId, enabled }: { serverId: string; enabled: boolean }) => { + if (!config) return + + setTogglingServerId(serverId) + + const currentMcp = (config.content?.mcp as Record) || {} + const serverConfig = currentMcp[serverId] + + if (!serverConfig) return + + const updatedConfig = { + ...config.content, + mcp: { + ...currentMcp, + [serverId]: { + ...serverConfig, + enabled, + }, + }, + } + + await onUpdate(updatedConfig) + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['opencode-config'] }) + }, + onSettled: () => { + setTogglingServerId(null) + }, + }) + + const deleteServerMutation = useMutation({ + mutationFn: async (serverId: string) => { + if (!config) return + + const currentMcp = (config.content?.mcp as Record) || {} + const { [serverId]: deleted, ...rest } = currentMcp + + const updatedConfig = { + ...config.content, + mcp: rest, + } + + await onUpdate(updatedConfig) + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['opencode-config'] }) + setDeleteConfirmServer(null) + }, + }) + + const mcpServers = config?.content?.mcp as Record || {} + + const isAnyOperationPending = toggleServerMutation.isPending || deleteServerMutation.isPending || togglingServerId !== null + + const handleToggleServer = (serverId: string, enabled: boolean) => { + toggleServerMutation.mutate({ serverId, enabled }) + } + + const handleDeleteServer = () => { + if (deleteConfirmServer) { + deleteServerMutation.mutate(deleteConfirmServer.id) + } + } + + const getServerDisplayName = (serverId: string): string => { + const name = serverId.replace(/[-_]/g, ' ') + return name.charAt(0).toUpperCase() + name.slice(1) + } + + const getServerDescription = (serverConfig: McpServerConfig): string => { + if (serverConfig.type === 'local' && serverConfig.command) { + const command = serverConfig.command.join(' ') + if (command.includes('filesystem')) return 'File system access' + if (command.includes('git')) return 'Git repository operations' + if (command.includes('sqlite')) return 'SQLite database access' + if (command.includes('postgres')) return 'PostgreSQL database access' + if (command.includes('brave-search')) return 'Web search via Brave' + if (command.includes('github')) return 'GitHub repository access' + if (command.includes('slack')) return 'Slack integration' + if (command.includes('puppeteer')) return 'Web automation' + if (command.includes('fetch')) return 'HTTP requests' + if (command.includes('memory')) return 'Persistent memory' + return `Local command: ${command}` + } else if (serverConfig.type === 'remote' && serverConfig.url) { + return `Remote server: ${serverConfig.url}` + } + return 'MCP server' + } + + if (!config) { + return ( +
+

Select a configuration to manage MCP servers.

+
+ ) + } + + return ( +
+ {isAnyOperationPending && ( +
+
+ + + {togglingServerId ? 'Updating MCP server...' : 'Processing...'} + + + Please wait while we update your configuration + +
+
+ )} +
+
+

MCP Servers

+

+ Manage Model Context Protocol servers for {config.name} +

+
+ + + + + + +
+ + {Object.keys(mcpServers).length === 0 ? ( + + +

No MCP servers configured. Add your first server to get started.

+
+
+ ) : ( +
+ {Object.entries(mcpServers).map(([serverId, serverConfig]) => ( + + +
+
+
+ {serverConfig.type === 'local' ? ( + + ) : ( + + )} + {getServerDisplayName(serverId)} +
+
+ + {serverConfig.enabled ? 'Enabled' : 'Disabled'} + + + {serverConfig.type} + +
+
+
+ handleToggleServer(serverId, enabled)} + disabled={isAnyOperationPending} + /> + +
+
+
+ +
+

{getServerDescription(serverConfig)}

+ {serverConfig.timeout && ( +

Timeout: {serverConfig.timeout}ms

+ )} + {serverConfig.environment && Object.keys(serverConfig.environment).length > 0 && ( +

Environment variables: {Object.keys(serverConfig.environment).length} configured

+ )} +
+
+
+ ))} +
+ )} + + setDeleteConfirmServer(null)} + onConfirm={handleDeleteServer} + onCancel={() => setDeleteConfirmServer(null)} + title="Delete MCP Server" + description="This will remove the MCP server configuration. This action cannot be undone." + itemName={deleteConfirmServer?.name} + isDeleting={deleteServerMutation.isPending} + /> +
+ ) +} \ No newline at end of file diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 3747f368..6a0d2a27 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -1,5 +1,5 @@ import { useState, useEffect, useRef } from 'react' -import { Loader2, Plus, Trash2, Edit, Star, StarOff, Download } from 'lucide-react' +import { Loader2, Plus, Trash2, Edit, Star, StarOff, Download, RotateCcw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' @@ -13,7 +13,9 @@ import { DeleteDialog } from '@/components/ui/delete-dialog' import { OpenCodeConfigEditor } from './OpenCodeConfigEditor' import { CommandsEditor } from './CommandsEditor' import { AgentsEditor } from './AgentsEditor' +import { McpManager } from './McpManager' import { settingsApi } from '@/api/settings' +import { useMutation } from '@tanstack/react-query' interface OpenCodeConfig { id: number @@ -30,6 +32,11 @@ export function OpenCodeConfigManager() { const [isUpdating, setIsUpdating] = useState(false) const [editingConfig, setEditingConfig] = useState(null) const [selectedConfig, setSelectedConfig] = useState(null) + const [expandedSections, setExpandedSections] = useState>({ + commands: false, + agents: false, + mcp: false, + }) const [newConfigName, setNewConfigName] = useState('') const [newConfigContent, setNewConfigContent] = useState('') const [newConfigIsDefault, setNewConfigIsDefault] = useState(false) @@ -40,6 +47,18 @@ export function OpenCodeConfigManager() { const [createError, setCreateError] = useState('') const [createErrorLine, setCreateErrorLine] = useState(null) const createTextareaRef = useRef(null) + + const restartServerMutation = useMutation({ + mutationFn: async () => { + return await settingsApi.restartOpenCodeServer() + }, + onSuccess: (data) => { + console.log('OpenCode server restarted successfully:', data.message) + }, + onError: (error) => { + console.error('Failed to restart OpenCode server:', error) + }, + }) const fetchConfigs = async () => { try { @@ -80,6 +99,13 @@ export function OpenCodeConfigManager() { fetchConfigs() }, []) + useEffect(() => { + if (configs.length > 0 && !selectedConfig) { + const defaultConfig = configs.find(config => config.isDefault) + setSelectedConfig(defaultConfig || configs[0]) + } + }, [configs, selectedConfig]) + const createConfig = async () => { if (!newConfigName.trim() || !newConfigContent.trim()) return @@ -212,13 +238,26 @@ export function OpenCodeConfigManager() {

OpenCode Configurations

- - - - +
+ + + + + Create OpenCode Config @@ -290,6 +329,7 @@ export function OpenCodeConfigManager() {
+
{configs.length === 0 ? ( @@ -375,12 +415,12 @@ export function OpenCodeConfigManager() { isUpdating={isUpdating} /> - {/* Commands and Agents Section */} + {/* Commands, Agents, and MCP Section */}
-

Configure Commands & Agents

+

Configure Commands, Agents & MCP Servers

- Add custom commands and agents to your OpenCode configurations. Select a configuration below to edit its commands and agents. + Add custom commands, agents, and MCP servers to your OpenCode configurations. Select a configuration below to edit its settings.

{configs.length > 0 && ( @@ -407,44 +447,94 @@ export function OpenCodeConfigManager() {
-
+
{selectedConfig ? ( <> -
-

Editing: {selectedConfig.name}

- -
- ) || {}} - onChange={(commands) => { - const updatedContent = { - ...selectedConfig.content, - command: commands - } - updateConfigContent(selectedConfig.name, updatedContent) - }} - /> +
+ +
+
+ ) || {}} + onChange={(commands) => { + const updatedContent = { + ...selectedConfig.content, + command: commands + } + updateConfigContent(selectedConfig.name, updatedContent) + }} + /> +
-
-
- ) || {}} - onChange={(agents) => { - const updatedContent = { - ...selectedConfig.content, - agent: agents - } - updateConfigContent(selectedConfig.name, updatedContent) - }} - /> +
+ +
+
+ ) || {}} + onChange={(agents) => { + const updatedContent = { + ...selectedConfig.content, + agent: agents + } + updateConfigContent(selectedConfig.name, updatedContent) + }} + /> +
+
+
+ +
+ +
+
+ updateConfigContent(selectedConfig.name, content)} + onConfigUpdate={updateConfigContent} + /> +
) : (
-

Select a configuration to edit its commands and agents.

+

Select a configuration to edit its commands, agents, and MCP servers.

)}
diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 0d4dc70c..651b95f2 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -104,6 +104,23 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory }); }; +export const useUpdateSession = (opcodeUrl: string | null | undefined, directory?: string) => { + const queryClient = useQueryClient(); + const client = useOpenCodeClient(opcodeUrl, directory); + + return useMutation({ + mutationFn: async ({ sessionID, title }: { sessionID: string; title: string }) => { + if (!client) throw new Error("No client available"); + return client.updateSession(sessionID, { title }); + }, + onSuccess: (_, variables) => { + const { sessionID } = variables; + queryClient.invalidateQueries({ queryKey: ["opencode", "session", opcodeUrl, sessionID, directory] }); + queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, directory] }); + }, + }); +}; + const createOptimisticUserMessage = ( sessionID: string, parts: ContentPart[], diff --git a/frontend/src/lib/mcpServerTemplates.ts b/frontend/src/lib/mcpServerTemplates.ts new file mode 100644 index 00000000..82fcb562 --- /dev/null +++ b/frontend/src/lib/mcpServerTemplates.ts @@ -0,0 +1,123 @@ +export interface McpServerTemplate { + id: string + name: string + description: string + type: 'local' | 'remote' + command?: string[] + url?: string + environment?: Record + docsUrl?: string +} + +export const MCP_SERVER_TEMPLATES: McpServerTemplate[] = [ + { + id: 'filesystem', + name: 'Filesystem', + description: 'Access and manipulate local files and directories', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-filesystem', '/tmp'], + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem', + }, + { + id: 'git', + name: 'Git', + description: 'Interact with Git repositories', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-git', '--repository', '.'], + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/git', + }, + { + id: 'sqlite', + name: 'SQLite', + description: 'Query and manage SQLite databases', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-sqlite', '--db-path', './data.db'], + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite', + }, + { + id: 'postgres', + name: 'PostgreSQL', + description: 'Connect to PostgreSQL databases', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-postgres'], + environment: { + POSTGRES_CONNECTION_STRING: 'postgresql://user:password@localhost:5432/dbname', + }, + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/postgres', + }, + { + id: 'brave-search', + name: 'Brave Search', + description: 'Web search using Brave Search API', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-brave-search'], + environment: { + BRAVE_API_KEY: 'your-brave-api-key-here', + }, + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search', + }, + { + id: 'github', + name: 'GitHub', + description: 'Interact with GitHub repositories and issues', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-github'], + environment: { + GITHUB_PERSONAL_ACCESS_TOKEN: 'your-github-token-here', + }, + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/github', + }, + { + id: 'slack', + name: 'Slack', + description: 'Read and send messages to Slack channels', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-slack'], + environment: { + SLACK_BOT_TOKEN: 'xoxb-your-slack-bot-token', + }, + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/slack', + }, + { + id: 'puppeteer', + name: 'Puppeteer', + description: 'Web automation and scraping with Puppeteer', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-puppeteer'], + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer', + }, + { + id: 'fetch', + name: 'Fetch', + description: 'Make HTTP requests to web APIs', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-fetch'], + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/fetch', + }, + { + id: 'memory', + name: 'Memory', + description: 'Persistent memory storage for conversations', + type: 'local', + command: ['npx', '@modelcontextprotocol/server-memory'], + docsUrl: 'https://github.com/modelcontextprotocol/servers/tree/main/src/memory', + }, + { + id: 'custom-local', + name: 'Custom Local Server', + description: 'Run a custom MCP server locally', + type: 'local', + command: ['node', '/path/to/your/server.js'], + }, + { + id: 'custom-remote', + name: 'Custom Remote Server', + description: 'Connect to a remote MCP server via HTTP', + type: 'remote', + url: 'http://localhost:3000/mcp', + }, +] + +export function getMcpServerTemplate(id: string): McpServerTemplate | undefined { + return MCP_SERVER_TEMPLATES.find((t) => t.id === id) +} \ No newline at end of file diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 5224e84f..d195e4e0 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -9,7 +9,7 @@ import { SessionDetailHeader } from "@/components/session/SessionDetailHeader"; import { SessionList } from "@/components/session/SessionList"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; -import { useSession, useMessages, useAbortSession } from "@/hooks/useOpenCode"; +import { useSession, useMessages, useAbortSession, useUpdateSession } from "@/hooks/useOpenCode"; import { OPENCODE_API_ENDPOINT } from "@/config"; import { useSSE } from "@/hooks/useSSE"; import { useSettings } from "@/hooks/useSettings"; @@ -52,6 +52,7 @@ export function SessionDetail() { const { data: messages } = useMessages(opcodeUrl, sessionId, repoDirectory); const { isConnected } = useSSE(opcodeUrl, repoDirectory); const abortSession = useAbortSession(opcodeUrl, repoDirectory); + const updateSession = useUpdateSession(opcodeUrl, repoDirectory); const { open: openSettings } = useSettingsDialog(); useKeyboardShortcuts({ @@ -166,6 +167,12 @@ export function SessionDetail() { setSelectedFilePath(pathToOpen) setFileBrowserOpen(true) }; + + const handleSessionTitleUpdate = (newTitle: string) => { + if (sessionId) { + updateSession.mutate({ sessionID: sessionId, title: newTitle }); + } + }; return ( @@ -180,6 +187,7 @@ export function SessionDetail() { repoDirectory={repoDirectory} onFileBrowserOpen={() => setFileBrowserOpen(true)} onSettingsOpen={openSettings} + onSessionTitleUpdate={handleSessionTitleUpdate} />
diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsx index 50882c0f..53c4b4fd 100644 --- a/frontend/src/pages/Settings.tsx +++ b/frontend/src/pages/Settings.tsx @@ -11,7 +11,7 @@ export function Settings() {
- + OpenCode - - Commands - - - Agents - @@ -52,7 +40,7 @@ export function Settings() { - +