Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog/entries/2026-06-22-mcp-next-actions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"id": "2026-06-22-mcp-next-actions",
"version": "0.9.4",
"date": "2026-06-22",
"category": "feat",
"title": "MCP tool errors now carry recovery steps",
"summary": "Every failed MCP tool call returns structured next_actions — concrete recovery steps (and the tool to call) so an agent can recover in one turn instead of guessing.",
"features": ["mcp", "agents"],
"mcpTools": []
}
20 changes: 19 additions & 1 deletion packages/mcp/src/__tests__/dispatch-persist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,30 @@ interface Fake {
rows: Map<string, Record<string, unknown>>;
posts: number;
gets: number;
/** Appends to the event spine (rpc/append_session_event) — counted apart
* from the document persist POSTs so each is asserted independently. */
appends: number;
}

function installFake(): Fake {
const rows = new Map<string, Record<string, unknown>>();
const fake: Fake = { rows, posts: 0, gets: 0 };
const fake: Fake = { rows, posts: 0, gets: 0, appends: 0 };
const eq = (sp: URLSearchParams, k: string): string | null => {
const v = sp.get(k);
return v && v.startsWith("eq.") ? v.slice(3) : null;
};
setSessionFetch((async (input: unknown, init: RequestInit = {}) => {
const url = new URL(String(input));
const method = (init.method ?? "GET").toUpperCase();
// Event spine append — a kernel mutation logs one row. Separate endpoint,
// separate counter; returns the RPC's jsonb result.
if (method === "POST" && url.pathname.endsWith("/rpc/append_session_event")) {
fake.appends++;
return new Response(JSON.stringify({ ok: true, id: fake.appends, seq: fake.appends }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
if (method === "POST") {
fake.posts++;
const body = JSON.parse(String(init.body)) as Array<
Expand Down Expand Up @@ -118,8 +130,11 @@ describe("dispatch persist wrapper (end-to-end through createServer)", () => {
const documentId = JSON.parse(firstText(open)).document_id as string;
expect(fake.posts).toBe(1);
expect(fake.rows.has(`user-1|mcp:${documentId}`)).toBe(true);
// A creator is a kernel mutation → exactly one event on the spine.
expect(fake.appends).toBe(1);

const postsAfterOpen = fake.posts;
const appendsAfterOpen = fake.appends;

// Reader: get_document runs in a fresh per-request scope, so it can only
// succeed by hydrating from the durable store — and it must NOT persist.
Expand All @@ -130,6 +145,7 @@ describe("dispatch persist wrapper (end-to-end through createServer)", () => {
expect(JSON.parse(firstText(got)).version).toBeDefined(); // IR round-tripped
expect(fake.gets).toBeGreaterThanOrEqual(1); // hydrate read happened
expect(fake.posts).toBe(postsAfterOpen); // reader did not write
expect(fake.appends).toBe(appendsAfterOpen); // reader emitted no event

await client.close();
await server.close();
Expand All @@ -152,6 +168,8 @@ describe("dispatch persist wrapper (end-to-end through createServer)", () => {
const documentId = JSON.parse(firstText(res)).document_id as string;
expect(fake.posts).toBe(1);
expect(fake.rows.has(`user-2|mcp:${documentId}`)).toBe(true);
// …and the same call logged exactly one kernel event to the spine.
expect(fake.appends).toBe(1);

await client.close();
await server.close();
Expand Down
147 changes: 147 additions & 0 deletions packages/mcp/src/__tests__/live.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { describe, it, expect } from "vitest";
import { appendOverlay, listEvents, OVERLAY_TYPES } from "../tools/live.js";
import type {
SessionEvent,
SessionEventStore,
StoredSessionEvent,
} from "../session-store.js";

class FakeEventStore implements SessionEventStore {
public appended: Array<{ sessionId: string } & SessionEvent> = [];
public lastSince: number | undefined;
private rows: StoredSessionEvent[] = [];
seed(rows: StoredSessionEvent[]): void {
this.rows = rows;
}
async append(sessionId: string, evt: SessionEvent): Promise<void> {
this.appended.push({ sessionId, ...evt });
}
async list(_sessionId: string, sinceSeq?: number): Promise<StoredSessionEvent[]> {
this.lastSince = sinceSeq;
return this.rows;
}
}

const row = (seq: number, over: Partial<StoredSessionEvent> = {}): StoredSessionEvent => ({
id: seq,
seq,
session_id: "doc_x",
author: "agent",
kind: "kernel",
type: "create",
payload: {},
created_at: new Date(0).toISOString(),
...over,
});

describe("appendOverlay", () => {
it("appends a valid pin as a kind:'overlay' event with the anchor payload", async () => {
const es = new FakeEventStore();
const res = await appendOverlay(es, "doc_x", {
type: "pin",
payload: { anchor: { node: 3, face: 1 }, text: "too thin" },
author: "reviewer",
});
expect(res.ok).toBe(true);
expect(es.appended).toHaveLength(1);
const evt = es.appended[0];
expect(evt.kind).toBe("overlay");
expect(evt.type).toBe("pin");
// An untrusted (anonymous) author is namespaced so it can't impersonate.
expect(evt.author).toBe("viewer:reviewer");
expect(evt.payload).toEqual({ anchor: { node: 3, face: 1 }, text: "too thin" });
});

it("namespaces an anonymous author as viewer:<name> and caps it", async () => {
const es = new FakeEventStore();
await appendOverlay(es, "doc_x", { type: "flag", payload: {} });
expect(es.appended[0].author).toBe("viewer:anon");

const es2 = new FakeEventStore();
await appendOverlay(es2, "doc_x", { type: "note", payload: {}, author: "x".repeat(200) });
expect(es2.appended[0].author).toBe("viewer:" + "x".repeat(48));
});

it("never lets an anonymous author impersonate a reserved identity", async () => {
const es = new FakeEventStore();
await appendOverlay(es, "doc_x", { type: "pin", payload: {}, author: "agent" });
expect(es.appended[0].author).toBe("viewer:agent"); // not the reserved "agent"
});

it("uses the verified identity authoritatively, ignoring a forged body author", async () => {
const es = new FakeEventStore();
await appendOverlay(
es,
"doc_x",
{ type: "pin", payload: {}, author: "victim@x.z" },
{ trustedAuthor: "alice@x.z" },
);
expect(es.appended[0].author).toBe("alice@x.z");
});

it("rejects an oversized payload (no spine bloat / broadcast amplification)", async () => {
const es = new FakeEventStore();
const res = await appendOverlay(es, "doc_x", {
type: "pin",
payload: { blob: "x".repeat(5000) },
});
expect(res.ok).toBe(false);
if (!res.ok) expect(res.error).toContain("too large");
expect(es.appended).toHaveLength(0);
});

it("rejects an unknown overlay type (never reaches the store)", async () => {
const es = new FakeEventStore();
const res = await appendOverlay(es, "doc_x", { type: "mutation", payload: {} });
expect(res.ok).toBe(false);
expect(es.appended).toHaveLength(0);
});

it("rejects a missing session id", async () => {
const es = new FakeEventStore();
const res = await appendOverlay(es, "", { type: "pin", payload: {} });
expect(res.ok).toBe(false);
});

it("tolerates a non-object payload", async () => {
const es = new FakeEventStore();
await appendOverlay(es, "doc_x", { type: "pin", payload: "oops" as unknown });
expect(es.appended[0].payload).toEqual({});
});

it("accepts every declared overlay type", async () => {
for (const t of OVERLAY_TYPES) {
const es = new FakeEventStore();
const res = await appendOverlay(es, "doc_x", { type: t, payload: {} });
expect(res.ok).toBe(true);
}
});
});

describe("listEvents", () => {
it("returns all events in seq order", async () => {
const es = new FakeEventStore();
es.seed([row(1), row(2), row(3)]);
const out = await listEvents(es, "doc_x");
expect(out.map((e) => e.seq)).toEqual([1, 2, 3]);
});

it("returns only events after sinceSeq (late-join catch-up)", async () => {
const es = new FakeEventStore();
es.seed([row(1), row(2), row(3), row(4)]);
const out = await listEvents(es, "doc_x", 2);
expect(out.map((e) => e.seq)).toEqual([3, 4]);
});

it("pushes sinceSeq down to the store (server-side filter)", async () => {
const es = new FakeEventStore();
es.seed([row(3), row(4)]);
await listEvents(es, "doc_x", 2);
expect(es.lastSince).toBe(2);
});

it("returns [] for a missing session id", async () => {
const es = new FakeEventStore();
expect(await listEvents(es, "")).toEqual([]);
});
});
Loading
Loading