Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(ts-sdk): initialize sessions before raw tool calls

Samir Hanna Verza8e121e5f792c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e65cba04..3ce39a85 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,9 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- Initialized the TypeScript SDK's MCP session before the first `callTool`,
+ fixing HTTP 422 responses with `--http-stateful`. Raw calls still skip
+ schema checks, and later wrapped calls reuse the session (#PR).
- Refused empty and whitespace-only `--workspace` and `--project` flags at the
shared CLI scope-resolution choke point (`resolve_scope`,
`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, and
diff --git a/companions/ai-memory-ts/CHANGELOG.md b/companions/ai-memory-ts/CHANGELOG.md
index 246da631..43baf6a9 100644
--- a/companions/ai-memory-ts/CHANGELOG.md
+++ b/companions/ai-memory-ts/CHANGELOG.md
@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Initialized the MCP session before the first `callTool`, so raw tool calls
+ work with `--http-stateful` without a preceding wrapped call. Raw calls
+ still skip `tools/list` and schema checks. (#PR)
+
### Added
- `query` takes the server's `memory_query` page filters: `kind`, `tier`,
diff --git a/companions/ai-memory-ts/README.md b/companions/ai-memory-ts/README.md
index ada5d75d..515d7f41 100644
--- a/companions/ai-memory-ts/README.md
+++ b/companions/ai-memory-ts/README.md
@@ -162,7 +162,9 @@ Not wrapped (call them with `callTool`):
<!-- generated:methods:end -->
`callTool(name, args)` calls any tool with wire-format arguments and returns
-its decoded JSON as `unknown`.
+its decoded JSON as `unknown`. It initializes the MCP session when needed,
+without listing tools or checking their schemas. Pass `workspace` and
+`project` yourself.
Root-only lifecycle operations live in a separate entry point, so an
application that only reads and writes pages never imports code that can
@@ -184,8 +186,9 @@ await admin.purgeProject({ workspace: "demo", project: "old", dryRun: false, con
|---|---|---|
| 0.1.x | 3.0.0 or newer | 22 or newer |
-The first wrapped call probes the server once (`initialize` and
-`tools/list`). A call the server cannot honour, such as a conditional write
+The first MCP tool call initializes the client, including `callTool`. The
+first wrapped call also probes `tools/list`; both results are cached. A call
+the server cannot honour, such as a conditional write
on a server older than 3.0.0, fails with `UnsupportedServerError` before
anything is written. Details in [docs/compatibility.md](docs/compatibility.md).
diff --git a/companions/ai-memory-ts/src/capabilities.ts b/companions/ai-memory-ts/src/capabilities.ts
index b228af81..f60f2f72 100644
--- a/companions/ai-memory-ts/src/capabilities.ts
+++ b/companions/ai-memory-ts/src/capabilities.ts
@@ -83,8 +83,11 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
-/** Run `initialize` (plus `notifications/initialized` when stateful) and `tools/list`. @internal */
-export async function probeTools(transport: Transport, options?: CallOptions): Promise<ToolIndex> {
+/** The handshake result, shared by raw and wrapped tool calls. @internal */
+export type SessionInfo = Omit<ToolIndex, "tools">;
+
+/** Run `initialize` plus `notifications/initialized` when stateful. @internal */
+export async function initialize(transport: Transport, options?: CallOptions): Promise<SessionInfo> {
transport.resetSession();
const newest = SUPPORTED_PROTOCOL_VERSIONS[0] ?? "2024-11-05";
const { result, headers } = await transport.rpcWithHeaders(
@@ -112,7 +115,19 @@ export async function probeTools(transport: Transport, options?: CallOptions): P
}
const statefulSession = transport.adoptSession(headers);
if (statefulSession) await transport.notify("notifications/initialized", options);
+ return {
+ server: { name: transport.safeText(server.name), version: transport.safeText(server.version) },
+ protocolVersion,
+ statefulSession,
+ };
+}
+/** List schemas after the shared handshake. @internal */
+export async function probeTools(
+ transport: Transport,
+ session: SessionInfo,
+ options?: CallOptions,
+): Promise<ToolIndex> {
const listed = await transport.rpc("tools/list", {}, false, options);
const rawTools = listed["tools"];
if (!Array.isArray(rawTools)) throw new ProtocolError("tools/list answered without tools");
@@ -124,12 +139,7 @@ export async function probeTools(transport: Transport, options?: CallOptions): P
isRecord(schema) && isRecord(schema["properties"]) ? Object.keys(schema["properties"]) : [];
tools[tool["name"]] = { properties };
}
- return {
- server: { name: transport.safeText(server.name), version: transport.safeText(server.version) },
- protocolVersion,
- statefulSession,
- tools,
- };
+ return { ...session, tools };
}
/**
diff --git a/companions/ai-memory-ts/src/client.ts b/companions/ai-memory-ts/src/client.ts
index 65bea6ce..91c953aa 100644
--- a/companions/ai-memory-ts/src/client.ts
+++ b/companions/ai-memory-ts/src/client.ts
@@ -895,7 +895,8 @@ export class AiMemoryClient {
* Call any MCP tool by name with wire-format arguments and return its
* decoded JSON as `unknown`. No feature checks and no scope handling:
* pass `workspace` and `project` yourself. For tools without a wrapper
- * and for servers newer than the SDK.
+ * and for servers newer than the SDK. Initializes the MCP session without
+ * listing tools.
*/
async callTool(
name: string,
diff --git a/companions/ai-memory-ts/src/core.ts b/companions/ai-memory-ts/src/core.ts
index b793cceb..9a9dedcc 100644
--- a/companions/ai-memory-ts/src/core.ts
+++ b/companions/ai-memory-ts/src/core.ts
@@ -6,7 +6,13 @@
* @module
*/
-import { probeTools, requireFeature, type ToolIndex } from "./capabilities.js";
+import {
+ initialize,
+ probeTools,
+ requireFeature,
+ type SessionInfo,
+ type ToolIndex,
+} from "./capabilities.js";
import { ArgumentError, ProtocolError, ToolError } from "./errors.js";
import { resolveScope, type Scope } from "./scope.js";
import type { CallOptions, Transport } from "./transport.js";
@@ -52,6 +58,7 @@ function firstText(content: unknown): string | undefined {
export class Core {
readonly transport: Transport;
readonly defaultScope: Scope | undefined;
+ #session: Promise<SessionInfo> | undefined;
#index: Promise<ToolIndex> | undefined;
constructor(transport: Transport, defaultScope: Scope | undefined) {
@@ -64,21 +71,36 @@ export class Core {
return resolveScope(callScope, this.defaultScope, where);
}
+ /** The handshake is needed even by calls that skip schema checks. */
+ #initialize(options?: CallOptions): Promise<SessionInfo> {
+ if (this.#session === undefined) {
+ const session = initialize(this.transport, options);
+ this.#session = session;
+ session.catch(() => {
+ if (this.#session === session) this.#session = undefined;
+ });
+ }
+ return this.#session;
+ }
+
/** `initialize` + `tools/list`, probed once per client and cached. */
toolIndex(options?: CallOptions): Promise<ToolIndex> {
if (this.#index === undefined) {
- const probe = probeTools(this.transport, options);
+ const probe = this.#initialize(options).then((session) =>
+ probeTools(this.transport, session, options),
+ );
this.#index = probe;
// A failed probe is not cached: the next call probes again.
probe.catch(() => {
- if (this.#index === probe) this.#index = undefined;
+ if (this.#index === probe) this.forgetToolIndex();
});
}
return this.#index;
}
- /** Drop the cached tool index. */
+ /** Drop the handshake and tool index so refresh opens a new session. */
forgetToolIndex(): void {
+ this.#session = undefined;
this.#index = undefined;
}
@@ -104,6 +126,7 @@ export class Core {
mutating: boolean,
options?: CallOptions,
): Promise<unknown> {
+ await this.#initialize(options);
const result = await this.transport.rpc(
"tools/call",
{ name: tool, arguments: args },
diff --git a/companions/ai-memory-ts/test/integration/reads.test.ts b/companions/ai-memory-ts/test/integration/reads.test.ts
index f924b550..90f9358c 100644
--- a/companions/ai-memory-ts/test/integration/reads.test.ts
+++ b/companions/ai-memory-ts/test/integration/reads.test.ts
@@ -146,6 +146,41 @@ describe("api namespace", () => {
});
describe("servers in other modes", () => {
+ it("callTool works as the first MCP call in stateless and stateful modes", async () => {
+ for (const stateful of [true, false]) {
+ const fresh = await startServer({ stateful, basePath: "/wiki" });
+ try {
+ const methods: string[] = [];
+ const client = new AiMemoryClient({
+ serverUrl: fresh.url,
+ token: fresh.rootToken,
+ scope,
+ fetch: async (url, init) => {
+ const body = JSON.parse(init.body as string) as { method: string };
+ methods.push(body.method);
+ return fetch(url, init);
+ },
+ });
+ await client.callTool("memory_write_page", {
+ ...scope,
+ path: "notes/raw-first.md",
+ body: "# Raw first\ncreated through callTool",
+ });
+ assert.deepEqual(
+ methods,
+ stateful
+ ? ["initialize", "notifications/initialized", "tools/call"]
+ : ["initialize", "tools/call"],
+ );
+ assert.equal((await client.pages.read({ path: "notes/raw-first.md" })).title, "Raw first");
+ assert.equal(methods.filter((method) => method === "initialize").length, 1);
+ assert.equal(methods.filter((method) => method === "tools/list").length, 1);
+ } finally {
+ await fresh.stop();
+ }
+ }
+ });
+
it("every /api/v1 route is NotFoundError without --enable-api", async () => {
const bare = await startServer({ api: false });
try {
diff --git a/companions/ai-memory-ts/test/unit/client.test.ts b/companions/ai-memory-ts/test/unit/client.test.ts
index 185f4eed..f63a0fbf 100644
--- a/companions/ai-memory-ts/test/unit/client.test.ts
+++ b/companions/ai-memory-ts/test/unit/client.test.ts
@@ -492,13 +492,14 @@ describe("capability gating", () => {
assert.equal(caps.identity, null);
});
- it("callTool skips probing and returns the decoded JSON", async () => {
+ it("callTool initializes without schema probing and returns the decoded JSON", async () => {
const { server, memory } = setup();
+ delete server.schemas["memory_lint"];
server.tools.set("memory_lint", () => ({ report: "ok" }));
assert.deepEqual(await memory.callTool("memory_lint", { dry_run: true }), { report: "ok" });
assert.deepEqual(
server.requests.map((r) => (r.body as { method: string }).method),
- ["tools/call"],
+ ["initialize", "tools/call"],
);
});
});
diff --git a/companions/ai-memory-ts/test/unit/transport.test.ts b/companions/ai-memory-ts/test/unit/transport.test.ts
index 81010dd0..43dce87a 100644
--- a/companions/ai-memory-ts/test/unit/transport.test.ts
+++ b/companions/ai-memory-ts/test/unit/transport.test.ts
@@ -62,42 +62,47 @@ describe("JSON-RPC response parsing", () => {
it("raises ProtocolError when the body holds no JSON-RPC message", async () => {
const server = new FakeServer();
- server.mcp = async () => text("event: ping\n\n", 200, { "content-type": "text/event-stream" });
+ server.tools.set("memory_status", () =>
+ text("event: ping\n\n", 200, { "content-type": "text/event-stream" }),
+ );
await assert.rejects(client(server).callTool("memory_status", {}), ProtocolError);
});
it("decodes an SSE answer to a tool call", async () => {
const server = new FakeServer();
- server.mcp = async (request) => {
+ server.tools.set("memory_status", (_args, request) => {
const id = (request.body as { id: number }).id;
const result = { content: [{ type: "text", text: '{"a":1}' }], isError: false };
return text(`data: \n\ndata: ${JSON.stringify({ jsonrpc: "2.0", id, result })}\n\n`, 200, {
"content-type": "text/event-stream",
});
- };
+ });
assert.deepEqual(await client(server).callTool("memory_status", {}), { a: 1 });
});
it("refuses an answer to a different request id", async () => {
const server = new FakeServer();
- server.mcp = async () => json({ jsonrpc: "2.0", id: 999, result: {} });
+ server.tools.set("memory_status", () => json({ jsonrpc: "2.0", id: 999, result: {} }));
await assert.rejects(client(server).callTool("memory_status", {}), ProtocolError);
});
it("raises ProtocolError for a result with no result member", async () => {
const server = new FakeServer();
- server.mcp = async (r) => json({ jsonrpc: "2.0", id: (r.body as { id: number }).id });
+ server.tools.set("memory_status", (_args, r) =>
+ json({ jsonrpc: "2.0", id: (r.body as { id: number }).id }),
+ );
await assert.rejects(client(server).callTool("memory_status", {}), ProtocolError);
});
it("raises ProtocolError when the tool text is not JSON", async () => {
const server = new FakeServer();
- server.mcp = async (r) =>
+ server.tools.set("memory_status", (_args, r) =>
json({
jsonrpc: "2.0",
id: (r.body as { id: number }).id,
result: { content: [{ type: "text", text: "plain words" }] },
- });
+ }),
+ );
await assert.rejects(client(server).callTool("memory_status", {}), ProtocolError);
});
@@ -123,7 +128,7 @@ describe("error taxonomy", () => {
];
for (const [status, expected] of cases) {
const server = new FakeServer();
- server.mcp = async () => json({ error: `status ${status}` }, status);
+ server.tools.set("memory_status", () => json({ error: `status ${status}` }, status));
await assert.rejects(client(server).callTool("memory_status", {}), (error: unknown) => {
assert.ok(error instanceof expected, `status ${status}`);
assert.equal((error as HttpError).status, status);
@@ -178,12 +183,13 @@ describe("error taxonomy", () => {
it("raises ToolError for result.isError", async () => {
const server = new FakeServer();
- server.mcp = async (r) =>
+ server.tools.set("memory_status", (_args, r) =>
json({
jsonrpc: "2.0",
id: (r.body as { id: number }).id,
result: { content: [{ type: "text", text: "tool blew up" }], isError: true },
- });
+ }),
+ );
await assert.rejects(client(server).callTool("memory_status", {}), (error: unknown) => {
assert.ok(error instanceof ToolError);
assert.equal(error.detail, "tool blew up");
@@ -266,7 +272,7 @@ describe("timeouts and aborts", () => {
describe("response bounds", () => {
it("refuses a body over maxResponseBytes", async () => {
const server = new FakeServer();
- server.mcp = async () => text("x".repeat(4096));
+ server.tools.set("memory_status", () => text("x".repeat(4096)));
await assert.rejects(
client(server, { maxResponseBytes: 1024 }).callTool("memory_status", {}),
ProtocolError,
@@ -282,6 +288,54 @@ describe("response bounds", () => {
});
describe("stateful sessions", () => {
+ it("raw and wrapped calls share one handshake and refresh opens a new session", async () => {
+ const server = new FakeServer();
+ server.sessionId = "session-raw";
+ server.tools.set("memory_status", () => payloads.status);
+ server.tools.set("memory_lint", () => ({ report: "ok" }));
+ const memory = client(server);
+ await Promise.all([
+ memory.callTool("memory_lint", { dry_run: true }),
+ memory.status(),
+ ]);
+ const count = (method: string) =>
+ server.requests.filter(
+ (r) => (r.body as { method?: string } | undefined)?.method === method,
+ ).length;
+ assert.equal(count("initialize"), 1);
+ assert.equal(count("notifications/initialized"), 1);
+ assert.equal(count("tools/list"), 1);
+ for (const request of server.requests.slice(1)) {
+ assert.equal(request.headers["mcp-session-id"], "session-raw");
+ }
+
+ server.sessionId = "session-refreshed";
+ await memory.capabilities({ refresh: true });
+ await memory.callTool("memory_lint", { dry_run: true });
+ assert.equal(count("initialize"), 2);
+ assert.equal(count("notifications/initialized"), 2);
+ assert.equal(server.requests.at(-1)?.headers["mcp-session-id"], "session-refreshed");
+ });
+
+ it("a failed handshake sends no raw mutation and a later call can initialize", async () => {
+ const server = new FakeServer();
+ server.sessionId = "session-recovered";
+ server.tools.set("memory_lint", () => ({ report: "ok" }));
+ server.mcp = async () => json({ error: "unavailable" }, 503);
+ const memory = client(server);
+ await assert.rejects(memory.callTool("memory_lint", {}), HttpError);
+ assert.equal(server.requests.length, 1, "no automatic retry or mutation after failure");
+ assert.equal(server.toolCalls().length, 0);
+
+ server.mcp = undefined;
+ assert.deepEqual(await memory.callTool("memory_lint", {}), { report: "ok" });
+ assert.deepEqual(
+ server.requests.map((r) => (r.body as { method: string }).method),
+ ["initialize", "initialize", "notifications/initialized", "tools/call"],
+ );
+ assert.equal(server.requests.at(-1)?.headers["mcp-session-id"], "session-recovered");
+ });
+
it("keeps Mcp-Session-Id, sends notifications/initialized and attaches it", async () => {
const server = new FakeServer();
server.sessionId = "session-123";