Merge remote-tracking branch 'origin/main' into artifacts-token-inventory
Jonas Templestein, 2026-11-26 16:08 UTC · c0f9c3538267287594c6ae9fa13efddbfa007941 · a merge of 4ef65a6 and 4933dde, shown against 4ef65a6
9 files changed
- M core/auth-worker/src/guest-sign-in.test.ts
- M core/auth-worker/src/members.ts
- M core/itx/src/person-context.test.ts
- M core/itx/src/person-context.ts
- M core/lib/src/mind-config.ts
- M core/lib/src/sdk/auth.ts
- M core/lib/src/sdk/mcp.ts
- M core/mind-worker/src/mcp-config.test.ts
- M core/mind-worker/src/mcp.ts
M core/auth-worker/src/guest-sign-in.test.ts
@@ -482,7 +482,13 @@ expect(factsOf(blocked).flatMap((fact) => fact.events.map((event) => event.type))).toEqual([ "events.iterate.com/account/grant-ended", "events.iterate.com/account/person-blocked", + "events.iterate.com/account/person-blocked", ]); + // the block is told on the guest's own context too: an open socket of theirs ends by it + expect(factsOf(blocked).at(-1)).toMatchObject({ + path: `/users/${bob.userId}`, + events: [{ type: "events.iterate.com/account/person-blocked" }], + }); expect(await tokenIdentity(env, token, MEET)).toBeNull(); expect(await tokenIdentity(env, evesToken, MEET)).toMatchObject({ name: "Eve" }); // the cookie earns nothing more, and the form says so with one event on the guest's context @@ -500,7 +506,13 @@ { path: `/users/${bob.userId}`, events: [{ payload: { reason: "blocked" } }] }, ]); - expect(await (await members("unblock", bob.userId)).text()).toContain("is no longer blocked"); + // the block's end is told on the guest's own context too, where the block is + const unblocked = await members("unblock", bob.userId); + expect(await unblocked.text()).toContain("is no longer blocked"); + expect(factsOf(unblocked).at(-1)).toMatchObject({ + path: `/users/${bob.userId}`, + events: [{ type: "events.iterate.com/account/person-unblocked" }], + }); expect(originAndPath(await meet.ask(bob.cookie))).toBe(`${MEET}/.iterate/callback`); });
M core/auth-worker/src/members.ts
@@ -510,6 +510,13 @@ type: "events.iterate.com/account/person-blocked", payload: { email }, }); + // and on the blocked person's own context: a socket of theirs that is open in the mind ends by + // it (core/itx/src/person-context.ts `blockWatchOf`), since no token is asked for again there + if (person) + facts.add(person.id, { + type: "events.iterate.com/account/person-blocked", + payload: { email }, + }); console.info({ event: "auth.person-blocked", by: actor.userId, known: Boolean(person) }); return { facts, @@ -549,6 +556,16 @@ type: "events.iterate.com/account/person-unblocked", payload: { email }, }); + // on the person's own context too, where their block is: what that log says last is whether + // an open socket of theirs ends (core/itx/src/person-context.ts `blockWatchOf`) + const person = await env.DB.prepare("select id from users where email = ?1") + .bind(email) + .first<{ id: string }>(); + if (person) + facts.add(person.id, { + type: "events.iterate.com/account/person-unblocked", + payload: { email }, + }); return { facts, notice: `${email} is no longer blocked.` }; }
M core/itx/src/person-context.test.ts
@@ -6,11 +6,16 @@ import { PERSON_METHOD_MAX_CHARS } from "./context/facet-public-methods.ts"; import { ADMITS_EVERY_MS, + ADMITTED_GUEST_SOCKET_MS, admissionOf, + BLOCK_EVERY_MS, + BLOCK_READ_FAILURES, + blockWatchOf, asAFacetIsTold, asAPersonReads, PersonContextRpcTarget, personItxSession, + socketEndOf, principalOf, readsOf, } from "./person-context.ts"; @@ -859,6 +864,112 @@ path, }); expect(answer).toMatchObject({ status }); +}); + +// A guest's sign-in on an app's host lasts 15 minutes. Its end cut every guest out of a call, +// while the call's own check still admitted them. +test("a guest's socket whose reach a facet is asked about outlives the guest's sign-in, for 4 hours at most", () => { + const now = 1_795_700_000_000; + const signInEndsAt = now + 15 * 60_000; + expect(socketEndOf({ signInEndsAt, admittedGuest: true, now })).toBe( + now + ADMITTED_GUEST_SOCKET_MS, + ); + expect(ADMITTED_GUEST_SOCKET_MS).toBe(4 * 60 * 60_000); + // a member, a person who proved an address, and a guest with no facet named: the sign-in's end + expect(socketEndOf({ signInEndsAt, admittedGuest: false, now })).toBe(signInEndsAt); +}); + +// What ends such a socket is the facet's no: a link that ended, on the next frame. +test("the facet's no ends an admitted guest's socket on its traffic, whatever the sign-in's end", async () => { + let clock = 0; + let live = true; + const { onFrame, gate } = admissionOf({ + facet: "call", + member: false, + ask: async () => live, + now: () => clock, + }); + // 20 minutes of traffic, past the sign-in's 15: still admitted + for (clock = 0; clock <= 20 * 60_000; clock += ADMITS_EVERY_MS) + expect(await onFrame!()).toBeUndefined(); + // the link ends: the next frame after the wait ends the session, and a write is refused + live = false; + clock += ADMITS_EVERY_MS; + expect(await onFrame!()).toBe("your access to this context ended"); + await expect(gate()).rejects.toThrow("your access to this context ended"); + // a no is final: a link that is live again does not bring the socket back + live = true; + clock += ADMITS_EVERY_MS; + expect(await onFrame!()).toBe("your access to this context ended"); +}); + +// The block, and its end, are on the guest's own context, written by the auth Worker. +const BLOCKED = { type: "events.iterate.com/account/person-blocked" }; +const UNBLOCKED = { type: "events.iterate.com/account/person-unblocked" }; +/** A watch over a log that the test writes, with its clock and the offsets it read from. */ +function blockWatch(log: unknown[]) { + const world = { clock: 1_795_700_000_000, reads: [] as number[], fails: false }; + const watch = blockWatchOf({ + now: () => world.clock, + read: async (afterOffset) => { + world.reads.push(afterOffset); + if (world.fails) throw new Error("no answer"); + return { events: log.slice(afterOffset), scannedThroughOffset: log.length, atHead: true }; + }, + }); + return { world, watch }; +} + +test("an owner's block ends a guest's open socket at the next read, and it is final", async () => { + // at the open: the sign-in, and a block from before that an owner took back + const log: unknown[] = [ + { type: "events.iterate.com/account/guest-signed-in" }, + BLOCKED, + UNBLOCKED, + ]; + const { world, watch } = blockWatch(log); + expect(await watch.blockedNow()).toBe(false); + // frames within the minute read nothing + world.clock += BLOCK_EVERY_MS - 1; + expect(await watch.onFrame()).toBeUndefined(); + expect(world.reads).toEqual([0]); + // an owner blocks the guest: the next read, from where the last one stopped, ends the session + log.push(BLOCKED); + world.clock += 1; + expect(await watch.onFrame()).toBe("your access to this context ended"); + expect(world.reads).toEqual([0, 3]); + // final: an owner who takes the block back does not bring the socket back, and nothing is read + log.push(UNBLOCKED); + world.clock += BLOCK_EVERY_MS; + expect(await watch.onFrame()).toBe("your access to this context ended"); + expect(world.reads).toEqual([0, 3]); +}); + +test("a guest who is blocked at the open gets no socket, whatever the time on the block", async () => { + expect(await blockWatch([BLOCKED]).watch.blockedNow()).toBe(true); + expect(await blockWatch([BLOCKED, UNBLOCKED, BLOCKED]).watch.blockedNow()).toBe(true); + expect(await blockWatch([]).watch.blockedNow()).toBe(false); +}); + +test("reads of the guest's log that fail: one says nothing, three in a row end the session", async () => { + const log: unknown[] = []; + const { world, watch } = blockWatch(log); + world.fails = true; + // the open is not refused for a read that failed (the first of the three) + expect(await watch.blockedNow()).toBe(false); + world.clock += BLOCK_EVERY_MS; + expect(await watch.onFrame()).toBeUndefined(); + // a read that answers starts the count again + world.fails = false; + world.clock += BLOCK_EVERY_MS; + expect(await watch.onFrame()).toBeUndefined(); + world.fails = true; + for (let n = 1; n < BLOCK_READ_FAILURES; n += 1) { + world.clock += BLOCK_EVERY_MS; + expect(await watch.onFrame()).toBeUndefined(); + } + world.clock += BLOCK_EVERY_MS; + expect(await watch.onFrame()).toBe("your access to this context ended"); }); // Who asked, as every event of theirs then names them (`source.onBehalfOf.principal`).
M core/itx/src/person-context.ts
@@ -72,6 +72,15 @@ /** How often a person's socket asks the named facet whether the person still reaches the * context, at most (`admissionOf`). */ export const ADMITS_EVERY_MS = 5_000; +/** How long a guest's socket lasts at most, when a facet is asked whether the guest still + * reaches the context (`socketEndOf`). */ +export const ADMITTED_GUEST_SOCKET_MS = 4 * 60 * 60_000; +/** How often such a socket reads whether an owner blocked its guest, at most (`blockWatchOf`). */ +export const BLOCK_EVERY_MS = 60_000; +/** How many reads of the guest's log in a row may fail before the socket ends. */ +export const BLOCK_READ_FAILURES = 3; +const PERSON_BLOCKED = "events.iterate.com/account/person-blocked"; +const PERSON_UNBLOCKED = "events.iterate.com/account/person-unblocked"; const ACCESS_ENDED = "your access to this context ended"; const FACET_NAME = /^[A-Za-z0-9_.-]+$/; // The only `invoke` texts: the seed of a live state, and a facet's state, for the chat's views. @@ -410,7 +419,8 @@ * named the context; it named no caller and handed over no Request. The person is the one the * boundary stamped on the Request this invocation was given, so nothing user code built or * altered is read. As a member's socket (serve-host.ts `itxSession`): a WebSocket upgrade from - * this origin alone, ended when the person's sign-in ends. */ + * this origin alone, ended when the person's sign-in ends; a guest's whose reach a facet is + * asked about lasts longer (`socketEndOf`). */ export async function personItxSession(args: { ctx: ExecutionContext; request: Request; @@ -477,11 +487,32 @@ true, ), }); + const admittedGuest = person.method === "guest" && !!admission.onFrame; + // the guest's own context, where the auth Worker writes a block of them + const ofThePerson = new IterateContextRpcTarget( + contexts(), + DurableObjectNameCodec.address(`/users/${person.userId}`), + new SessionTeardown(), + (promise) => ctx.waitUntil(promise), + { principal: null }, + ); + const block = blockWatchOf({ + read: (afterOffset) => + ofThePerson.invoke(["itx", "builtins", ["readEvents", afterOffset, 200]]), + }); + // a guest who is blocked gets no such socket, whatever the upgrade's stamp says + if (admittedGuest && (await block.blockedNow())) + return new Response("Your access ended\n", { status: 403 }); + const onFrame = admittedGuest + ? async () => (await admission.onFrame!()) || (await block.onFrame()) + : admission.onFrame; return serveSession(ctx, { caller: { principal: null }, - endsAt, - endReason: "the sign-in for this session ended: sign in again", - onFrame: admission.onFrame, + endsAt: socketEndOf({ signInEndsAt: endsAt, admittedGuest, now: Date.now() }), + endReason: admittedGuest + ? "this socket was open for 4 hours: open the page again" + : "the sign-in for this session ended: sign in again", + onFrame, root: (context, teardown) => { const reads = context.cd(path); // The kernel's own code names the person here, so no signed token is needed, and a redial @@ -505,6 +536,87 @@ ); }, }); +} + +/** WHEN A PERSON'S SOCKET ENDS AT THE LATEST. A sign-in's end ends the socket. One case differs: + * a GUEST whose reach a facet is asked about (`admissionOf`: the app's answer named `admits`). + * A guest's sign-in on an app's host lasts 15 minutes and is renewed only by a page load + * (core/auth-worker/src/guest-sign-in.ts), so its end cut every guest out of a call four times + * an hour, while the call's own check said that the guest was still in. For such a socket the + * facet's answer is what ends it (asked on the socket's traffic at most every `ADMITS_EVERY_MS`, + * and a session with no traffic is probed, which is traffic): a link that ends, ends the socket. + * The sign-in's renewal is not asked while the socket is open, so the socket itself reads + * whether an owner blocked the guest (`blockWatchOf`): a block ends it about a minute and a + * half later, at the latest. The bound is 4 hours, as long as a member's relay credentials + * last in a call. + * A member, a person who proved an address, and a guest's socket with no facet named end with + * the sign-in, as before. */ +export function socketEndOf(args: { + signInEndsAt: number; + admittedGuest: boolean; + now: number; +}): number { + return args.admittedGuest ? args.now + ADMITTED_GUEST_SOCKET_MS : args.signInEndsAt; +} + +/** A BLOCK ENDS A GUEST'S OPEN SOCKET. An owner's block ends the guest's tokens at once, and a + * socket that outlives the sign-in asks for no token again. The auth Worker writes a block, and + * its end, on the guest's own context (`/users/<id>`, core/auth-worker/src/members.ts), and + * `read` reads that log from an offset on. Whether the guest is blocked is what the log says + * last: no clock is compared. + * - `blockedNow` reads the log at the open: a guest who is blocked gets no socket, also when the + * upgrade was stamped a moment before the block. + * - `onFrame` reads on the socket's traffic, at most every `BLOCK_EVERY_MS`. A socket has a frame + * every 30 to 40 s or is ended (./end-when-silent.ts), so a block ends the session about a + * minute and a half after it is in the log, at the latest. It is final. + * - A read that fails says nothing; `BLOCK_READ_FAILURES` of them in a row end the session, so + * a guest whose block cannot be read is not kept. The guest's page opens a socket again, and + * the sign-in refuses a blocked guest there. + * What this cannot see: a block whose fact never reached the mind (the auth Worker's facts are + * delivered best effort, iterate/facts). Such a guest's socket ends by the facet's no or the + * socket's own bound (`socketEndOf`), and they come in nowhere again. */ +export function blockWatchOf(args: { + read: (afterOffset: number) => Promise<unknown>; + now?: () => number; +}) { + const now = args.now || Date.now; + const Page = z.object({ + events: z.array(z.object({ type: z.string() }).loose()), + scannedThroughOffset: z.number(), + atHead: z.boolean(), + }); + let after = 0; + let askedAt = 0; + let blocked = false; + let failures = 0; + let ended = false; + const look = async () => { + askedAt = now(); + // at most 10 pages a look: a log longer than that is read on at the next one + for (let pages = 0; pages < 10; pages += 1) { + const page = Page.safeParse(await args.read(after).catch(() => null)); + if (!page.success) return void (failures += 1); + for (const event of page.data.events) { + if (event.type === PERSON_BLOCKED) blocked = true; + else if (event.type === PERSON_UNBLOCKED) blocked = false; + } + after = Math.max(after, page.data.scannedThroughOffset); + if (page.data.atHead) return void (failures = 0); + } + }; + return { + blockedNow: async () => { + await look(); + return blocked; + }, + onFrame: async () => { + if (!ended && now() - askedAt >= BLOCK_EVERY_MS) { + await look(); + ended = blocked || failures >= BLOCK_READ_FAILURES; + } + if (ended) return ACCESS_ENDED; + }, + }; } /** ADMITS: whether a person who is no member still reaches the context, by the facet the app's
M core/lib/src/mind-config.ts
@@ -66,7 +66,8 @@ * that answers an MCP server's class for the client that asks (iterate/sdk `McpServerTarget`): * its instructions, the description of `run`, more tools, and the mind's skills. Absent: the * platform's defaults. Set, and the method fails, is slow or answers what is no such class: - * the failure is logged and the defaults answer. */ + * the failure is logged, the defaults answer, and the server tells the client which part + * failed. */ mcpTarget: z .string() .regex(/^[A-Za-z_$][\w$]{0,63}$/, "the name of a method")
M core/lib/src/sdk/auth.ts
@@ -214,7 +214,11 @@ * person still reaches it. For a person who is no member, the platform asks it before each * write and at most once every 5 seconds of the socket's traffic, and a `false` or a throw * ends the socket: a guest whose link ended is out of the context, not only of a call. A - * member is never asked. */ + * member is never asked. A GUEST'S socket with `admits` does not end with the guest's 15 + * minutes on your host: the facet's answer ends it, and 4 hours at the latest. So a guest stays + * in a call while your facet admits them, and your `admits()` is the whole check for an open + * socket, but for a block: a guest whom an owner blocks is out of an open socket about a + * minute and a half later, and comes in nowhere again. */ /** AN MCP SERVER OF THIS APP, SERVED BY THE PLATFORM (./mcp.ts). Call it in `fetch` for the * app's host, before the app's own paths: it answers for `/mcp` and for the document that * tells a client where to sign in, and null for every other path. `target` names the method
M core/lib/src/sdk/mcp.ts
@@ -17,7 +17,8 @@ // - THE MIND'S OWN MCP SERVER, at its control-plane hostname, for members. The platform serves // it, with its tool `run`. A deploy's config may name a method of the config's class // (`mcpTarget`, iterate/mind-config) that answers the class for a client; what the class says -// is added to the platform's defaults, and when it fails the defaults answer alone. +// is added to the platform's defaults. When a part of it fails, the default answers for that +// part, and the server tells the client which part failed. // - ANY HOST OF THE MIND, from the config's `fetch`: `this.auth.mcpServer(request, { target })` // (./auth.ts) answers for `/mcp` and names the method that answers the class. import { RpcTarget } from "cloudflare:workers";
M core/mind-worker/src/mcp-config.test.ts
@@ -218,11 +218,15 @@ const [defaultRun] = (defaults.result || {}).tools as { name: string; description: string }[]; expect(defaultRun).toMatchObject({ name: "run" }); - const custom = classOf({ - instructions: () => "Read the skills first.", - tools: () => [{ name: "run", description: "Run, as this mind says." }, { name: "hello" }], - hello: () => "hi", - }); + const calls: unknown[][] = []; + const custom = classOf( + { + instructions: () => "Read the skills first.", + tools: () => [{ name: "run", description: "Run, as this mind says." }, { name: "hello" }], + hello: () => "hi", + }, + calls, + ); expect((await answerOf(await mind(custom, "initialize", INIT))).result).toMatchObject({ instructions: "Read the skills first.", }); @@ -231,6 +235,19 @@ expect.objectContaining({ name: "run", description: "Run, as this mind says." }), ]); + // A CALL OF `run` ASKS THE CLASS NOTHING: the tool is the platform's, so a slow class holds no + // run. A call of the class's own tool asks for its tools, and then calls the method. + calls.length = 0; + const ran = await answerOf( + await mind(custom, "tools/call", { name: "run", arguments: { script: "async () => 1" } }), + ); + expect(ran.result).toHaveProperty("content"); + expect(calls).toEqual([]); + expect( + (await answerOf(await mind(custom, "tools/call", { name: "hello", arguments: {} }))).result, + ).toMatchObject({ content: [{ type: "text", text: "hi" }], isError: false }); + expect(calls.map(([, method]) => method)).toEqual(["tools", "hello"]); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const broken = classOf({ instructions: () => { @@ -244,17 +261,76 @@ await vi.advanceTimersByTimeAsync(6000); vi.useRealTimers(); const init = await answerOf(await pending); - expect(init.result?.instructions).toMatch(/^One tool, `run/); + // the client is told what failed, before the default instructions + const [note, defaultInstructions] = String(init.result?.instructions).split("\n\n"); + expect(note).toMatch(/^THIS MIND'S OWN MCP SETTINGS FAILED/); + expect(note).toContain( + "What failed: instructions() threw an error; skills() gave no answer in 5000 ms; tools() answered what the platform cannot use.", + ); + expect(defaultInstructions).toMatch(/^One tool, `run/); expect(init.result?.capabilities).not.toHaveProperty("resources"); - expect((await answerOf(await mind(broken, "tools/list"))).result?.tools).toEqual([ - expect.objectContaining({ name: "run", description: defaultRun.description }), + // A LIST OF THE TOOLS THAT THE CLASS FAILED TO ANSWER has `run` alone, and its description + // begins with the note: the instructions do not travel with a list + const listed = ((await answerOf(await mind(broken, "tools/list"))).result || {}).tools; + expect(listed).toEqual([ + expect.objectContaining({ + name: "run", + description: expect.stringMatching( + /^THIS MIND'S OWN MCP SETTINGS FAILED.* What failed: tools\(\) answered what the platform cannot use\. /, + ), + }), ]); + expect(listed).toEqual([ + expect.objectContaining({ description: expect.stringContaining(defaultRun.description) }), + ]); + // THE ERROR'S OWN TEXT REACHES NO CLIENT: the config's code wrote it, perhaps from another + // party's answer, and a client hands what it gets to a model + expect(JSON.stringify([init, listed])).not.toContain("the config broke"); // each failure is one log line: the initialize asked all three, the list its tools again expect(warn.mock.calls.map(([line]) => (line as { what: string }).what).sort()).toEqual([ "iterate-mind.instructions", "iterate-mind.skills", "iterate-mind.tools", "iterate-mind.tools", + ]); + warn.mockRestore(); +}); + +test("the mind's own server tells its client which part of the class failed; an app's server does not", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const half = classOf({ + instructions: () => "Read the skills first.", + skills: () => { + throw new Error("no folder\n /srv/config/skills"); + }, + }); + // ONE PART FAILS: the note names it in the platform's words, and the class's own instructions + // stay + const own = await serveMcp( + post("initialize", INIT, { "x-itx-principal": JSON.stringify(member) }), + () => Promise.reject(new Error("no file is read")), + half, + ).then(answerOf); + expect(own.result?.instructions).toMatch( + /^THIS MIND'S OWN MCP SETTINGS FAILED.* What failed: skills\(\) threw an error\. .*\n\nRead the skills first\.$/, + ); + expect(JSON.stringify(own)).not.toContain("/srv/config"); + // a class that has no such method failed nothing: no note + const quiet = await serveMcp( + post("initialize", INIT, { "x-itx-principal": JSON.stringify(member) }), + () => Promise.reject(new Error("no file is read")), + classOf({ instructions: () => "Read the skills first." }), + ).then(answerOf); + expect(quiet.result?.instructions).toBe("Read the skills first."); + + // AN APP'S SERVER answers people who are no members: the words of the config's code stay in + // the log + const told = await app(half, "initialize", INIT); + expect(told.result?.instructions).toBe("Read the skills first."); + expect(JSON.stringify(told)).not.toContain("/srv/config"); + expect(warn.mock.calls.map(([line]) => (line as { what: string }).what)).toEqual([ + "iterate-mind.skills", + "guestbook.skills", ]); warn.mockRestore(); });
M core/mind-worker/src/mcp.ts
@@ -24,7 +24,9 @@ // // THE CONFIG CANNOT BREAK A SERVER. Each thing it is asked (`askConfig`) has a time limit and a // schema. What fails, is slow or does not fit is logged, and the default stands: the mind's own -// server then answers as it does with no `mcpTarget`. +// server then answers that part as it does with no `mcpTarget`, and its instructions tell the +// client what failed (`configFailedNote`). A call of the platform's own `run` asks the config +// nothing, so a slow class holds no run. /** One call of the config's class for this server: `method` with `args` * (iterate/sdk `IterateConfigEntrypoint.mcpCall`). */ @@ -334,6 +336,9 @@ instructions?: string; tools?: z.infer<typeof ConfigTools>; skills?: SkillCatalog; + /** Each part that failed, as "<method>() <why>" in the platform's words, on the mind's own + * server alone. */ + failed?: string[]; }; const CONFIG_ANSWER_TIMEOUT_MS = 5000; @@ -369,27 +374,32 @@ const AnyResult = z.looseObject({}); /** ONE QUESTION TO THE CONFIG'S CLASS, which cannot break the server: its answer within the time - * limit and in `schema`'s shape, or undefined, with one log line that says what went wrong. */ + * limit and in `schema`'s shape, or undefined, with one log line that says what went wrong. + * `failed` gets why in the platform's own words, one of three. The error's text goes to the log + * alone: the config's code wrote it, and may have copied it from somewhere else. */ async function askConfig<T>( ask: () => Promise<unknown>, schema: z.ZodType<T>, what: string, + failed: (why: string) => void, ): Promise<T | undefined> { let timer: ReturnType<typeof setTimeout> | undefined; + let why = "threw an error"; try { const answer = await Promise.race([ ask(), new Promise<never>((_resolve, reject) => { - timer = setTimeout( - () => reject(new Error(`no answer in ${CONFIG_ANSWER_TIMEOUT_MS} ms`)), - CONFIG_ANSWER_TIMEOUT_MS, - ); + timer = setTimeout(() => { + why = `gave no answer in ${CONFIG_ANSWER_TIMEOUT_MS} ms`; + reject(new Error(`no answer in ${CONFIG_ANSWER_TIMEOUT_MS} ms`)); + }, CONFIG_ANSWER_TIMEOUT_MS); }), ]); // the class has no such method: the default stands, and nothing is wrong if (!answer) return undefined; const parsed = schema.safeParse(answer); if (parsed.success) return parsed.data; + why = "answered what the platform cannot use"; throw new Error(`not the expected shape: ${parsed.error.issues[0]?.message || "invalid"}`); } catch (error) { console.warn({ @@ -397,14 +407,31 @@ what, message: (error instanceof Error ? error.message : String(error)).slice(0, 300), }); + failed(why); return undefined; } finally { clearTimeout(timer); } } +/** WHAT THE MIND'S OWN SERVER TELLS A CLIENT WHEN THE CONFIG'S CLASS FAILED. Without it a broken + * config looks like a mind that has no instructions, tools or skills of its own, and only the + * log says otherwise. It goes first in the instructions, and first in the description of `run` + * when a list of the tools failed: a client may cut either (Claude Code keeps 4,096 characters + * of the instructions). + * + * EVERY WORD OF IT IS THE PLATFORM'S. `failed` names one of the three methods and one of three + * reasons (`askConfig`). An error's own text stays in the log: a client hands these words to its + * model, so text that the config's code took from another party would instruct that model, and + * a secret in it would go to the model's provider. + * + * An app's server does not say it: the people it answers can do nothing about the mind's config. */ +const configFailedNote = (failed: string[]) => + `THIS MIND'S OWN MCP SETTINGS FAILED, and the platform's defaults answer in their place. What failed: ${failed.join("; ")}. Tell the person you work for: the mind's own instructions, tools or skills can be missing here. \`run\` works. The class that failed is in the mind's config repo (\`mcp.ts\` in the default config), and the mind Worker's log says why (\`mcp.config-target-failed\`).`; + function buildServer(caller: Caller, served: Served, said: Said, client: McpClient): McpServer { - const instructions = said.instructions || (served.run ? runInstructions : undefined); + const own = said.instructions || (served.run ? runInstructions : undefined); + const instructions = said.failed && own ? `${configFailedNote(said.failed)}\n\n${own}` : own; const mcpServer = new McpServer( { name: served.name, version: "0.1.0" }, instructions ? { instructions } : {}, @@ -443,7 +470,11 @@ "run", { title: "Run a script", - description: said.tools?.find((tool) => tool.name === "run")?.description || runDescription, + // a list that the class failed to answer has `run` alone: its description says so + description: [ + ...(said.failed ? [configFailedNote(said.failed)] : []), + said.tools?.find((tool) => tool.name === "run")?.description || runDescription, + ].join("\n\n"), inputSchema: fromJsonSchema( { type: "object", @@ -553,17 +584,28 @@ const said: Said = {}; const { config } = served; if (config) { + const failed: string[] = []; const say = <T>(method: string, schema: z.ZodType<T>) => - askConfig(() => config(client, method, []), schema, `${served.name}.${method}`); - const [instructions, tools, files] = await Promise.all([ + askConfig( + () => config(client, method, []), + schema, + `${served.name}.${method}`, + (why) => failed.push(`${method}() ${why}`), + ); + // A call of the platform's own `run` needs nothing of the class: it does not wait for one + // that is slow. + const tools = asked.tools && !(served.run && asked.callsRunAlone); + const [instructions, toolList, files] = await Promise.all([ asked.instructions ? say("instructions", ConfigInstructions) : undefined, // an initialize says whether the server has tools and skills at all - asked.tools || asked.instructions ? say("tools", ConfigTools) : undefined, + tools || asked.instructions ? say("tools", ConfigTools) : undefined, asked.skills || asked.instructions ? say("skills", ConfigSkillFiles) : undefined, ]); said.instructions = instructions; - said.tools = tools; + said.tools = toolList; if (files) said.skills = await skillCatalog(files); + // in one order, whichever part failed first + if (served.run && failed.length > 0) said.failed = failed.sort(); } return createMcpHandler( () => buildServer(caller, served, said, client), @@ -616,13 +658,14 @@ } const ClientInfo = z.looseObject({ name: z.string().max(256), version: z.string().max(64) }); -/** One JSON-RPC message, as far as this file reads it before the SDK does: its method, and how - * the client named itself (`initialize`'s `clientInfo`, or each call's envelope from MCP - * 2026-07-28 on). */ +/** One JSON-RPC message, as far as this file reads it before the SDK does: its method, the tool + * a `tools/call` names, and how the client named itself (`initialize`'s `clientInfo`, or each + * call's envelope from MCP 2026-07-28 on). */ const AskedMessage = z.looseObject({ method: z.string(), params: z .looseObject({ + name: z.string().optional().catch(undefined), clientInfo: ClientInfo.optional().catch(undefined), _meta: z .looseObject({ @@ -647,6 +690,7 @@ return parsed.success ? [parsed.data] : []; }); const methods = messages.map((message) => message.method); + const ofTools = messages.filter((message) => message.method.startsWith("tools/")); const named = messages .map( (message) => @@ -656,7 +700,11 @@ return { client: named ? { name: named.name, version: named.version } : {}, instructions: methods.some((method) => method === "initialize" || method === "server/discover"), - tools: methods.some((method) => method.startsWith("tools/")), + tools: ofTools.length > 0, + /** Every message about tools is a call of the tool named `run`. */ + callsRunAlone: + ofTools.length > 0 && + ofTools.every((message) => message.method === "tools/call" && message.params?.name === "run"), skills: methods.some( (method) => method.startsWith("skills/") || method.startsWith("resources/"), ),