mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(schedules): attach MCP servers to scheduled runs
This commit is contained in:
1 parent
24e2037b73
commit
8e32507f21
20 files changed
+714
-165
No files matched your search
@@ -1,36 +1,21 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeAll } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { McpServerConfig } from '@opencode-manager/shared/opencode'
|
||||
import { AddMcpServerDialog } from './AddMcpServerDialog'
|
||||
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
|
||||
|
||||
const {
|
||||
mockGetOpenCodeConfig,
|
||||
mockUpdateOpenCodeConfig,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getOpenCodeConfig: mockGetOpenCodeConfig,
|
||||
updateOpenCodeConfig: mockUpdateOpenCodeConfig,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
|
||||
const config = makeOpenCodeConfigFile()
|
||||
type SubmitHandler = (serverId: string, config: McpServerConfig) => Promise<void>
|
||||
|
||||
function renderDialog(onUpdate: (content: Record<string, unknown>) => Promise<void>) {
|
||||
function renderDialog(onSubmit: SubmitHandler, showConnectToggle?: boolean) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AddMcpServerDialog open onOpenChange={vi.fn()} onUpdate={onUpdate} />
|
||||
<AddMcpServerDialog open onOpenChange={vi.fn()} onSubmit={onSubmit} showConnectToggle={showConnectToggle} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
@@ -43,40 +28,27 @@ describe('AddMcpServerDialog', () => {
|
||||
Element.prototype.scrollIntoView ??= () => {}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetOpenCodeConfig.mockResolvedValue(config)
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(config)
|
||||
})
|
||||
|
||||
it('issues exactly one config update through the owner callback and never writes directly', async () => {
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
it('submits the server ID and a local server config exactly once', async () => {
|
||||
const onSubmit = vi.fn<SubmitHandler>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderDialog(onUpdate)
|
||||
renderDialog(onSubmit)
|
||||
|
||||
await user.type(screen.getByLabelText('Server ID'), 'filesystem')
|
||||
await user.type(screen.getByLabelText('Command'), 'npx server-filesystem /tmp')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1))
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(onUpdate).toHaveBeenCalledWith({
|
||||
mcp: {
|
||||
servers: {
|
||||
filesystem: {
|
||||
type: 'local',
|
||||
command: ['npx', 'server-filesystem', '/tmp'],
|
||||
disabled: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit).toHaveBeenCalledWith('filesystem', {
|
||||
type: 'local',
|
||||
command: ['npx', 'server-filesystem', '/tmp'],
|
||||
disabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('writes a remote server with V2 OAuth keys and the Manager callback', async () => {
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
it('submits a remote server with V2 OAuth keys and the Manager callback', async () => {
|
||||
const onSubmit = vi.fn<SubmitHandler>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderDialog(onUpdate)
|
||||
renderDialog(onSubmit)
|
||||
|
||||
await user.type(screen.getByLabelText('Server ID'), 'remote-tools')
|
||||
await user.click(screen.getByRole('combobox'))
|
||||
@@ -87,8 +59,8 @@ describe('AddMcpServerDialog', () => {
|
||||
await user.type(screen.getByLabelText('Timeout (ms)'), '9000')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1))
|
||||
const serverConfig = {
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit).toHaveBeenCalledWith('remote-tools', {
|
||||
type: 'remote',
|
||||
url: 'https://mcp.example.com',
|
||||
oauth: {
|
||||
@@ -97,26 +69,36 @@ describe('AddMcpServerDialog', () => {
|
||||
},
|
||||
disabled: false,
|
||||
timeout: { catalog: 9000, execution: 9000 },
|
||||
}
|
||||
expect(onUpdate).toHaveBeenCalledWith({ mcp: { servers: { 'remote-tools': serverConfig } } })
|
||||
})
|
||||
})
|
||||
|
||||
it('passes only the merged content to onUpdate', async () => {
|
||||
const fetched = makeOpenCodeConfigFile({ revision: 'rev-B' })
|
||||
mockGetOpenCodeConfig.mockResolvedValue(fetched)
|
||||
const onUpdate = vi.fn<(content: Record<string, unknown>) => Promise<void>>().mockResolvedValue(undefined)
|
||||
it('submits a remote server with bearer headers and OAuth turned off', async () => {
|
||||
const onSubmit = vi.fn<SubmitHandler>().mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
renderDialog(onUpdate)
|
||||
renderDialog(onSubmit)
|
||||
|
||||
await user.type(screen.getByLabelText('Server ID'), 'filesystem')
|
||||
await user.type(screen.getByLabelText('Command'), 'npx server-filesystem /tmp')
|
||||
await user.type(screen.getByLabelText('Server ID'), 'token-tools')
|
||||
await user.click(screen.getByRole('combobox'))
|
||||
await user.click(screen.getByRole('option', { name: 'Remote (HTTP)' }))
|
||||
await user.type(screen.getByLabelText('Server URL'), 'https://mcp.example.com/mcp')
|
||||
await user.click(screen.getByRole('button', { name: 'Add Headers' }))
|
||||
await user.type(screen.getByLabelText('Headers name 1'), 'Authorization')
|
||||
await user.type(screen.getByLabelText('Headers value 1'), 'Bearer secret-token')
|
||||
await user.click(screen.getByRole('button', { name: 'Add MCP Server' }))
|
||||
|
||||
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1))
|
||||
const [content] = onUpdate.mock.calls[0]
|
||||
expect(onUpdate.mock.calls[0]).toHaveLength(1)
|
||||
const mcp = content.mcp as Record<string, unknown>
|
||||
expect(mcp.servers).toBeDefined()
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit).toHaveBeenCalledWith('token-tools', {
|
||||
type: 'remote',
|
||||
url: 'https://mcp.example.com/mcp',
|
||||
headers: { Authorization: 'Bearer secret-token' },
|
||||
oauth: false,
|
||||
disabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('hides the connect toggle when the caller controls connection', () => {
|
||||
renderDialog(vi.fn<SubmitHandler>(), false)
|
||||
|
||||
expect(screen.queryByLabelText('Connect immediately after adding')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,6 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import {
|
||||
mcpOAuthRedirectUri,
|
||||
type McpServerConfig,
|
||||
@@ -17,20 +16,92 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
interface AddMcpServerDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onUpdate: (content: Record<string, unknown>) => Promise<void>
|
||||
onSubmit: (serverId: string, config: McpServerConfig) => Promise<void>
|
||||
showConnectToggle?: boolean
|
||||
}
|
||||
|
||||
interface EnvironmentVariable {
|
||||
interface KeyValueEntry {
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServerDialogProps) {
|
||||
function toRecord(entries: KeyValueEntry[]): Record<string, string> | undefined {
|
||||
const record = Object.fromEntries(
|
||||
entries
|
||||
.filter((entry) => entry.key.trim() && entry.value.trim())
|
||||
.map((entry) => [entry.key.trim(), entry.value.trim()]),
|
||||
)
|
||||
return Object.keys(record).length > 0 ? record : undefined
|
||||
}
|
||||
|
||||
interface KeyValueRowsProps {
|
||||
label: string
|
||||
hint: string
|
||||
entries: KeyValueEntry[]
|
||||
onChange: (entries: KeyValueEntry[]) => void
|
||||
keyPlaceholder: string
|
||||
valuePlaceholder: string
|
||||
}
|
||||
|
||||
function KeyValueRows({ label, hint, entries, onChange, keyPlaceholder, valuePlaceholder }: KeyValueRowsProps) {
|
||||
const updateEntry = (index: number, field: keyof KeyValueEntry, value: string) => {
|
||||
onChange(entries.map((entry, i) => (i === index ? { ...entry, [field]: value } : entry)))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>{label}</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className='h-6'
|
||||
aria-label={`Add ${label}`}
|
||||
onClick={() => onChange([...entries, { key: '', value: '' }])}
|
||||
>
|
||||
+
|
||||
</Button>
|
||||
</div>
|
||||
{entries.map((entry, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={entry.key}
|
||||
onChange={(e) => updateEntry(index, 'key', e.target.value)}
|
||||
placeholder={keyPlaceholder}
|
||||
aria-label={`${label} name ${index + 1}`}
|
||||
className="bg-background border-border font-mono"
|
||||
/>
|
||||
<Input
|
||||
value={entry.value}
|
||||
onChange={(e) => updateEntry(index, 'value', e.target.value)}
|
||||
placeholder={valuePlaceholder}
|
||||
aria-label={`${label} value ${index + 1}`}
|
||||
className="bg-background border-border font-mono"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
aria-label={`Remove ${label} ${index + 1}`}
|
||||
onClick={() => onChange(entries.filter((_, i) => i !== index))}
|
||||
>
|
||||
x
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function AddMcpServerDialog({ open, onOpenChange, onSubmit, showConnectToggle = true }: 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 [environment, setEnvironment] = useState<KeyValueEntry[]>([])
|
||||
const [headers, setHeaders] = useState<KeyValueEntry[]>([])
|
||||
const [timeout, setTimeout] = useState('')
|
||||
const [enabled, setEnabled] = useState(true)
|
||||
const [oauthEnabled, setOauthEnabled] = useState(false)
|
||||
@@ -58,16 +129,12 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
throw new Error('Command is required for local MCP servers')
|
||||
}
|
||||
|
||||
const environmentVariables = Object.fromEntries(
|
||||
environment
|
||||
.filter((env) => env.key.trim() && env.value.trim())
|
||||
.map((env) => [env.key.trim(), env.value.trim()]),
|
||||
)
|
||||
const environmentVariables = toRecord(environment)
|
||||
|
||||
return {
|
||||
type: 'local',
|
||||
command: commandArray,
|
||||
...(Object.keys(environmentVariables).length > 0 ? { environment: environmentVariables } : {}),
|
||||
...(environmentVariables ? { environment: environmentVariables } : {}),
|
||||
...shared,
|
||||
}
|
||||
}
|
||||
@@ -76,57 +143,32 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
throw new Error('URL is required for remote MCP servers')
|
||||
}
|
||||
|
||||
const requestHeaders = toRecord(headers)
|
||||
|
||||
return {
|
||||
type: 'remote',
|
||||
url: url.trim(),
|
||||
...(oauthEnabled
|
||||
...(requestHeaders ? { headers: requestHeaders } : {}),
|
||||
oauth: oauthEnabled
|
||||
? {
|
||||
oauth: {
|
||||
...(oauthClientId.trim() ? { client_id: oauthClientId.trim() } : {}),
|
||||
...(oauthClientSecret.trim() ? { client_secret: oauthClientSecret.trim() } : {}),
|
||||
...(oauthScope.trim() ? { scope: oauthScope.trim() } : {}),
|
||||
redirect_uri: mcpOAuthRedirectUri(window.location.origin),
|
||||
},
|
||||
...(oauthClientId.trim() ? { client_id: oauthClientId.trim() } : {}),
|
||||
...(oauthClientSecret.trim() ? { client_secret: oauthClientSecret.trim() } : {}),
|
||||
...(oauthScope.trim() ? { scope: oauthScope.trim() } : {}),
|
||||
redirect_uri: mcpOAuthRedirectUri(window.location.origin),
|
||||
}
|
||||
: {}),
|
||||
: false,
|
||||
...shared,
|
||||
}
|
||||
}
|
||||
|
||||
const addMcpServerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const config = await settingsApi.getOpenCodeConfig()
|
||||
const mcpServerConfig = buildMcpServerConfig()
|
||||
const mcp = (config.content.mcp as Record<string, unknown> | undefined) ?? {}
|
||||
|
||||
await onUpdate({
|
||||
...config.content,
|
||||
mcp: {
|
||||
...mcp,
|
||||
servers: { ...(mcp.servers as Record<string, unknown> | undefined), [serverId]: mcpServerConfig },
|
||||
},
|
||||
})
|
||||
},
|
||||
mutationFn: () => onSubmit(serverId, buildMcpServerConfig()),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
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()
|
||||
@@ -139,6 +181,7 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
setCommand('')
|
||||
setUrl('')
|
||||
setEnvironment([])
|
||||
setHeaders([])
|
||||
setTimeout('')
|
||||
setEnabled(true)
|
||||
setOauthEnabled(false)
|
||||
@@ -268,49 +311,25 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
)}
|
||||
|
||||
{serverType === 'local' && (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Environment Variables</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className='h-6'
|
||||
onClick={handleAddEnvironmentVar}
|
||||
>
|
||||
+
|
||||
</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)}
|
||||
>
|
||||
x
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Environment variables to set when running the MCP server
|
||||
</p>
|
||||
</div>
|
||||
<KeyValueRows
|
||||
label="Environment Variables"
|
||||
hint="Environment variables to set when running the MCP server"
|
||||
entries={environment}
|
||||
onChange={setEnvironment}
|
||||
keyPlaceholder="API_KEY"
|
||||
valuePlaceholder="your-api-key-here"
|
||||
/>
|
||||
)}
|
||||
|
||||
{serverType === 'remote' && (
|
||||
<KeyValueRows
|
||||
label="Headers"
|
||||
hint="HTTP headers sent with every request, for example Authorization: Bearer <token>. Turn OAuth off when authenticating with a token."
|
||||
entries={headers}
|
||||
onChange={setHeaders}
|
||||
keyPlaceholder="Authorization"
|
||||
valuePlaceholder="Bearer your-token"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
@@ -327,14 +346,16 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="enabled"
|
||||
checked={enabled}
|
||||
onCheckedChange={setEnabled}
|
||||
/>
|
||||
<Label htmlFor="enabled">Connect immediately after adding</Label>
|
||||
</div>
|
||||
{showConnectToggle && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="enabled"
|
||||
checked={enabled}
|
||||
onCheckedChange={setEnabled}
|
||||
/>
|
||||
<Label htmlFor="enabled">Connect immediately after adding</Label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import type { McpAuthStartResponse } from '@/api/mcp'
|
||||
import { mcpApi } from '@/api/mcp'
|
||||
import { mcpServersFromConfig } from '@opencode-manager/shared/opencode'
|
||||
import { mcpServersFromConfig, type McpServerConfig } from '@opencode-manager/shared/opencode'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { formatMcpServerName } from '@/lib/mcp'
|
||||
@@ -77,6 +78,18 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
},
|
||||
})
|
||||
|
||||
const addServer = async (serverId: string, serverConfig: McpServerConfig) => {
|
||||
const latest = await settingsApi.getOpenCodeConfig()
|
||||
const mcp = (latest.content.mcp as Record<string, unknown> | undefined) ?? {}
|
||||
await onUpdate({
|
||||
...latest.content,
|
||||
mcp: {
|
||||
...mcp,
|
||||
servers: { ...(mcp.servers as Record<string, unknown> | undefined), [serverId]: serverConfig },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const isAnyOperationPending = deleteServerMutation.isPending || togglingServerId !== null
|
||||
|
||||
const handleToggleServer = async (serverId: string) => {
|
||||
@@ -191,7 +204,7 @@ export function McpManager({ config, onUpdate }: McpManagerProps) {
|
||||
<AddMcpServerDialog
|
||||
open={isAddDialogOpen}
|
||||
onOpenChange={setIsAddDialogOpen}
|
||||
onUpdate={onUpdate}
|
||||
onSubmit={addServer}
|
||||
/>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user