Public: anyone can read this; the crew can change it.
Talk on a hosted forge has its tools: MCP initialize always names a version (#16409) #16414
Check · Review · Land · Live done — Landed and live in production.
talk/cells-fixes → main 0 commits
7 files
changed +241
−15
src/crew/agent_runner.ts +5
| @@ -73,6 +73,11 @@ export interface AgentRun { | ||
| 73 | 73 | readonly mcp?: { readonly config: string; readonly allow: readonly string[] } | undefined; |
| 74 | 74 | /** The session id, once the init record names it (a restart resumes it). */ |
| 75 | 75 | readonly onSession?: ((sessionId: string) => void) | undefined; |
| 76 | /** | |
| 77 | * The servers named in `mcp.config` that the agent says, as its session starts, it could not | |
| 78 | * connect to. The session goes on without their tools; the caller decides whether that is a turn. | |
| 79 | */ | |
| 80 | readonly onToolsMissing?: ((servers: readonly string[]) => void) | undefined; | |
| 76 | 81 | /** What the agent said or called, as each assistant message arrives. */ |
| 77 | 82 | readonly onSaid?: ((said: { readonly kind: "text" | "tool" | "thinking"; readonly text: string; readonly id?: string }) => void) | undefined; |
| 78 | 83 | /** |
src/crew/claude.ts +21 −1
| @@ -212,6 +212,20 @@ export function answeredOf(message: unknown, calling: Map<string, string>): Delt | ||
| 212 | 212 | return ended; |
| 213 | 213 | } |
| 214 | 214 | |
| 215 | /** | |
| 216 | * The MCP servers an init record says did not connect (`failed`, `needs-auth`). One still | |
| 217 | * `pending` is not counted: it may yet connect. | |
| 218 | */ | |
| 219 | export function unreachedServers(value: unknown): string[] { | |
| 220 | const names: string[] = []; | |
| 221 | for (const s of Array.isArray(value) ? value : []) { | |
| 222 | const r = recordOf(s); | |
| 223 | if ((r["status"] === "failed" || r["status"] === "needs-auth") && typeof r["name"] === "string") | |
| 224 | names.push(r["name"].slice(0, 64)); | |
| 225 | } | |
| 226 | return names; | |
| 227 | } | |
| 228 | ||
| 215 | 229 | /** Run Claude Code to completion. Never throws; every ending is an outcome. */ |
| 216 | 230 | export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { |
| 217 | 231 | return withLimit(await runClaudeRaw(input), new Date()); |
| @@ -404,8 +418,14 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 404 | 418 | return; |
| 405 | 419 | } |
| 406 | 420 | if (type === "system") { |
| 407 | if (e["subtype"] === "init") | |
| 421 | if (e["subtype"] === "init") { | |
| 408 | 422 | input.log(`session ${sessionId} (${String(e["model"] ?? "")})`); |
| 423 | const missing = unreachedServers(e["mcp_servers"]); | |
| 424 | if (missing.length > 0) { | |
| 425 | input.log(`MCP not connected: ${missing.join(", ")}`); | |
| 426 | input.onToolsMissing?.(missing); | |
| 427 | } | |
| 428 | } | |
| 409 | 429 | return; |
| 410 | 430 | } |
| 411 | 431 | if (type === "assistant") { |
src/crew/conversation.ts +19 −4
| @@ -156,6 +156,11 @@ const RESUME_PROMPT = | ||
| 156 | 156 | |
| 157 | 157 | /** The line a stopped turn leaves after what it had said. */ |
| 158 | 158 | export const STOPPED_LINE = "Stopped."; |
| 159 | /** | |
| 160 | * What a turn says when the forge's own tools did not connect to it: the model would otherwise | |
| 161 | * answer that it has none, and blame the conversation. | |
| 162 | */ | |
| 163 | export const NO_TOOLS_LINE = "This turn could not reach the forge's tools, so it stopped before answering; the forge has logged why. Try again in a moment."; | |
| 159 | 164 | |
| 160 | 165 | /** Stops for the turns running, by conversation id. */ |
| 161 | 166 | const stoppers = new Map<string, { runId: string; userId: string; stop: () => void }>(); |
| @@ -631,7 +636,9 @@ function begin( | ||
| 631 | 636 | live.set(conversation.id, runId); |
| 632 | 637 | const stopper = new AbortController(); |
| 633 | 638 | stoppers.set(conversation.id, { runId, userId, stop: () => stopper.abort() }); |
| 634 | const signal = AbortSignal.any([options.signal, stopper.signal]); | |
| 639 | // Aborted when the agent says the forge's MCP server did not connect: no answer without tools. | |
| 640 | const toolless = new AbortController(); | |
| 641 | const signal = AbortSignal.any([options.signal, stopper.signal, toolless.signal]); | |
| 635 | 642 | const put = (role: "agent" | "tool", text: string): void => { |
| 636 | 643 | // Kept with every held value and credential shape taken out: a turn that says its credential |
| 637 | 644 | // leaves `[redacted]`, as the live block showed it. |
| @@ -700,6 +707,13 @@ function begin( | ||
| 700 | 707 | onSteer: (send) => { |
| 701 | 708 | unlisten = listenForSteer(runId, send); |
| 702 | 709 | }, |
| 710 | onToolsMissing: (servers) => { | |
| 711 | if (toolless.signal.aborted) return; | |
| 712 | const url = `${options.localUrl.replace(/\/+$/, "")}/mcp`; | |
| 713 | app.log.warn("talk turn stopped: its MCP server did not connect", { conversation: conversation.id, run: runId, servers: servers.join(","), url }); | |
| 714 | appendRunLog(app.config.dataDir, runId, `stopped: the forge's MCP server at ${url} did not connect`); | |
| 715 | toolless.abort(); | |
| 716 | }, | |
| 703 | 717 | onSession: (sessionId) => { |
| 704 | 718 | named = true; |
| 705 | 719 | app.db.query("UPDATE conversation_run SET session_id = ?2 WHERE id = ?1").run(runId, sessionId); |
| @@ -783,7 +797,8 @@ function begin( | ||
| 783 | 797 | for (const turn of streamed) if (raw(turn.text)) removeTurn(app.db, userId, conversation.id, turn.id); |
| 784 | 798 | appendTurn(app.db, userId, conversation.id, { role: "agent", text, failed: true }); |
| 785 | 799 | }; |
| 786 | if (outcome === undefined) couldNot(failureLine("error"), () => false); | |
| 800 | if (toolless.signal.aborted) couldNot(NO_TOOLS_LINE, () => true); | |
| 801 | else if (outcome === undefined) couldNot(failureLine("error"), () => false); | |
| 787 | 802 | else if (isRateLimited(outcome)) { |
| 788 | 803 | const first = outcome.result.split("\n").find((l) => l.trim() !== "")?.trim() ?? ""; |
| 789 | 804 | couldNot(limitLine(app, picked, outcome.limit), (said) => said === outcome!.result || (first !== "" && said.includes(first))); |
| @@ -792,12 +807,12 @@ function begin( | ||
| 792 | 807 | else if (answer.trim() === "" && lastText === "") couldNot(failureLine("error"), () => false); |
| 793 | 808 | // Where the line went (#13942): each issue a tell opened, on every outcome; the plain word |
| 794 | 809 | // that none was only when the turn answered. |
| 795 | for (const text of filedTurns(app.db, via, prompt, outcome?.ok === true)) put("tool", text); | |
| 810 | for (const text of filedTurns(app.db, via, prompt, outcome?.ok === true && !toolless.signal.aborted)) put("tool", text); | |
| 796 | 811 | app.db |
| 797 | 812 | .query( |
| 798 | 813 | "UPDATE conversation_run SET state = ?2, tokens_in = ?3, tokens_out = ?4, cost_usd = ?5, finished_at = ?6, context_tokens = ?7, context_window = ?8, reported_usd = ?9 WHERE id = ?1", |
| 799 | 814 | ) |
| 800 | .run(runId, outcome?.ok ? "ok" : "failed", outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0, reported); | |
| 815 | .run(runId, outcome?.ok === true && !toolless.signal.aborted ? "ok" : "failed", outcome?.tokensIn ?? 0, outcome?.tokensOut ?? 0, cost, new Date().toISOString(), outcome?.contextTokens ?? 0, outcome?.contextWindow ?? 0, reported); | |
| 801 | 816 | // Against the account's lifetime budget, like a run's cost (`subscription.spent_usd`). |
| 802 | 817 | app.db.query("UPDATE subscription SET spent_usd = spent_usd + ?2 WHERE id = ?1").run(subscriptionId, cost); |
| 803 | 818 | } finally { |
src/http/mcp.ts +7 −6
| @@ -23,7 +23,7 @@ import { getRepo } from "../core/repos.ts"; | ||
| 23 | 23 | import { scopeAllows } from "../core/tokens.ts"; |
| 24 | 24 | import type { User } from "../core/users.ts"; |
| 25 | 25 | import type { Ctx, Handler } from "./context.ts"; |
| 26 | import { announcedVersion } from "../kernel/version.ts"; | |
| 26 | import { announcedOr } from "../kernel/version.ts"; | |
| 27 | 27 | import { bearerChallenge } from "./oauth.ts"; |
| 28 | 28 | import { BodyTooLarge, json } from "./respond.ts"; |
| 29 | 29 | import { bodyCapFor, readBounded } from "./limits.ts"; |
| @@ -115,11 +115,12 @@ export const TOOLS_PAGE_BYTES = 20_000; | ||
| 115 | 115 | export const roleHere = (ctx: Ctx, user: User): Role => |
| 116 | 116 | user.kind === "user" ? roleOf(ctx.app.db, user) : "member"; |
| 117 | 117 | |
| 118 | /** Who answers: the forge, at the version its build stamped. */ | |
| 119 | const server = () => { | |
| 120 | const version = announcedVersion(); | |
| 121 | return version === null ? { name: "forge" } : { name: "forge", version }; | |
| 122 | }; | |
| 118 | /** | |
| 119 | * Who answers: the forge, at the version its build stamped. MCP's `Implementation` requires a | |
| 120 | * version, and a client that checks the schema refuses an `initialize` without one: a cell runs | |
| 121 | * unstamped, and its Talk had no tools at all. So an unstamped build says `unreleased` here. | |
| 122 | */ | |
| 123 | const server = () => ({ name: "forge", version: announcedOr() }); | |
| 123 | 124 | |
| 124 | 125 | /** The role a token acts as, and for a guest what is listed and how to reach the rest. */ |
| 125 | 126 | const roleNote = (role: Role): string => |
test/mcp-version.test.ts +2 −2
| @@ -52,7 +52,7 @@ test("a stamped build names its release in all three", async () => { | ||
| 52 | 52 | expect(a.raw).not.toContain('"dev"'); |
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | test("an unstamped build answers the short commit, and omits version when there is none", async () => { | |
| 55 | test("an unstamped build answers the short commit; with none, initialize says unreleased and the door omits it", async () => { | |
| 56 | 56 | delete process.env["FORGE_VERSION"]; |
| 57 | 57 | process.env["FORGE_COMMIT"] = "abcdef0123456789"; |
| 58 | 58 | const a = await answers(); |
| @@ -64,7 +64,7 @@ test("an unstamped build answers the short commit, and omits version when there | ||
| 64 | 64 | delete process.env["FORGE_COMMIT"]; |
| 65 | 65 | delete process.env["FORGE_APP_COMMIT"]; |
| 66 | 66 | const b = await answers(); |
| 67 | expect(b.serverInfo.version).toBeUndefined(); | |
| 67 | expect(b.serverInfo.version).toBe("unreleased"); | |
| 68 | 68 | expect(b.door.version).toBeUndefined(); |
| 69 | 69 | expect(b.spec.info.version).toBe("unreleased"); |
| 70 | 70 | expect(b.raw).not.toContain('"dev"'); |
test/talk-cell-tools.test.ts added +184
| @@ -0,0 +1,184 @@ | ||
| 1 | /** | |
| 2 | * Talk on a cell had no tools (#16409): a cell runs the forge unstamped, its MCP `initialize` | |
| 3 | * answered `serverInfo` with no `version`, and Claude Code's schema check refused the server, so | |
| 4 | * the turn ran with no tools and the model said so. The answer now always names a version; and a | |
| 5 | * turn whose agent says the forge's server did not connect stops with one plain sentence, logged, | |
| 6 | * instead of answering without tools. | |
| 7 | */ | |
| 8 | ||
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { chmodSync, writeFileSync } from "node:fs"; | |
| 11 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { listTurns, openConversation } from "../src/core/conversations.ts"; | |
| 16 | import { createUser, type User } from "../src/core/users.ts"; | |
| 17 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 18 | import { unreachedServers } from "../src/crew/claude.ts"; | |
| 19 | import { NO_TOOLS_LINE, say } from "../src/crew/conversation.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { readRunLog } from "../src/runs/log.ts"; | |
| 22 | ||
| 23 | const STAMPS = [ | |
| 24 | "FORGE_VERSION", | |
| 25 | "FORGE_COMMIT", | |
| 26 | "FORGE_APP_COMMIT", | |
| 27 | "FORGE_APP_RELEASE", | |
| 28 | ] as const; | |
| 29 | const saved = Object.fromEntries(STAMPS.map((k) => [k, process.env[k]])); | |
| 30 | ||
| 31 | let dir: string; | |
| 32 | let app: App; | |
| 33 | let servers: Servers; | |
| 34 | let alice: User; | |
| 35 | ||
| 36 | beforeAll(async () => { | |
| 37 | // A cell: the forge's code with no build stamp in its environment. | |
| 38 | for (const k of STAMPS) delete process.env[k]; | |
| 39 | dir = await mkdtemp(join(tmpdir(), "forge-talk-cell-tools-")); | |
| 40 | app = createApp({ dataDir: dir, port: 0 }); | |
| 41 | servers = await serve(app); | |
| 42 | const a = await createUser(app.db, { | |
| 43 | origin: "seed", | |
| 44 | trusted: true, | |
| 45 | username: "alice", | |
| 46 | email: "[email protected]", | |
| 47 | password: "a-good-passphrase", | |
| 48 | adminIfFirst: true, | |
| 49 | }); | |
| 50 | if (!a.ok) throw new Error("user"); | |
| 51 | alice = a.value; | |
| 52 | }); | |
| 53 | afterAll(async () => { | |
| 54 | for (const k of STAMPS) { | |
| 55 | const v = saved[k]; | |
| 56 | if (v === undefined) delete process.env[k]; | |
| 57 | else process.env[k] = v; | |
| 58 | } | |
| 59 | await servers.stop?.(); | |
| 60 | app.db.close(); | |
| 61 | await rm(dir, { recursive: true, force: true }); | |
| 62 | }); | |
| 63 | ||
| 64 | describe("Talk's tools on an unstamped forge", () => { | |
| 65 | test("initialize answers what MCP's schema requires: a name and a version, both strings", async () => { | |
| 66 | const minted = mintViaToken( | |
| 67 | app.db, | |
| 68 | alice.id, | |
| 69 | "conversation:cell", | |
| 70 | "hello", | |
| 71 | new Date(Date.now() + 60_000).toISOString(), | |
| 72 | ); | |
| 73 | if (!minted.ok) throw new Error(minted.error); | |
| 74 | const res = await fetch(`${servers.url}/mcp`, { | |
| 75 | method: "POST", | |
| 76 | headers: { | |
| 77 | "content-type": "application/json", | |
| 78 | accept: "application/json, text/event-stream", | |
| 79 | authorization: `Bearer ${minted.value.token}`, | |
| 80 | }, | |
| 81 | body: JSON.stringify({ | |
| 82 | jsonrpc: "2.0", | |
| 83 | id: 1, | |
| 84 | method: "initialize", | |
| 85 | params: { | |
| 86 | protocolVersion: "2025-06-18", | |
| 87 | capabilities: {}, | |
| 88 | clientInfo: { name: "claude-code", version: "2" }, | |
| 89 | }, | |
| 90 | }), | |
| 91 | }); | |
| 92 | expect(res.status).toBe(200); | |
| 93 | const text = await res.text(); | |
| 94 | // JSON, or one SSE event carrying it. | |
| 95 | const sse = text.split("\n").find((l) => l.startsWith("data:")); | |
| 96 | const body = JSON.parse( | |
| 97 | text.trimStart().startsWith("{") || sse === undefined | |
| 98 | ? text | |
| 99 | : sse.slice(5), | |
| 100 | ); | |
| 101 | expect(typeof body.result.serverInfo.name).toBe("string"); | |
| 102 | expect(typeof body.result.serverInfo.version).toBe("string"); | |
| 103 | expect(body.result.serverInfo.version).not.toBe("dev"); | |
| 104 | }); | |
| 105 | ||
| 106 | test("an init record's failed servers are named; a pending or connected one is not", () => { | |
| 107 | expect( | |
| 108 | unreachedServers([ | |
| 109 | { name: "forge", status: "failed" }, | |
| 110 | { name: "x", status: "connected" }, | |
| 111 | { name: "y", status: "pending" }, | |
| 112 | { name: "z", status: "needs-auth" }, | |
| 113 | ]), | |
| 114 | ).toEqual(["forge", "z"]); | |
| 115 | expect(unreachedServers(undefined)).toEqual([]); | |
| 116 | }); | |
| 117 | ||
| 118 | test("a turn whose forge server did not connect stops, says one plain sentence, and is logged", async () => { | |
| 119 | const path = join(dir, "toolless"); | |
| 120 | // What Claude Code did on the cell: its init names the forge's server failed, then the model | |
| 121 | // answers that it has no tools. The stand-in waits before that answer; the turn must not. | |
| 122 | writeFileSync( | |
| 123 | path, | |
| 124 | `#!/bin/sh | |
| 125 | if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi | |
| 126 | IFS= read -r first | |
| 127 | echo '{"type":"system","subtype":"init","session_id":"sess-t","model":"fake","mcp_servers":[{"name":"forge","status":"failed","source":"dynamic"}]}' | |
| 128 | sleep 20 | |
| 129 | echo '{"type":"assistant","session_id":"sess-t","message":{"id":"m1","content":[{"type":"text","text":"this session gives me no tools"}],"usage":{"input_tokens":1,"output_tokens":1}}}' | |
| 130 | echo '{"type":"result","subtype":"success","is_error":false,"result":"this session gives me no tools","total_cost_usd":0.01,"num_turns":1,"session_id":"sess-t","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}' | |
| 131 | `, | |
| 132 | ); | |
| 133 | chmodSync(path, 0o755); | |
| 134 | const warned: string[] = []; | |
| 135 | const warn = app.log.warn; | |
| 136 | app.log.warn = (message, fields) => { | |
| 137 | warned.push(message); | |
| 138 | warn(message, fields); | |
| 139 | }; | |
| 140 | try { | |
| 141 | const started = performance.now(); | |
| 142 | const said = say( | |
| 143 | app, | |
| 144 | { | |
| 145 | binary: path, | |
| 146 | localUrl: servers.url, | |
| 147 | budgetUsd: 1, | |
| 148 | timeoutMs: 60_000, | |
| 149 | signal: new AbortController().signal, | |
| 150 | }, | |
| 151 | alice.id, | |
| 152 | "bring trevato/voxel in", | |
| 153 | ); | |
| 154 | expect(said.ok && said.value.how).toBe("started"); | |
| 155 | if (said.ok) await said.value.done; | |
| 156 | // Stopped at the init record, not after the stand-in's 20 s wait. | |
| 157 | expect(performance.now() - started).toBeLessThan(15_000); | |
| 158 | } finally { | |
| 159 | app.log.warn = warn; | |
| 160 | } | |
| 161 | const conversation = openConversation(app.db, alice.id); | |
| 162 | const turns = listTurns(app.db, alice.id, conversation.id); | |
| 163 | const shown = turns.ok ? turns.value.map((t) => `${t.role}:${t.text}`) : []; | |
| 164 | expect(shown).toEqual([ | |
| 165 | "person:bring trevato/voxel in", | |
| 166 | `agent:${NO_TOOLS_LINE}`, | |
| 167 | ]); | |
| 168 | expect(shown.join()).not.toContain("no tools"); | |
| 169 | expect(turns.ok && turns.value.at(-1)!.failed).toBe(true); | |
| 170 | const run = app.db | |
| 171 | .query< | |
| 172 | { id: string; state: string }, | |
| 173 | [string] | |
| 174 | >("SELECT id, state FROM conversation_run WHERE conversation_id = ?1") | |
| 175 | .get(conversation.id); | |
| 176 | expect(run?.state).toBe("failed"); | |
| 177 | expect(warned).toContain( | |
| 178 | "talk turn stopped: its MCP server did not connect", | |
| 179 | ); | |
| 180 | expect(readRunLog(dir, run!.id).lines.join("\n")).toContain( | |
| 181 | `stopped: the forge's MCP server at ${servers.url}/mcp did not connect`, | |
| 182 | ); | |
| 183 | }); | |
| 184 | }); |
test/version.test.ts +3 −2
| @@ -326,7 +326,7 @@ describe("where the stamp is read", () => { | ||
| 326 | 326 | expect(page).not.toContain("reduced-protection"); |
| 327 | 327 | }); |
| 328 | 328 | |
| 329 | test("with no stamp every one of them says dev, but the MCP door omits it", async () => { | |
| 329 | test("with no stamp every one of them says dev, but MCP's initialize says unreleased", async () => { | |
| 330 | 330 | stamp(); |
| 331 | 331 | try { |
| 332 | 332 | const health = (await ( |
| @@ -338,7 +338,8 @@ describe("where the stamp is read", () => { | ||
| 338 | 338 | capabilities: {}, |
| 339 | 339 | clientInfo: { name: "test", version: "0" }, |
| 340 | 340 | }); |
| 341 | expect(init.serverInfo.version).toBeUndefined(); | |
| 341 | // MCP's schema requires a version: one left out fails the client's check (a cell's Talk). | |
| 342 | expect(init.serverInfo).toEqual({ name: "forge", version: "unreleased" }); | |
| 342 | 343 | } finally { |
| 343 | 344 | stamp("9.8.7", COMMIT); |
| 344 | 345 | } |
new above
offline