Skip to content

perf(memory): index the write tools' lookups with Set and Map - #5724

Merged
cliffhall merged 5 commits into
v2/mainfrom
v2/feat/5693-memory-write-lookups
Nov 30, 2026
Merged

cliffhall merged 5 commits into
v2/mainfrom
v2/feat/5693-memory-write-lookups

Conversation

@cliffhall

Copy link
Copy Markdown
Member

Closes #5693

Description

The six KnowledgeGraphManager write 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 a Set or Map once per call:

Method Before After
createEntities graph.entities.some + entities.slice(0, i).some per item one seen name Set, seeded from the graph and grown through the batch
createRelations graph.relations.some + relations.slice(0, i).some per item one seen key Set, the same way
addObservations graph.entities.find per entry, observations.includes per string a name → entity Map, and a per-entity observation Set kept in step with what is pushed
deleteEntities entityNames.includes per entity and per relation end Set(entityNames)
deleteObservations graph.entities.find per entry, d.observations.includes per stored string the name → entity Map, and Set(d.observations)
deleteRelations relations.some per stored relation a key Set of the requested relations

Two helpers carry the parts that could change behavior if done naively:

  • relationKey is JSON.stringify([from, to, relationType]). Entity names are arbitrary strings, so a joined key such as from|to|type would make {from:"a|b", to:"c"} and {from:"a", to:"b|c"} the same relation.
  • firstEntityByName keeps each name's first entity, the one Array.prototype.find returned. A hand-edited file can hold two entities with one name; only the first was ever matched, and still is.

createEntities still returns the requested objects themselves (it filters the input array), so skippedEntityNames, which tells created from skipped by identity, is unaffected.

Strictly behavior-preserving. Same results, same order, same messages, same skipped report, 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:

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 of deleteEntities, deleteObservations and deleteRelations), so it should keep passing once those land. Repeats are still generated where they are the dedup under test (entity names in createEntities, relations in createRelations, observations in addObservations).

Server Details

  • Server: memory
  • Changes to: the write path of all six write tools (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 createRelations then deleteRelations, 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 seeded run of 300 random writes across all six methods, from a hand-edited starting file (two entities named 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 of createRelations and addObservations, so a change to the generator cannot turn it into no-ops.
  • Protocol-level cases over an in-memory client: relations with | in their fields kept apart by create_relations and delete_relations; every stored copy of a relation deleted in stored order; add_observations / delete_observations acting only on the first of two same-named entities, with a second entry for the same entity seeing what the first added; delete_entities removing every same-named entity and every touching relation; create_entities reporting stored names and in-batch repeats as skipped, in request order.
  • Mutation check (by hand, not committed): a |-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.ts above the per-file gate.

Inspector CLI (@modelcontextprotocol/inspector@2.12.0 --cli), both eras (--protocol-era legacy and --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's src/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:

create_entities  [a|b, c, a, b|c, c(dup)]   → entities [a|b, c, a, b|c], skipped ["c"]
create_entities  [a(again), d]              → entities [d], skipped ["a"]
create_relations [a|b→c, a→b|c, a|b→c]      → [a|b→c, a→b|c]
create_relations [a→nobody]                 → isError: "Entity with name nobody not found"
add_observations a:[o1,o2], a:[o2,o3]       → a:[o1,o2], a:[o3]
delete_observations a:[o1,o3], ghost:[x]    → "Deleted 2 of 3 observations. Entities not found: ghost"
delete_relations [a→b|c]                    → "Relations deleted successfully"
delete_entities [d, ghost]                  → "Deleted 1 of 2 entities. Not found: ghost"
read_graph                                  → a|b:[x], c, a:[o2], b|c; relation a|b→c

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

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality): a performance improvement, with no behavior change
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Protocol Documentation
  • My changes follow MCP security best practices
  • I have updated the server's README accordingly (not applicable: nothing user-visible changed)
  • I have added a changeset (npm run changeset) if this changes what a TypeScript server publishes (patch)
  • I have tested this with an LLM client
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling (not applicable: no new error paths; the existing messages are unchanged)
  • I have documented all environment variables and configuration options (not applicable: none added)

Additional context

skippedEntityNames (the create_entities handler's identity check) still uses created.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

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-bot

changeset-bot Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d1d7add

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@modelcontextprotocol/server-memory Patch

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

@cliffhall
cliffhall requested a balanced review from Copilot November 30, 2026 09:10
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

memory: MCP interface diff

Base: 706d3f846794 (Merge pull request #5711 from modelcontextprotocol/v2/fix/5655-memory-delete-repeated-items)
Head: the build in this checkout, at d90a447d8a19 (Merge d1d7add into 706d3f8)

Diffed because it was named (--server).

✅ No interface changes detected.

Tools Prompts Resources Resource templates
Base 9 0 1 0
Head 9 0 1 0

Updated by this run for d1d7add4317b838122171102a6cb43f1205f9abc.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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

@cliffhall

Copy link
Copy Markdown
Member Author

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.

cliffhall and others added 2 commits November 30, 2026 04:19
…es conflict

Keeps the Set-seeded name filter from #5693 and the per-entity observation
dedupe from #5653.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: cliffhall <cliff@futurescale.com>
…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>
@cliffhall

Copy link
Copy Markdown
Member Author

Coordinator note: this branch now merges #5707 (#5653) and #5711 (#5655) to resolve their conflicts in createEntities, deleteObservations and deleteRelations. The Set/Map lookups from this PR are kept, together with #5653's observation dedupe and #5655's distinct-item counting. The duplicate relationKey helper is collapsed into one. Merge order: #5707 and #5711 before this PR. The gate passed at 0aa4a38.

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

everything: MCP interface diff

Base: 8cecbb16b005 (Merge pull request #5714 from modelcontextprotocol/v2/chore/5700-ts-license-packaging)
Head: the build in this checkout, at 48421dff4a83 (Merge 79b9f02 into dcb5cb3)

Diffed because it was named (--server).

⚠️ Interface changes detected in 2 part(s) of the interface. Review them below to confirm they are intended.

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>
@github-actions

Copy link
Copy Markdown
Contributor

time: MCP interface diff

Base: 8cecbb16b005 (Merge pull request #5714 from modelcontextprotocol/v2/chore/5700-ts-license-packaging)
Head: the build in this checkout, at 48421dff4a83 (Merge 79b9f02 into dcb5cb3)

Diffed because it was named (--server).

✅ No interface changes detected.

Tools Prompts Resources Resource templates
Base 3 0 0 0
Head 3 0 0 0

Updated by this run for 79b9f023b1f0bdf281987184eeb77ccc9290f47c.

@github-actions

Copy link
Copy Markdown
Contributor

fetch: MCP interface diff

Base: 8cecbb16b005 (Merge pull request #5714 from modelcontextprotocol/v2/chore/5700-ts-license-packaging)
Head: the build in this checkout, at 48421dff4a83 (Merge 79b9f02 into dcb5cb3)

Diffed because it was named (--server).

✅ No interface changes detected.

Tools Prompts Resources Resource templates
Base 1 1 0 0
Head 1 1 0 0

Updated by this run for 79b9f023b1f0bdf281987184eeb77ccc9290f47c.

@cliffhall
cliffhall merged commit 002bcce into v2/main Nov 30, 2026
47 checks passed
@cliffhall
cliffhall deleted the v2/feat/5693-memory-write-lookups branch November 30, 2026 11:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

memory: replace O(N*M + M^2) linear scans in KnowledgeGraphManager write tools with Set/Map lookups (~79x faster at 10k relations)

2 participants