From 8e32507f2178dce1d1e12cdd669e866736d071f7 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:43:02 -0400 Subject: [PATCH] feat(schedules): attach MCP servers to scheduled runs --- .../db/migrations/023-schedule-mcp-servers.ts | 23 ++ backend/src/db/migrations/index.ts | 2 + backend/src/db/schedules.ts | 28 ++- backend/src/services/schedule-config.ts | 4 + backend/src/services/schedules.ts | 55 ++++- backend/test/db/schedules.permission.test.ts | 1 + backend/test/db/schedules.test.ts | 4 + backend/test/helpers/stub-schedule-api.ts | 17 ++ backend/test/services/schedule-config.test.ts | 8 + .../services/schedules.permission.test.ts | 1 + backend/test/services/schedules.test.ts | 74 ++++++ docs/features/schedules.md | 11 + frontend/src/components/schedules/McpTab.tsx | 120 ++++++++++ .../schedules/ScheduleJobDialog.mcp.test.tsx | 111 +++++++++ .../schedules/ScheduleJobDialog.tsx | 23 +- .../settings/AddMcpServerDialog.test.tsx | 104 ++++----- .../settings/AddMcpServerDialog.tsx | 215 ++++++++++-------- .../src/components/settings/McpManager.tsx | 17 +- shared/src/schemas/schedule.ts | 59 +++++ shared/src/types/index.ts | 2 + 20 files changed, 714 insertions(+), 165 deletions(-) create mode 100644 backend/src/db/migrations/023-schedule-mcp-servers.ts create mode 100644 frontend/src/components/schedules/McpTab.tsx create mode 100644 frontend/src/components/schedules/ScheduleJobDialog.mcp.test.tsx diff --git a/backend/src/db/migrations/023-schedule-mcp-servers.ts b/backend/src/db/migrations/023-schedule-mcp-servers.ts new file mode 100644 index 00000000..32a0d5b0 --- /dev/null +++ b/backend/src/db/migrations/023-schedule-mcp-servers.ts @@ -0,0 +1,23 @@ +import type { Migration } from '../migration-runner' + +interface ColumnInfo { + name: string +} + +const migration: Migration = { + version: 23, + name: 'schedule-mcp-servers', + + up(db) { + const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[] + if (!columns.some((column) => column.name === 'mcp_servers')) { + db.run('ALTER TABLE schedule_jobs ADD COLUMN mcp_servers TEXT') + } + }, + + down(db) { + db.run('ALTER TABLE schedule_jobs DROP COLUMN mcp_servers') + }, +} + +export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index d3b02688..83fca911 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -21,6 +21,7 @@ import migration019 from './019-drop-opencode-configs' import migration020 from './020-drop-opencode-model-state' import migration021 from './021-drop-schedule-run-workspace-id' import migration022 from './022-schedule-runs-session-index' +import migration023 from './023-schedule-mcp-servers' export const allMigrations: Migration[] = [ migration001, @@ -45,4 +46,5 @@ export const allMigrations: Migration[] = [ migration020, migration021, migration022, + migration023, ] diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index 57490e19..6bf70b00 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -1,10 +1,12 @@ import type { Database } from 'bun:sqlite' import { ScheduleJobSchema, + ScheduleMcpServersSchema, SchedulePermissionConfigSchema, ScheduleRunSchema, ScheduleSkillMetadataSchema, type ScheduleJob, + type ScheduleMcpServer, type ScheduleMode, type SchedulePermissionConfig, type ScheduleRun, @@ -29,6 +31,7 @@ interface ScheduleJobRow { model: string | null skill_metadata: string | null permission_config: string | null + mcp_servers: string | null branch: string | null created_at: number updated_at: number @@ -83,6 +86,19 @@ function parsePermissionConfig(raw: string | null): SchedulePermissionConfig | n } } +function parseMcpServers(raw: string | null): ScheduleMcpServer[] { + if (!raw) { + return [] + } + + try { + const result = ScheduleMcpServersSchema.safeParse(JSON.parse(raw)) + return result.success ? result.data : [] + } catch { + return [] + } +} + function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob { return ScheduleJobSchema.parse({ id: row.id, @@ -99,6 +115,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob { model: row.model, skillMetadata: parseSkillMetadata(row.skill_metadata), permissionConfig: parsePermissionConfig(row.permission_config), + mcpServers: parseMcpServers(row.mcp_servers), branch: row.branch, createdAt: row.created_at, updatedAt: row.updated_at, @@ -144,6 +161,10 @@ function serializePermissionConfig(permissionConfig: ScheduleJobPersistenceInput return JSON.stringify(permissionConfig) } +function serializeMcpServers(mcpServers: ScheduleJobPersistenceInput['mcpServers']): string | null { + return mcpServers.length > 0 ? JSON.stringify(mcpServers) : null +} + export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] { const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC') const rows = stmt.all(repoId) as ScheduleJobRow[] @@ -174,10 +195,11 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ INSERT INTO schedule_jobs ( repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata, permission_config, + mcp_servers, branch, created_at, updated_at, last_run_at, next_run_at ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `) const result = stmt.run( @@ -194,6 +216,7 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ input.model ?? null, serializeSkillMetadata(input.skillMetadata), serializePermissionConfig(input.permissionConfig), + serializeMcpServers(input.mcpServers), input.branch, now, now, @@ -219,7 +242,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i const stmt = db.prepare(` UPDATE schedule_jobs SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?, - agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, branch = ?, updated_at = ?, next_run_at = ? + agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, updated_at = ?, next_run_at = ? WHERE repo_id = ? AND id = ? `) @@ -236,6 +259,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i input.model, serializeSkillMetadata(input.skillMetadata), serializePermissionConfig(input.permissionConfig), + serializeMcpServers(input.mcpServers), input.branch, now, input.nextRunAt, diff --git a/backend/src/services/schedule-config.ts b/backend/src/services/schedule-config.ts index 4cb575cc..8faf3245 100644 --- a/backend/src/services/schedule-config.ts +++ b/backend/src/services/schedule-config.ts @@ -2,6 +2,7 @@ import { Cron } from 'croner' import type { CreateScheduleJobRequest, ScheduleJob, + ScheduleMcpServer, ScheduleMode, SchedulePermissionConfig, ScheduleSkillMetadata, @@ -23,6 +24,7 @@ export interface ScheduleJobPersistenceInput { model: string | null skillMetadata: ScheduleSkillMetadata | null | undefined permissionConfig: SchedulePermissionConfig | null + mcpServers: ScheduleMcpServer[] branch: string | null nextRunAt: number | null } @@ -109,6 +111,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ ...base, ...scheduleConfig, permissionConfig: input.permissionConfig ?? null, + mcpServers: input.mcpServers ?? [], nextRunAt: base.enabled ? scheduleConfig.nextRunAt : null, } } @@ -157,6 +160,7 @@ export function buildUpdatedSchedulePersistenceInput( model: input.model === undefined ? existing.model : (input.model?.trim() || null), skillMetadata: input.skillMetadata !== undefined ? input.skillMetadata : existing.skillMetadata, permissionConfig: input.permissionConfig === undefined ? existing.permissionConfig : (input.permissionConfig ?? null), + mcpServers: input.mcpServers ?? existing.mcpServers, branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null), nextRunAt, } diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 2499fecd..85e51e59 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -7,7 +7,7 @@ import { type ScheduleRunTriggerSource, type UpdateScheduleJobRequest, } from '@opencode-manager/shared/types' -import { assistantText, openCodeLocation, sessionIDFromEvent, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode' +import { assistantText, mcpStatusByName, openCodeLocation, sessionIDFromEvent, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode' import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas' import { getRepoById } from '../db/queries' import type { ScheduleJobWithRepo } from '../db/schedules' @@ -587,6 +587,12 @@ export class ScheduleService { return this.abandonCancelledStartup(repoId, jobId, run, job, repo) } + await this.connectMcpServers(runDirectory, job.mcpServers) + + if (abort.signal.aborted) { + return this.abandonCancelledStartup(repoId, jobId, run, job, repo) + } + const sessionTitle = buildSessionTitle(job) let session: { id: string } try { @@ -1265,6 +1271,53 @@ export class ScheduleService { } } + /** + * Makes every MCP server attached to the job available at the run's location before the + * session starts. Schedule-only servers are added to that location, and configured servers + * are connected even when their config disables them; both last until OpenCode restarts. + */ + private async connectMcpServers(directory: string, servers: ScheduleJob['mcpServers']): Promise { + if (servers.length === 0) { + return + } + + const api = this.openCodeClient.api + const location = openCodeLocation(directory) + const readStatuses = async () => mcpStatusByName((await api.mcp.list(location)).data) + + try { + await Promise.all(servers.flatMap((server) => + server.config ? [api.mcp.add({ server: server.name, config: server.config, ...location })] : [], + )) + + const statuses = await readStatuses() + const missing = servers.filter((server) => !statuses[server.name]).map((server) => server.name) + if (missing.length > 0) { + throw new ScheduleServiceError(`MCP servers are not configured for this location: ${missing.join(', ')}`, 400) + } + + await Promise.all(servers + .filter((server) => statuses[server.name]?.status !== 'connected') + .map((server) => api.mcp.connect({ server: server.name, ...location }))) + + const connected = await readStatuses() + const failed = servers.flatMap((server) => { + const status = connected[server.name] + if (status?.status === 'connected') return [] + const reason = status && 'error' in status ? status.error : status?.status ?? 'missing' + return [`${server.name} (${reason})`] + }) + if (failed.length > 0) { + throw new ScheduleServiceError(`MCP servers failed to connect: ${failed.join(', ')}`, 502) + } + } catch (error) { + if (error instanceof ScheduleServiceError) { + throw error + } + throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to connect MCP servers', 502) + } + } + private async resolveSkillAttachments( directory: string, skillMetadata: ScheduleJob['skillMetadata'], diff --git a/backend/test/db/schedules.permission.test.ts b/backend/test/db/schedules.permission.test.ts index 1842c4ad..7f102710 100644 --- a/backend/test/db/schedules.permission.test.ts +++ b/backend/test/db/schedules.permission.test.ts @@ -33,6 +33,7 @@ describe('schedule permission config persistence', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.now() + 3600000, ...overrides, diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index 1d31f8b9..da019847 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -113,6 +113,7 @@ describe('schedule database queries', () => { model: 'openai/gpt-5-mini', skillMetadata: { skillSlugs: ['planning'], notes: 'Optional notes' }, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), }) @@ -132,6 +133,7 @@ describe('schedule database queries', () => { JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }), null, null, + null, expect.any(Number), expect.any(Number), null, @@ -169,6 +171,7 @@ describe('schedule database queries', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: null, }) @@ -187,6 +190,7 @@ describe('schedule database queries', () => { null, null, null, + null, expect.any(Number), null, 42, diff --git a/backend/test/helpers/stub-schedule-api.ts b/backend/test/helpers/stub-schedule-api.ts index 83688de6..829f17ec 100644 --- a/backend/test/helpers/stub-schedule-api.ts +++ b/backend/test/helpers/stub-schedule-api.ts @@ -1,5 +1,6 @@ import { vi } from 'vitest' import type { + McpStatus, OpenCodeApi, SessionMessageAssistant, SessionMessageInfo, @@ -12,6 +13,8 @@ export interface ScheduleApiState { active: Record skills: SkillInfo[] agents: string[] + mcp: Record + mcpConnectResults: Record createError?: Error promptError?: Error interruptError?: Error @@ -32,6 +35,8 @@ export function createStubScheduleApi(state: Partial = {}): Sc active: {}, skills: [], agents: ['build', 'plan'], + mcp: {}, + mcpConnectResults: {}, ...state, } @@ -71,6 +76,18 @@ export function createStubScheduleApi(state: Partial = {}): Sc agent: { list: vi.fn(async () => ({ location: { directory: '' }, data: resolved.agents.map((id) => ({ id, name: id })) })), }, + mcp: { + list: vi.fn(async () => ({ + location: { directory: '' }, + data: Object.entries(resolved.mcp).map(([name, status]) => ({ name, status })), + })), + add: vi.fn(async ({ server }: { server: string }) => { + resolved.mcp[server] = { status: 'pending' } + }), + connect: vi.fn(async ({ server }: { server: string }) => { + resolved.mcp[server] = resolved.mcpConnectResults[server] ?? { status: 'connected' } + }), + }, } return { api: api as unknown as OpenCodeApi, state: resolved } diff --git a/backend/test/services/schedule-config.test.ts b/backend/test/services/schedule-config.test.ts index 38fd1c63..d8000b67 100644 --- a/backend/test/services/schedule-config.test.ts +++ b/backend/test/services/schedule-config.test.ts @@ -34,6 +34,7 @@ describe('schedule-config', () => { model: 'openai/gpt-5', skillMetadata: undefined, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: currentDate + 60 * 60_000, }) @@ -73,6 +74,7 @@ describe('schedule-config', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0), @@ -104,6 +106,7 @@ describe('schedule-config', () => { model: 'openai/gpt-5-mini', skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0), @@ -138,6 +141,7 @@ describe('schedule-config', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: 'feature/foo', nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: null, @@ -168,6 +172,7 @@ describe('schedule-config', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: null, @@ -198,6 +203,7 @@ describe('schedule-config', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: 'feature/foo', nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: null, @@ -228,6 +234,7 @@ describe('schedule-config', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: null, lastRunAt: null, @@ -271,6 +278,7 @@ describe('schedule-config', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: null, lastRunAt: null, diff --git a/backend/test/services/schedules.permission.test.ts b/backend/test/services/schedules.permission.test.ts index 38603934..a41b0883 100644 --- a/backend/test/services/schedules.permission.test.ts +++ b/backend/test/services/schedules.permission.test.ts @@ -121,6 +121,7 @@ const baseJob: ScheduleJob = { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0), diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index a5861f9b..ea1d20ef 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -144,6 +144,7 @@ const job: ScheduleJob = { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0), lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0), @@ -1151,6 +1152,74 @@ describe('ScheduleService', () => { }) }) }) + + describe('MCP servers attached to the job', () => { + const runWithSession: ScheduleRun = { + ...baseRun, + sessionId: 'ses-mcp-1', + sessionTitle: 'Scheduled: Weekly engineering summary', + logText: 'Run started. Waiting for assistant response...', + } + + beforeEach(() => { + mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession) + mocks.getScheduleRunById.mockReturnValue(runWithSession) + mocks.updateScheduleRun.mockReturnValue({ ...baseRun, status: 'failed' }) + }) + + it('adds schedule-only servers and connects configured ones at the run location before the session starts', async () => { + const stub = createStubScheduleApi({ + sessionID: 'ses-mcp-1', + messages: [assistantMessage('Done.', { completed: true })], + mcp: { github: { status: 'disabled' }, linear: { status: 'connected' } }, + }) + const service = makeService(stub.api) + const config = { type: 'remote' as const, url: 'https://mcp.example.com/mcp' } + mocks.getScheduleJobById.mockReturnValue({ + ...job, + mcpServers: [{ name: 'github' }, { name: 'linear' }, { name: 'custom', config }], + }) + + await service.runJob(42, 7, 'manual') + + const location = { location: { directory: repo.fullPath } } + expect(stub.api.mcp.add).toHaveBeenCalledWith({ server: 'custom', config, ...location }) + expect(stub.api.mcp.connect).toHaveBeenCalledWith({ server: 'github', ...location }) + expect(stub.api.mcp.connect).toHaveBeenCalledWith({ server: 'custom', ...location }) + expect(stub.api.mcp.connect).not.toHaveBeenCalledWith({ server: 'linear', ...location }) + const [firstConnect] = vi.mocked(stub.api.mcp.connect).mock.invocationCallOrder + const [sessionCreate] = vi.mocked(stub.api.session.create).mock.invocationCallOrder + expect(firstConnect).toBeLessThan(sessionCreate ?? 0) + }) + + it('fails the run without creating a session when an attached server cannot connect', async () => { + const stub = createStubScheduleApi({ + mcp: { github: { status: 'disabled' } }, + mcpConnectResults: { github: { status: 'needs_auth', error: 'Authorization required' } }, + }) + const service = makeService(stub.api) + mocks.getScheduleJobById.mockReturnValue({ ...job, mcpServers: [{ name: 'github' }] }) + + await expect(service.runJob(42, 7, 'manual')).rejects.toThrow('MCP servers failed to connect: github (Authorization required)') + + expect(stub.api.session.create).not.toHaveBeenCalled() + expect(mocks.updateScheduleRun).toHaveBeenCalledWith(expect.anything(), 42, 7, baseRun.id, expect.objectContaining({ + status: 'failed', + errorText: 'MCP servers failed to connect: github (Authorization required)', + })) + }) + + it('fails the run when a referenced server is not configured', async () => { + const stub = createStubScheduleApi() + const service = makeService(stub.api) + mocks.getScheduleJobById.mockReturnValue({ ...job, mcpServers: [{ name: 'missing' }] }) + + await expect(service.runJob(42, 7, 'manual')).rejects.toThrow('MCP servers are not configured for this location: missing') + + expect(stub.api.mcp.connect).not.toHaveBeenCalled() + expect(stub.api.session.create).not.toHaveBeenCalled() + }) + }) }) describe('ScheduleService startup cancellation', () => { @@ -2081,6 +2150,7 @@ describe('ScheduleRunner', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.now(), lastRunAt: null, @@ -2118,6 +2188,7 @@ describe('ScheduleRunner', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.now(), lastRunAt: null, @@ -2153,6 +2224,7 @@ describe('ScheduleRunner', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.now(), lastRunAt: null, @@ -2187,6 +2259,7 @@ describe('ScheduleRunner', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.now(), lastRunAt: null, @@ -2221,6 +2294,7 @@ describe('ScheduleRunner', () => { model: null, skillMetadata: null, permissionConfig: null, + mcpServers: [], branch: null, nextRunAt: Date.now(), lastRunAt: null, diff --git a/docs/features/schedules.md b/docs/features/schedules.md index cd67894b..a572d4f7 100644 --- a/docs/features/schedules.md +++ b/docs/features/schedules.md @@ -82,6 +82,17 @@ The **Skills** tab in the schedule dialog lets you: When the run starts, the Manager resolves the selected skill slugs against the skills available in the run's location and attaches the matching skills directly to the submitted prompt, making them available to the agent for that run only. Skill slugs that are not available in the location are omitted, and if the available skills cannot be listed the run continues without any skill attachments. +## MCP Servers + +The **MCP** tab attaches MCP servers to a schedule. Each run starts in a fresh worktree, which OpenCode treats as a new location. MCP servers you connected by hand in the repo are not connected there, so any server a run needs has to be attached here. + +- **Configured MCP servers** - Choose from the servers available in the repo, including ones turned off in the OpenCode configuration. Each run connects the selected servers before it starts. +- **Schedule-only MCP servers** - Define a local or remote server that exists only for this schedule. It is added to each run's location and never written to the OpenCode configuration. The definition is stored with the schedule, so use `{env:NAME}` or `{file:path}` placeholders instead of pasting secrets. + +The Manager connects every attached server before it creates the run's session. The run fails with the server name and reason if a server is not configured for the location, cannot connect, or needs OAuth authorization. Runs are unattended and cannot complete an OAuth flow, so authorize OAuth servers in **Settings > MCP Servers** before attaching them. + +Connections are made at the run's directory, so they do not affect other sessions. OpenCode stops a run location's MCP servers once that location has been idle for about an hour. Schedules without a worktree, such as Assistant schedules, run in the repo directory itself. There, a connection stays until OpenCode restarts, just like turning on the server in the repo's MCP dialog. + ## Worktree Isolation Each scheduled run executes in a **throwaway git worktree** — an isolated working copy branched off the repository's base branch. This provides two key guarantees: diff --git a/frontend/src/components/schedules/McpTab.tsx b/frontend/src/components/schedules/McpTab.tsx new file mode 100644 index 00000000..1d0c2011 --- /dev/null +++ b/frontend/src/components/schedules/McpTab.tsx @@ -0,0 +1,120 @@ +import { useState } from 'react' +import type { ScheduleMcpServer } from '@opencode-manager/shared/types' +import type { McpServerConfig, McpStatusMap } from '@opencode-manager/shared/opencode' +import { ScheduleMcpServerConfigSchema } from '@opencode-manager/shared/schemas' +import { showToast } from '@/lib/toast' +import { Button } from '@/components/ui/button' +import { Label } from '@/components/ui/label' +import { TabsContent } from '@/components/ui/tabs' +import { MultiSelect } from '@/components/ui/multi-select' +import { AddMcpServerDialog } from '@/components/settings/AddMcpServerDialog' +import { Loader2, Plus, X } from 'lucide-react' + +type McpTabProps = { + mcpServers: ScheduleMcpServer[] + onMcpServersChange: (value: ScheduleMcpServer[]) => void + availableServers: McpStatusMap + availableServersLoading: boolean +} + +function describeConfig(config: NonNullable): string { + return config.type === 'local' ? config.command.join(' ') : config.url +} + +export function McpTab({ mcpServers, onMcpServersChange, availableServers, availableServersLoading }: McpTabProps) { + const [addDialogOpen, setAddDialogOpen] = useState(false) + + const configuredNames = mcpServers.filter((server) => !server.config).map((server) => server.name) + const customServers = mcpServers.filter((server) => server.config) + const options = [...new Set([...Object.keys(availableServers), ...configuredNames])] + .sort((left, right) => left.localeCompare(right)) + .map((name) => ({ + value: name, + label: name, + description: availableServers[name] ? `Currently ${availableServers[name].status}` : 'Not configured for this repo', + })) + + const handleConfiguredChange = (names: string[]) => { + onMcpServersChange([...names.map((name) => ({ name })), ...customServers.filter((server) => !names.includes(server.name))]) + } + + const handleAddCustom = async (name: string, serverConfig: McpServerConfig) => { + const parsed = ScheduleMcpServerConfigSchema.safeParse(serverConfig) + if (!parsed.success) { + showToast.error(parsed.error.issues[0]?.message ?? 'Invalid MCP server configuration') + throw parsed.error + } + onMcpServersChange([...mcpServers.filter((server) => server.name !== name), { name, config: parsed.data }]) + } + + const handleRemoveCustom = (name: string) => { + onMcpServersChange(mcpServers.filter((server) => server.name !== name)) + } + + return ( + +
+
+ +

+ Selected servers are connected for every run, even when they are disabled in the OpenCode configuration. A run fails if one cannot connect. +

+ {availableServersLoading ? ( +
+ +
+ ) : ( + + )} +
+ +
+
+ + +
+

+ Servers defined here are added only for this schedule's runs and are not saved to the OpenCode configuration. Use {'{env:NAME}'} for secrets. +

+ {customServers.length > 0 && ( +
    + {customServers.map((server) => ( +
  • +
    +

    {server.name}

    +

    {server.config && describeConfig(server.config)}

    +
    + +
  • + ))} +
+ )} +
+
+ + +
+ ) +} diff --git a/frontend/src/components/schedules/ScheduleJobDialog.mcp.test.tsx b/frontend/src/components/schedules/ScheduleJobDialog.mcp.test.tsx new file mode 100644 index 00000000..e5f98a9c --- /dev/null +++ b/frontend/src/components/schedules/ScheduleJobDialog.mcp.test.tsx @@ -0,0 +1,111 @@ +import { describe, it, expect, vi } from 'vitest' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { ScheduleJobDialog } from './ScheduleJobDialog' +import type { ScheduleJob } from '@opencode-manager/shared/types' + +Element.prototype.scrollIntoView = vi.fn() + +const mocks = vi.hoisted(() => ({ + getStatus: vi.fn(), +})) + +vi.mock('@/hooks/usePromptTemplates', () => ({ + usePromptTemplates: () => ({ data: [], isLoading: false }), + useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }), + useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }), + useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }), +})) + +vi.mock('@/api/providers', () => ({ + getProvidersWithModels: () => Promise.resolve([]), +})) + +vi.mock('@/hooks/useOpenCode', () => ({ + useAgents: () => ({ data: [] }), +})) + +vi.mock('@/hooks/useScheduleTarget', () => ({ + useScheduleTarget: () => ({ scheduleTarget: { fullPath: '/workspace/repos/sample' } }), +})) + +vi.mock('@/api/settings', () => ({ + settingsApi: { + listManagedSkills: () => Promise.resolve([]), + }, +})) + +vi.mock('@/api/mcp', () => ({ + mcpApi: { getStatus: mocks.getStatus }, +})) + +vi.mock('@/api/repos', () => ({ + listRepos: () => Promise.resolve([]), + listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }), +})) + +function createWrapper() { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return ({ children }: { children: React.ReactNode }) => ( + {children} + ) +} + +const job: ScheduleJob = { + id: 1, + repoId: 1, + name: 'Test Job', + description: null, + enabled: true, + scheduleMode: 'interval', + intervalMinutes: 60, + cronExpression: null, + timezone: null, + agentSlug: null, + prompt: 'Test prompt', + model: null, + skillMetadata: null, + permissionConfig: null, + mcpServers: [ + { name: 'github' }, + { name: 'old-remote', config: { type: 'remote', url: 'https://old.example.com/mcp' } }, + ], + branch: null, + createdAt: Date.now(), + updatedAt: Date.now(), + lastRunAt: null, + nextRunAt: null, +} + +describe('ScheduleJobDialog — MCP servers', () => { + it('lists servers from the schedule directory and submits configured and schedule-only servers', async () => { + mocks.getStatus.mockResolvedValue({ github: { status: 'disabled' }, linear: { status: 'connected' } }) + const onSubmit = vi.fn() + const user = userEvent.setup() + + render(, { wrapper: createWrapper() }) + + await user.click(screen.getByRole('tab', { name: 'MCP' })) + await waitFor(() => expect(mocks.getStatus).toHaveBeenCalledWith('/workspace/repos/sample')) + expect(await screen.findByText('old-remote')).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Remove old-remote' })) + await user.click(screen.getByRole('button', { name: 'Add server' })) + const addDialog = await screen.findByRole('dialog', { name: 'Add MCP Server' }) + expect(within(addDialog).queryByLabelText('Connect immediately after adding')).not.toBeInTheDocument() + await user.type(within(addDialog).getByLabelText('Server ID'), 'filesystem') + await user.type(within(addDialog).getByLabelText('Command'), 'npx server-filesystem /tmp') + await user.click(within(addDialog).getByRole('button', { name: 'Add MCP Server' })) + + expect(await screen.findByText('filesystem')).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Save changes' })) + + expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ + mcpServers: [ + { name: 'github' }, + { name: 'filesystem', config: { type: 'local', command: ['npx', 'server-filesystem', '/tmp'] } }, + ], + })) + }) +}) diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index 9f11efa9..0e3d5293 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -1,11 +1,12 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { useQuery } from '@tanstack/react-query' -import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob } from '@opencode-manager/shared/types' +import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer } from '@opencode-manager/shared/types' import { useScheduleModels } from '@/hooks/useScheduleModels' import { resolveScheduleModel } from '@/lib/schedules/schedule-model' import { useAgents } from '@/hooks/useOpenCode' import { useScheduleTarget } from '@/hooks/useScheduleTarget' import { settingsApi } from '@/api/settings' +import { mcpApi } from '@/api/mcp' import { listRepos, listBranches } from '@/api/repos' import type { Repo } from '@/api/types' import { Button } from '@/components/ui/button' @@ -29,6 +30,7 @@ import { GeneralTab } from './GeneralTab' import { TimingTab } from './TimingTab' import { PromptTab } from './PromptTab' import { SkillsTab } from './SkillsTab' +import { McpTab } from './McpTab' const EMPTY_TEMPLATES: PromptTemplate[] = [] @@ -65,6 +67,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, const [skillNotes, setSkillNotes] = useState('') const initialSkillSlugsRef = useRef(undefined) const initialSkillNotesRef = useRef(undefined) + const [mcpServers, setMcpServers] = useState([]) const [branch, setBranch] = useState('') const [allowExternalDirectory, setAllowExternalDirectory] = useState(false) const [allowQuestions, setAllowQuestions] = useState(false) @@ -95,6 +98,12 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, staleTime: 5 * 60 * 1000, }) + const { data: mcpStatuses = {}, isLoading: mcpStatusesLoading } = useQuery({ + queryKey: ['mcp-status', scheduleDirectory], + queryFn: () => mcpApi.getStatus(scheduleDirectory), + enabled: open && !!scheduleDirectory, + }) + const { data: repos = [] } = useQuery({ queryKey: ['repos'], queryFn: listRepos, @@ -215,6 +224,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, setSkillNotes(initialSkillNotes) initialSkillSlugsRef.current = initialSkillSlugs initialSkillNotesRef.current = initialSkillNotes + setMcpServers(job?.mcpServers ?? []) setBranch(job?.branch ?? '') setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false) setAllowQuestions(job?.permissionConfig?.allowQuestions ?? false) @@ -264,6 +274,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, model: resolvedModel ?? undefined, prompt: prompt.trim(), branch: branch.trim() || null, + mcpServers, permissionConfig: { allowExternalDirectory, allowQuestions, @@ -317,11 +328,12 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
- + General Timing Prompt Skills + MCP
@@ -393,6 +405,13 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, skills={skills} skillsLoading={skillsLoading} /> + +
diff --git a/frontend/src/components/settings/AddMcpServerDialog.test.tsx b/frontend/src/components/settings/AddMcpServerDialog.test.tsx index 9329bc4a..ff613531 100644 --- a/frontend/src/components/settings/AddMcpServerDialog.test.tsx +++ b/frontend/src/components/settings/AddMcpServerDialog.test.tsx @@ -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 -function renderDialog(onUpdate: (content: Record) => Promise) { +function renderDialog(onSubmit: SubmitHandler, showConnectToggle?: boolean) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) return render( - + , ) } @@ -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) => Promise>().mockResolvedValue(undefined) + it('submits the server ID and a local server config exactly once', async () => { + const onSubmit = vi.fn().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) => Promise>().mockResolvedValue(undefined) + it('submits a remote server with V2 OAuth keys and the Manager callback', async () => { + const onSubmit = vi.fn().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) => Promise>().mockResolvedValue(undefined) + it('submits a remote server with bearer headers and OAuth turned off', async () => { + const onSubmit = vi.fn().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 - 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(), false) + + expect(screen.queryByLabelText('Connect immediately after adding')).not.toBeInTheDocument() }) }) diff --git a/frontend/src/components/settings/AddMcpServerDialog.tsx b/frontend/src/components/settings/AddMcpServerDialog.tsx index f65c2665..a5a9ebee 100644 --- a/frontend/src/components/settings/AddMcpServerDialog.tsx +++ b/frontend/src/components/settings/AddMcpServerDialog.tsx @@ -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) => Promise + onSubmit: (serverId: string, config: McpServerConfig) => Promise + showConnectToggle?: boolean } -interface EnvironmentVariable { +interface KeyValueEntry { key: string value: string } -export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServerDialogProps) { +function toRecord(entries: KeyValueEntry[]): Record | 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 ( +
+
+ + +
+ {entries.map((entry, index) => ( +
+ updateEntry(index, 'key', e.target.value)} + placeholder={keyPlaceholder} + aria-label={`${label} name ${index + 1}`} + className="bg-background border-border font-mono" + /> + updateEntry(index, 'value', e.target.value)} + placeholder={valuePlaceholder} + aria-label={`${label} value ${index + 1}`} + className="bg-background border-border font-mono" + /> + +
+ ))} +

