createEntities, createRelations, addObservations, deleteEntities,
deleteObservations, and deleteRelations each independently did
load -> mutate -> save with no synchronization. Concurrent tool
calls (e.g. multiple mutations dispatched from one LLM turn) could
race: both read the same starting state, both write back their own
copy, and whichever write landed last silently discarded the other's
changes. Interleaved writes could also corrupt the file outright.
Adds an in-process async mutex (KnowledgeGraphManager.withLock) that
serializes all six mutation methods through a single queue. Read-only
methods (readGraph, searchNodes, openNodes) are unaffected.
Verified: reverting the fix and re-running the new concurrency tests
reproduces the bug exactly (lost entities, lost relations, malformed
JSONL lines). With the fix, all 39 tests pass.
Fixes#1819
Co-authored-by: olaservo <olahungerford@gmail.com>
create_entities and create_relations only de-duplicated against the existing
graph, so passing the same entity name (or identical relation) twice in one
call persisted duplicate records. This contradicts the documented behavior
("Ignores entities with existing names" / "Skips duplicate relations") and
breaks the implicit name-uniqueness invariant the rest of the manager relies
on (e.g. addObservations/deleteEntities key on name).
De-duplicate within the input batch as well, keeping the first occurrence.
Co-authored-by: JSap0914 <JSap0914@users.noreply.github.com>
Co-authored-by: olaservo <olahungerford@gmail.com>
The search_nodes tool accepted an unbounded query string (per
modelcontextprotocol/servers#3537, official servers should constrain
string parameters). An oversized query costs an O(graph) scan per
call with no value. Cap it at 2048 chars via an exported
SearchNodesQuerySchema, and add vitest coverage for the boundary
(at-limit accepted, over-limit rejected, non-string still rejected).
Signed-off-by: fei <204683769+feiiiiii5@users.noreply.github.com>
loadGraph() trusted the persisted memory file and pushed entities and
relations without validating their fields. A corrupted or legacy entry
(e.g. an entity missing entityType, or an observation that is not a string)
would reach searchNodes and crash with "Cannot read properties of undefined
(reading 'toLowerCase')".
Validate each line against the existing EntitySchema/RelationSchema and skip
malformed entries with a warning, so the in-memory graph only ever contains
well-formed data. Malformed JSON lines are skipped as well.
Fixes#2044
delete_entities, delete_observations and delete_relations returned
success: true with a hardcoded "deleted successfully" message regardless
of what matched. An agent that mistypes an entity name is told its memory
is clean while the data is still on disk, and nothing in the response
contradicts that. addObservations throws for the same condition ten lines
above, so the file already disagreed with itself.
Staying quiet is deliberate and documented, so nothing throws and the
output schema is unchanged. The three manager methods now return what
they matched, and the handlers say so. A delete where everything is found
returns the same message it always did.
README updated: the three "Silent operation" bullets described the
absence of an error, which is still true, but read as if the response
said nothing either.
* fix(memory): expand leading ~ in MEMORY_FILE_PATH to the home directory
MCP clients pass MEMORY_FILE_PATH from JSON config, where no shell
expands a leading "~". Because path.isAbsolute("~/memory.jsonl") is
false, the value was joined onto the package directory, so the server
persisted to a literal "~" folder inside the install instead of the
user's intended location.
Add an expandHome() helper that mirrors the one already used by the
filesystem server (src/filesystem/path-utils.ts) and apply it in
ensureMemoryFilePath() before the existing absolute/relative resolution.
Absolute paths, relative paths, and a "~" not at the start are
unaffected. Adds unit tests for expandHome plus an end-to-end test
through ensureMemoryFilePath.
Addresses #1600
* test(memory): use a literal ~/ path in the tilde expansion test
path.join('~', ...) produces a backslash on Windows, which expandHome does
not match, so the test failed there.
---------
Co-authored-by: olaservo <olahungerford@gmail.com>
Fixes#4406. The memory server previously hardcoded serverInfo.version as
"0.6.3", which no longer matched published calendar versions. Resolve
package.json from both source and dist layouts so Docker and npm installs
report the installed package version.
Co-authored-by: syf2211 <syf2211@users.noreply.github.com>
Wrap the addObservations call in an async closure before asserting with
.rejects.toThrow(). This prevents Vitest's global unhandled rejection
handler from capturing the expected error before the assertion can
intercept it, eliminating the false-positive "Unhandled Errors" warning
that was failing CI.
Fixes#3073
Observed on #4714 and #4726: addLabels returned 403 "Resource not
accessible by integration" because pull_request gives fork PRs a
read-only token. The job only calls the GitHub API and never checks
out PR code, so pull_request_target is safe here.
Claude-Session: https://claude.ai/code/session_01CK8vvB229h6orvkokG8YxU
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Update Dockerfile for fetch
Initial patch for podman and SELinux contexts.
* Update Dockerfile for time
podman and SELinux
* Update Dockerfile
* Also include app user / group (securely) such that the build succeeds
* Container app user optional add (#1)
* Update Dockerfile git
* Update Dockerfile fetch
* Update Dockerfile time
* Update Dockerfile
* Update Dockerfile
* Update Dockerfile
---------
Co-authored-by: Ola Hungerford <olahungerford@gmail.com>
validatePath()'s ENOENT fallback checked only the immediate parent
directory before allowing a new path through. Creating a path with
more than one missing level (e.g. a/b/c when none of a, b, c exist)
made the immediate parent check fail with "Parent directory does not
exist", even though fs.mkdir was already called with recursive: true
one level up in the create_directory handler and an existing allowed
ancestor was available further up the tree.
Walk up through missing ancestors until an existing one is found (or
the filesystem root is reached), verifying that ancestor still
resolves inside an allowed directory via realpath. The top-level
lexical containment check already ran against the full target path,
so this only extends how far the existence/symlink check climbs.
Fixes#4629
Co-authored-by: Riley <313779891+rileybuilds@users.noreply.github.com>
Co-authored-by: olaservo <olahungerford@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(sequentialthinking): restore nextThoughtNeeded in the advertised inputSchema required array
commit 1cdf806d (#3533) wrapped nextThoughtNeeded in a z.preprocess-based
coercedBoolean to fix a real footgun (string "false" coercing to true).
zod's toJSONSchema(..., { io: "input" }) treats a z.preprocess()-wrapped
field's input type as unknown, so it silently drops that field from the
emitted required array, even though it carries no .optional(). A client
that builds its call arguments from the advertised schema then omits
nextThoughtNeeded and gets a -32602 Invalid params from the runtime
validator, which still requires it.
Rebuild coercedBoolean as a transform on an explicit z.union([z.boolean(),
z.string()]) instead of z.preprocess. The union gives toJSONSchema a
concrete input type to report, so nextThoughtNeeded stays in required,
while parse behavior (including the case-insensitive string coercion
#3533 added) is unchanged.
Fixes#4651
* test(sequentialthinking): pin nextThoughtNeeded in required and string coercion
Runs against the built server so it checks the schema the SDK emits.
Skips when dist/ is absent, matching server-version.test.ts.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018Wo28CHPXyM3DHoLWvKnCK
---------
Co-authored-by: olaservo <olahungerford@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(sequentialthinking): read server version from package.json
Replace the hardcoded 0.2.0 so initialize serverInfo tracks the
package version (0.6.2 in-tree; CalVer after release), matching the
approach used for memory server version sync.
Skip the dist-layout assertion when dist/ is absent so CI's
test-before-build job (and local runs without prepare) still pass.
* test(sequentialthinking): smoke stdio initialize serverInfo.version
Spawn the built server over stdio and assert getServerVersion() matches
package.json (and is not the old hardcoded 0.2.0). Skip when dist/ is
absent so test-before-build CI still passes.
* fix(memory): write the knowledge graph atomically
`saveGraph()` wrote the graph straight to the memory file:
await fs.writeFile(this.memoryFilePath, lines.join("\n"));
`fs.writeFile` opens the target with `'w'`, which truncates it before any
new bytes are written. If the process is interrupted between truncation
and completion — SIGKILL, container or host stop, OOM kill, power loss —
the memory file is left empty or half-written.
That file is the only persistence layer for the knowledge graph, so the
window is small but the loss is total and unrecoverable.
The fix writes to a temporary file in the same directory and renames it
over the target. `rename(2)` is atomic on POSIX filesystems: a reader
sees either the complete old file or the complete new one, never an
intermediate state. Keeping the temp file in the same directory ensures
the rename stays on one filesystem, since cross-device renames fail with
EXDEV. On failure the temp file is removed so no strays accumulate.
Tests added in `__tests__/atomic-save.test.ts`:
- the live memory file is never opened for truncating writes
- a committed graph survives a write that fails midway
- no temporary files remain after a successful write
- the temporary file is cleaned up when the rename fails
- graph contents still round-trip correctly across reloads
The first and fourth fail against the previous implementation.
Full suite: 55 passed (50 existing, 5 new). `tsc --noEmit` clean.
Fixes#4614
* fix(memory): use randomBytes for temp filename to avoid concurrent collision
---------
Co-authored-by: teddiesloco <teddiesloco@users.noreply.github.com>
The move_file tool description and README both state the operation fails if
the destination already exists, but the handler called fs.rename directly,
which silently overwrites the destination. Since this server ships no delete
tool, move_file effectively provided unadvertised, irreversible file
deletion: moving any file onto an existing target destroyed the target.
Add a moveFile helper in lib.ts that rejects when the destination already
exists (checked with lstat, so an existing symlink is detected rather than
followed) and only renames when the target is free, and use it from the
move_file handler. Behaviour now matches the documented contract.
Fixes#4628
* fix(filesystem): preserve file permissions during write and edit operations
The atomic write pattern (write temp file + rename) replaces the original
inode, causing the new file to have default 0644 permissions regardless of
what the original file had. This breaks executable scripts and other files
with non-default permissions.
Fix: capture stat.mode before writing and restore it with chmod after rename.
Fixes both writeFileContent() and applyFileEdits().
* fix(filesystem): mask chmod mode and keep chmod failure from failing the write
Pass origStats.mode & 0o777 to chmod instead of the full st_mode. Move
the chmod out of the try whose catch unlinks the temp file and rethrows,
since rename has already succeeded by then. Add a test that an EPERM
from chmod does not reject the write.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018Wo28CHPXyM3DHoLWvKnCK
---------
Co-authored-by: Dustin Rudiger <drudiger@apple.com>
Co-authored-by: olaservo <olahungerford@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
resources/templates.ts:
- `parseResourceId` had a guard that compared the URI against both
`textUriBase` and `blobUriBase` with `&&`. Those prefixes are mutually
exclusive, so the condition is always false and the branch is dead.
Drop it; the SDK's template-based routing already guarantees the URI
prefix is one of the two before the handler runs. The remaining
positive-integer check on `resourceId` is preserved.
resources/subscriptions.ts:
- `sendSimulatedResourceUpdates` had an `else` branch that called
`subscribers.delete(sessionId)` whenever the session wasn't in a URI's
subscriber set, with a comment claiming the session had disconnected.
That conclusion doesn't follow — a session not subscribed to URI A
can still be subscribed to URI B — and the delete is a no-op when
the element is absent anyway. Remove the branch.
No behavioral change. Existing 95 / 95 tests in `__tests__` still pass.
Co-authored-by: Jia Xuan <1060996408+jiaxuan@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Return '0 B' for negative byte values instead of 'NaN B'.
File sizes cannot be negative, so this is a safe default.
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Users hitting the 2.0.0 startup failure land on the README first. Also makes
the three packages qualify for the next release: the release workflow selects
packages by .py/.ts/.md changes, so a dependency-only fix would merge without
publishing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
mcp 2.0.0 renamed McpError to MCPError and replaced the low-level Server
decorators with constructor handlers. The three servers had no upper bound,
so a fresh uvx install has resolved 2.0.0 since 2026-07-28 and failed to
start: fetch and time raise ImportError on the McpError import, git raises
AttributeError on server.list_tools().
The floor moves to 1.29.0, the last 1.x release. The previous floors (1.0.0
for git, 1.1.3 for fetch, 1.23.0 for time) resolved versions affected by
GHSA-vj7q-gjh5-988w, GHSA-jpw9-pfvf-9f58, and GHSA-hvrp-rf83-w775.
Porting to the v2 SDK is tracked separately.
Closes#4560Closes#4570Closes#4580
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Every filesystem tool operates only on the local filesystem within its allowed
directories — none reaches an open or external world — but none declared the
MCP `openWorldHint` annotation, leaving open-world-hint coverage at 0/14. Set
`openWorldHint: false` on all 14 tools and document it in the README's tool
annotations section.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>