@mnemoverse/mcp-memory-server 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.js ADDED
@@ -0,0 +1,1915 @@
1
+ /**
2
+ * The ten memory tools, as one function any MCP server can register.
3
+ *
4
+ * ADR-025 (mnemoverse-core): this package defines the MCP surface, and every
5
+ * server that exposes Mnemoverse memory over MCP registers the SAME tools from
6
+ * here instead of keeping its own copy. The stdio server in src/index.ts is one
7
+ * such server; the hosted connector (mnemoverse-mcp-remote) is the other.
8
+ *
9
+ * What differs between servers is only how a request reaches the API: which
10
+ * credential it carries, where it goes, and how a transport failure is worded.
11
+ * That is `MemoryToolDeps.apiFetch`. Nothing in this file reads configuration
12
+ * or the environment.
13
+ */
14
+ import { z } from "zod";
15
+ import { CURSOR_RE, formatReadItem, formatRecentPage, safeInline, structuredItem, } from "./render.js";
16
+ // `NO_MATCH_MESSAGE` is no longer imported here: this file used to pick between
17
+ // it and buildReadEmptyResponse by testing a note string for truthiness, which
18
+ // is how "we could not check" came to be spelled like "the store is there".
19
+ // Assembling the whole answer belongs in one place — src/teaching.ts.
20
+ import { buildReadEmptyResponse } from "./teaching.js";
21
+ import { classifyRooms, futureSinceNote, probeReadScope, readScopeNote, scopeLabel, } from "./scope.js";
22
+ import { readRequestBody, recentRequestBody, writeRequestBody, searchedScope, } from "./requests.js";
23
+ import { exactLiteral, formatDomainList, roomNamePhrase, structuredText, withDomainEscapeLegend, } from "./names.js";
24
+ import { ApiError } from "./errors.js";
25
+ // Field limits, generated from core's contract (src/limits.ts, ADR-025).
26
+ import { CORE_LIMITS } from "./limits.js";
27
+ // Hard cap on tool result size — required by Claude Connectors Directory
28
+ // (https://support.claude.com/en/articles/12922490-remote-mcp-server-submission-guide).
29
+ // Approximate token count = chars / 4. Cap at 24,000 tokens to leave headroom under the 25K limit.
30
+ const MAX_RESULT_CHARS = 24_000 * 4;
31
+ /**
32
+ * Truncate a result string to MAX_RESULT_CHARS, appending a notice if truncated.
33
+ * Required by Claude Connectors Directory submission policy.
34
+ *
35
+ * Defensive against splitting UTF-16 surrogate pairs: if the character right
36
+ * before the cut point is a high surrogate (U+D800–U+DBFF), drop it so the
37
+ * result stays well-formed. Otherwise an emoji or non-BMP character at the
38
+ * boundary can produce a lone surrogate and corrupt downstream JSON encoding.
39
+ */
40
+ function capResult(text,
41
+ // The default recommends ONLY the control that works. A previous draft also
42
+ // said "or smaller top_k" — but top_k is not a hard cap (association
43
+ // expansion can return more, the relevance floor fewer; the same query at
44
+ // 1/5/20 returned 6/7/4 items), which this release's own top_k description
45
+ // already admits. One surface must not recommend the knob another refutes.
46
+ moreHint = "Use a more specific query to see all results.") {
47
+ if (text.length <= MAX_RESULT_CHARS)
48
+ return text;
49
+ let truncated = text.slice(0, MAX_RESULT_CHARS - 200);
50
+ const lastCode = truncated.charCodeAt(truncated.length - 1);
51
+ if (lastCode >= 0xd800 && lastCode <= 0xdbff) {
52
+ truncated = truncated.slice(0, -1);
53
+ }
54
+ // `moreHint` lets no-input tools (the discovery lists) give accurate truncation
55
+ // guidance instead of the read-tool default (which points at a query control a
56
+ // repeated no-arg call cannot use). Existing callers keep the default message.
57
+ return `${truncated}\n\n[…truncated to fit the 25K token limit. ${moreHint}]`;
58
+ }
59
+ /**
60
+ * A 2xx whose body does not carry what core always sends for this operation.
61
+ *
62
+ * Reading such a body as an EMPTY list is the substitution this release exists
63
+ * to remove: `Array.isArray(x) ? x : []` turned "this client could not read
64
+ * the response" into "there is nothing there" — an absence claim on zero
65
+ * evidence. `classifyRooms` (src/scope.ts) and the stats domains guard closed
66
+ * it for rooms and domains; this builder is the same answer for the remaining
67
+ * list surfaces (search results, the feed, the vault), phrased the way the
68
+ * room list already phrases it. The three parts are the subject, what the body
69
+ * is NOT ("a list of your rooms"), and the absence it is NOT evidence of
70
+ * ("you have none") — so every consumer states its own boundary while the
71
+ * sentence stays one sentence everywhere (truth F13, 2026-08-08).
72
+ *
73
+ * NOT ONLY LISTS any more: memory_write was the last surface still reading
74
+ * a missing field as a stated one — `if (r?.stored)`, whose else-branch was an
75
+ * unconditional "NOT STORED — nothing was saved" plus a mechanism nobody sent.
76
+ * It is the same class of claim about a different shape, so it gets the same
77
+ * sentence, and the name no longer says "List".
78
+ *
79
+ * `extra` exists for the write surface alone: a list that could not be read
80
+ * leaves the caller merely uninformed, whereas a WRITE that could not be read
81
+ * leaves an operation whose outcome is unknown, and the caller must be told not
82
+ * to report either outcome to the user.
83
+ *
84
+ * Carries `isError: true`, not a text-only success. Once a tool declares an
85
+ * `outputSchema`, the SDK's `validateToolOutput` (see the comment on
86
+ * `structured()` below) rejects a non-error result that has no
87
+ * `structuredContent`, and there is no honest `structuredContent` for "this
88
+ * client could not read the body": an empty shape such as `{items: []}` would
89
+ * make exactly the absence claim this sentence exists to avoid. `isError` is
90
+ * the one shape the SDK exempts from that check, so it is the shape this
91
+ * reply must take (pinned against the installed SDK in
92
+ * test/structured-output.test.ts).
93
+ */
94
+ function unreadableAnswerReply(subject, notA, absence, extra = "") {
95
+ return {
96
+ content: [
97
+ {
98
+ type: "text",
99
+ text: unreadableAnswerText(subject, notA, absence, extra),
100
+ },
101
+ ],
102
+ isError: true,
103
+ };
104
+ }
105
+ /**
106
+ * The sentence behind {@link unreadableAnswerReply}, exported so the memory
107
+ * resource (src/resources.ts) says the same thing about an unreadable answer
108
+ * rather than keeping its own copy.
109
+ *
110
+ * The tail attributes the unreadable 200 to "whatever answered this call", not
111
+ * to "the memory service" — this client cannot establish WHO answered: a
112
+ * gateway, a proxy, or the endpoint a mis-set MNEMOVERSE_API_URL points at
113
+ * produces the same 200 with an unrecognised body (truth re-verification,
114
+ * 2026-08-09). Pinned in test/handlers.test.ts.
115
+ */
116
+ export function unreadableAnswerText(subject, notA, absence, extra = "") {
117
+ return (`${subject} came back in a shape this client does not recognise — so this ` +
118
+ `is not ${notA}, and it is not evidence that ${absence}.${extra} Retry; ` +
119
+ `if it persists, whatever answered this call — the memory service, a ` +
120
+ `gateway or proxy in front of it, or the endpoint a mis-set ` +
121
+ `MNEMOVERSE_API_URL points at — is answering in a shape this client ` +
122
+ `cannot read.`);
123
+ }
124
+ /**
125
+ * A success result carrying both a text block and `structuredContent`, which
126
+ * is what a tool with a declared `outputSchema` must return, or the SDK
127
+ * itself rejects the call. `validateToolOutput` in the installed SDK
128
+ * (node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js:185-207)
129
+ * turns a non-error, text-only result into an `isError` "Output validation
130
+ * error: … has an output schema but no structured content was provided", the
131
+ * moment a tool declares that schema, even though the same text alone was a
132
+ * fine answer the day before the schema was added. Pinned against that
133
+ * installed SDK in test/structured-output.test.ts.
134
+ *
135
+ * Deliberately dumb: it does not call `capResult` or `withDomainEscapeLegend`
136
+ * itself. Every tool already measures and caps its own text with a per-tool
137
+ * hint and applies the legend after the cap (see memory_read below), so a
138
+ * helper that capped again would double-truncate; callers pass `text`
139
+ * already finished.
140
+ */
141
+ export function structured(text, data) {
142
+ return {
143
+ content: [{ type: "text", text }],
144
+ structuredContent: data,
145
+ };
146
+ }
147
+ /**
148
+ * Two renderers, and which one a value gets is a decision, not a style choice.
149
+ *
150
+ * `safeInline` (src/render.ts) SANITISES an untrusted display string for inline
151
+ * rendering in tool output that a DIFFERENT principal's LLM will read (CN-032
152
+ * anti-injection): strip to a conservative charset, collapse whitespace, cap
153
+ * the length. The treatment `formatAuthorTag` applies to a server-stamped
154
+ * author, and the defensive second pass the machine-shaped room fields
155
+ * (address, room_id, role, scope — all charset-validated or enum-shaped in
156
+ * core) get here. It is lossy on purpose, and everything it still renders is a
157
+ * value the reader looks at and never has to retype or compare.
158
+ *
159
+ * `exactLiteral` / `domainPhrase` / `roomNamePhrase` (src/names.ts) print a
160
+ * value as a JSON string literal, or refuse to print it. Domain names because
161
+ * the engine matches them byte-for-byte, so the reader must be able to send
162
+ * the exact bytes back. Room NAMES (0.8.1) because the sanitiser did not make
163
+ * them harmless so much as it made them WRONG: "проект" echoed back as `""` on
164
+ * create, "Zoë" as "Zo" inside quotes that claim to be the name. The literal
165
+ * is one line with quotes, backslashes and invisibles escaped, so it is as
166
+ * injection-safe as the sanitised spelling was — without the renaming.
167
+ */
168
+ /**
169
+ * True for a shared-room address (`xroom:<room_id>`).
170
+ *
171
+ * Mirrors core's own predicate (`memory_engine._is_room_domain`), which is a
172
+ * plain prefix test — deliberately, so a padded or otherwise non-canonical
173
+ * address does NOT normalise into a room. Byte-for-byte, no trimming: this
174
+ * file's write handler documents at length why trimming a domain here once
175
+ * nearly wrote into a room visible to other accounts.
176
+ *
177
+ * Used only to choose which TRUE sentence to print about a refusal. It never
178
+ * changes what is sent, so a wrong answer here misinforms and cannot misroute.
179
+ */
180
+ function isRoomDomain(domain) {
181
+ return typeof domain === "string" && domain.startsWith("xroom:");
182
+ }
183
+ /**
184
+ * The three outcomes this client will ever print a WRITE promise about for a
185
+ * room membership. Core grants exactly two scopes — "read" and "read_write"
186
+ * (rooms_routes.py `_VALID_SCOPES`) — and refuses a read-only member's
187
+ * memory_write with a 403 "Read-only membership cannot write to this room"
188
+ * (src/errors.ts). Anything else on the wire (missing field, a Copilot-shaped
189
+ * partial body) is UNSPECIFIED: the server did not say what memory_write would
190
+ * do for this membership, so this client does not guess either — it is treated
191
+ * like "read" for the purpose of NOT promising write, but is not told it is
192
+ * read-only, because that is also a claim the response did not make.
193
+ *
194
+ * Bug hunt (pre-0.9.2, P2): memory_join_room's usage sentence and
195
+ * memory_list_rooms's per-row tail both used to print "use domain=... [on
196
+ * memory_write / memory_read] to read and write" unconditionally — true for a
197
+ * read_write membership, false for a read-only one.
198
+ */
199
+ function roomScopeVerdict(scope) {
200
+ if (scope === "read_write")
201
+ return "read_write";
202
+ if (scope === "read")
203
+ return "read";
204
+ return "unspecified";
205
+ }
206
+ /**
207
+ * How long a HONESTY PROBE may take before the answer goes out without it (#73).
208
+ *
209
+ * The probes are a courtesy: they let a zero-result answer say what it did NOT
210
+ * cover. They are not the answer. Without a deadline they inherit undici's
211
+ * default (~300s), so one slow engine endpoint turns an empty read — which
212
+ * 0.8.0 answered instantly, having probed nothing — into a multi-minute stall.
213
+ * `probeReadScope` already treats a failed probe as "unknown" and says so, so
214
+ * an abort degrades into the honest fallback rather than an error.
215
+ *
216
+ * 4s is chosen against measured production latency: `/memory/read` averaged
217
+ * 1,330 ms with a 10.2 s maximum (core observability, 2026-08), and these two
218
+ * are cheaper GETs. Long enough not to fire on a normal slow day, short enough
219
+ * that a hung endpoint costs seconds instead of minutes.
220
+ */
221
+ const PROBE_TIMEOUT_MS = 4000;
222
+ /**
223
+ * The memory-item shape shared by memory_read's `outputSchema` and
224
+ * memory_list_recent's (S5, structured-output plan): copied from the
225
+ * connector's `memoryItemOutput` (mnemoverse-mcp-remote, src/tools/index.ts),
226
+ * field for field and description for description, with the SAME ONE
227
+ * deliberate difference memory_write's outputSchema already carries:
228
+ * `memory_id` here is `z.string()`, not `z.guid()` (decision OD-7, owner,
229
+ * 2026-09-22). This package's ids are opaque strings, and nothing in the
230
+ * contract promises they are UUIDs; a guid validator would turn any future
231
+ * id-format change into a whole-page "Output validation error" instead of a
232
+ * value this client simply could not shape-check further.
233
+ *
234
+ * A raw shape, not a `z.object(...)`, so both tools can build their own
235
+ * object around it (`z.object(MEMORY_ITEM_OUTPUT)`) without importing a
236
+ * schema instance neither owns, so memory_read's emitted JSON schema
237
+ * stays byte-identical to what it was before this constant existed
238
+ * (test/read-structured.test.ts pins it unchanged).
239
+ */
240
+ const MEMORY_ITEM_OUTPUT = {
241
+ memory_id: z.string().describe("Identifier needed to rate or manage this saved memory."),
242
+ content: z.string().describe("Stored memory content."),
243
+ domain: z.string().describe("User-defined memory namespace or domain."),
244
+ created_at: z
245
+ .string()
246
+ .optional()
247
+ .describe("UTC creation instant, ISO-8601; absent on legacy memories without a timestamp."),
248
+ author: z
249
+ .string()
250
+ .optional()
251
+ .describe("Sanitized AGENT identity of the writer (never the human principal) — attribution in shared rooms."),
252
+ };
253
+ /**
254
+ * Register the ten memory tools on `server`. Call once per server instance.
255
+ * `deps.apiFetch` is the only way the tools reach the API.
256
+ */
257
+ export function registerMemoryTools(server, deps) {
258
+ const { apiFetch } = deps;
259
+ // ANNOTATIONS, decided once for every server that registers these tools
260
+ // (owner, 2026-09-21; the stdio server and the hosted connector had answered
261
+ // both opposite ways):
262
+ // - openWorldHint is false on all ten. Every tool works on the user's own
263
+ // memory store and reaches nothing else; that the store sits behind an API
264
+ // does not make it an open world.
265
+ // - destructiveHint is true only for a tool that deletes. None of these ten
266
+ // does. Rating a memory moves its ranking signals and never alters or
267
+ // erases what was saved (see memory_feedback).
268
+ /**
269
+ * What we know about the scope this read actually covered — a VALUE rather
270
+ * than a sentence-or-empty-string. Costs one GET (rooms or stats, chosen by
271
+ * the scope) and runs on zero-result paths only — but it is not that path's
272
+ * only probe: the plain unscoped empty read also hands buildReadEmptyResponse
273
+ * a stats call for the first-contact greeting, so that answer makes two
274
+ * probes where 0.8.0 made one, and the scoped/filtered answers make one where
275
+ * 0.8.0 made none. Disclosed in the 0.8.1 CHANGELOG entry.
276
+ *
277
+ * This replaces `domainMissNote`, whose `catch { return ""; }` made three
278
+ * different states share one spelling: the store is there and the query missed,
279
+ * the room is there and the query missed, and the probe failed. The caller then
280
+ * read that string as a boolean, so "we could not check" was rendered exactly
281
+ * like "the store exists" — the collision this release is about, at the point
282
+ * where the whole scoped path converges. The states are now arms of a union
283
+ * (src/scope.ts) and every consumer must answer for each of them.
284
+ *
285
+ * The probe routing lives in src/scope.ts: a room address is checked against the
286
+ * ROOM list and a domain against `/memory/stats`, because stats never contains a
287
+ * room address (CodeRabbit #65). `searched` is the RAW value that went over the
288
+ * wire, so the diagnosis can never describe a different store than the request.
289
+ */
290
+ function probeScope(searched) {
291
+ return probeReadScope(searched, () => apiFetch("/memory/stats", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) }), () => apiFetch("/memory/rooms", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) }), safeInline);
292
+ }
293
+ // --- Tool: memory_write ---
294
+ server.registerTool("memory_write", {
295
+ description: "Store a long-term memory that persists across sessions AND across every AI tool the user has connected to Mnemoverse (Claude, ChatGPT, Cursor, VS Code) — write once, recall everywhere. Call this PROACTIVELY the moment the user states a preference, makes a decision, or you learn a durable fact (people, roles, project setup, a lesson). Don't wait to be asked. Never store passwords, API keys, payment data, MFA codes, government IDs, or health records; skip transient chatter that only matters this turn. Behavior: an importance gate may filter low-value writes, so the result tells you whether the memory was stored or filtered. Write `content` as a self-contained statement that still makes sense when recalled out of context.",
296
+ inputSchema: {
297
+ content: z
298
+ .string()
299
+ .min(CORE_LIMITS.writeContent.minLength)
300
+ .max(CORE_LIMITS.writeContent.maxLength)
301
+ .describe("The memory to store as a self-contained statement, e.g. 'User prefers TypeScript strict mode' or 'Decided to deploy the API on Cloudflare Workers (2026-06)'."),
302
+ concepts: z
303
+ .array(z.string())
304
+ .max(CORE_LIMITS.writeConcepts.maxItems)
305
+ .optional()
306
+ .describe("Key concepts for linking related memories (e.g. ['deploy', 'friday', 'staging'])"),
307
+ // The only domain the contract bounds is this one: core's write
308
+ // schema caps it at 100 characters, and a longer one is refused there.
309
+ // Read, list_recent and feedback have no limit in the contract, so
310
+ // none is invented for them here (src/limits.ts, ADR-025).
311
+ domain: z
312
+ .string()
313
+ .max(CORE_LIMITS.domain.maxLength)
314
+ .optional()
315
+ .describe("Namespace to organize memories (e.g. 'engineering', 'user:alice', 'project:acme')." +
316
+ " Matched byte-for-byte — a leading space, a different case, or an invisible" +
317
+ " character opens a SEPARATE, permanent store, so reuse an exact name from" +
318
+ " memory_stats rather than retyping one. To write into a shared room, pass its" +
319
+ " address here instead (e.g. 'xroom:room_01ABC'). Find room addresses with" +
320
+ " memory_list_rooms."),
321
+ },
322
+ // Copied from the connector's `memoryWriteOutput` (mnemoverse-mcp-remote,
323
+ // src/tools/index.ts), field for field and description for description,
324
+ // except that `reason`'s description also states the 400-character cap and
325
+ // the normalised-to-empty case (the connector's text promises exact
326
+ // preservation while capping the same way; review, 2026-09-23), and with ONE
327
+ // deliberate difference in a validator: `memory_id` here is `z.string()`, not
328
+ // `z.guid()` (decision OD-7, owner, 2026-09-22). This package's ids are
329
+ // opaque strings, and nothing in the contract promises they are UUIDs;
330
+ // a guid validator would turn any future id-format change into a
331
+ // whole-page "Output validation error" instead of a value this client
332
+ // simply could not shape-check further.
333
+ outputSchema: {
334
+ stored: z
335
+ .boolean()
336
+ .describe("Whether the memory passed the novelty gate and was stored."),
337
+ memory_id: z
338
+ .string()
339
+ .nullable()
340
+ .describe("Identifier of the stored memory, or null when it was not stored."),
341
+ reason: z
342
+ .string()
343
+ .optional()
344
+ .describe("The memory service's own explanation of this outcome, quoted as sent — when stored is false this is the ONLY statement of WHY, e.g. \"Below importance threshold (0.047 < 0.1)\". Ordinary text is preserved exactly; only control, bidi, zero-width, and repeated-whitespace characters are normalized before display, and the value is capped at 400 characters. Absent when the service sent no explanation, or when nothing remains after that normalization."),
345
+ importance: z
346
+ .number()
347
+ .optional()
348
+ .describe("Novelty score for this write (0-1): how much it adds over the nearest memories already saved in the same domain. A first-generation metric UNDER ACTIVE DEVELOPMENT and known to be unreliable — the same content has measured ~0.08 in Russian against ~0.55 in English, so it under-reads non-English text. It is not a verdict on whether the memory was worth keeping. Absent when the service sent no score."),
349
+ },
350
+ annotations: {
351
+ title: "Store Memory",
352
+ readOnlyHint: false,
353
+ destructiveHint: false,
354
+ idempotentHint: false,
355
+ openWorldHint: false,
356
+ },
357
+ }, async ({ content, concepts, domain }) => {
358
+ // NO NORMALISATION HERE — deliberately, after a review found two ways it
359
+ // breaks (2026-08-08). Trimming looked like an obvious win: domain names
360
+ // are matched byte-for-byte in core, so " engineering" opens a permanent
361
+ // second store beside "engineering". But:
362
+ //
363
+ // 1. Core REJECTS a non-canonical room address on purpose — 400
364
+ // "Non-canonical room address", so a write "can't be mis-routed and
365
+ // tagged with a spoofed xroom domain" in its own words. Trimming
366
+ // " xroom:room_01ABC" normalises past that guard, and the atom lands
367
+ // in the ROOM's store, visible to every member. Content that never
368
+ // left the caller in 0.8.0 would leave the account in 0.8.1. The
369
+ // address in that shape is one our own output hands the model.
370
+ // 2. For a caller who has been padding a domain for months, trimming
371
+ // silently relocates new writes and orphans the old corpus, and (at
372
+ // the time this was written) memory_delete_domain did NOT trim, so
373
+ // the same client could no longer even name the shard it created —
374
+ // that tool was withdrawn to an administrative REST-only operation
375
+ // on 2026-08-20, so this specific consequence no longer applies, but
376
+ // the orphaned-corpus risk from silently relocating writes does.
377
+ //
378
+ // Both are behaviour changes, so they do not belong in a patch whose
379
+ // whole claim is that it only changes wording. Normalisation, if it ever
380
+ // returns, needs room addresses deliberately EXEMPT and zero-width
381
+ // characters handled (JS trim() does not strip them — verified, contrary
382
+ // to what an earlier comment here asserted).
383
+ const r = await apiFetch("/memory/write", {
384
+ method: "POST",
385
+ body: JSON.stringify(writeRequestBody({ content, concepts, domain })),
386
+ });
387
+ // `stored` MUST BE A BOOLEAN before either verdict below may be printed.
388
+ //
389
+ // This was the last surface reading a MISSING field as a field that said
390
+ // false. `if (r?.stored)` sent every body that did not say `true` to the
391
+ // else-branch, whose first four words are "NOT STORED — nothing was saved"
392
+ // and whose last sentence explains WHY: "Writes are gated on how much a
393
+ // memory adds… so a near-duplicate is refused." So a 204, an empty `{}`, a
394
+ // proxy or gateway answering `{"ok":true}`, and a mis-set
395
+ // MNEMOVERSE_API_URL all produced an absence claim about the user's memory
396
+ // AND a fabricated mechanism for it — two statements, neither with any
397
+ // evidence behind it. The write is also the surface where being wrong costs
398
+ // most: a caller told "nothing was saved" re-words and retries, or drops
399
+ // the fact, and the atom that may in fact be sitting in the store is not
400
+ // what the user is told about.
401
+ //
402
+ // The four LIST surfaces have had this guard since 0.8.1 (truth F13); the
403
+ // write did not. The test for `boolean` and not for presence is deliberate:
404
+ // `{"stored":"yes"}` is not core speaking either.
405
+ if (typeof r?.stored !== "boolean") {
406
+ return unreadableAnswerReply("The write result", "confirmation that the memory was stored", "it was refused", " Whether the content reached memory is unknown from here — report the" +
407
+ " outcome of the RETRY, not of this call, and do not tell the user it" +
408
+ " was saved or that it was rejected.");
409
+ }
410
+ // "unknown", not 0.00, when the server didn't send a score — the same rule
411
+ // memory_stats got in this release. A live surface exists that answers
412
+ // {"stored":false} with no reason and no score; printing "0.00" there
413
+ // fabricates the gate's verdict (review, 2026-08-08).
414
+ // A non-finite number is no score either: JSON can carry `1e400`, which
415
+ // parses as Infinity, passes a `typeof` check, prints as "Infinity" and
416
+ // fails the output schema (zod rejects non-finite numbers), so the whole
417
+ // reply would turn into an SDK validation error (review, 2026-09-23).
418
+ const importance = typeof r?.importance === "number" && Number.isFinite(r.importance)
419
+ ? r.importance.toFixed(2)
420
+ : "unknown";
421
+ // `Server reason:` is a VERBATIM label, and safeInline made it a lie on
422
+ // every occurrence: core's only rejection reason is
423
+ // "Below importance threshold (0.412 < 0.500)", whose parentheses and `<`
424
+ // are outside the sanitiser's charset — so the relay read "Below importance
425
+ // threshold 0.412 0.500", with the comparison operator and both delimiters
426
+ // deleted and the two numbers left unlabelled and order-only. Quoted
427
+ // exactly instead (src/names.ts). If it will not fit, say THAT rather than
428
+ // drop the clause: omitting it would report a server that gave no reason.
429
+ const reasonQuote = r?.reason
430
+ ? (exactLiteral(r.reason, 400)?.literal ?? "(too long to quote exactly)")
431
+ : "";
432
+ // Structured twins of the two text-only values above, for
433
+ // `structuredContent`: the raw number instead of the two-decimal
434
+ // string, and the control/bidi/zero-width-normalised text (src/names.ts
435
+ // `structuredText`) instead of the quoted JSON literal `reasonQuote`
436
+ // uses, since a `structuredContent` consumer reads `reason` as a plain
437
+ // string field, not a literal it must decode. Computed once and used on
438
+ // BOTH verdict branches below, since core can send either on a stored
439
+ // write too. Core's `superseded` array (the ids this write replaced) is
440
+ // deliberately not carried in this slice.
441
+ const reasonStructured = structuredText(r.reason, 400);
442
+ const importanceStructured = typeof r.importance === "number" && Number.isFinite(r.importance)
443
+ ? r.importance
444
+ : undefined;
445
+ const optionalStructured = {
446
+ ...(reasonStructured === undefined ? {} : { reason: reasonStructured }),
447
+ ...(importanceStructured === undefined ? {} : { importance: importanceStructured }),
448
+ };
449
+ // Narrowed to `true` by the guard above, so this is now the server's stated
450
+ // verdict rather than "the body was not falsy".
451
+ if (r.stored) {
452
+ // core's WriteResponseSchema carries `atom_id` on every stored write,
453
+ // so a `stored: true` body without one is not core's answer: the
454
+ // same class of unreadable 2xx the guard above catches for a missing
455
+ // `stored`, just discovered one field later. `structuredContent`
456
+ // needs `memory_id` to be a string (the declared outputSchema), and
457
+ // there is no honest value to put there for a write whose own result
458
+ // does not say what was stored.
459
+ if (typeof r.atom_id !== "string") {
460
+ return unreadableAnswerReply("The write result", "confirmation that the memory was stored", "it was refused", " Whether the content reached memory is unknown from here — report the" +
461
+ " outcome of the RETRY, not of this call, and do not tell the user it" +
462
+ " was saved or that it was rejected.");
463
+ }
464
+ return structured(`Stored (importance: ${importance}). ID: ${r.atom_id}`, {
465
+ stored: true,
466
+ memory_id: r.atom_id,
467
+ ...optionalStructured,
468
+ });
469
+ }
470
+ // NOT STORED. The old wording ("Filtered — …") named the mechanism but
471
+ // never the outcome, so a caller could read it as a soft success and move
472
+ // on. In dogfooding this ate a CORRECTION to a wrong fact: the stale
473
+ // version stayed as the only record, and looked more authoritative for
474
+ // having no competitor (2026-08-07).
475
+ //
476
+ // The ADVICE was wrong until 2026-08-08, and wrong in a way that made
477
+ // things worse. It told the caller to rewrite the content as a cleaner
478
+ // factual statement — but the gate scores GEOMETRIC NOVELTY against the
479
+ // nearest existing atom in the same domain, not phrasing or factuality.
480
+ // "Below importance threshold" means TOO SIMILAR TO SOMETHING ALREADY
481
+ // STORED. A rewrite of the same fact therefore produces a near-identical
482
+ // embedding, scores the same or lower, and is rejected again — and the old
483
+ // text ended with "write it again", so a compliant agent looped. It was
484
+ // anti-correlated with the mechanism in exactly the case it was written
485
+ // for: a correction, which is by nature similar to what it corrects.
486
+ // WHAT IS CONDITIONAL HERE, stated exactly, because a previous
487
+ // version of this comment claimed more than the code does.
488
+ //
489
+ // Conditional: the SERVER'S VERDICT and the SCORE. `Server reason:`
490
+ // is printed only when `reason` came back, and `Novelty score` only
491
+ // when a numeric `importance` did — a live surface answers
492
+ // `{"stored":false}` with neither, and quoting a verdict nobody sent
493
+ // would be a claim on zero evidence.
494
+ //
495
+ // Unconditional: the MECHANISM sentence below, and it is not derived
496
+ // from this response. It is a statement about core: `/memory/write`
497
+ // refuses for exactly one reason — the importance gate, scoring
498
+ // geometric novelty against the nearest existing atom in the same
499
+ // domain, with "Below importance threshold (x < y)" as its only text
500
+ // (two branches in memory_engine, one reason). The BATCH endpoint has
501
+ // other failure paths; this client does not call it. So for any
502
+ // rejection this client can receive, that sentence is true whether or
503
+ // not the server bothered to say why. The earlier comment here read
504
+ // "the cause is named only when the server named it", which describes
505
+ // a draft that did not carry this sentence at all.
506
+ //
507
+ // NOT PRESENT AT ALL: a prediction about the retry. "Rewording will
508
+ // score the same or lower" was asserted as fact and is probably
509
+ // BACKWARDS — novelty decreases with similarity to the blocking
510
+ // memory, so a reworded sentence is usually LESS similar and scores
511
+ // HIGHER. And delete-then-write advice an earlier draft carried was
512
+ // impossible for a room write even when memory_delete still existed:
513
+ // the blocker is a room atom, which that tool could not touch either
514
+ // (reviews, 2026-08-08). Deletion is administrative-only now
515
+ // (2026-08-20), so this message never suggests it at all.
516
+ return structured(`NOT STORED — nothing was saved.` +
517
+ (reasonQuote ? ` Server reason: ${reasonQuote}.` : ``) +
518
+ (importance === "unknown"
519
+ ? ``
520
+ : ` Novelty score ${importance}. That score is a first-generation` +
521
+ ` metric under active development and known to be unreliable —` +
522
+ ` identical content has measured ~0.08 in Russian against ~0.55 in` +
523
+ ` English — so read it as a rough hint about similarity, not as a` +
524
+ ` judgement of whether this memory was worth keeping.`) +
525
+ (isRoomDomain(domain)
526
+ ? // ROOM RULE (core#482, 2026-08-13). A room is a message bus:
527
+ // the second agent's job is to receive a restatement of what
528
+ // the first was told, so a briefing or a status summary STORES
529
+ // here. Only a write the embedder cannot distinguish from one
530
+ // already present is refused. Telling a caller to "write the
531
+ // delta" in a room would be advice against the room's purpose.
532
+ ` Restatements are allowed in rooms — this one was refused only` +
533
+ ` because it is indistinguishable by embedding from a message` +
534
+ ` already there. Similarity is judged on roughly the first 500` +
535
+ ` tokens, so a long message that OPENS like an earlier one can` +
536
+ ` land here even when its body differs: lead with what is new.`
537
+ : ` Writes are gated on how much a memory adds over what is already in the` +
538
+ ` same domain, so a near-duplicate is refused. If the point is genuinely` +
539
+ ` new, write what is DIFFERENT rather than restating the whole fact.`),
540
+ // `memory_id` is a literal null on a refusal, per the field's own
541
+ // description ("null when it was not stored"); the connector's refusal
542
+ // fixtures carry `atom_id: null` as well. The connector forwards
543
+ // `res.atom_id` on both verdicts; this package does not forward an id
544
+ // for a write that was not stored, since a refusal carrying one would
545
+ // be a body this client cannot vouch for.
546
+ { stored: false, memory_id: null, ...optionalStructured });
547
+ });
548
+ // --- Tool: memory_read ---
549
+ server.registerTool("memory_read", {
550
+ description: "Search your long-term memory before answering anything that may have come up before — user preferences, past decisions, project setup, people, or earlier context. This memory is shared: it persists across sessions and across every AI tool the user has connected (Claude, ChatGPT, Cursor, VS Code). ALWAYS check here first when you're unsure whether you already know something; no need to call it for general world knowledge you already hold. Returns matches ranked by relevance (or newest-first with order_by: 'recency'); each result carries an id you can pass to memory_feedback. A wrong or stale memory is corrected by writing a fresh one with memory_write, not by deleting it.",
551
+ inputSchema: {
552
+ query: z
553
+ .string()
554
+ .min(CORE_LIMITS.readQuery.minLength)
555
+ .max(CORE_LIMITS.readQuery.maxLength)
556
+ .describe("Natural-language description of what you're looking for, e.g. 'database choice for the API' or 'user's preferred testing framework'."),
557
+ top_k: z
558
+ .number()
559
+ .int()
560
+ .min(CORE_LIMITS.readTopK.minimum)
561
+ .max(CORE_LIMITS.readTopK.maximum)
562
+ .optional()
563
+ .describe("Requested number of results (default: 5, what this server asks for when you omit it; the engine's own default of 10 never applies, because the field is always sent). ⚠️ Not a hard cap: association expansion can return MORE than this, and the relevance floor can return fewer — raising it does not reliably widen the result set. For a complete, exactly-bounded listing use memory_list_recent instead."),
564
+ domain: z
565
+ .string()
566
+ .optional()
567
+ .describe("Restrict the search to one domain namespace (e.g. 'project:acme'). Omitting it searches your OWN domains — it does NOT include shared rooms, which are separate stores: to search a room, pass its address here (e.g. 'xroom:room_01ABC'). Find room addresses with memory_list_rooms."),
568
+ order_by: z
569
+ .enum(["relevance", "recency"])
570
+ .optional()
571
+ .describe("'relevance' (default) = ranking order. 'recency' = the matched " +
572
+ "set re-sorted newest-first. For a complete newest-first feed " +
573
+ "with no search at all, use memory_list_recent instead."),
574
+ since: z
575
+ .string()
576
+ .max(40)
577
+ .optional()
578
+ .describe("Only memories created at/after this ISO-8601 instant (naive = " +
579
+ "UTC) — e.g. your last-seen watermark in a shared room."),
580
+ until: z
581
+ .string()
582
+ .max(40)
583
+ .optional()
584
+ .describe("Only memories created at/before this ISO-8601 instant."),
585
+ exclude_author: z
586
+ .string()
587
+ .max(200)
588
+ .optional()
589
+ .describe("Drop memories written by this author PRINCIPAL — the server-side " +
590
+ "identity. ⚠️ NOT USABLE FROM HERE YET: the principal is not shown " +
591
+ "in these results, so there is no value you can obtain through " +
592
+ "this tool, and a guess like 'me' silently matches nothing and " +
593
+ "filters nothing. Only pass it if your system knows the exact " +
594
+ "principal from elsewhere (e.g. the REST API). A self-exclusion " +
595
+ "shortcut is planned."),
596
+ },
597
+ // Item shape is MEMORY_ITEM_OUTPUT (above), shared with
598
+ // memory_list_recent's outputSchema as of S5; see that constant's
599
+ // comment for provenance and the OD-7 id-type note.
600
+ outputSchema: {
601
+ items: z
602
+ .array(z.object(MEMORY_ITEM_OUTPUT))
603
+ .describe("Matching memories, ordered per order_by."),
604
+ },
605
+ annotations: {
606
+ title: "Search Memories",
607
+ readOnlyHint: true,
608
+ destructiveHint: false,
609
+ idempotentHint: true,
610
+ openWorldHint: false,
611
+ },
612
+ }, async ({ query, top_k, domain, order_by, since, until, exclude_author }) => {
613
+ // ONE value, used for the request AND for every decision about it.
614
+ //
615
+ // A previous draft sent the raw string but decided the wording from a
616
+ // TRIMMED copy, and the two disagreed in the release's own founding case:
617
+ // a read on " engineering" searched the padded store (correct) while the
618
+ // diagnosis checked "engineering", found it, and stayed silent — so the
619
+ // one note that would have said "a stray space makes a different store"
620
+ // was suppressed exactly when a stray space had made a different store.
621
+ // For a whitespace-only domain it went the other way and claimed the
622
+ // search had covered the caller's own domains when it had covered none
623
+ // (reviews, 2026-08-08).
624
+ //
625
+ // `|| undefined` is what 0.8.0 sent and must stay: core filters on
626
+ // `domain is not None`, not on truthiness, so passing "" through would
627
+ // become `WHERE domain = ''` — a store that cannot exist — turning a
628
+ // search of every domain into a guaranteed miss. That is data movement,
629
+ // not wording, and it does not belong in a patch.
630
+ const searched = searchedScope(domain);
631
+ const r = await apiFetch("/memory/read", {
632
+ method: "POST",
633
+ body: JSON.stringify(readRequestBody({ query, top_k, domain, order_by, since, until, exclude_author })),
634
+ });
635
+ // `items` must be a REAL array before anything below may speak. Core's
636
+ // read response always carries one on a 200, so a body without it is not
637
+ // core's answer — and the old `Array.isArray(r?.items) ? r.items : []`
638
+ // fed exactly that body to the entire zero-result machinery: head
639
+ // sentence, scope probe, diagnosis. An absence claim derived from a body
640
+ // this client could not read — the substitution classifyRooms removed for
641
+ // rooms, one level up from the probes (truth F13, 2026-08-08).
642
+ const items = r?.items;
643
+ if (!Array.isArray(items)) {
644
+ return unreadableAnswerReply("The search result", "a list of matches", "nothing matched");
645
+ }
646
+ if (items.length === 0 && (since || until || exclude_author)) {
647
+ // A bounded/filtered read that finds nothing is NOT a bad query —
648
+ // the truthful answer is "nothing new for these filters" (the feed's
649
+ // filtered head uses the same sentence; no stats probe, no broaden
650
+ // hint). Unscoped, it also has to name the rooms it never looked in.
651
+ const scopeNote = readScopeNote(await probeScope(searched));
652
+ // The scope is IN the sentence, not appended after it. This branch
653
+ // was already the honest one in 0.8.0 — it names its filters — and
654
+ // it is the model the feed's copy now follows.
655
+ //
656
+ // The legend wraps the WHOLE message and is added at most once:
657
+ // `scopeNote` may itself have named a store (a case-twin), and one
658
+ // explanation of the escaping per answer is the point of it.
659
+ return structured(withDomainEscapeLegend(`Nothing in ${scopeLabel(searched)} matches within the given time/author filters.` +
660
+ futureSinceNote(since, Date.now()) +
661
+ scopeNote, searched), { items: [] });
662
+ }
663
+ if (items.length === 0) {
664
+ // Zero results. The scope is probed FIRST and the whole answer is then
665
+ // assembled from that ONE value in src/teaching.ts — head sentence and
666
+ // disclosure together, per state.
667
+ //
668
+ // ORDER MATTERS and is now structural: whether the caller has rooms we
669
+ // could not search decides whether the first-contact greeting is even
670
+ // true, so the room knowledge is an INPUT to the answer rather than a flag
671
+ // consulted beside it. `total_atoms` counts the personal org only, so a
672
+ // joiner with three full rooms and no personal writes would otherwise be
673
+ // told "nothing has been saved yet" and contradicted by the note right
674
+ // underneath (review, 2026-08-08).
675
+ //
676
+ // Nothing is appended here any more. While the head came from teaching.ts
677
+ // and the tail was concatenated at this line, the two could disagree — a
678
+ // head promising "that is not the whole picture:" with an empty tail after
679
+ // it was a live bug for an account whose only room was archived.
680
+ const scope = await probeScope(searched);
681
+ const text = await buildReadEmptyResponse(
682
+ // THE THIRD PROBE, and the one the first pass at #73 missed. An
683
+ // UNSCOPED empty read takes this path: probeScope only fetches the
684
+ // room list (scope.ts: `if (!searched) return { kind: "own-domains" }`),
685
+ // and the stats call for the first-contact greeting is issued here.
686
+ // Deadlining only the two inside probeScope left the commonest empty
687
+ // read of all still able to hang for undici's ~300s default — the exact
688
+ // symptom #73 names.
689
+ () => apiFetch("/memory/stats", {
690
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
691
+ }), scope);
692
+ // NO legend wrapper here, on purpose — `withDomainEscapeLegend(
693
+ // text, searched)` stood on this line and was dead code that
694
+ // looked load-bearing (tests-lens F9, 2026-08-08): every arm of
695
+ // buildReadEmptyResponse either names no store at all (fixed
696
+ // sentences), or names it inside a note that appends its own
697
+ // legend (the case-twin diagnosis, src/scope.ts) — and the
698
+ // unscoped path passes `searched === undefined`, which can never
699
+ // need one. So there was no input on which the wrapper fired.
700
+ // Pinned by "the plain-empty read is legended by its notes" in
701
+ // test/handlers.test.ts.
702
+ return structured(text, { items: [] });
703
+ }
704
+ // Every item must carry the three fields core's MemoryItemSchema always
705
+ // sends before this handler may render OR structure it: `atom_id`,
706
+ // `content` and `domain`. A body with items but missing one of those on
707
+ // any entry is not core's answer to memory_read, the same "unreadable
708
+ // 2xx" class the guard above catches one level up, discovered one field
709
+ // later. `structuredItem` (src/render.ts) needs all three to build a
710
+ // schema-honest structuredContent item, and there is no honest value to
711
+ // put in a required field this response did not send.
712
+ if (items.some((it) => typeof it?.atom_id !== "string" ||
713
+ typeof it?.content !== "string" ||
714
+ typeof it?.domain !== "string")) {
715
+ return unreadableAnswerReply("The search result", "a list of matches", "nothing matched");
716
+ }
717
+ // Rendering lives in src/render.ts (testable): each line carries the
718
+ // CN-001 author tag, the created_at date (#404 R1 — a reader cannot
719
+ // reason about recency it cannot see) and the full atom id (the tool
720
+ // description always promised ids for memory_feedback/memory_delete;
721
+ // the old render never delivered them, making both uncallable from
722
+ // read results).
723
+ const lines = items.map((item, i) => formatReadItem(item, i));
724
+ // `?? 0` prints a FABRICATED `(0ms)` when the server sent no timing — the
725
+ // same class as "Associations: 0" for an unknown count, which memory_stats
726
+ // fixed in this release. Untouched here and recorded in CHANGELOG's "Known
727
+ // and NOT fixed here" with the other three.
728
+ const searchMs = (r?.search_time_ms ?? 0).toFixed(0);
729
+ const text = lines.join("\n\n") + `\n\n(${searchMs}ms)`;
730
+ // Each line's `@"domain"` tag is an exact literal; the legend that
731
+ // explains an escape belongs to the answer, not to twenty tags.
732
+ //
733
+ // Legend AFTER the cap, never before. capResult truncates from the
734
+ // END, and the legend is appended at the end — so applied first it
735
+ // was the first thing the cap ate, on exactly the pages long enough
736
+ // to need both: a hundred escaped tags left with nothing saying that
737
+ // \u00a0 is ONE character, not six (truth F6, 2026-08-08). Applied
738
+ // to the CAPPED text the legend survives; and since it fires only
739
+ // when an escaped literal is still on the page, a cap that removed
740
+ // every escaped name drops the legend with it.
741
+ //
742
+ // `structuredContent` carries every item, uncapped (OD-11): the cap
743
+ // and its legend are TEXT-side concerns, and `structuredItem`
744
+ // (src/render.ts) is deliberately not run through either.
745
+ return structured(withDomainEscapeLegend(capResult(text), ...items.map((it) => it?.domain)), { items: items.map(structuredItem) });
746
+ });
747
+ // --- Tool: memory_list_recent ---
748
+ /**
749
+ * How big ONE feed page may get, and how the handler stays under it (#104).
750
+ *
751
+ * THE INCIDENT. `memory_list_recent(domain: "xroom:…", limit: 40, cursor: …)`
752
+ * over a shared room of long archival entries produced a single tool result of
753
+ * 72,648 characters. Claude Code refused to inline it and spilled it to a file;
754
+ * a client without that fallback loses the page. MAX_RESULT_CHARS did not fire,
755
+ * and could not have: 72,648 is comfortably under 96,000. That number is
756
+ * `24,000 tokens × 4 chars/token`, and the 4 is an average over ordinary prose —
757
+ * archival room entries carry ids, code, punctuation and non-ASCII, which
758
+ * tokenize far worse. A cap derived from an optimistic ratio is not a promise
759
+ * about a client's real limit.
760
+ *
761
+ * WHY `limit` COULD NOT SOLVE IT. `limit` bounds the COUNT. Whether a count is
762
+ * safe depends entirely on how long the entries happen to be — 1,500–4,000+
763
+ * chars each in coordination rooms, against a 10,000-char write cap — and the
764
+ * caller cannot know that before asking. Too high explodes; too low costs
765
+ * dozens of round trips for the same catch-up.
766
+ *
767
+ * WHAT THIS IS. A page is assembled from small sub-requests and stops BEFORE
768
+ * the budget is exceeded, returning the server cursor of the last FULLY
769
+ * accepted sub-batch. The cursor is per-batch, which is why the batch is small:
770
+ * it is the granularity at which the page can end without losing or repeating
771
+ * an entry. Nothing is dropped silently — an entry that exceeds the budget on
772
+ * its own is returned whole, as a page of one, because per-entry truncation
773
+ * needs a fetch-one-by-id verb this server does not have (#104, suggestion 2).
774
+ *
775
+ * THE NUMBER IS DELIBERATELY CONSERVATIVE AND DELIBERATELY LOCAL. 40,000 is
776
+ * roughly half of what already failed in production; the true boundary of any
777
+ * given client is unmeasured, and calibrating it is follow-up work. It does NOT
778
+ * touch MAX_RESULT_CHARS, which is shared with memory_read and every other
779
+ * surface and remains the final backstop after this budget has done its work.
780
+ */
781
+ const LIST_PAGE_CHAR_BUDGET = 40_000;
782
+ /**
783
+ * Entries per sub-request. Small enough that the budget can end a page at a
784
+ * useful granularity, large enough that an ordinary short-entry feed still
785
+ * costs one or two round trips (the default `limit` of 20 costs two).
786
+ */
787
+ const LIST_PAGE_CHUNK = 10;
788
+ /**
789
+ * A ceiling on sub-requests per call — the loop's own stop condition is the
790
+ * budget, the caller's `limit`, or the end of the feed, and this fires only if
791
+ * a server answers in a way none of those three catch. `limit: 100` needs ten,
792
+ * plus a few for narrowing an over-budget batch.
793
+ */
794
+ const LIST_PAGE_MAX_REQUESTS = 16;
795
+ /**
796
+ * Appended when the page stopped because a LATER sub-request failed. Chunking
797
+ * multiplies the requests per call and therefore the chance one of them fails
798
+ * mid-page; discarding the entries already in hand would make this change a
799
+ * regression for exactly the long-entry rooms it exists for. Saying nothing
800
+ * would be worse — a short page with a valid cursor is indistinguishable from
801
+ * a page the budget ended, which is the could-not-fetch/does-not-exist
802
+ * collision this codebase keeps closing.
803
+ */
804
+ const LIST_PAGE_EARLY_STOP_NOTE = "\n\n(This page stopped early — the request for the next batch of older " +
805
+ "entries did not come back usable, so this page holds fewer entries than " +
806
+ "asked for. The cursor above is unaffected: continue from it.)";
807
+ server.registerTool("memory_list_recent", {
808
+ description: "List the NEWEST memories first — no search query needed. Semantic search answers 'what do I know about X'; this answers 'what happened lately': resuming work after a break, catching up on a shared room ('any new messages?'), or reviewing what was saved recently. Pass `since` (your last-seen time) to get only what's new, and page through older entries with the returned cursor. Complete by construction WITHIN ONE SCOPE — nothing is skipped there, unlike a semantic search. A page is also bounded by SIZE, so a page of long entries comes back shorter than `limit` and hands you a cursor for the rest — nothing is dropped, and following the cursor is how you get it. To catch up on a shared room you MUST pass its address as `domain`: rooms are separate stores and an unscoped call never covers them.",
809
+ inputSchema: {
810
+ domain: z
811
+ .string()
812
+ .optional()
813
+ .describe("Restrict to one domain. REQUIRED to read a shared room — pass its address ('xroom:room_01ABC'), because rooms are separate stores that an unscoped feed does NOT cover. Omit only when you mean your own domains. Room addresses come from memory_list_rooms. Room entries are often long — a room feed usually reaches its size budget after a handful of them, so expect to page (see `limit`)."),
814
+ since: z
815
+ .string()
816
+ .optional()
817
+ .describe("Only entries created at/after this ISO-8601 instant (naive = UTC) — your novelty watermark."),
818
+ until: z
819
+ .string()
820
+ .optional()
821
+ .describe("Only entries created at/before this ISO-8601 instant (inclusive). Pair with `since` to read a closed window — 'what happened on Monday' — instead of paging back from now."),
822
+ exclude_author: z
823
+ .string()
824
+ .max(200)
825
+ .optional()
826
+ .describe("Drop entries written by this author PRINCIPAL. ⚠️ NOT USABLE FROM HERE YET — the principal is never shown in these results, so there is no value you can get through this tool; a guess like 'me' filters nothing, silently. Same caveat as on memory_read."),
827
+ limit: z
828
+ .number()
829
+ .int()
830
+ .min(CORE_LIMITS.recentLimit.minimum)
831
+ .max(CORE_LIMITS.recentLimit.maximum)
832
+ .optional()
833
+ .describe("Most entries per page (default: 20). Newest first. ⚠️ A CEILING, not a promise: the page is ALSO bounded by size, so a page of long entries stops early and returns a cursor for the rest. In rooms whose entries run long, ask for 5–10 — a large `limit` there buys nothing the size budget will not take back, and costs round trips."),
834
+ cursor: z
835
+ .string()
836
+ .max(CORE_LIMITS.recentCursor.maxLength)
837
+ .optional()
838
+ .describe("Opaque cursor from a previous page's 'More older entries exist' line — continues the listing without skips or duplicates."),
839
+ },
840
+ // Item shape is MEMORY_ITEM_OUTPUT, shared with memory_read's
841
+ // outputSchema (S5, structured-output plan; see that constant's
842
+ // comment). `next_cursor` copies the connector's own field, same name
843
+ // and meaning (mnemoverse-mcp-remote `memoryListRecentOutput`), but
844
+ // this package derives it differently, because it pages through
845
+ // several core requests per call instead of one; see the comment on
846
+ // `acceptedCursor` where the value is produced, below.
847
+ outputSchema: {
848
+ items: z
849
+ .array(z.object(MEMORY_ITEM_OUTPUT))
850
+ .describe("Entries newest-first (creation time descending)."),
851
+ // Optional, unlike the connector's required field (decision OD-12,
852
+ // 2026-09-23): the key is ABSENT when the service sent a continuation
853
+ // token this client will not pass on (CN-032 shape gate, the same one
854
+ // the text applies), because null would claim the listing is complete.
855
+ next_cursor: z
856
+ .string()
857
+ .nullable()
858
+ .optional()
859
+ .describe("Pass back as cursor for the next (older) page; null = listing complete. Absent when the service sent a continuation token this client will not pass on; the text then says the token could not be displayed."),
860
+ },
861
+ annotations: {
862
+ title: "List Recent Memories",
863
+ readOnlyHint: true,
864
+ destructiveHint: false,
865
+ idempotentHint: true,
866
+ openWorldHint: false,
867
+ },
868
+ }, async ({ domain, since, until, exclude_author, limit, cursor }) => {
869
+ // ONE value for the request and for every decision about it — see the note
870
+ // at the top of memory_read.
871
+ const searched = searchedScope(domain);
872
+ // The caller's `limit` is a CEILING on the item count. The page also has a
873
+ // character budget (LIST_PAGE_CHAR_BUDGET), and whichever binds first ends
874
+ // the page — which is why this is a loop over small sub-requests rather
875
+ // than one request for `limit` entries followed by a cap that arrives too
876
+ // late to do anything but truncate.
877
+ const ceiling = limit || 20;
878
+ const accepted = [];
879
+ // The server cursor of the last FULLY accepted sub-batch: the only value
880
+ // that can be handed back without losing or repeating an entry, since a
881
+ // cursor names a batch boundary and nothing finer.
882
+ let acceptedCursor;
883
+ // Where the next sub-request continues from — the caller's cursor first,
884
+ // the server's thereafter. Resending the caller's would replay page one.
885
+ let position = cursor || undefined;
886
+ let ask = Math.min(LIST_PAGE_CHUNK, ceiling);
887
+ let stoppedEarly = false;
888
+ for (let attempt = 0; attempt < LIST_PAGE_MAX_REQUESTS; attempt++) {
889
+ let r;
890
+ try {
891
+ r = await apiFetch("/memory/recent", {
892
+ method: "POST",
893
+ body: JSON.stringify(recentRequestBody({
894
+ domain,
895
+ since,
896
+ until,
897
+ exclude_author,
898
+ limit: ask,
899
+ cursor: position,
900
+ })),
901
+ });
902
+ }
903
+ catch (e) {
904
+ // A failure with entries already in hand ends the page instead of the
905
+ // call: the caller keeps what was fetched plus a cursor that still
906
+ // continues correctly, and the appended note says the page was cut
907
+ // short by a failed request rather than by the budget. With nothing
908
+ // accepted there is no page to return, so the error surfaces exactly
909
+ // as it did before chunking.
910
+ if (accepted.length > 0) {
911
+ stoppedEarly = true;
912
+ break;
913
+ }
914
+ // Graceful degradation while the server side rolls out: a 404 with no
915
+ // error `code` in the body is what an undeployed /memory/recent looks
916
+ // like, so degrade to a usable alternative instead of surfacing a raw
917
+ // HTTP error.
918
+ //
919
+ // NAMED FOR WHAT IT TESTS. This was `endpointAbsent`, which asserted a
920
+ // deployment fact the check cannot establish: every engine 404 carries a
921
+ // `code`, so a real room-404 is excluded, but a gateway, a proxy or a
922
+ // wrong MNEMOVERSE_API_URL produces the same bare 404 and is
923
+ // indistinguishable from here. The MESSAGE below still states the
924
+ // deployment cause outright, which is more than this boolean knows —
925
+ // listed in CHANGELOG's "Known and NOT fixed here" rather than papered
926
+ // over with a hedge.
927
+ //
928
+ // NOW READ FROM STRUCTURED FIELDS. It used to be
929
+ // `e.message.startsWith("Mnemoverse API error 404:")` plus a substring
930
+ // hunt for `"code"` in the same string — a behavioural branch keyed to the
931
+ // exact prefix of a user-facing sentence. Rewording that sentence, which
932
+ // is precisely what src/errors.ts does, would have flipped this branch
933
+ // silently: every per-request 404 would have degraded into "the service
934
+ // does not support the feed yet". `ApiError.isBare404` asks the parsed
935
+ // envelope instead, so the prose and the branch can no longer collide.
936
+ const bare404 = e instanceof ApiError && e.isBare404;
937
+ if (bare404) {
938
+ // OD-9 (owner, 2026-09-23): this reply is now `isError`, not a
939
+ // silent success. Once this tool declares an outputSchema (S5),
940
+ // the SDK's own `validateToolOutput` (see the comment on
941
+ // `structured()` above) rejects a non-error result with no
942
+ // `structuredContent`, and there is no honest structuredContent
943
+ // to give it: `{items: [], next_cursor: null}` would be a
944
+ // schema-valid EMPTY PAGE, exactly the absence claim about the
945
+ // feed this sentence exists to avoid making. `isError` is the one
946
+ // shape the SDK exempts from that check, so it is the shape this
947
+ // reply takes now. The sentence itself is unchanged.
948
+ return {
949
+ content: [
950
+ {
951
+ type: "text",
952
+ text: "The memory service does not support the recent-entries feed yet. " +
953
+ "Use memory_read with order_by: 'recency' as an approximation.",
954
+ },
955
+ ],
956
+ isError: true,
957
+ };
958
+ }
959
+ throw e;
960
+ }
961
+ // Same guard as memory_read: a 200 without an items array is UNREADABLE,
962
+ // not empty — and the feed's empty heads below are precisely the absence
963
+ // claims that must not be derived from it (truth F13, 2026-08-08). Mid
964
+ // page it is treated like a failed sub-request, for the same reason.
965
+ const batch = r?.items;
966
+ if (!Array.isArray(batch)) {
967
+ if (accepted.length > 0) {
968
+ stoppedEarly = true;
969
+ break;
970
+ }
971
+ return unreadableAnswerReply("The recent-entries feed", "an empty feed", "there is nothing to list");
972
+ }
973
+ const next = r?.next_cursor;
974
+ // Measured on the TEXT THAT WOULD SHIP, rendered by the same function
975
+ // that renders the answer — an estimate from item lengths would drift
976
+ // from the renderer the first time a line gained a field. The early-stop
977
+ // note's length is reserved up front: it is appended only when a LATER
978
+ // sub-request fails, which cannot be known while this batch is being
979
+ // sized, so every page keeps room for it (CodeRabbit, PR #108).
980
+ const fits = formatRecentPage(accepted.concat(batch), next).length <=
981
+ LIST_PAGE_CHAR_BUDGET - LIST_PAGE_EARLY_STOP_NOTE.length;
982
+ if (fits) {
983
+ accepted.push(...batch);
984
+ // An EMPTY cursor ends the feed for the page as well as for this loop.
985
+ // The loop below already stops on it (`position` is undefined), but
986
+ // the raw "" went to formatRecentPage, which reads only null as the
987
+ // end, so a finished feed printed "More entries exist but the
988
+ // continuation token could not be displayed" (CodeRabbit, #144).
989
+ // Only "" is normalised: any other non-null value still reaches the
990
+ // renderer, which says entries exist but refuses to print the token.
991
+ acceptedCursor = next === "" ? null : next;
992
+ // The same gate the two surfaces apply (CURSOR_RE, src/render.ts):
993
+ // a token this client will not print or carry is not passed back
994
+ // to the service either, so paging stops here and the page says
995
+ // the token could not be displayed (Copilot, #159).
996
+ position =
997
+ typeof next === "string" && next && CURSOR_RE.test(next) ? next : undefined;
998
+ // No cursor: the feed ended, and the page says so. No entries: the
999
+ // server is not advancing, so continuing would spend requests on the
1000
+ // same nothing. Ceiling reached: the caller's count is spent.
1001
+ if (!position || batch.length === 0 || accepted.length >= ceiling)
1002
+ break;
1003
+ ask = Math.min(LIST_PAGE_CHUNK, ceiling - accepted.length);
1004
+ continue;
1005
+ }
1006
+ // Over budget. With entries already accepted, THIS is the ordinary stop:
1007
+ // keep the batches that fit and hand back the cursor of the last one.
1008
+ if (accepted.length > 0)
1009
+ break;
1010
+ // Nothing accepted yet, so this one batch is over budget by itself and
1011
+ // the page cannot be empty — something must be returned.
1012
+ //
1013
+ // `batch.length > ask` means the server ignored `limit`; asking again,
1014
+ // smaller, would be a wasted round trip against a deployment that is not
1015
+ // listening, and MAX_RESULT_CHARS is the backstop for it. A batch of one
1016
+ // is the entry that exceeds the budget alone: it ships whole, because
1017
+ // dropping it is silent loss and truncating it needs a fetch-by-id verb
1018
+ // that does not exist yet (#104).
1019
+ //
1020
+ // KNOWN EDGE, inherited rather than introduced (CodeRabbit, PR #108):
1021
+ // when a limit-ignoring server's batch ships whole and capResult then
1022
+ // truncates the tail, the printed cursor points past entries the reader
1023
+ // never saw. 0.9.1 had the identical hazard (one request, the server's
1024
+ // cursor, the same cap). The alternatives are worse lies: slicing to
1025
+ // `ask` keeps the server's cursor and SKIPS the sliced entries silently;
1026
+ // rejecting the batch outright answers a working feed with "unreadable".
1027
+ // A contract-violating server is the precondition; the real fix is
1028
+ // fetch-by-id (#104 follow-up), not a guess here.
1029
+ const narrower = Math.max(1, Math.min(Math.floor(ask / 2), batch.length - 1));
1030
+ if (batch.length <= 1 || batch.length > ask || narrower >= ask) {
1031
+ accepted.push(...batch);
1032
+ acceptedCursor = next === "" ? null : next; // same end-of-feed rule as above
1033
+ break;
1034
+ }
1035
+ // Re-ask the SAME position for fewer entries. `narrower < batch.length`
1036
+ // by construction, so the ask strictly shrinks and the loop converges.
1037
+ ask = narrower;
1038
+ }
1039
+ const items = accepted;
1040
+ // Every ACCEPTED item must carry the three fields core's
1041
+ // MemoryItemSchema always sends before this handler may render OR
1042
+ // structure it: `atom_id`, `content` and `domain`; same guard as
1043
+ // memory_read's (S4), added here for S5. A body with items but missing
1044
+ // one of those on any entry is not core's answer, the same "unreadable
1045
+ // 2xx" class the batch guard above catches one request earlier;
1046
+ // `structuredItem` (src/render.ts) needs all three to build a
1047
+ // schema-honest structuredContent item, and there is no honest value to
1048
+ // put in a required field a batch did not send. Trivially satisfied
1049
+ // when `items` is empty, so this runs before the zero-length branch
1050
+ // rather than only inside the non-empty one.
1051
+ if (items.some((it) => typeof it?.atom_id !== "string" ||
1052
+ typeof it?.content !== "string" ||
1053
+ typeof it?.domain !== "string")) {
1054
+ return unreadableAnswerReply("The recent-entries feed", "an empty feed", "there is nothing to list");
1055
+ }
1056
+ if (items.length === 0) {
1057
+ // THE SENTENCE ITSELF carries the scope — and it is selected by EVERY
1058
+ // filter that narrowed the window, not by `since` alone.
1059
+ //
1060
+ // Two prior shapes of this branch were wrong the same way. In 0.8.0 it
1061
+ // printed "Nothing new since your watermark." with no scope in it — the
1062
+ // sentence src/scope.ts was written to eliminate. The first fix put the
1063
+ // scope into the clause but kept choosing BETWEEN the two heads by
1064
+ // looking at `since` only, so {until} alone and {exclude_author} alone
1065
+ // fell to "No memories in ${where} yet." — an emptiness claim about a
1066
+ // store holding a thousand atoms outside the window — and {since, until}
1067
+ // kept the watermark phrasing, which pretends the read reached the
1068
+ // present when `until` stopped it years short (review, 2026-08-08).
1069
+ //
1070
+ // Four heads, one rule: the emptiness claim ("yet") is allowed only
1071
+ // when NOTHING narrowed the window; the watermark phrasing only when
1072
+ // `since` was the whole narrowing; any other filter combination gets the
1073
+ // sentence memory_read's filtered branch uses — the filters are named as
1074
+ // what bounded the result, and nothing is claimed beyond them.
1075
+ //
1076
+ // A `cursor` outranks all three. It is not a filter over the store — it
1077
+ // is a POSITION in a listing whose earlier pages the caller has already
1078
+ // read, so every other head is false here: "No memories in ${where}
1079
+ // yet." is an absence claim about a store the caller has just SEEN
1080
+ // entries from, and the watermark phrasing pretends a continuation that
1081
+ // stopped mid-listing was a clean catch-up. The engine hands out a
1082
+ // cursor only when more entries existed at that moment, so an empty
1083
+ // continued page means the listing moved under the caller — entries
1084
+ // removed between page fetches — and the head speaks about the
1085
+ // continuation only, never about what the store holds (follow-up to the
1086
+ // head-selection fix, 2026-08-08). Decided by the same truthiness the
1087
+ // request used: an empty-string cursor never reaches the wire
1088
+ // (src/requests.ts), so it may not pick the sentence either.
1089
+ const scopeNote = readScopeNote(await probeScope(searched));
1090
+ const where = scopeLabel(searched);
1091
+ const head = cursor
1092
+ ? `Nothing further in ${where} past this cursor — entries may have been ` +
1093
+ `removed since the previous page was fetched.` +
1094
+ (since || until || exclude_author
1095
+ ? ` The given time/author filters still bounded this page.`
1096
+ : ``)
1097
+ : since && !until && !exclude_author
1098
+ ? `Nothing new in ${where} since your watermark.`
1099
+ : since || until || exclude_author
1100
+ ? `Nothing in ${where} matches within the given time/author filters.`
1101
+ : `No memories in ${where} yet.`;
1102
+ // `structuredContent.next_cursor` is unconditionally null on this
1103
+ // branch: none of the four heads above ever prints a NEW cursor to
1104
+ // continue from (a `cursor` in the args is the caller's OWN, already
1105
+ // spent; the others are absence claims over the whole scope), so
1106
+ // there is no cursor value the text could be said to agree with.
1107
+ return structured(withDomainEscapeLegend(head + futureSinceNote(since, Date.now()) + scopeNote, searched), { items: [], next_cursor: null });
1108
+ }
1109
+ return structured(
1110
+ // The page body comes from src/render.ts; the escape legend is
1111
+ // applied HERE, to the CAPPED text. formatRecentPage used to append
1112
+ // it itself, which put it before capResult, and capResult truncates
1113
+ // from the end, so the one sentence explaining the escapes was the
1114
+ // first casualty on every page long enough to be capped (truth F6,
1115
+ // 2026-08-08). Same order as memory_read's result page, same
1116
+ // automatic drop: a cap that removed every escaped name removes the
1117
+ // reason for the legend too.
1118
+ //
1119
+ // The cursor is the last ACCEPTED batch's, never the newest one
1120
+ // seen: a batch that did not fit the budget was not returned, so
1121
+ // pointing past it would skip every entry in it.
1122
+ withDomainEscapeLegend(capResult(formatRecentPage(items, acceptedCursor) +
1123
+ (stoppedEarly ? LIST_PAGE_EARLY_STOP_NOTE : ""),
1124
+ // Still true, and now only reachable when ONE entry is larger
1125
+ // than the whole budget: the case `limit` cannot fix and the
1126
+ // global cap has to.
1127
+ "Lower `limit` or add a `domain` for smaller pages."), ...items.map((it) => it?.domain)), {
1128
+ items: items.map(structuredItem),
1129
+ // Same field name and meaning as the connector's `next_cursor`
1130
+ // (mnemoverse-mcp-remote `memoryListRecentOutput`): the cursor a
1131
+ // client can safely pass back to continue, null when the feed is
1132
+ // finished. DIFFERENT derivation, because this package pages
1133
+ // through several core requests per call (LIST_PAGE_CHAR_BUDGET)
1134
+ // instead of one: it is `acceptedCursor`, the cursor of the last
1135
+ // FULLY accepted batch (set above, same value `formatRecentPage`
1136
+ // just printed), not core's newest-seen cursor: a batch that did
1137
+ // not fit the budget is absent from `items` too, so pointing past
1138
+ // it would both skip entries and contradict the page just shown.
1139
+ // `acceptedCursor` is normalised to null in the loop already
1140
+ // (`next === "" ? null : next`) before it ever reaches here. One
1141
+ // more gate, the same one the text applies (CURSOR_RE, src/render.ts):
1142
+ // a token of a shape this client will not pass on is withheld from
1143
+ // the data too, and the key is then ABSENT, not null, since null
1144
+ // would claim the listing is complete (decision OD-12, 2026-09-23;
1145
+ // the schema marks the field optional for exactly this case).
1146
+ // `typeof` first: the wire value is declared a string but a number
1147
+ // would pass the regex by coercion and then fail the schema.
1148
+ ...(acceptedCursor == null
1149
+ ? { next_cursor: null }
1150
+ : typeof acceptedCursor === "string" && CURSOR_RE.test(acceptedCursor)
1151
+ ? { next_cursor: acceptedCursor }
1152
+ : {}),
1153
+ });
1154
+ });
1155
+ // --- Tool: memory_feedback ---
1156
+ /**
1157
+ * Why ids can miss, listed once and used by both branches that need it — the
1158
+ * total miss (`updated_count: 0`) and the partial one (a count short of the
1159
+ * ids sent). They are the same event at two scales, and when the sentence
1160
+ * lived inline in the zero branch only, the partial case got no explanation at
1161
+ * all.
1162
+ *
1163
+ * No frequency claim. "Most often that means…" was a statistic we do not have
1164
+ * (review, 2026-08-08); the causes are listed as possibilities, with the one
1165
+ * the caller cannot otherwise guess first. A room memory lives in the room's
1166
+ * own store, and a rating reaches it only when that room's address is the
1167
+ * `domain` (core routes the rating by it, routes.py `feedback` →
1168
+ * `_resolve_target_org`). Until 0.11 this tool had no `domain` at all, so a
1169
+ * room memory could not be rated from here; now the miss is a wrong or
1170
+ * missing address, and the text says which store was searched.
1171
+ */
1172
+ const feedbackMissCauses = (domain) => isRoomDomain(domain)
1173
+ ? "Possible causes: the ids did not come from that room (your own memories " +
1174
+ "are rated without a domain, and another room's only with its own address); " +
1175
+ "the memory was deleted; or the id came from somewhere other than a " +
1176
+ "memory_read result."
1177
+ : "Possible causes: the ids came from a shared room, which is reached only " +
1178
+ "when domain is that room's address; the memory was deleted; or the id came " +
1179
+ "from somewhere other than a memory_read result.";
1180
+ const feedbackScope = (domain) => isRoomDomain(domain) ? "in that room" : "in your own domains";
1181
+ server.registerTool("memory_feedback", {
1182
+ description:
1183
+ // "negative feedback lets it fade" was withdrawn as false by 0.9.1
1184
+ // (#95) — and survived here, in the sentence every connected model
1185
+ // reads. Nothing time-decays and nothing is auto-deleted: a downvoted
1186
+ // memory is OUT-RANKED, and deletion has been administrative-only since
1187
+ // 0.9.0. The replacement is the wording that release put on the README.
1188
+ "Report whether memories returned by memory_read were actually helpful. This is a learning signal, not a log: positive feedback raises a memory's ranking so it surfaces faster next time (across all of the user's tools), negative feedback lowers it so other memories out-rank it — nothing is erased and nothing decays with time. Call it right after you act on (or reject) recalled memories, passing the ids from the memory_read results as memory_ids. For memories read from a shared room, also pass that room's address as domain; your own memories need no domain. A read-only room member cannot rate the room's memories.",
1189
+ // `memory_ids` is the name (2026-09-21): the tool rates memories, which
1190
+ // is what every result is (an atom is the engine's word for its smallest
1191
+ // unit), and the hosted connector already names the parameter so. Both
1192
+ // fields are optional in the schema only so the handler can refuse the
1193
+ // two ways a call can get this wrong with a sentence instead of a
1194
+ // validation dump. Neither carries a format or a count cap: the engine
1195
+ // validates the ids and sets no maximum, and ADR-025 keeps such checks
1196
+ // with the engine rather than copying them here.
1197
+ inputSchema: {
1198
+ memory_ids: z
1199
+ .array(z.string())
1200
+ .min(1)
1201
+ .optional()
1202
+ .describe("Required: IDs of the memories to rate, the `id:` line of each memory_read result. (Optional in this schema only while the deprecated atom_ids is still accepted in its place.)"),
1203
+ atom_ids: z
1204
+ .array(z.string())
1205
+ .min(1)
1206
+ .optional()
1207
+ .describe("Deprecated since 0.11, removed in 0.12: atom_ids is the old name of memory_ids, still accepted on its own until then. Pass memory_ids instead."),
1208
+ outcome: z
1209
+ .number()
1210
+ .min(CORE_LIMITS.feedbackOutcome.minimum)
1211
+ .max(CORE_LIMITS.feedbackOutcome.maximum)
1212
+ .describe("How helpful was this? 1.0 = very helpful, 0 = neutral, -1.0 = harmful/wrong"),
1213
+ // Added in 0.11 (owner, 2026-09-22). Core has always accepted it and
1214
+ // routes the rating to the room's store when it is an xroom address,
1215
+ // refusing a non-member, an archived room and a read-only member with
1216
+ // a 403 that explain403 names. Any other value changes nothing: the
1217
+ // rating goes to the caller's own store, as it does without one. No
1218
+ // format or length check here (ADR-025). The value is sent untouched,
1219
+ // like every other domain this package passes on, except that an
1220
+ // empty string counts as none (searchedScope, as on memory_read).
1221
+ domain: z
1222
+ .string()
1223
+ .optional()
1224
+ .describe("Only for memories read from a shared room: that room's address (xroom:...), exactly as you read it. Omit it for your own memories, which are rated by id alone."),
1225
+ },
1226
+ // Copied from the connector's `memoryFeedbackOutput` (mnemoverse-mcp-remote,
1227
+ // src/tools/index.ts), field for field and description for description,
1228
+ // with one noun changed: the connector's `coactivation_edges` text says
1229
+ // "This connector does not send query_concepts"; here it says "This
1230
+ // server", since the fact holds for this tool's own request body (the
1231
+ // POST above carries only atom_ids, outcome and domain) and the noun was
1232
+ // wrong for a local stdio server. `updated_count` is required, matching both the connector's
1233
+ // schema and core's FeedbackResponseSchema (decision OD-8, owner,
1234
+ // 2026-09-23): a body without a usable count is not core's answer. See
1235
+ // the unknown-count branch below, which is `isError` for exactly that
1236
+ // reason, since there is no honest default to declare for it here.
1237
+ outputSchema: {
1238
+ updated_count: z
1239
+ .number()
1240
+ .int()
1241
+ .nonnegative()
1242
+ .describe("How many memories the service reports it applied the rating to. Processed synchronously this is the real count of memories that existed and were updated; processed asynchronously it is a best-effort ACCEPTED-count estimate — the number of IDs submitted — and the authoritative number is not known until the background worker runs. Zero means no submitted ID matched in the service's resolved request scope."),
1243
+ avg_valence: z
1244
+ .number()
1245
+ .optional()
1246
+ .describe("Average valence of the rated memories after the update. Reported as 0 in an asynchronous acknowledgement, where the real value is computed later — a 0 here is therefore not evidence of a neutral outcome."),
1247
+ coactivation_edges: z
1248
+ .number()
1249
+ .int()
1250
+ .nonnegative()
1251
+ .optional()
1252
+ .describe("Number of feedback-driven query/result concept co-activation edges changed by the service. This is separate from ordinary Hebbian strengthening among a memory's own concepts. This server does not send query_concepts, so live calls through this tool report 0; asynchronous acknowledgements also report 0."),
1253
+ },
1254
+ annotations: {
1255
+ title: "Rate Memory Helpfulness",
1256
+ readOnlyHint: false,
1257
+ // NOT destructive (owner, 2026-09-21: "only deletion is destructive;
1258
+ // rating is a good action"). A rating moves the memory's valence and
1259
+ // the weights of its associations, which decide how it ranks; the
1260
+ // saved text, its concepts and its domain are untouched, and later
1261
+ // ratings keep moving those scores. Until 0.11 this said true, citing
1262
+ // the spec's "destructive update" to stored state. A client that asks
1263
+ // for confirmation on destructive tools would then have asked before
1264
+ // every rating, taxing the one signal the ranking learns from. The
1265
+ // engine still replaces the previous scores on each rating; keeping
1266
+ // every rating so any one can be undone is planned there, and the
1267
+ // 0.11 CHANGELOG entry says so until it ships.
1268
+ destructiveHint: false,
1269
+ idempotentHint: false,
1270
+ openWorldHint: false,
1271
+ },
1272
+ }, async ({ memory_ids, atom_ids: legacyIds, outcome, domain }) => {
1273
+ // Both names at once is ambiguous (which list did the caller mean?), so
1274
+ // it is refused rather than resolved by a silent preference.
1275
+ if (memory_ids !== undefined && legacyIds !== undefined) {
1276
+ return {
1277
+ isError: true,
1278
+ content: [
1279
+ {
1280
+ type: "text",
1281
+ text: "Pass the ids as memory_ids only. atom_ids is its old name, still " +
1282
+ "accepted on its own, but both at once is ambiguous. Nothing was rated.",
1283
+ },
1284
+ ],
1285
+ };
1286
+ }
1287
+ const atom_ids = memory_ids ?? legacyIds;
1288
+ if (atom_ids === undefined) {
1289
+ return {
1290
+ isError: true,
1291
+ content: [
1292
+ {
1293
+ type: "text",
1294
+ text: "memory_feedback needs memory_ids: the ids from the memory_read results " +
1295
+ "you are rating. Nothing was rated.",
1296
+ },
1297
+ ],
1298
+ };
1299
+ }
1300
+ // `atom_ids` below is the ENGINE's field name for the same list; the
1301
+ // wire contract is unchanged. `domain` goes through `searchedScope`, as
1302
+ // on memory_read and memory_list_recent: an empty string counts as no
1303
+ // domain and is not sent, so a call without one is byte-identical to one
1304
+ // from before 0.11 and core applies its own default. Any other value is
1305
+ // sent untouched.
1306
+ const scope = searchedScope(domain);
1307
+ const r = await apiFetch("/memory/feedback", {
1308
+ method: "POST",
1309
+ body: JSON.stringify(scope === undefined ? { atom_ids, outcome } : { atom_ids, outcome, domain: scope }),
1310
+ });
1311
+ // A FIELD THE SERVER DID NOT SEND IS UNKNOWN, NOT ZERO — the rule
1312
+ // memory_stats already applies with `num()`, broken here by
1313
+ // `r?.updated_count ?? 0` in three directions at once:
1314
+ //
1315
+ // 1. A 200 with the field absent, an explicit null, and a 204 (which
1316
+ // apiFetch turns into `{}`) all became 0, and 0 prints "No feedback
1317
+ // was recorded" plus three causes for it — an absence claim read out
1318
+ // of a body that carried no claim. Under core's async path the
1319
+ // rating may well have been applied while the ack said nothing.
1320
+ // 2. A string "0" is not 0, so `??` passed it straight through and the
1321
+ // ±1 branches printed "The service reports 0 memories updated — they
1322
+ // should surface sooner next time": two clauses contradicting each
1323
+ // other in one sentence.
1324
+ // 3. Nothing rejected a negative: "reports -2 memories updated".
1325
+ //
1326
+ // So: usable means a non-negative integer. Anything else is UNKNOWN and
1327
+ // gets its own sentence, which diagnoses nothing — the causes of a miss
1328
+ // belong to a reported zero, not to a number we never received.
1329
+ const reported = r?.updated_count;
1330
+ const count =
1331
+ // isSafeInteger, not isInteger: the output schema is z.number().int(),
1332
+ // and zod 4 rejects an integer above 2^53 - 1, so such a count would
1333
+ // turn the whole reply into an SDK validation error (review, 2026-09-23).
1334
+ typeof reported === "number" && Number.isSafeInteger(reported) && reported >= 0
1335
+ ? reported
1336
+ : undefined;
1337
+ // Structured twin of the text's average-valence clause built further
1338
+ // below (`the service reports their average valence is now …`): the
1339
+ // RAW number, not the two-decimal string. Computed here, ahead of that
1340
+ // clause, because it is also carried on the count===0 branch just
1341
+ // below, which returns before the later clause exists. Same rule as
1342
+ // the text: a value that is not a finite number is unknown and absent
1343
+ // from structuredContent, never defaulted to 0.
1344
+ const avgValenceRaw = r?.avg_valence;
1345
+ const avgValenceStructured = typeof avgValenceRaw === "number" && Number.isFinite(avgValenceRaw)
1346
+ ? avgValenceRaw
1347
+ : undefined;
1348
+ // Structured twin of `coactivation_edges`, left out of the TEXT below
1349
+ // for the reason the comment on `valence` gives (this tool sends no
1350
+ // query_concepts, so the number is always 0 here and a sentence about
1351
+ // it would report nothing) but not out of structuredContent, where the
1352
+ // connector's schema carries it as a genuine data field, on every
1353
+ // path, the count===0 one included (review, 2026-09-23). Forwarded
1354
+ // only when it is a non-negative integer, the shape the schema itself
1355
+ // requires, so a value core could never send in that shape is simply
1356
+ // absent here rather than turning this whole reply into an SDK
1357
+ // "Output validation error".
1358
+ const coactivationRaw = r?.coactivation_edges;
1359
+ const coactivationEdges = typeof coactivationRaw === "number" &&
1360
+ Number.isSafeInteger(coactivationRaw) &&
1361
+ coactivationRaw >= 0
1362
+ ? coactivationRaw
1363
+ : undefined;
1364
+ // Direction is echoed for every outcome, including the ones with no count
1365
+ // to report: the same four words for +1 and -1 gave a caller no evidence
1366
+ // the loop did anything, which is why nobody calls it twice.
1367
+ const sent = outcome > 0
1368
+ ? `Rating sent: +${outcome} (helpful).`
1369
+ : outcome < 0
1370
+ ? `Rating sent: ${outcome} (unhelpful).`
1371
+ : "Rating sent: 0.";
1372
+ // Zero has no effect clause to offer — promising "this shifts how they
1373
+ // rank" for outcome 0 would be a claim we cannot make (dogfooding saw a
1374
+ // neutral rating move a score UP by about five points, CodeRabbit #65) —
1375
+ // so it offers the one thing that is actionable instead.
1376
+ //
1377
+ // WHAT 0 ACTUALLY DOES, restated against core#493 (merged 2026-08-13). The
1378
+ // valence step used to be `sign(outcome) * |prediction error|`, so outcome
1379
+ // 0 took the POSITIVE branch and pushed valence UP — which is what
1380
+ // dogfooding saw, and what the previous version of this comment recorded.
1381
+ // That is no longer true: core now uses the SIGNED error,
1382
+ // `pe = outcome - valence` (memory_engine.py:5167-5169), so a 0 against a
1383
+ // positive valence moves it DOWN, toward neutral. Either way 0 is not a
1384
+ // no-op and the line must not imply one — but the old explanation is now
1385
+ // backwards, and it ships verbatim inside dist/index.js, so it cannot be
1386
+ // left to rot in a comment.
1387
+ const pickADirection = outcome === 0
1388
+ ? " Use +1 (helpful) or -1 (harmful/wrong) to express a clear direction."
1389
+ : "";
1390
+ if (count === undefined) {
1391
+ // OD-8 (owner, 2026-09-23): this reply is now `isError`, not a
1392
+ // silent non-error text. Once this tool declares an outputSchema
1393
+ // (S6), the SDK's own `validateToolOutput` (see the comment on
1394
+ // `structured()` above) rejects a non-error result with no
1395
+ // `structuredContent`, and `updated_count` is REQUIRED in that
1396
+ // schema (matching core's own FeedbackResponseSchema), so there is
1397
+ // no honest value to put there for a body that sent none. `isError`
1398
+ // is the one shape the SDK exempts from that check, so it is the
1399
+ // shape this reply takes now. The sentence itself is unchanged,
1400
+ // "do not re-send the same rating" included.
1401
+ return {
1402
+ isError: true,
1403
+ content: [
1404
+ {
1405
+ type: "text",
1406
+ text: `${sent} The service accepted the call but did not report how many ` +
1407
+ `memories it updated, so whether any changed is unknown from here. ` +
1408
+ `That is not evidence of a failure — do not re-send the same rating ` +
1409
+ `on the strength of it.` + pickADirection,
1410
+ },
1411
+ ],
1412
+ };
1413
+ }
1414
+ // "Feedback recorded for 0 memories." is one character away from the
1415
+ // success line and reads like one. But the DIAGNOSIS matters as much as
1416
+ // the fact: an earlier version of this branch blamed deletion, which is
1417
+ // usually the wrong cause (review, 2026-08-08).
1418
+ //
1419
+ // Core resolves the feedback org from `domain`, defaulting to the
1420
+ // caller's own store. So the ordinary way to get zero is to rate atoms
1421
+ // that live somewhere else: read a room, take the ids off the `id:`
1422
+ // lines, rate them without the room's address (or with another room's),
1423
+ // and every one silently misses. The atoms exist, the ids are valid, and
1424
+ // telling the caller they were deleted sends them to look for a problem
1425
+ // that isn't there. Before 0.11 there was no `domain` to pass at all.
1426
+ if (count === 0) {
1427
+ return structured("No feedback was recorded — none of those ids matched a memory " +
1428
+ `${feedbackScope(scope)}. ${feedbackMissCauses(scope)}`, {
1429
+ updated_count: 0,
1430
+ ...(avgValenceStructured === undefined ? {} : { avg_valence: avgValenceStructured }),
1431
+ ...(coactivationEdges === undefined ? {} : { coactivation_edges: coactivationEdges }),
1432
+ });
1433
+ }
1434
+ // WHOSE NUMBER THIS IS (#68). `updated_count` is the count of memories the
1435
+ // service says it touched — and that is true only while core runs
1436
+ // `feedback_async = False`. Under async it returns the number of ids
1437
+ // SUBMITTED, not applied (core schemas.py:826-838, memory_engine.py:4898-4902),
1438
+ // and nothing in the response says which mode ran. A server-side config
1439
+ // flip would therefore turn a confident sentence here false on every
1440
+ // installed client, silently. So the number is reported as the SERVICE'S
1441
+ // report rather than asserted as an outcome this client verified. The
1442
+ // hosted connector took the same correction on 2026-08-13
1443
+ // (mnemoverse-mcp-remote#38); one number, one degree of confidence,
1444
+ // whichever surface a model reaches it through.
1445
+ const noun = `${count} memor${count === 1 ? "y" : "ies"}`;
1446
+ const effect = outcome > 0
1447
+ ? " — they should surface sooner next time."
1448
+ : outcome < 0
1449
+ // No fade. 0.9.1 (#95) withdrew "lets it fade" as false — nothing
1450
+ // time-decays, nothing is auto-deleted, and deletion has been
1451
+ // administrative-only since 0.9.0 — and this line kept promising it
1452
+ // after the release that deleted the claim from the README.
1453
+ ? " — they should rank lower next time. Out-ranked, not erased: nothing is deleted and nothing decays with time."
1454
+ : ".";
1455
+ // WHAT THE COUNT IS NOT: a guarantee that every id landed. `atom_ids.length`
1456
+ // was never compared with it, so five ids and `updated_count: 2` printed
1457
+ // the unqualified success line and three silent misses — the typical shape
1458
+ // of the room case, where half the ids came off a read of a room this
1459
+ // call did not address. A SHORTFALL can only come from core's sync path (the async
1460
+ // ack is exactly `len(atom_ids)`, memory_engine.py:4898-4902), where the
1461
+ // number is the authoritative count of atoms that existed — so the same
1462
+ // causes as the zero branch apply, at a smaller scale, and the string is
1463
+ // shared so the two cannot drift apart.
1464
+ //
1465
+ // An EXCESS is not a shape core produces at all (sync counts one per id
1466
+ // that resolved, async counts the ids). But MNEMOVERSE_API_URL points
1467
+ // wherever it is pointed, and "reports 9 memories updated" for one id
1468
+ // would otherwise read as nine of the caller's memories rated. Say what it
1469
+ // cannot be rather than pass it off as a per-id result.
1470
+ const idsSent = `${atom_ids.length} id${atom_ids.length === 1 ? "" : "s"} you sent`;
1471
+ const mismatch = count < atom_ids.length
1472
+ ? ` That is fewer than the ${idsSent}: ${atom_ids.length - count} of them ` +
1473
+ `matched nothing ${feedbackScope(scope)}. ${feedbackMissCauses(scope)}`
1474
+ : count > atom_ids.length
1475
+ ? ` That is more than the ${idsSent}, so it cannot be a per-id result — ` +
1476
+ `read it as the service's own tally, not as how many of your memories ` +
1477
+ `were rated.`
1478
+ : "";
1479
+ // AVERAGE VALENCE, which core returns and this tool dropped until 0.11
1480
+ // (the hosted connector already passed it on). It is the mean valence of
1481
+ // the memories the rating reached, AFTER the rating: the one number that
1482
+ // shows the rating moved something. Same degree of confidence as the
1483
+ // count, and the same rule: a value that is not a finite number is
1484
+ // unknown and prints nothing, never 0. Core's async mode acks with 0
1485
+ // before the worker runs (memory_engine.py `feedback` docstring), which
1486
+ // is why this is the service's report too; production ran the sync path
1487
+ // for every rating in the week checked (Axiom 2026-09-15..22:
1488
+ // feedback_completed 630, feedback_completed_async 0).
1489
+ //
1490
+ // coactivation_edges is left out of the text on purpose: core links
1491
+ // concepts only when the request carries query_concepts, which this tool
1492
+ // does not send, so the number is always 0 here and a sentence about it
1493
+ // would report nothing.
1494
+ //
1495
+ // toFixed keeps the sign of a value that rounds to zero: (-0.001) prints
1496
+ // "-0.00", which reads as a negative valence. Shown as "0.00" instead
1497
+ // (CodeRabbit on #146).
1498
+ const avg = r?.avg_valence;
1499
+ const valence = typeof avg === "number" && Number.isFinite(avg)
1500
+ ? ` The service reports their average valence is now ${avg.toFixed(2).replace(/^-0\.00$/, "0.00")} (on a scale from -1 to 1).`
1501
+ : "";
1502
+ // Order: what was sent, what the service reported, what that means
1503
+ // for the ids — then the advice. Putting `pickADirection` before the
1504
+ // mismatch clause interrupted the report with a suggestion and
1505
+ // resumed it afterwards.
1506
+ return structured(`${sent} The service reports ${noun} updated${effect}${valence}${mismatch}${pickADirection}`, {
1507
+ updated_count: count,
1508
+ ...(avgValenceStructured === undefined ? {} : { avg_valence: avgValenceStructured }),
1509
+ ...(coactivationEdges === undefined ? {} : { coactivation_edges: coactivationEdges }),
1510
+ });
1511
+ });
1512
+ // --- Tool: memory_stats ---
1513
+ server.registerTool("memory_stats", {
1514
+ description: "Get an overview of the stored memory: total count, episodes vs consolidated prototypes, number of learned associations, the list of domains, and average quality scores. This memory is shared across all AI tools the user has connected to Mnemoverse. Use it to orient yourself, to confirm the exact domain name before writing to it, or when the user asks what you remember. Read-only — changes nothing.",
1515
+ inputSchema: {},
1516
+ annotations: {
1517
+ title: "Memory Statistics",
1518
+ readOnlyHint: true,
1519
+ destructiveHint: false,
1520
+ idempotentHint: true,
1521
+ openWorldHint: false,
1522
+ },
1523
+ }, async () => {
1524
+ const r = await apiFetch("/memory/stats");
1525
+ // A field the server did not send is UNKNOWN, not zero. Rendering it as
1526
+ // "0" is the same class of lie as an empty search claiming emptiness:
1527
+ // "Associations: 0" reads as "this memory has learned nothing", which is
1528
+ // a strong and possibly false statement about the product itself.
1529
+ const num = (v) => (typeof v === "number" ? String(v) : "unknown");
1530
+ const dec = (v) => (typeof v === "number" ? v.toFixed(2) : "unknown");
1531
+ // THE surface this tool's own description sends the reader to, to
1532
+ // confirm the exact domain name before writing to it — so it has to be
1533
+ // able to answer that. (Until 2026-08-20 memory_delete_domain also sent
1534
+ // readers here for the same reason, before deletion was withdrawn to an
1535
+ // administrative REST-only operation; see CHANGELOG.)
1536
+ //
1537
+ // Quoting was tried, then withdrawn as a fix that wasn't one: safeInline
1538
+ // collapses and trims whitespace BEFORE the quotes go on, so " engineering"
1539
+ // and "engineering" printed identically and the list read like a tool bug.
1540
+ // The conclusion drawn then — "revealing whitespace needs escaping rather
1541
+ // than quoting" — was right; this is that escaping. Each name is a JSON
1542
+ // string literal, so a leading space, a no-break space, a newline and a
1543
+ // zero-width character are all visible, Cyrillic stays Cyrillic, and two
1544
+ // different names can no longer print as one. Assembly lives in
1545
+ // src/names.ts, where it is unit-tested against those exact inputs.
1546
+ //
1547
+ // The assembly also BOUNDS the list (MAX_DOMAIN_LIST_CHARS), which is what
1548
+ // makes this handler respect the 25K-token cap every other surface already
1549
+ // respected. The line is linear in the number of stores and nothing bounded
1550
+ // it: 4,000 domains rendered past 100,000 characters — deterministically,
1551
+ // with no hostile input involved. Bounding the LIST rather than leaning on
1552
+ // capResult alone is the point: capResult truncates from the END, so the
1553
+ // wall of names would have taken the average-quality line and the rooms
1554
+ // reminder down with it, leaving the answer nothing but names.
1555
+ const domains = formatDomainList(r?.domains);
1556
+ const text = [
1557
+ `Memories: ${num(r?.total_atoms)} (${num(r?.episodes)} episodes, ${num(r?.prototypes)} prototypes)`,
1558
+ // The gloss names the real mechanism. Core's `hebbian_edges` counts
1559
+ // concept-concept edges (api/schemas.py: "Number of Hebbian
1560
+ // concept-concept edges"), and every path that learns one links two
1561
+ // CONCEPTS: `strengthen` walks pairs within one atom's concept list at
1562
+ // write time and again on feedback, `co_activate` links query concepts
1563
+ // to result concepts on use. An earlier gloss said "links between
1564
+ // memories that get used together" — wrong unit (memories, not
1565
+ // concepts) and wrong trigger (an edge records co-occurrence, not two
1566
+ // memories being used together).
1567
+ `Associations: ${num(r?.hebbian_edges)} Hebbian edges — concept-to-concept links learned from concepts that occur together as memories are stored and used`,
1568
+ `Domains: ${domains}`,
1569
+ `Avg quality: valence ${dec(r?.avg_valence)} (how well recalls turned out, -1..1), importance ${dec(r?.avg_importance)} (0..1)`,
1570
+ "",
1571
+ "Counts cover your own domains. Shared rooms are separate stores and are not included — see memory_list_rooms.",
1572
+ ].join("\n");
1573
+ return {
1574
+ content: [
1575
+ {
1576
+ type: "text",
1577
+ // Array.isArray, not `?? []`: `domains` is typed as a string[] but
1578
+ // arrives over the wire, and spreading a non-iterable object would
1579
+ // throw here — turning a malformed payload into a dead tool instead
1580
+ // of the "none reported" it degrades to two lines up.
1581
+ //
1582
+ // capResult is the second belt, not the mechanism: the domain list is
1583
+ // already bounded above, so this only fires if some future line grows
1584
+ // unboundedly. It stays because this was the ONE tool result with no
1585
+ // cap at all, and "every surface is capped" is worth being an
1586
+ // invariant rather than an argument about which surfaces can grow.
1587
+ // Its hint names a control this no-input tool actually has — none —
1588
+ // rather than the read tool's "use a more specific query".
1589
+ //
1590
+ // Legend AFTER the cap, as everywhere else: it must describe the names
1591
+ // that SURVIVED, and it is appended at the end, where the cap cuts.
1592
+ text: withDomainEscapeLegend(capResult(text, "The domain list was truncated — some domain names are not shown."), ...(Array.isArray(r?.domains) ? r.domains : [])),
1593
+ },
1594
+ ],
1595
+ };
1596
+ });
1597
+ // --- Tool: memory_create_room ---
1598
+ //
1599
+ // CORE'S `next_steps` IS NOT PRINTED, on purpose (checked 2026-09-22, step
1600
+ // 3c). Core returns it on create and on join, and the closed
1601
+ // mnemoverse-mcp-remote#29 proposed echoing it. It is written for REST
1602
+ // callers ("POST /api/v1/memory/write ... mint an invite with POST
1603
+ // .../invites"), which would steer a model toward calls it does not have;
1604
+ // on join it tells every member to write, a read-only one included; and it
1605
+ // carries the owner-chosen room name raw, which this file prints only
1606
+ // through roomNamePhrase (CN-032). The usage lines below say the same
1607
+ // things in MCP terms, scope-gated on join.
1608
+ server.registerTool("memory_create_room", {
1609
+ description: "Create a SHARED memory room — a space OTHER people's assistants can read, and write too when their invite granted read_write (the default scope), across Claude/ChatGPT/Cursor. Use when the user wants to share context or collaborate with someone else (e.g. 'make a room for me and Olya'). Returns the room's address; pass that address as the `domain` on memory_write/memory_read to use it, and on memory_list_recent to catch up on what others added. To bring someone in, call memory_invite_to_room next.",
1610
+ inputSchema: {
1611
+ name: z
1612
+ .string()
1613
+ .min(CORE_LIMITS.roomName.minLength)
1614
+ .max(CORE_LIMITS.roomName.maxLength)
1615
+ .describe("Room name, unique within your account (e.g. 'me-and-olya')."),
1616
+ description: z
1617
+ .string()
1618
+ .max(CORE_LIMITS.roomDescription.maxLength)
1619
+ .optional()
1620
+ .describe("Optional description of the room."),
1621
+ },
1622
+ annotations: {
1623
+ title: "Create shared room",
1624
+ readOnlyHint: false,
1625
+ destructiveHint: false,
1626
+ idempotentHint: false,
1627
+ openWorldHint: false,
1628
+ },
1629
+ }, async ({ name, description }) => {
1630
+ const r = await apiFetch("/memory/rooms", {
1631
+ method: "POST",
1632
+ body: JSON.stringify({ name, description }),
1633
+ });
1634
+ // The name is echoed back to the caller who CHOSE it, so it is printed
1635
+ // exactly (src/names.ts): safeInline turned `memory_create_room({name:
1636
+ // "проект"})` into `Created shared room ""` — an echo claiming the caller
1637
+ // named their room the empty string.
1638
+ const rawName = r?.name ?? name;
1639
+ const roomName = roomNamePhrase(rawName);
1640
+ const address = safeInline(r?.address);
1641
+ const roomId = safeInline(r?.room_id);
1642
+ // If core returned no usable id (empty body / sanitized away), don't print
1643
+ // broken `domain=""` guidance — say so instead (Copilot).
1644
+ const text = address
1645
+ ? `Created shared room ${roomName}. Address: ${address}\n` +
1646
+ `Use it now: pass domain="${address}" on memory_write / memory_read, and on memory_list_recent to catch up on what others added.\n` +
1647
+ (roomId
1648
+ ? `To add someone: call memory_invite_to_room with room_id="${roomId}".`
1649
+ : "")
1650
+ : `Room ${roomName} was created but the server did not return a usable address — ` +
1651
+ `retry, or check that your API key is set.`;
1652
+ return {
1653
+ content: [
1654
+ {
1655
+ type: "text",
1656
+ // Legend AFTER the cap (same rule as memory_read/memory_list_recent):
1657
+ // capResult cuts from the end, so a legend applied first would be the
1658
+ // first casualty; applied to the capped text it also drops itself when
1659
+ // the cap removed the only escaped name.
1660
+ text: withDomainEscapeLegend(capResult(text), rawName),
1661
+ },
1662
+ ],
1663
+ };
1664
+ });
1665
+ // --- Tool: memory_invite_to_room ---
1666
+ server.registerTool("memory_invite_to_room", {
1667
+ description: "Mint an invite for a room you own and get a ready-to-forward message. An invite is single-use by default; pass max_uses to let several people join with the same one. The user sends that message to the person they want to add (any messenger); the recipient opens the link or tells THEIR assistant the code to join. Use after memory_create_room, or whenever the user says 'invite <someone>' to an existing room.",
1668
+ inputSchema: {
1669
+ room_id: z
1670
+ .string()
1671
+ .min(1)
1672
+ .max(100)
1673
+ .describe("The room's id (room_...), from memory_create_room."),
1674
+ scope: z
1675
+ .enum(["read", "read_write"])
1676
+ .optional()
1677
+ .describe("Role the invitee gets — 'read' or 'read_write' (default read_write)."),
1678
+ expires_in_days: z
1679
+ .number()
1680
+ .int()
1681
+ .min(CORE_LIMITS.inviteExpiresInDays.minimum)
1682
+ .max(CORE_LIMITS.inviteExpiresInDays.maximum)
1683
+ .optional()
1684
+ .describe("Days until the invite expires (default 7)."),
1685
+ // Added in 0.11 (step 3c; the hosted connector already had it). Core
1686
+ // takes 1 to 1000, default 1. Both ends come from the contract now
1687
+ // (src/limits.ts), so an engine that widens the range widens this
1688
+ // parameter with it rather than being refused here.
1689
+ max_uses: z
1690
+ .number()
1691
+ .int()
1692
+ .min(CORE_LIMITS.inviteMaxUses.minimum)
1693
+ .max(CORE_LIMITS.inviteMaxUses.maximum)
1694
+ .optional()
1695
+ .describe("How many people may join with this invite (default 1, single-use)."),
1696
+ },
1697
+ annotations: {
1698
+ title: "Invite to room",
1699
+ readOnlyHint: false,
1700
+ destructiveHint: false,
1701
+ idempotentHint: false,
1702
+ openWorldHint: false,
1703
+ },
1704
+ }, async ({ room_id, scope, expires_in_days, max_uses }) => {
1705
+ // JSON.stringify drops undefined keys, so a call without max_uses sends
1706
+ // exactly the body it sent before 0.11 and core applies its default of 1.
1707
+ const r = await apiFetch(`/memory/rooms/${encodeURIComponent(room_id)}/invites`, {
1708
+ method: "POST",
1709
+ body: JSON.stringify({ scope, expires_in_days, max_uses }),
1710
+ });
1711
+ return {
1712
+ content: [
1713
+ {
1714
+ type: "text",
1715
+ // Shown to the room OWNER (who minted it), not a foreign principal, so
1716
+ // the core-generated share_message is fine as-is; capResult only bounds
1717
+ // its length for the Connectors-Directory 25K cap.
1718
+ text: capResult(`Invite ready. Forward this message to the person you're inviting:\n\n` +
1719
+ `${r?.share_message ?? r?.join_url ?? "(no message returned)"}`),
1720
+ },
1721
+ ],
1722
+ };
1723
+ });
1724
+ // --- Tool: memory_join_room ---
1725
+ server.registerTool("memory_join_room", {
1726
+ description: "Join a shared memory room using an invite code (starts with 'mnvr_'). Use when the user pastes an invite code or says something like 'join room with code ...'. After joining, use the returned address as the `domain` on memory_read to read the shared room — the result tells you what you may do with it: memory_write to that address is only allowed when your membership scope is read_write; a read-only membership has that write refused; and when the server does not report a scope, whether memory_write would succeed is stated as unknown rather than promised either way.",
1727
+ inputSchema: {
1728
+ code: z.string().min(1).max(200).describe("The invite code (mnvr_...)."),
1729
+ },
1730
+ annotations: {
1731
+ title: "Join room",
1732
+ readOnlyHint: false,
1733
+ destructiveHint: false,
1734
+ idempotentHint: true,
1735
+ openWorldHint: false,
1736
+ },
1737
+ }, async ({ code }) => {
1738
+ const r = await apiFetch("/memory/rooms/join", {
1739
+ method: "POST",
1740
+ body: JSON.stringify({ code }),
1741
+ });
1742
+ // The room name is OWNER-chosen and rendered into the JOINER's LLM context
1743
+ // (CN-032) — and it is printed EXACTLY (src/names.ts): the literal is one
1744
+ // line with quotes and invisibles escaped, so it cannot forge an
1745
+ // instruction block, and "Zoë" stops being quoted as "Zo" in a sentence
1746
+ // that presents it as the name. `scope` stays sanitised: server-shaped
1747
+ // enum, display-only.
1748
+ const roomName = roomNamePhrase(r?.name);
1749
+ const scope = safeInline(r?.scope) || "member";
1750
+ const address = safeInline(r?.address);
1751
+ const prefix = r?.already_member
1752
+ ? `You're already a member of ${roomName}.`
1753
+ : `Joined ${roomName} (${scope}).`;
1754
+ // Don't print broken `domain=""` guidance if no address came back (Copilot).
1755
+ // The write half of this sentence is scope-gated (roomScopeVerdict, above
1756
+ // isRoomDomain): a "read" invite gets told memory_write will be refused
1757
+ // rather than offered it, and a scope the response did not report at all
1758
+ // gets no promise about write either way.
1759
+ const verdict = roomScopeVerdict(r?.scope);
1760
+ const usage = !address
1761
+ ? `The server did not return a room address — retry, or check that your API key is set.`
1762
+ : verdict === "read_write"
1763
+ ? `Use it: pass domain="${address}" on memory_write / memory_read to read and write the shared room, and on memory_list_recent to catch up on what is new.`
1764
+ : verdict === "read"
1765
+ ? `Use it: pass domain="${address}" on memory_read or memory_list_recent to read it; this membership is read-only, so memory_write to that address will be refused.`
1766
+ : `Use it: pass domain="${address}" on memory_read or memory_list_recent to read it — the server did not report this membership's write access, so whether memory_write to that address would succeed is unknown.`;
1767
+ return {
1768
+ content: [
1769
+ {
1770
+ type: "text",
1771
+ // Legend after the cap — same ordering rule as everywhere else.
1772
+ text: withDomainEscapeLegend(capResult(`${prefix}\n${usage}`), r?.name),
1773
+ },
1774
+ ],
1775
+ };
1776
+ });
1777
+ // --- Tool: memory_list_rooms ---
1778
+ server.registerTool("memory_list_rooms", {
1779
+ description: "List the shared memory rooms you can use — the ones you OWN plus the ones you've JOINED — each with the address to pass as `domain` on memory_read, and on memory_write too where your membership scope is read_write; a read-only membership has that write refused. Use this to RE-FIND a room in a new session (e.g. 'what rooms do I have?', 'resume the room with Olya') instead of having to create or re-join it.",
1780
+ inputSchema: {},
1781
+ annotations: {
1782
+ title: "List rooms",
1783
+ readOnlyHint: true,
1784
+ destructiveHint: false,
1785
+ idempotentHint: true,
1786
+ openWorldHint: false,
1787
+ },
1788
+ }, async () => {
1789
+ // The same classifier the scope notes use, for the same reason: this handler
1790
+ // did `Array.isArray(rooms) ? rooms : []` and then asserted "You have no
1791
+ // shared rooms yet" — a claim about the account derived from a body it could
1792
+ // not read. It is the third consumer of this payload and the third place the
1793
+ // substitution was made; all three now go through one function that maps an
1794
+ // unreadable body to `unknown`, never to `none`.
1795
+ const rooms = classifyRooms(await apiFetch("/memory/rooms"), safeInline);
1796
+ if (rooms.state === "unknown") {
1797
+ // Byte-identical to the inline wording this replaces — the builder is
1798
+ // shared so the four list surfaces answer the unreadable case with one
1799
+ // sentence, not four drifting ones.
1800
+ return unreadableAnswerReply("The room list", "a list of your rooms", "you have none");
1801
+ }
1802
+ if (rooms.state === "none") {
1803
+ return {
1804
+ content: [
1805
+ {
1806
+ type: "text",
1807
+ text: "You have no shared rooms yet. Create one with memory_create_room, " +
1808
+ "or join one with memory_join_room using an invite code.",
1809
+ },
1810
+ ],
1811
+ };
1812
+ }
1813
+ // ARCHIVED ROOMS ARE LISTED HERE, unlike in the scope note — this tool's job
1814
+ // is the inventory, and the `[archived]` tag says which ones cannot be read.
1815
+ const list = rooms.rooms;
1816
+ // Room name is OWNER-chosen — printed EXACTLY (src/names.ts), like every
1817
+ // other room-name surface as of 0.8.1: the sanitiser listed "проект" and
1818
+ // "план" as two "(unnamed room)" entries and quoted "Zoë" as "Zo".
1819
+ // address/role/scope are server-shaped and keep the defensive sanitiser.
1820
+ const lines = list.map((r) => {
1821
+ const name = roomNamePhrase(r?.name);
1822
+ const roomId = safeInline(r?.room_id);
1823
+ // Always surface the canonical address: fall back to xroom:<room_id> when the server
1824
+ // omits `address`, so the domain guidance this tool promises is never silently dropped.
1825
+ const address = safeInline(r?.address) || (roomId ? `xroom:${roomId}` : "");
1826
+ const role = safeInline(r?.role);
1827
+ const scope = safeInline(r?.scope);
1828
+ // No "use domain=..." on an archived room: core refuses EVERY read of one
1829
+ // with a 403, for owner and member alike (see the archived-only note in
1830
+ // src/scope.ts), so that clause was an instruction to make a call that
1831
+ // cannot succeed. The address stays visible — it is the room's identity —
1832
+ // but the line says what a read against it will do.
1833
+ //
1834
+ // For a live room, the write half is scope-gated the same way
1835
+ // memory_join_room's usage sentence is (roomScopeVerdict, near
1836
+ // isRoomDomain): this used to say "use domain=..." with no operation
1837
+ // named, which read as an unqualified read+write invitation even for a
1838
+ // "read" member — false, since core refuses that member's memory_write.
1839
+ const verdict = roomScopeVerdict(scope);
1840
+ const tail = r?.archived
1841
+ ? address
1842
+ ? ` [archived] — address ${address}, but every read is refused while it is archived`
1843
+ : ` [archived] — every read is refused while it is archived`
1844
+ : !address
1845
+ ? ""
1846
+ : verdict === "read_write"
1847
+ ? ` — use domain="${address}" to read and write it`
1848
+ : verdict === "read"
1849
+ ? ` — use domain="${address}" on memory_read only; this membership is read-only, so memory_write to it will be refused`
1850
+ : ` — use domain="${address}" on memory_read; this membership's write access was not reported`;
1851
+ return `- ${name} (${role}${scope ? `, ${scope}` : ""})${tail}`;
1852
+ });
1853
+ const text = `Your shared rooms (${list.length}):\n${lines.join("\n")}`;
1854
+ return {
1855
+ content: [
1856
+ {
1857
+ type: "text",
1858
+ // Legend after the cap: this is the one room surface long enough to
1859
+ // actually overflow, and the legend must describe the names that
1860
+ // SURVIVED the cut, not the ones it removed.
1861
+ text: withDomainEscapeLegend(capResult(text, "The room list was truncated — some rooms are not shown."), ...list.map((r) => r?.name)),
1862
+ },
1863
+ ],
1864
+ };
1865
+ });
1866
+ // --- Tool: vault_list ---
1867
+ server.registerTool("vault_list", {
1868
+ description: "List the secrets stored in your Mnemoverse Vault — by ALIAS and purpose only; the secret VALUE is never returned or shown to you, and no tool on this server returns it. Use this to check WHICH secrets the user has stored and under what alias (e.g. the user says 'do I have a GitHub token saved?'). Only YOUR account's secrets are listed.",
1869
+ inputSchema: {},
1870
+ annotations: {
1871
+ title: "List vault secrets",
1872
+ readOnlyHint: true,
1873
+ destructiveHint: false,
1874
+ idempotentHint: true,
1875
+ openWorldHint: false,
1876
+ },
1877
+ }, async () => {
1878
+ const r = await apiFetch("/vault/secrets");
1879
+ // A 200 missing the `secrets` array used to print "No secrets are stored
1880
+ // in your Vault yet." — an absence claim about the Vault derived from a
1881
+ // body this client could not read. The family fix (classifyRooms, the
1882
+ // domains guard) had stopped one tool short of here (truth F13,
1883
+ // 2026-08-08). A genuinely empty array keeps the absence claim below.
1884
+ const list = r?.secrets;
1885
+ if (!Array.isArray(list)) {
1886
+ return unreadableAnswerReply("The secret list", "a list of your Vault secrets", "none are stored");
1887
+ }
1888
+ if (list.length === 0) {
1889
+ return {
1890
+ content: [
1891
+ {
1892
+ type: "text",
1893
+ text: "No secrets are stored in your Vault yet.",
1894
+ },
1895
+ ],
1896
+ };
1897
+ }
1898
+ const lines = list.map((s) => {
1899
+ const alias = safeInline(s?.alias) || "(no alias)";
1900
+ const context = safeInline(s?.context);
1901
+ return context ? `- ${alias} — ${context}` : `- ${alias}`;
1902
+ });
1903
+ const text = `Your Vault secrets (${list.length}) — alias and purpose only, never the value:\n` +
1904
+ lines.join("\n");
1905
+ return {
1906
+ content: [
1907
+ {
1908
+ type: "text",
1909
+ text: capResult(text, "The secret list was truncated — some secrets are not shown."),
1910
+ },
1911
+ ],
1912
+ };
1913
+ });
1914
+ }
1915
+ //# sourceMappingURL=tools.js.map