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
@@ -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
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
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'],
|
||||
|
||||
Reference in new issue
Block a user