Merge pull request #3 from chriswritescode-dev/feature-mcp

Add MCP server management with auto-restart functionality
This commit is contained in:
Chris Scott authored and GitHub committed 2025-11-27 00:02:43 -05:00
commit 0293bdbfa8
13 files changed
+916 -55

No files matched your search

+38
View File
@@ -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<string, unknown>, newContent: Record<string, unknown>): boolean {
const oldMcp = oldContent.mcp as Record<string, any> || {}
const newMcp = newContent.mcp as Record<string, any> || {}
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 {
@@ -120,6 +120,13 @@ class OpenCodeServerManager {
this.isHealthy = false
}
async restart(): Promise<void> {
logger.info('Restarting OpenCode server')
await this.stop()
await new Promise(r => setTimeout(r, 1000))
await this.start()
}
getPort(): number {
return OPENCODE_SERVER_PORT
}
Executable
BIN
View File
Binary file not shown.
+5
View File
@@ -55,6 +55,11 @@ export class OpenCodeClient {
await this.client.delete(`/session/${sessionID}`)
}
async updateSession(sessionID: string, data: { title?: string }) {
const response = await this.client.patch(`/session/${sessionID}`, data)
return response.data
}
async forkSession(sessionID: string, messageID?: string) {
const response = await this.client.post<SessionResponse>(`/session/${sessionID}/fork`, {
messageID
+5
View File
@@ -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
},
}
@@ -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 (
<div className="sticky top-0 z-10 border-b border-border bg-gradient-to-b from-background via-background to-background backdrop-blur-sm px-2 sm:px-4 py-1.5 sm:py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 sm:gap-3 min-w-0 flex-1">
<BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
<div className="min-w-0 flex-1">
<h1 className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate">
{isEditing ? (
<form onSubmit={handleTitleSubmit} className="min-w-0">
<input
type="text"
value={editTitle}
onChange={(e) => 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
/>
</form>
) : (
<h1
className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate cursor-pointer hover:opacity-80 transition-opacity"
onClick={handleTitleClick}
>
{sessionTitle}
</h1>
)}
<div className="flex items-center gap-2">
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
{repoName}
@@ -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<string, unknown>) => Promise<void>
}
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<EnvironmentVariable[]>([])
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<string, any>) || {}
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<string, string> = {}
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 (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-2xl bg-card border-border">
<DialogHeader>
<DialogTitle>Add MCP Server</DialogTitle>
<DialogDescription>
Configure a new Model Context Protocol server for your OpenCode configuration
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="serverId">Server ID</Label>
<Input
id="serverId"
value={serverId}
onChange={(e) => setServerId(e.target.value)}
placeholder="e.g., filesystem, git, my-server"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Unique identifier for this MCP server (lowercase, no spaces)
</p>
</div>
<div className="space-y-2">
<Label htmlFor="serverType">Server Type</Label>
<Select value={serverType} onValueChange={(value: 'local' | 'remote') => setServerType(value)}>
<SelectTrigger className="bg-background border-border">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="local">Local (Command)</SelectItem>
<SelectItem value="remote">Remote (HTTP)</SelectItem>
</SelectContent>
</Select>
</div>
{serverType === 'local' ? (
<div className="space-y-2">
<Label htmlFor="command">Command</Label>
<Input
id="command"
value={command}
onChange={(e) => setCommand(e.target.value)}
placeholder="npx @modelcontextprotocol/server-filesystem /tmp"
className="bg-background border-border font-mono"
/>
<p className="text-xs text-muted-foreground">
Command and arguments to run the MCP server
</p>
</div>
) : (
<div className="space-y-2">
<Label htmlFor="url">Server URL</Label>
<Input
id="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="http://localhost:3000/mcp"
className="bg-background border-border font-mono"
/>
<p className="text-xs text-muted-foreground">
URL of the remote MCP server
</p>
</div>
)}
{serverType === 'local' && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>Environment Variables</Label>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleAddEnvironmentVar}
>
Add Variable
</Button>
</div>
{environment.map((env, index) => (
<div key={index} className="flex gap-2">
<Input
value={env.key}
onChange={(e) => handleUpdateEnvironmentVar(index, 'key', e.target.value)}
placeholder="API_KEY"
className="bg-background border-border font-mono"
/>
<Input
value={env.value}
onChange={(e) => handleUpdateEnvironmentVar(index, 'value', e.target.value)}
placeholder="your-api-key-here"
className="bg-background border-border font-mono"
/>
{environment.length > 1 && (
<Button
type="button"
variant="outline"
size="icon"
onClick={() => handleRemoveEnvironmentVar(index)}
>
×
</Button>
)}
</div>
))}
<p className="text-xs text-muted-foreground">
Environment variables to set when running the MCP server
</p>
</div>
)}
<div className="space-y-2">
<Label htmlFor="timeout">Timeout (ms)</Label>
<Input
id="timeout"
value={timeout}
onChange={(e) => setTimeout(e.target.value)}
placeholder="5000"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Timeout in milliseconds for fetching tools (default: 5000)
</p>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
id="enabled"
checked={enabled}
onChange={(e) => setEnabled(e.target.checked)}
className="rounded"
/>
<Label htmlFor="enabled">Enable server on startup</Label>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleAdd}
disabled={!serverId || addMcpServerMutation.isPending}
>
{addMcpServerMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Add MCP Server
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -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<string, string>
timeout?: number
}
interface McpManagerProps {
config: {
name: string
content: Record<string, unknown>
} | null
onUpdate: (content: Record<string, unknown>) => Promise<void>
onConfigUpdate?: (configName: string, content: Record<string, unknown>) => Promise<void>
}
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<string | null>(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<string, any>) || {}
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<string, any>) || {}
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<string, McpServerConfig> || {}
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 (
<div className="text-center py-8">
<p className="text-muted-foreground">Select a configuration to manage MCP servers.</p>
</div>
)
}
return (
<div className="space-y-6 relative min-h-[200px]">
{isAnyOperationPending && (
<div className="absolute inset-0 -m-4 bg-background/90 backdrop-blur-sm flex items-center justify-center z-50">
<div className="flex flex-col items-center gap-3 bg-card border border-border rounded-lg p-6 shadow-lg">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<span className="text-sm font-medium text-foreground">
{togglingServerId ? 'Updating MCP server...' : 'Processing...'}
</span>
<span className="text-xs text-muted-foreground">
Please wait while we update your configuration
</span>
</div>
</div>
)}
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold">MCP Servers</h3>
<p className="text-sm text-muted-foreground">
Manage Model Context Protocol servers for {config.name}
</p>
</div>
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Server
</Button>
</DialogTrigger>
<AddMcpServerDialog
open={isAddDialogOpen}
onOpenChange={setIsAddDialogOpen}
onUpdate={onConfigUpdate}
/>
</Dialog>
</div>
{Object.keys(mcpServers).length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No MCP servers configured. Add your first server to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{Object.entries(mcpServers).map(([serverId, serverConfig]) => (
<Card key={serverId}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
{serverConfig.type === 'local' ? (
<Terminal className="h-4 w-4 text-muted-foreground" />
) : (
<Globe className="h-4 w-4 text-muted-foreground" />
)}
<CardTitle className="text-base">{getServerDisplayName(serverId)}</CardTitle>
</div>
<div className="flex items-center gap-2">
<Badge variant={serverConfig.enabled ? 'default' : 'secondary'} className="text-xs">
{serverConfig.enabled ? 'Enabled' : 'Disabled'}
</Badge>
<Badge variant="outline" className="text-xs">
{serverConfig.type}
</Badge>
</div>
</div>
<div className="flex items-center gap-2">
<Switch
checked={serverConfig.enabled}
onCheckedChange={(enabled) => handleToggleServer(serverId, enabled)}
disabled={isAnyOperationPending}
/>
<Button
variant="ghost"
size="sm"
onClick={() => setDeleteConfirmServer({ id: serverId, name: getServerDisplayName(serverId) })}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground space-y-1">
<p>{getServerDescription(serverConfig)}</p>
{serverConfig.timeout && (
<p>Timeout: {serverConfig.timeout}ms</p>
)}
{serverConfig.environment && Object.keys(serverConfig.environment).length > 0 && (
<p>Environment variables: {Object.keys(serverConfig.environment).length} configured</p>
)}
</div>
</CardContent>
</Card>
))}
</div>
)}
<DeleteDialog
open={!!deleteConfirmServer}
onOpenChange={() => 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}
/>
</div>
)
}
@@ -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<OpenCodeConfig | null>(null)
const [selectedConfig, setSelectedConfig] = useState<OpenCodeConfig | null>(null)
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
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<number | null>(null)
const createTextareaRef = useRef<HTMLTextAreaElement>(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() {
<div className="space-y-6 overflow-y-auto">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-foreground">OpenCode Configurations</h2>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
New Config
</Button>
</DialogTrigger>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => restartServerMutation.mutate()}
disabled={restartServerMutation.isPending}
>
{restartServerMutation.isPending ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<RotateCcw className="h-4 w-4 mr-2" />
)}
Restart Server
</Button>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
New Config
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create OpenCode Config</DialogTitle>
@@ -290,6 +329,7 @@ export function OpenCodeConfigManager() {
</div>
</DialogContent>
</Dialog>
</div>
</div>
{configs.length === 0 ? (
@@ -375,12 +415,12 @@ export function OpenCodeConfigManager() {
isUpdating={isUpdating}
/>
{/* Commands and Agents Section */}
{/* Commands, Agents, and MCP Section */}
<div className="mt-8 space-y-6">
<div className="border-t border-border pt-6">
<h3 className="text-lg font-semibold mb-4">Configure Commands & Agents</h3>
<h3 className="text-lg font-semibold mb-4">Configure Commands, Agents & MCP Servers</h3>
<p className="text-sm text-muted-foreground mb-6">
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.
</p>
{configs.length > 0 && (
@@ -407,44 +447,94 @@ export function OpenCodeConfigManager() {
</Select>
</div>
<div className="space-y-8 pb-20">
<div className="flex flex-col gap-4 pb-20">
{selectedConfig ? (
<>
<div className="bg-card border border-border rounded-lg p-6">
<h4 className="text-md font-medium mb-4">Editing: {selectedConfig.name}</h4>
<div className="max-h-[60vh] overflow-y-auto">
<CommandsEditor
commands={(selectedConfig.content.command as Record<string, any>) || {}}
onChange={(commands) => {
const updatedContent = {
...selectedConfig.content,
command: commands
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
<div className="bg-card border border-border rounded-lg overflow-hidden">
<button
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors"
onClick={() => setExpandedSections(prev => ({ ...prev, commands: !prev.commands }))}
>
<div className="flex items-center gap-3">
<h4 className="text-sm font-medium">Commands</h4>
<span className="text-xs text-muted-foreground">
{Object.keys(selectedConfig.content.command as Record<string, any> || {}).length} configured
</span>
</div>
<Edit className={`h-4 w-4 transition-transform ${expandedSections.commands ? 'rotate-90' : ''}`} />
</button>
<div className={`${expandedSections.commands ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<CommandsEditor
commands={(selectedConfig.content.command as Record<string, any>) || {}}
onChange={(commands) => {
const updatedContent = {
...selectedConfig.content,
command: commands
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
</div>
</div>
</div>
<div className="bg-card border border-border rounded-lg p-6">
<div className="max-h-[60vh] overflow-y-auto">
<AgentsEditor
agents={(selectedConfig.content.agent as Record<string, any>) || {}}
onChange={(agents) => {
const updatedContent = {
...selectedConfig.content,
agent: agents
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
<div className="bg-card border border-border rounded-lg overflow-hidden">
<button
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors"
onClick={() => setExpandedSections(prev => ({ ...prev, agents: !prev.agents }))}
>
<div className="flex items-center gap-3">
<h4 className="text-sm font-medium">Agents</h4>
<span className="text-xs text-muted-foreground">
{Object.keys(selectedConfig.content.agent as Record<string, any> || {}).length} configured
</span>
</div>
<Edit className={`h-4 w-4 transition-transform ${expandedSections.agents ? 'rotate-90' : ''}`} />
</button>
<div className={`${expandedSections.agents ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<AgentsEditor
agents={(selectedConfig.content.agent as Record<string, any>) || {}}
onChange={(agents) => {
const updatedContent = {
...selectedConfig.content,
agent: agents
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
</div>
</div>
</div>
<div className="bg-card border border-border rounded-lg overflow-hidden">
<button
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors"
onClick={() => setExpandedSections(prev => ({ ...prev, mcp: !prev.mcp }))}
>
<div className="flex items-center gap-3">
<h4 className="text-sm font-medium">MCP Servers</h4>
<span className="text-xs text-muted-foreground">
{Object.keys((selectedConfig.content.mcp as Record<string, any>) || {}).length} configured
</span>
</div>
<Edit className={`h-4 w-4 transition-transform ${expandedSections.mcp ? 'rotate-90' : ''}`} />
</button>
<div className={`${expandedSections.mcp ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<McpManager
config={selectedConfig}
onUpdate={(content) => updateConfigContent(selectedConfig.name, content)}
onConfigUpdate={updateConfigContent}
/>
</div>
</div>
</div>
</>
) : (
<div className="bg-card border border-border rounded-lg p-6">
<p className="text-muted-foreground text-center">Select a configuration to edit its commands and agents.</p>
<p className="text-muted-foreground text-center">Select a configuration to edit its commands, agents, and MCP servers.</p>
</div>
)}
</div>
+17
View File
@@ -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[],
+123
View File
@@ -0,0 +1,123 @@
export interface McpServerTemplate {
id: string
name: string
description: string
type: 'local' | 'remote'
command?: string[]
url?: string
environment?: Record<string, string>
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)
}
+9 -1
View File
@@ -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}
/>
<div className="flex-1 overflow-hidden relative">
+2 -14
View File
@@ -11,7 +11,7 @@ export function Settings() {
<div className="max-w-4xl mx-auto p-6">
<Tabs defaultValue="general" className="w-full">
<TabsList className="grid w-full grid-cols-5 mb-8 bg-[#141414] border border-[#262626] p-1">
<TabsList className="grid w-full grid-cols-3 mb-8 bg-[#141414] border border-[#262626] p-1">
<TabsTrigger
value="general"
className="data-[state=active]:bg-blue-800 data-[state=active]:text-white text-zinc-400"
@@ -30,18 +30,6 @@ export function Settings() {
>
OpenCode
</TabsTrigger>
<TabsTrigger
value="commands"
className="data-[state=active]:bg-blue-800 data-[state=active]:text-white text-zinc-400"
>
Commands
</TabsTrigger>
<TabsTrigger
value="agents"
className="data-[state=active]:bg-blue-800 data-[state=active]:text-white text-zinc-400"
>
Agents
</TabsTrigger>
</TabsList>
<TabsContent value="general">
@@ -52,7 +40,7 @@ export function Settings() {
<KeyboardShortcuts />
</TabsContent>
<TabsContent value="opencode">
<TabsContent value="opencode">
<OpenCodeConfigManager />
</TabsContent>