{hint}

+
+ ) +} + +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([]) + const [environment, setEnvironment] = useState([]) + const [headers, setHeaders] = useState([]) 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 | undefined) ?? {} - - await onUpdate({ - ...config.content, - mcp: { - ...mcp, - servers: { ...(mcp.servers as Record | 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' && ( -
-
- - -
- {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 -

-
+ + )} + + {serverType === 'remote' && ( + )}
@@ -327,14 +346,16 @@ export function AddMcpServerDialog({ open, onOpenChange, onUpdate }: AddMcpServe

-
- - -
+ {showConnectToggle && ( +
+ + +
+ )}
diff --git a/frontend/src/components/settings/McpManager.tsx b/frontend/src/components/settings/McpManager.tsx index 9a6c4d82..04b72a7f 100644 --- a/frontend/src/components/settings/McpManager.tsx +++ b/frontend/src/components/settings/McpManager.tsx @@ -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 | undefined) ?? {} + await onUpdate({ + ...latest.content, + mcp: { + ...mcp, + servers: { ...(mcp.servers as Record | undefined), [serverId]: serverConfig }, + }, + }) + } + const isAnyOperationPending = deleteServerMutation.isPending || togglingServerId !== null const handleToggleServer = async (serverId: string) => { @@ -191,7 +204,7 @@ export function McpManager({ config, onUpdate }: McpManagerProps) { diff --git a/shared/src/schemas/schedule.ts b/shared/src/schemas/schedule.ts index 15abdd87..d81fcb97 100644 --- a/shared/src/schemas/schedule.ts +++ b/shared/src/schemas/schedule.ts @@ -15,6 +15,62 @@ export const ScheduleSkillMetadataSchema = z.object({ }) export type ScheduleSkillMetadata = z.infer +const ScheduleMcpTimeoutSchema = z.object({ + startup: z.number().int().positive().optional(), + catalog: z.number().int().positive().optional(), + execution: z.number().int().positive().optional(), +}) + +const ScheduleMcpProtocolSchema = z.enum(['legacy', 'auto', '2026-07-28']) + +export const ScheduleMcpServerConfigSchema = z.discriminatedUnion('type', [ + z.object({ + type: z.literal('local'), + command: z.array(z.string().min(1)).min(1), + cwd: z.string().optional(), + environment: z.record(z.string(), z.string()).optional(), + codemode: z.boolean().optional(), + timeout: ScheduleMcpTimeoutSchema.optional(), + protocol: ScheduleMcpProtocolSchema.optional(), + }), + z.object({ + type: z.literal('remote'), + url: z.string().url(), + headers: z.record(z.string(), z.string()).optional(), + oauth: z.union([ + z.object({ + client_id: z.string().optional(), + client_secret: z.string().optional(), + scope: z.string().optional(), + callback_port: z.number().int().min(1).max(65535).optional(), + redirect_uri: z.string().optional(), + auth_server_metadata_url: z.string().optional(), + }), + z.literal(false), + ]).optional(), + codemode: z.boolean().optional(), + timeout: ScheduleMcpTimeoutSchema.optional(), + protocol: ScheduleMcpProtocolSchema.optional(), + }), +]) +export type ScheduleMcpServerConfig = z.infer + +/** + * An MCP server attached to a schedule. Without `config` it names a server from + * the OpenCode configuration, which is connected for the run even when disabled. + * With `config` it is a schedule-only server added to the run's location. + */ +export const ScheduleMcpServerSchema = z.object({ + name: z.string().trim().min(1).max(100), + config: ScheduleMcpServerConfigSchema.optional(), +}) +export type ScheduleMcpServer = z.infer + +export const ScheduleMcpServersSchema = z.array(ScheduleMcpServerSchema).max(50).refine( + (servers) => new Set(servers.map((server) => server.name)).size === servers.length, + { message: 'MCP server names must be unique' }, +) + /** * Bash commands whose blast radius escapes the throwaway worktree: host-level * commands that damage the machine regardless of cwd, plus force-pushes that can @@ -95,6 +151,7 @@ export const ScheduleJobSchema = z.object({ model: z.string().nullable(), skillMetadata: ScheduleSkillMetadataSchema.nullable(), permissionConfig: SchedulePermissionConfigSchema.nullable(), + mcpServers: ScheduleMcpServersSchema, branch: z.string().nullable(), createdAt: z.number(), updatedAt: z.number(), @@ -132,6 +189,7 @@ const ScheduleJobBaseRequestSchema = z.object({ model: z.string().min(1).max(200).optional(), skillMetadata: ScheduleSkillMetadataSchema.nullable().optional(), permissionConfig: SchedulePermissionConfigSchema.nullable().optional(), + mcpServers: ScheduleMcpServersSchema.optional(), branch: z.string().min(1).max(200).nullable().optional(), }) @@ -161,6 +219,7 @@ export const UpdateScheduleJobRequestSchema = z.object({ model: z.string().min(1).max(200).nullable().optional(), skillMetadata: ScheduleSkillMetadataSchema.nullable().optional(), permissionConfig: SchedulePermissionConfigSchema.nullable().optional(), + mcpServers: ScheduleMcpServersSchema.optional(), branch: z.string().min(1).max(200).nullable().optional(), }) export type UpdateScheduleJobRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 56e1b3c2..4c9e7a31 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -125,6 +125,8 @@ export type { ScheduleRunTriggerSource, ScheduleRunStatus, ScheduleSkillMetadata, + ScheduleMcpServer, + ScheduleMcpServerConfig, ScheduleJob, ScheduleRun, CreateScheduleJobRequest,