Skip to content

Commit 0071aef

Browse files
committed
feat(mcp): add auto-reconnection for MCP servers
- Add restart config (enabled, maxAttempts, delayMs) for local and remote MCPs - Auto-reconnect when transport closes (enabled by default) - Add 'reconnecting' status with attempt tracking - Add 'opencode mcp reconnect [name|all]' command - Show reconnection status in 'opencode mcp list' Addresses anomalyco#1878 and anomalyco#829
1 parent 52b9962 commit 0071aef

4 files changed

Lines changed: 545 additions & 14 deletions

File tree

‎packages/opencode/src/cli/cmd/mcp.ts‎

Lines changed: 120 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -36,19 +36,6 @@ function getAuthStatusText(status: MCP.AuthStatus): string {
3636
}
3737
}
3838

39-
export const McpCommand = cmd({
40-
command: "mcp",
41-
builder: (yargs) =>
42-
yargs
43-
.command(McpAddCommand)
44-
.command(McpListCommand)
45-
.command(McpAuthCommand)
46-
.command(McpLogoutCommand)
47-
.command(McpDebugCommand)
48-
.demandCommand(),
49-
async handler() {},
50-
})
51-
5239
export const McpListCommand = cmd({
5340
command: "list",
5441
aliases: ["ls"],
@@ -98,6 +85,12 @@ export const McpListCommand = cmd({
9885
statusIcon = "✗"
9986
statusText = "needs client registration"
10087
hint = "\n " + status.error
88+
} else if (status.status === "reconnecting") {
89+
statusIcon = "↻"
90+
statusText =
91+
status.attempt && status.maxAttempts
92+
? `reconnecting (${status.attempt}/${status.maxAttempts})`
93+
: "reconnecting"
10194
} else {
10295
statusIcon = "✗"
10396
statusText = "failed"
@@ -652,3 +645,117 @@ export const McpDebugCommand = cmd({
652645
})
653646
},
654647
})
648+
649+
export const McpReconnectCommand = cmd({
650+
command: "reconnect [name]",
651+
describe: "manually reconnect to an MCP server",
652+
builder: (yargs) =>
653+
yargs.positional("name", {
654+
describe: "name of the MCP server (or 'all' to reconnect all failed)",
655+
type: "string",
656+
}),
657+
async handler(args) {
658+
await Instance.provide({
659+
directory: process.cwd(),
660+
async fn() {
661+
UI.empty()
662+
prompts.intro("MCP Reconnect")
663+
664+
const config = await Config.get()
665+
const mcpServers = config.mcp ?? {}
666+
const statuses = await MCP.status()
667+
668+
if (Object.keys(mcpServers).length === 0) {
669+
prompts.log.warn("No MCP servers configured")
670+
prompts.outro("Done")
671+
return
672+
}
673+
674+
if (args.name === "all") {
675+
// Reconnect all failed MCPs
676+
const failed = Object.entries(statuses).filter(([_, s]) => s.status === "failed")
677+
if (failed.length === 0) {
678+
prompts.log.info("No failed MCP servers to reconnect")
679+
prompts.outro("Done")
680+
return
681+
}
682+
683+
for (const [name] of failed) {
684+
const spinner = prompts.spinner()
685+
spinner.start(`Reconnecting ${name}...`)
686+
const result = await MCP.reconnectMcp(name)
687+
if (result.status === "connected") {
688+
spinner.stop(`${name}: reconnected`)
689+
} else if (result.status === "failed" && "error" in result) {
690+
spinner.stop(`${name}: ${result.error}`, 1)
691+
} else {
692+
spinner.stop(`${name}: ${result.status}`, 1)
693+
}
694+
}
695+
prompts.outro("Done")
696+
return
697+
}
698+
699+
// Single server reconnect
700+
let serverName = args.name
701+
if (!serverName) {
702+
const reconnectableStatuses = ["failed", "disabled"] as const
703+
const options = Object.entries(statuses)
704+
.filter(([_, s]) => reconnectableStatuses.includes(s.status as (typeof reconnectableStatuses)[number]))
705+
.map(([name, status]) => ({
706+
label: `${name} (${status.status})`,
707+
value: name,
708+
}))
709+
710+
if (options.length === 0) {
711+
prompts.log.info("No disconnected or failed MCP servers to reconnect")
712+
prompts.outro("Done")
713+
return
714+
}
715+
716+
const selected = await prompts.select({
717+
message: "Select MCP server to reconnect",
718+
options,
719+
})
720+
if (prompts.isCancel(selected)) throw new UI.CancelledError()
721+
serverName = selected
722+
}
723+
724+
if (!mcpServers[serverName]) {
725+
prompts.log.error(`MCP server not found: ${serverName}`)
726+
prompts.outro("Done")
727+
return
728+
}
729+
730+
const spinner = prompts.spinner()
731+
spinner.start(`Reconnecting to ${serverName}...`)
732+
733+
const result = await MCP.reconnectMcp(serverName)
734+
735+
if (result.status === "connected") {
736+
spinner.stop("Reconnected successfully")
737+
} else if (result.status === "failed" && "error" in result) {
738+
spinner.stop(`Failed: ${result.error}`, 1)
739+
} else {
740+
spinner.stop(`Status: ${result.status}`, 1)
741+
}
742+
743+
prompts.outro("Done")
744+
},
745+
})
746+
},
747+
})
748+
749+
export const McpCommand = cmd({
750+
command: "mcp",
751+
builder: (yargs) =>
752+
yargs
753+
.command(McpAddCommand)
754+
.command(McpListCommand)
755+
.command(McpAuthCommand)
756+
.command(McpLogoutCommand)
757+
.command(McpDebugCommand)
758+
.command(McpReconnectCommand)
759+
.demandCommand(),
760+
async handler() {},
761+
})

‎packages/opencode/src/config/config.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,23 @@ export namespace Config {
310310
return plugins
311311
}
312312

313+
export const McpRestart = z
314+
.object({
315+
enabled: z.boolean().optional().describe("Enable auto-reconnect on connection loss. Defaults to true."),
316+
maxAttempts: z.number().int().positive().optional().describe("Maximum reconnection attempts. Defaults to 3."),
317+
delayMs: z
318+
.number()
319+
.int()
320+
.positive()
321+
.optional()
322+
.describe("Delay between reconnection attempts in milliseconds. Defaults to 1000."),
323+
})
324+
.strict()
325+
.meta({
326+
ref: "McpRestartConfig",
327+
})
328+
export type McpRestart = z.infer<typeof McpRestart>
329+
313330
export const McpLocal = z
314331
.object({
315332
type: z.literal("local").describe("Type of MCP server connection"),
@@ -327,6 +344,7 @@ export namespace Config {
327344
.describe(
328345
"Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.",
329346
),
347+
restart: McpRestart.optional().describe("Auto-reconnection configuration. Enabled by default."),
330348
})
331349
.strict()
332350
.meta({
@@ -368,6 +386,7 @@ export namespace Config {
368386
.describe(
369387
"Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.",
370388
),
389+
restart: McpRestart.optional().describe("Auto-reconnection configuration. Enabled by default."),
371390
})
372391
.strict()
373392
.meta({

0 commit comments

Comments
 (0)