Skip to content

Commit e7659e1

Browse files
Bewinxedclaude
andcommitted
An OpenCode session refuses work only when CawCo's own MCP server does not connect
The gate (opencode-client.ts waitForMcp) refused a session when any MCP server failed or needed sign-in, so a fleet OAuth server the hub is not signed in to (ElevenLabs, answering 503) stopped every OpenCode session on the fleet. Now: - A failed or needs_auth server is settled: not waited for, not refused. - A pending server is still waited for up to MCP_CONNECT_TIMEOUT_MS (a prompt sent while it connects loses its tools for the turn, anomalyco/opencode#54794, #51812); one still pending then is settled. - CawCo's server ("cawco") must reach connected: failed, needs_auth or disabled refuses at once, not connected at the deadline refuses then. - Every other server that did not connect is said once per session start (core MCP_NOT_CONNECTED, a ui.system_note): live, and as resume:false synthetic input under the same id, so the model is told and a transcript read gives the same line back. Also fixes OpenCode's paged history read: 2.0.28 refuses a page asked with both cursor and order ("Cursor cannot be combined with order"), and names a next cursor whenever a page holds a message, so every read of a non-empty session failed. The order now goes on the first page only. Proved by scripts/probe-opencode-mcp-gate.ts on a scratch fleet (OpenCode 2.0.28): a 503 fleet server noted and the turn run, a slow server's tool in the first turn, and a session refused when CawCo's MCP answers 503. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 08b1ac6 commit e7659e1

8 files changed

Lines changed: 592 additions & 50 deletions

File tree

‎packages/agent/src/harnesses/opencode-client.ts‎

Lines changed: 64 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
* Promise client (pinned with the CLI at 2.0.28), its HTTP Basic
44
* authentication, how its errors read, and the two checks a server must pass
55
* before a session runs in a location there: CawCo's plugin loaded (the gate
6-
* fails closed), and every configured MCP server connected.
6+
* fails closed), and CawCo's MCP server connected with every other server
7+
* settled.
78
*
89
* 2.0.28's auth: user `opencode`, the password the server was launched with
910
* (`OPENCODE_SERVER_PASSWORD`); an unauthenticated call answers 401
@@ -187,52 +188,85 @@ export const assertPluginLoaded = async (
187188
*/
188189
export const MCP_CONNECT_TIMEOUT_MS = 60_000;
189190

191+
/** CawCo's own MCP server, as every server's launch config names it (`mcp.servers.cawco`). */
192+
export const CAWCO_MCP_SERVER = "cawco";
193+
194+
/** An MCP server that had not connected when a location took its first prompt, and why. */
195+
export interface McpNotConnected {
196+
name: string;
197+
why: string;
198+
}
199+
190200
/**
191-
* Waits until every MCP server the location has configured is `connected`.
192-
* A prompt sent before then loses the tools of a server still connecting:
193-
* Code Mode's catalog drops them for the turn ("The following tools are no
194-
* longer available…", anomalyco/opencode#54794 and #51812, both open at
195-
* 2.0.28). A server that fails, needs auth, or is still pending at the
196-
* deadline ends the wait with its name and why. A disabled server is not
197-
* waited for.
201+
* Waits until none of the location's MCP servers is still connecting, and
202+
* answers the ones that did not connect. A prompt sent while a server is
203+
* connecting loses its tools: Code Mode's catalog drops them for the turn
204+
* ("The following tools are no longer available…", anomalyco/opencode#54794
205+
* and #51812, both open at 2.0.28). So a `pending` server is waited for, up
206+
* to the deadline.
207+
*
208+
* A server that `failed` or `needs_auth` is settled: it is not waited for,
209+
* and the session runs without its tools, as a Claude session does; so is
210+
* one still `pending` at the deadline. Each is answered with why, for the
211+
* session to say. A `disabled` server is nobody's concern.
212+
*
213+
* CawCo's own server is the one that must connect: the session's hub tools
214+
* come through it. One that failed, needs sign-in or is disabled refuses at
215+
* once, and one not connected at the deadline refuses then, as Claude's
216+
* harness refuses a launch whose CawCo slot never connects (claude.ts
217+
* `#connectedCawcoSnapshot`).
198218
*/
199219
export const waitForMcp = async (
200220
client: OpencodeClient,
201221
directory: string,
202222
signal: AbortSignal,
203223
timeoutMs = MCP_CONNECT_TIMEOUT_MS
204-
): Promise<void> => {
224+
): Promise<McpNotConnected[]> => {
205225
const deadline = Date.now() + timeoutMs;
206226
for (;;) {
207227
signal.throwIfAborted();
208228
// biome-ignore lint/performance/noAwaitInLoops: each read decides whether the next is needed
209229
const listed = await client.mcp.list(at(directory), {
210230
signal: oneRead(signal),
211231
});
212-
const waiting = listed.data.filter(
213-
(server) =>
214-
server.status.status !== "connected" &&
215-
server.status.status !== "disabled"
216-
);
217-
if (waiting.length === 0) {
218-
return;
232+
const cawco = listed.data.find(
233+
(server) => server.name === CAWCO_MCP_SERVER
234+
)?.status;
235+
if (
236+
cawco?.status === "failed" ||
237+
cawco?.status === "needs_auth" ||
238+
cawco?.status === "disabled"
239+
) {
240+
throw new Error(
241+
`CawCo's MCP server at ${directory} is not connected (${cawco.status}${"error" in cawco ? `: ${cawco.error}` : ""}).`
242+
);
219243
}
220-
const broken = waiting.find(
221-
(server) =>
222-
server.status.status === "failed" ||
223-
server.status.status === "needs_auth"
244+
const over = Date.now() >= deadline;
245+
const connecting = listed.data.some(
246+
(server) => server.status.status === "pending"
224247
);
225-
if (broken || Date.now() >= deadline) {
226-
const named = (broken ? [broken] : waiting)
227-
.map((server) => {
228-
const status = server.status as { status: string; error?: string };
229-
return `${server.name} (${status.status}${status.error ? `: ${status.error}` : ""})`;
230-
})
231-
.join(", ");
248+
if (cawco?.status === "connected" && (over || !connecting)) {
249+
return listed.data.flatMap((server): McpNotConnected[] => {
250+
const { status } = server;
251+
switch (status.status) {
252+
case "failed":
253+
case "needs_auth":
254+
return [{ name: server.name, why: status.error }];
255+
case "pending":
256+
return [
257+
{
258+
name: server.name,
259+
why: `still connecting after ${timeoutMs / 1000} s`,
260+
},
261+
];
262+
default:
263+
return [];
264+
}
265+
});
266+
}
267+
if (over) {
232268
throw new Error(
233-
broken
234-
? `OpenCode's MCP server ${named} at ${directory} did not connect.`
235-
: `OpenCode's MCP servers ${named} at ${directory} were still not connected after ${timeoutMs / 1000} s.`
269+
`CawCo's MCP server at ${directory} did not connect within ${timeoutMs / 1000} seconds.`
236270
);
237271
}
238272
await Bun.sleep(250);

‎packages/agent/src/harnesses/opencode-session.ts‎

Lines changed: 60 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,10 @@ import {
5454
CONTROL_SUPPORTED_MODELS,
5555
EFFORT_READ,
5656
INSTALL_SESSION_CREDENTIAL,
57+
MCP_NOT_CONNECTED,
5758
MESSAGES_READ,
5859
MESSAGES_STORED,
60+
mcpNotConnectedLine,
5961
PROVIDER_LIMIT,
6062
PROVIDER_RETRY,
6163
REPEATED_FAILURE,
@@ -79,8 +81,10 @@ import { holdRestart, withRestartHold } from "../restart";
7981
import { acknowledgeSessionCredential } from "../session-identity";
8082
import {
8183
at,
84+
CAWCO_MCP_SERVER,
8285
errorTag,
8386
errorText,
87+
type McpNotConnected,
8488
type OpencodeClient,
8589
} from "./opencode-client";
8690
import {
@@ -300,7 +304,7 @@ const leadMcpFence = async (
300304
signal: AbortSignal.timeout(65_000),
301305
});
302306
return listed.data
303-
.filter((server) => server.name !== "cawco")
307+
.filter((server) => server.name !== CAWCO_MCP_SERVER)
304308
.map((server) => deny(`${server.name.replace(MCP_NAME_UNSAFE, "_")}_*`));
305309
};
306310

@@ -566,11 +570,13 @@ export interface OpencodeSessionOptions {
566570
/** Whether the server says this session is running a turn now. */
567571
readActivity: () => Promise<boolean>;
568572
/**
569-
* The location's readiness: CawCo's plugin loaded and every MCP server
570-
* connected. No prompt or command reaches the server before it; a location
571-
* that never gets there fails the session with why.
573+
* The location's readiness: CawCo's plugin loaded, CawCo's MCP server
574+
* connected and every other server settled. No prompt or command reaches
575+
* the server before it; a location that never gets there fails the session
576+
* with why. It answers the servers that did not connect, which the session
577+
* says once, at its first dispatch.
572578
*/
573-
ready: Promise<void>;
579+
ready: Promise<McpNotConnected[]>;
574580
registerChild: (childId: string, callID: string) => void;
575581
sessionId: string;
576582
workflowStepId?: string;
@@ -603,6 +609,8 @@ export class OpencodeSession implements HarnessSession {
603609
readonly #prepareDispatch: () => Promise<void>;
604610
readonly #liveSessions: () => ReadonlySet<string>;
605611
readonly #lifetime = new AbortController();
612+
/** The MCP servers that did not connect, by name, said for this start of the session. */
613+
readonly #mcpSaid = new Set<string>();
606614

607615
#lastTokens = EMPTY_TOKENS;
608616
/** The tokens the session's last answered request sent: its context then. */
@@ -691,8 +699,10 @@ export class OpencodeSession implements HarnessSession {
691699
this.#readActivity = options.readActivity;
692700
this.#liveSessions = options.liveSessions;
693701
// No prompt or command reaches the server before its location is ready:
694-
// a location whose plugin is missing or whose MCP servers never connect
695-
// fails the session with why, and every send it was handed fails with it.
702+
// a location whose plugin is missing or whose CawCo MCP server does not
703+
// connect fails the session with why, and every send it was handed fails
704+
// with it. Any other server that did not connect is said once, and the
705+
// session runs without it.
696706
// Awaited at dispatch, never at publication (bb65de38: publishing must
697707
// not wait on cold MCP servers).
698708
const admitted = options.ready.catch((error: unknown) => {
@@ -706,8 +716,9 @@ export class OpencodeSession implements HarnessSession {
706716
// Its rejection is a send's, at dispatch; unawaited it is not unhandled.
707717
admitted.catch(() => undefined);
708718
this.#prepareDispatch = async () => {
709-
await admitted;
719+
const unconnected = await admitted;
710720
await options.prepareDispatch();
721+
await this.#sayUnconnected(unconnected);
711722
await this.#applySettings();
712723
await this.#syncInstructions();
713724
};
@@ -2735,6 +2746,47 @@ export class OpencodeSession implements HarnessSession {
27352746
});
27362747
}
27372748

2749+
/**
2750+
* Each MCP server that did not connect when the session started, said once
2751+
* per start: drawn on the live stream now, and written into the session as
2752+
* synthetic input that starts no turn (`resume: false`) under the same id,
2753+
* which {@link toTranscript} reads back as the same line and which reaches
2754+
* the model with its next turn, so it knows those tools are not there.
2755+
*/
2756+
async #sayUnconnected(unconnected: McpNotConnected[]): Promise<void> {
2757+
const sessionID = this.#opencodeSessionId();
2758+
for (const server of unconnected) {
2759+
if (this.#mcpSaid.has(server.name)) {
2760+
continue;
2761+
}
2762+
const id = messageId();
2763+
const line = mcpNotConnectedLine(server.name, server.why);
2764+
// biome-ignore lint/performance/noAwaitInLoops: one note per server, in the order the server listed them
2765+
await this.#client.session.synthetic(
2766+
{
2767+
sessionID,
2768+
id,
2769+
text: line,
2770+
description: `${server.name} didn't connect`,
2771+
metadata: { cawco: MCP_NOT_CONNECTED, server: server.name, line },
2772+
resume: false,
2773+
},
2774+
{ signal: AbortSignal.timeout(RECOVERY_TIMEOUT_MS) }
2775+
);
2776+
console.warn(`[opencode] ${this.instanceId}: ${line}`);
2777+
this.#ctx.frame({
2778+
type: "system",
2779+
subtype: MCP_NOT_CONNECTED,
2780+
uuid: id,
2781+
session_id: sessionID,
2782+
timestamp: new Date().toISOString(),
2783+
mcp_server: server.name,
2784+
content: line,
2785+
});
2786+
this.#mcpSaid.add(server.name);
2787+
}
2788+
}
2789+
27382790
async stop(): Promise<void> {
27392791
this.#lifetime.abort();
27402792
this.#onRelease();

‎packages/agent/src/harnesses/opencode-transcript.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ import type {
1919
UserQuestion,
2020
UserQuestionResult,
2121
} from "@cawco/core";
22-
import { ASK_USER_QUESTION, REPEATED_FAILURE } from "@cawco/core";
22+
import {
23+
ASK_USER_QUESTION,
24+
MCP_NOT_CONNECTED,
25+
REPEATED_FAILURE,
26+
} from "@cawco/core";
2327
import type {
2428
SessionInboxInfo,
2529
SessionMessageAssistant,
@@ -462,11 +466,34 @@ export function toTranscript(
462466
}
463467
case "synthetic": {
464468
// CawCo's own stop of a session failing the same way again and again
465-
// (`noteStopped`), read back as the line the live stream drew. Any
469+
// (`noteStopped`), and its word that an MCP server did not connect
470+
// (`sayUnconnected`), read back as the lines the live stream drew. Any
466471
// other synthetic input is OpenCode's or a plugin's, not anyone's words.
467472
const meta = message.metadata as
468-
| { cawco?: unknown; words?: unknown }
473+
| {
474+
cawco?: unknown;
475+
words?: unknown;
476+
server?: unknown;
477+
line?: unknown;
478+
}
469479
| undefined;
480+
if (meta?.cawco === MCP_NOT_CONNECTED) {
481+
entries.push(
482+
entry(sessionKey, timestamp, {
483+
type: "system",
484+
uuid: message.id,
485+
message: {
486+
type: "system",
487+
subtype: MCP_NOT_CONNECTED,
488+
uuid: message.id,
489+
session_id: sessionKey,
490+
timestamp,
491+
mcp_server: String(meta.server),
492+
content: String(meta.line),
493+
},
494+
})
495+
);
496+
}
470497
if (meta?.cawco === REPEATED_FAILURE) {
471498
entries.push(
472499
entry(sessionKey, timestamp, {

‎packages/agent/src/harnesses/opencode.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ import {
114114
at,
115115
errorText,
116116
MCP_CONNECT_TIMEOUT_MS,
117+
type McpNotConnected,
117118
notFound,
118119
OPENCODE_BIN,
119120
OPENCODE_VERSION,
@@ -977,7 +978,12 @@ const allSessions = async (
977978
return sessions;
978979
};
979980

980-
/** Every projected message of a session, oldest first. */
981+
/**
982+
* Every projected message of a session, oldest first. The order goes on the
983+
* first page only: 2.0.28's cursor carries it, and a page asked with both
984+
* answers 400 "Cursor cannot be combined with order". A page names a next
985+
* cursor whenever it holds a message, so the read ends on an empty page.
986+
*/
981987
const allMessages = async (
982988
client: OpencodeClient,
983989
sessionID: string
@@ -989,9 +995,8 @@ const allMessages = async (
989995
const page = await client.message.list(
990996
{
991997
sessionID,
992-
order: "asc",
993998
limit: 200,
994-
...(cursor ? { cursor } : {}),
999+
...(cursor ? { cursor } : { order: "asc" as const }),
9951000
},
9961001
{ signal: AbortSignal.timeout(RECOVERY_TIMEOUT_MS) }
9971002
);
@@ -3770,15 +3775,17 @@ export class OpencodeHarness implements Harness {
37703775
...(spec.denyTools ?? []),
37713776
]);
37723777
// The location's readiness, awaited at the first dispatch, never at
3773-
// publication: CawCo's plugin loaded there (the gate, failing closed) and
3774-
// every MCP server connected (a prompt before then loses the tools of a
3775-
// server still connecting, anomalyco/opencode#54794).
3776-
const ready = existing?.running
3777-
? Promise.resolve()
3778+
// publication: CawCo's plugin loaded there (the gate, failing closed),
3779+
// CawCo's MCP server connected, and no other server still connecting (a
3780+
// prompt before then loses the tools of a server still connecting,
3781+
// anomalyco/opencode#54794). It answers the servers that did not connect,
3782+
// which the session says once.
3783+
const ready: Promise<McpNotConnected[]> = existing?.running
3784+
? Promise.resolve([])
37783785
: (async () => {
37793786
// Each wait has its own deadline, which says what it waited for.
37803787
await assertPluginLoaded(client, ctx.cwd, this.#lifetimeSignal());
3781-
await waitForMcp(client, ctx.cwd, this.#lifetimeSignal());
3788+
return await waitForMcp(client, ctx.cwd, this.#lifetimeSignal());
37823789
})();
37833790
ready.catch(() => undefined);
37843791
let sessionId: string;

‎packages/core/src/harness.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,21 @@ export const MESSAGES_READ = "read";
854854
*/
855855
export const PROVIDER_RETRY = "provider_retry";
856856

857+
/**
858+
* The `system` subtype saying one of the session's MCP servers did not
859+
* connect when it started, so the session runs without that server's tools:
860+
* the server's name in `mcp_server`, the line ({@link mcpNotConnectedLine})
861+
* in `content`. CawCo's own server not connecting refuses the session
862+
* instead; this is every other server's.
863+
*/
864+
export const MCP_NOT_CONNECTED = "mcp_not_connected";
865+
866+
const FINAL_STOP = /\.$/;
867+
868+
/** What a session's transcript and its model are told of a server that did not connect ({@link MCP_NOT_CONNECTED}). */
869+
export const mcpNotConnectedLine = (name: string, why: string): string =>
870+
`${name} didn't connect: ${why.trim().replace(FINAL_STOP, "")}. This session runs without its tools.`;
871+
857872
/**
858873
* The `system` subtype saying the agent stopped a session that failed the same
859874
* way {@link REPEATED_FAILURE_LIMIT} times in a row with no send in between —
@@ -1078,6 +1093,8 @@ export interface NeutralSystemMessage {
10781093
// transcript draws (its output is otherwise startup noise, and never stored)
10791094
hook_name?: string;
10801095
last_tool_name?: string;
1096+
// mcp_not_connected ({@link MCP_NOT_CONNECTED}) — the server that did not connect
1097+
mcp_server?: string;
10811098
mcp_servers?: { name: string; status: string }[];
10821099
// stream_so_far ({@link STREAM_SO_FAR}) — the id the harness stores the
10831100
// message being written under, when it stores it while it is written

0 commit comments

Comments
 (0)