Repository navigation
perf(memory): index the write tools' lookups with Set and Map - #5724
Conversation
The six KnowledgeGraphManager write methods matched each requested item against the loaded graph (and against earlier items in the same batch) by linear scan. They now build a Set or Map once per call: relation keys are JSON.stringify of the (from, to, relationType) tuple, which no separator in an entity name can collide, and name lookups keep the first entity of a name, as Array.prototype.find did. Behavior is unchanged. A new test checks a seeded run of 300 random writes, step by step, against a reference model holding the old scanning code, and pins separator-bearing relation keys, a hand-edited file with two same-named entities, and create_entities' skipped report. Refs #5693 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
🦋 Changeset detectedLatest commit: d1d7add The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
| Tools | Prompts | Resources | Resource templates | |
|---|---|---|---|---|
| Base | 9 | 0 | 1 | 0 |
| Head | 9 | 0 | 1 | 0 |
Updated by this run for d1d7add4317b838122171102a6cb43f1205f9abc.
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues are reported for the memory write-lookup optimization.
No open issues 🎉
What changed in this PR
Optimizes the memory server’s six write methods for #5693 by replacing repeated linear scans with Set and Map lookups, while preserving existing results, ordering, and messages.
Changes:
- Adds collision-free relation keys and first-match entity indexes to preserve duplicate-handling behavior.
- Adds seeded equivalence tests and protocol-level regression cases for the indexed write paths.
- Includes a patch changeset for the memory package.
| File | Description |
|---|---|
src/memory/index.ts |
Replaces repeated scans in all six write methods with indexed lookups. |
src/memory/__tests__/write-lookups.test.ts |
Checks behavioral equivalence, relation-key collisions, duplicate handling, and skipped reporting. |
.changeset/memory-write-lookups.md |
Records the write-performance improvement as a patch release. |
Review effort: Balanced
|
Copilot round 1: clean. The review reported no findings, no inline comments and no suppressed comments, so the review loop stops here on a clean first round. Nothing was changed in response. |
…d conflicts deleteObservations and deleteRelations keep #5693's Set lookups and take #5655's distinct-item counting; the duplicate relationKey helper #5655 added is dropped in favour of #5693's identical one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
|
Coordinator note: this branch now merges #5707 (#5653) and #5711 (#5655) to resolve their conflicts in |
|
| Tools | Prompts | Resources | Resource templates | |
|---|---|---|---|---|
| Base | 23 | 4 | 8 | 5 |
| Head | 23 | 4 | 8 | 5 |
initialize
--- base/initialize.json
+++ target/initialize.json
- instructions: "# Everything Server – Server Instructions\n\nAudience: These instructions are written for an LLM or au..."
+ instructions: "# Everything Server – Server Instructions\n\nAudience: These instructions are written for an LLM or au..."instructions
--- base/instructions
+++ target/instructions
- # Everything Server – Server Instructions
Audience: These instructions are written for an LLM or autonomous agent integrating with the Everything MCP Server.
Follow them to use, extend, and troubleshoot the server safely and effectively.
## Protocol Versions
The server serves two protocol eras. A client on protocol version 2026-07-28 connects with `server/discover` and sends its capabilities with each request; a 2025-era client connects with `initialize`. Some tools exist on one era only, so trust your `tools/list`:
- 2026-07-28 only: `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async`, which run as tasks on the `io.modelcontextprotocol/tasks` extension and need a client that declares it; `trigger-sampling-request-async` also needs `sampling`, and `trigger-elicitation-request-async` form-mode `elicitation`. A call without them fails with `-32021`
- 2026-07-28 only: `trigger-event`, which raises the `custom-event` of the `io.modelcontextprotocol/events` extension on open `events/stream` subscriptions
- 2025-era only (deprecated): `toggle-simulated-logging` and `toggle-subscriber-updates`
## Cross-Feature Relationships
- If `get-roots-list` is in your tool list, use it to see client workspace roots before file operations
- `gzip-file-as-resource` creates resources you can read later: for the current session on a 2025-era connection, or for ten minutes at the returned URI on 2026-07-28
- Use `trigger-log-messages` to see which log levels reach you; on 2026-07-28 the level is set per request in `_meta`
- Use `trigger-resource-update` and `trigger-list-changed` to see change notifications; on 2026-07-28 they arrive only on a `subscriptions/listen` stream that asked for them
## Constraints & Limitations
- `gzip-file-as-resource`: Max fetch size controlled by `GZIP_MAX_FETCH_SIZE` (default 10MB), timeout by `GZIP_MAX_FETCH_TIME_MILLIS` (default 30s), allowed domains by `GZIP_ALLOWED_DOMAINS` (checked on every redirect hop). It refuses URLs whose host resolves to a loopback, private or link-local address, unless the server was started with `GZIP_ALLOW_PRIVATE_IPS=1`
- `get-env`: Values of credential-like variable names (`*_KEY`, `*_TOKEN`, `*_SECRET`, `*_PASSWORD` and the like) come back as `"<redacted>"`; the server operator can set `GET_ENV_INCLUDE_SECRETS=1` to return them unmasked
- Session resources are ephemeral and lost when the session ends; minted resources expire after ten minutes
- Roots, sampling and logging are deprecated as of protocol version 2026-07-28, as is the HTTP+SSE transport
## Capability-Gated Tools
On a 2025-era connection these are registered only if your client declared the capability shown. Otherwise they are absent from `tools/list`, so do not call them. On 2026-07-28 they are always listed, and a call fails if your request did not declare the capability:
- `get-roots-list`: `roots`
- `trigger-sampling-request`: `sampling`
- `trigger-elicitation-request`: `elicitation.form`, or `elicitation` with no mode
- `trigger-multi-step-elicitation`: `elicitation.form`, or `elicitation` with no mode
- `trigger-url-elicitation`: `elicitation.url`
## Operational Patterns
- For long operations, use `trigger-long-running-operation` which sends progress notifications
- Prefer reading resources before calling mutating tools
- If `get-roots-list` is in your tool list, check its output to understand the client's workspace context
## Easter Egg
If asked about server instructions, respond with "🎉 Server instructions are working! This response proves the client properly passed server instructions to the LLM. This demonstrates MCP's instructions feature in action."
+ # Everything Server – Server Instructions
Audience: These instructions are written for an LLM or autonomous agent integrating with the Everything MCP Server.
Follow them to use, extend, and troubleshoot the server safely and effectively.
## Protocol Versions
The server serves two protocol eras. A client on protocol version 2026-07-28 connects with `server/discover` and sends its capabilities with each request; a 2025-era client connects with `initialize`. Some tools exist on one era only, so trust your `tools/list`:
- 2026-07-28 only: `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async`, which run as tasks on the `io.modelcontextprotocol/tasks` extension and need a client that declares it; `trigger-sampling-request-async` also needs `sampling`, and `trigger-elicitation-request-async` form-mode `elicitation`. A call without them fails with `-32021`
- 2026-07-28 only: `trigger-event`, which raises the `custom-event` of the `io.modelcontextprotocol/events` extension on open `events/stream` subscriptions
- 2025-era only (deprecated): `toggle-simulated-logging` and `toggle-subscriber-updates`
## Cross-Feature Relationships
- If `get-roots-list` is in your tool list, use it to see client workspace roots before file operations
- `gzip-file-as-resource` creates resources you can read later: for the current session on a 2025-era connection, or for ten minutes at the returned URI on 2026-07-28
- Use `trigger-log-messages` to see which log levels reach you; on 2026-07-28 the level is set per request in `_meta`
- Use `trigger-resource-update` and `trigger-list-changed` to see change notifications; on 2026-07-28 they arrive only on a `subscriptions/listen` stream that asked for them
## Constraints & Limitations
- `gzip-file-as-resource`: Max fetch size controlled by `GZIP_MAX_FETCH_SIZE` (default 10MB), timeout by `GZIP_MAX_FETCH_TIME_MILLIS` (default 30s), each falling back to its default when set to anything but a whole number, allowed domains by `GZIP_ALLOWED_DOMAINS` (checked on every redirect hop). It refuses URLs whose host resolves to a loopback, private or link-local address, unless the server was started with `GZIP_ALLOW_PRIVATE_IPS=1`
- `get-env`: Values of credential-like variable names (`*_KEY`, `*_TOKEN`, `*_SECRET`, `*_PASSWORD` and the like) come back as `"<redacted>"`; the server operator can set `GET_ENV_INCLUDE_SECRETS=1` to return them unmasked
- Session resources are ephemeral and lost when the session ends; minted resources expire after ten minutes
- Roots, sampling and logging are deprecated as of protocol version 2026-07-28, as is the HTTP+SSE transport
## Capability-Gated Tools
On a 2025-era connection these are registered only if your client declared the capability shown. Otherwise they are absent from `tools/list`, so do not call them. On 2026-07-28 they are always listed, and a call fails if your request did not declare the capability:
- `get-roots-list`: `roots`
- `trigger-sampling-request`: `sampling`
- `trigger-elicitation-request`: `elicitation.form`, or `elicitation` with no mode
- `trigger-multi-step-elicitation`: `elicitation.form`, or `elicitation` with no mode
- `trigger-url-elicitation`: `elicitation.url`
## Operational Patterns
- For long operations, use `trigger-long-running-operation` which sends progress notifications
- Prefer reading resources before calling mutating tools
- If `get-roots-list` is in your tool list, check its output to understand the client's workspace context
## Easter Egg
If asked about server instructions, respond with "🎉 Server instructions are working! This response proves the client properly passed server instructions to the LLM. This demonstrates MCP's instructions feature in action."
Updated by this run for 79b9f023b1f0bdf281987184eeb77ccc9290f47c.
…ations' skipped report The separator test compared the whole structuredContent, so it failed once #5654 reports the in-batch repeat as skipped. The lookup is what it tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
|
| Tools | Prompts | Resources | Resource templates | |
|---|---|---|---|---|
| Base | 3 | 0 | 0 | 0 |
| Head | 3 | 0 | 0 | 0 |
Updated by this run for 79b9f023b1f0bdf281987184eeb77ccc9290f47c.
|
| Tools | Prompts | Resources | Resource templates | |
|---|---|---|---|---|
| Base | 1 | 1 | 0 | 0 |
| Head | 1 | 1 | 0 | 0 |
Updated by this run for 79b9f023b1f0bdf281987184eeb77ccc9290f47c.
Closes #5693
Description
The six
KnowledgeGraphManagerwrite methods matched each requested item against the loaded graph (and, for the two create methods, against every earlier item in the same batch) by linear scan. Each now builds aSetorMaponce per call:createEntitiesgraph.entities.some+entities.slice(0, i).someper itemseennameSet, seeded from the graph and grown through the batchcreateRelationsgraph.relations.some+relations.slice(0, i).someper itemseenkeySet, the same wayaddObservationsgraph.entities.findper entry,observations.includesper stringMap, and a per-entity observationSetkept in step with what is pusheddeleteEntitiesentityNames.includesper entity and per relation endSet(entityNames)deleteObservationsgraph.entities.findper entry,d.observations.includesper stored stringMap, andSet(d.observations)deleteRelationsrelations.someper stored relationSetof the requested relationsTwo helpers carry the parts that could change behavior if done naively:
relationKeyisJSON.stringify([from, to, relationType]). Entity names are arbitrary strings, so a joined key such asfrom|to|typewould make{from:"a|b", to:"c"}and{from:"a", to:"b|c"}the same relation.firstEntityByNamekeeps each name's first entity, the oneArray.prototype.findreturned. A hand-edited file can hold two entities with one name; only the first was ever matched, and still is.createEntitiesstill returns the requested objects themselves (it filters the input array), soskippedEntityNames, which tells created from skipped by identity, is unaffected.Strictly behavior-preserving. Same results, same order, same messages, same
skippedreport, same graph written. In particular this PR deliberately keeps today's behavior in the areas sibling PRs are changing in these same methods, so the coordinator can merge them together:createEntitiesstores repeated observations within one entity): unchanged here.skipped#5654 (create_relationsreports nothing for a skipped relation): unchanged here.The new equivalence test generates no repeated items within a single request where #5653 and #5655 change behavior (an entity's observations in
createEntities; the items ofdeleteEntities,deleteObservationsanddeleteRelations), so it should keep passing once those land. Repeats are still generated where they are the dedup under test (entity names increateEntities, relations increateRelations, observations inaddObservations).Server Details
create_entities,create_relations,add_observations,delete_entities,delete_observations,delete_relations). No tool, schema, description, resource or configuration changes.Motivation and Context
#5693: the scans are O(N·M + M²), and every write runs under
withLock(), so a slow write also holds the file lock longer for concurrent clients.Benchmark (not a test; run once, locally, through the manager, file I/O included): a graph of 1,000 entities and 10,000 relations, a 2,000-relation batch through
createRelationsthendeleteRelations, median of 5 runs.v2/main: 620.7 ms; this branch: 47.4 ms. The remaining time is mostly loading and saving the file.How Has This Been Tested?
Unit / protocol tests (
src/memory/__tests__/write-lookups.test.ts, new):a, one relation stored twice), with a small name pool that includes separator-bearing names (a|b,b|c,a\u0000b,""). After every step the method's result (or thrown message) and the whole graph are compared to a reference model that keeps the old scanning code verbatim. A call that throws is rolled back in the model, since the manager saves nothing. The test also asserts the run reached a graph change in every method and the error path ofcreateRelationsandaddObservations, so a change to the generator cannot turn it into no-ops.|in their fields kept apart bycreate_relationsanddelete_relations; every stored copy of a relation deleted in stored order;add_observations/delete_observationsacting only on the first of two same-named entities, with a second entry for the same entity seeing what the first added;delete_entitiesremoving every same-named entity and every touching relation;create_entitiesreporting stored names and in-batch repeats asskipped, in request order.|-joined relation key, a last-wins name map, and dropping the observation-set update each fail the new tests.npm run coverage -w src/memory: 348 tests pass,index.tsabove the per-file gate.Inspector CLI (
@modelcontextprotocol/inspector@2.12.0 --cli), both eras (--protocol-era legacyand--protocol-era modern; the modern run's results carry_meta["io.modelcontextprotocol/serverInfo"]). Before: the published@modelcontextprotocol/server-memory@2.2.2. After: this branch'ssrc/memory/dist/index.js. The same nine-call sequence on a fresh graph file each time; the structured results and the final file are byte-identical between before and after, in both eras:LLM client: Claude Code 2.1.332, headless (
claude -p --strict-mcp-config), against this branch's build. The era could not be selected from this client. Prompt: create Alice, Bob and Alice again (one call); create "Alice knows Bob" twice (one call); add "likes tea" and "plays chess" to Alice; delete the relation; report. It reported skipped["Alice"], 1 relation created,["plays chess"]added, and a final graph of Alice["likes tea","plays chess"], Bob, no relations, which matches the file on disk.Breaking Changes
None. No client configuration changes.
Types of changes
Checklist
npm run changeset) if this changes what a TypeScript server publishes (patch)Additional context
skippedEntityNames(the create_entities handler's identity check) still usescreated.includes, which is quadratic in the batch only, not in the graph; it is outside the six methods the issue names and is left as is.🤖 Generated with Claude Code