From a2cf2533dfc1eb714d72d0d6dbf6ebe91d69a7a2 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:21:44 -0500 Subject: [PATCH 01/76] fix(filesystem): describe edit_file's oldText matching rule in its schema The edits[].oldText parameter description said "must match exactly", contradicting edit_file's own description and its matching: line endings never matter, and with no exact match a run of whole lines matches when each is equal ignoring leading and trailing whitespace, newText taking the file's indentation. State that rule, align the README's oldText entry, and pin the tools/list description in a protocol-level test. Closes #5688 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/filesystem-oldtext-description.md | 5 ++ src/filesystem/README.md | 2 +- .../edit-oldtext-description.test.ts | 79 +++++++++++++++++++ src/filesystem/server.ts | 10 ++- 4 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 .changeset/filesystem-oldtext-description.md create mode 100644 src/filesystem/__tests__/edit-oldtext-description.test.ts diff --git a/.changeset/filesystem-oldtext-description.md b/.changeset/filesystem-oldtext-description.md new file mode 100644 index 0000000000..433bc05b9b --- /dev/null +++ b/.changeset/filesystem-oldtext-description.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-filesystem": patch +--- + +`edit_file`'s `edits[].oldText` parameter description now states the matching rule the tool applies (exact apart from line endings, else whole lines ignoring leading and trailing whitespace), instead of "must match exactly", which contradicted the tool's own description. diff --git a/src/filesystem/README.md b/src/filesystem/README.md index 7435ff3606..280364c14e 100644 --- a/src/filesystem/README.md +++ b/src/filesystem/README.md @@ -221,7 +221,7 @@ Files inside the allowed directories are also [resources](https://modelcontextpr - Inputs: - `path` (string): File to edit - `edits` (array): List of edit operations - - `oldText` (string): Text to search for (can be substring) + - `oldText` (string): Text to search for: an exact substring of the file (line endings aside) or, when there is none, a run of whole lines that differ only in leading and trailing whitespace (see Matching below) - `newText` (string): Text to replace with - `dryRun` (boolean): Preview changes without applying (default: false) - Returns detailed diff and match information for dry runs, otherwise applies changes diff --git a/src/filesystem/__tests__/edit-oldtext-description.test.ts b/src/filesystem/__tests__/edit-oldtext-description.test.ts new file mode 100644 index 0000000000..7bc889a06c --- /dev/null +++ b/src/filesystem/__tests__/edit-oldtext-description.test.ts @@ -0,0 +1,79 @@ +// edit_file's edits[].oldText parameter description, as a client reads it from +// tools/list (#5688). It once said "must match exactly" while the tool's own +// description, and the matching it does, allow line endings to differ and fall +// back to whole lines compared without leading and trailing whitespace. A +// model reads both, so this pins the parameter description to the same rule +// and proves the fallback it describes actually applies. + +import fs from "fs/promises"; +import path from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + call, + connect, + makeTempDir, + quietStderr, + type Connected, +} from "./helpers.js"; + +type SchemaNode = { + description?: string; + properties?: Record; + items?: SchemaNode; +}; + +let dir: string; +let conn: Connected; + +beforeEach(async () => { + // The server logs its roots decision to stderr on every connect. + quietStderr(); + dir = await makeTempDir("mcp-fs-oldtext-"); + conn = await connect([dir]); +}); + +afterEach(async () => { + vi.restoreAllMocks(); + await conn.close(); + await fs.rm(dir, { recursive: true, force: true }); +}); + +async function oldTextDescription(): Promise { + const { tools } = await conn.client.listTools(); + const editFile = tools.find((tool) => tool.name === "edit_file"); + const schema = editFile?.inputSchema as SchemaNode | undefined; + const oldText = schema?.properties?.edits?.items?.properties?.oldText; + expect(typeof oldText?.description).toBe("string"); + return oldText?.description ?? ""; +} + +describe("edit_file edits[].oldText description (#5688)", () => { + it("no longer claims oldText must match exactly", async () => { + expect(await oldTextDescription()).not.toMatch(/must match exactly/i); + }); + + it("states the line-ending and whole-line whitespace rule", async () => { + const description = await oldTextDescription(); + expect(description).toContain("line endings (LF or CRLF) never matter"); + expect(description).toContain( + "a run of whole lines matches if each line is equal once leading and " + + "trailing whitespace is ignored", + ); + expect(description).toContain("newText then takes the file's indentation"); + }); + + it("matches the behavior it describes: unindented lines edit indented ones", async () => { + // "x = 1\ny = 2" is not a substring of the file, so only the whole-line + // fallback can match it, and the replacement takes the file's indentation. + const file = path.join(dir, "sample.py"); + await fs.writeFile(file, "def f():\n x = 1\n y = 2\n"); + const result = await call(conn.client, "edit_file", { + path: file, + edits: [{ oldText: "x = 1\ny = 2", newText: "x = 3\ny = 4" }], + }); + expect(result.isError).toBeFalsy(); + expect(await fs.readFile(file, "utf8")).toBe( + "def f():\n x = 3\n y = 4\n", + ); + }); +}); diff --git a/src/filesystem/server.ts b/src/filesystem/server.ts index 4b7a59ef30..94f74fa9f5 100644 --- a/src/filesystem/server.ts +++ b/src/filesystem/server.ts @@ -111,7 +111,15 @@ const AppendFileArgsSchema = z.object({ }); const EditOperation = z.object({ - oldText: z.string().describe("Text to search for - must match exactly"), + oldText: z + .string() + .describe( + "Text to search for. It matches the file's text exactly, except that line " + + "endings (LF or CRLF) never matter; when there is no exact match, a run of " + + "whole lines matches if each line is equal once leading and trailing " + + "whitespace is ignored, and newText then takes the file's indentation. " + + "Whitespace inside a line must match.", + ), newText: z.string().describe("Text to replace with"), }); From 6fcfd186cea781dd11efa0381b2c24704bddfff9 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:22:02 -0500 Subject: [PATCH 02/76] test(everything): pin that error paths carry no credential value Plant a credential-like OPENAI_API_KEY and assert that it appears in neither the validation errors of get-structured-content and get-annotated-message nor gzip-file-as-resource's private-address refusal, with GET_ENV_INCLUDE_SECRETS off and on. Each case also pins what the error does say, and the opt-in case first shows get-env returning the value unmasked, so no absence assertion is vacuous. Cases first prototyped on the issue by Shanmukh-l33t. Closes #5646 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .../error-path-secret-hygiene.test.ts | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 src/everything/__tests__/error-path-secret-hygiene.test.ts diff --git a/src/everything/__tests__/error-path-secret-hygiene.test.ts b/src/everything/__tests__/error-path-secret-hygiene.test.ts new file mode 100644 index 0000000000..08d595ad1a --- /dev/null +++ b/src/everything/__tests__/error-path-secret-hygiene.test.ts @@ -0,0 +1,130 @@ +/** + * Characterizes that a credential value does not surface through the error + * paths of tools other than `get-env` (#5646). The `get-env` masking contract + * is pinned on its own success path in `tools.test.ts`; this file plants a + * value under a name every reading of the masking rule treats as + * credential-like (`OPENAI_API_KEY`) and checks the whole serialized result + * of a validation error and of `gzip-file-as-resource`'s private-address + * refusal for it, with `GET_ENV_INCLUDE_SECRETS` off and on. The opt-in is + * documented as opening `get-env`'s own output, not other tools' errors. + * + * An absence assertion passes vacuously when the surface it reads is empty + * or is not the one intended, so each case also pins what the error does + * say (the problem with the argument, or that the address is not public), + * and the opt-in case first shows `get-env` really returns the value + * unmasked, so the flag is known to be in effect. + * + * The gzip tool reads `GZIP_ALLOW_PRIVATE_IPS` when its module loads, so it + * is cleared before the server is imported: the refusal must not depend on + * the developer's shell. The cases were first prototyped by GitHub user + * Shanmukh-l33t on the issue. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { connect, contentOf, textOf, type Session } from "./harness.js"; +import { INCLUDE_SECRETS_VAR } from "../tools/get-env.js"; + +vi.hoisted(() => { + vi.stubEnv("GZIP_ALLOW_PRIVATE_IPS", ""); +}); + +/** The planted credential value, unique enough not to occur by accident. */ +const SECRET = "planted-secret-5646-7f3a"; + +/** A loopback URL the gzip tool refuses before requesting anything. */ +const LOOPBACK_URL = "http://127.0.0.1:9/secret"; + +let session: Session | undefined; + +afterEach(async () => { + await session?.close(); + session = undefined; + vi.unstubAllEnvs(); +}); + +/** + * Plants the secret, sets the opt-in, and opens a session on a fresh server. + * + * @param {string | undefined} includeSecrets - The value for GET_ENV_INCLUDE_SECRETS. + * @returns {Promise} The connected session. + */ +async function open(includeSecrets: string | undefined): Promise { + vi.stubEnv("OPENAI_API_KEY", SECRET); + vi.stubEnv(INCLUDE_SECRETS_VAR, includeSecrets); + session = await connect(); + return session; +} + +/** + * Calls a tool and returns the result with the text of its content joined. + * + * @param {Session} s - The session to call through. + * @param {string} name - The tool name. + * @param {Record} args - The tool arguments. + * @returns {Promise<{ serialized: string; text: string; isError: unknown }>} + * The whole result as JSON, its text, and its error flag. + */ +async function callTool( + s: Session, + name: string, + args: Record, +): Promise<{ serialized: string; text: string; isError: unknown }> { + const result = await s.client.callTool({ name, arguments: args }); + return { + serialized: JSON.stringify(result), + text: contentOf(result).map(textOf).join("\n"), + isError: result.isError, + }; +} + +describe("error paths carry no credential value", () => { + it("not in a validation error, with masking on", async () => { + const s = await open(undefined); + + const structured = await callTool(s, "get-structured-content", { + location: "Paris", + }); + expect(structured.isError).toBe(true); + expect(structured.text).toContain( + "Invalid arguments for tool get-structured-content", + ); + expect(structured.text).toContain("location: Invalid option"); + expect(structured.serialized).not.toContain(SECRET); + + const annotated = await callTool(s, "get-annotated-message", { + messageType: "info", + }); + expect(annotated.isError).toBe(true); + expect(annotated.text).toContain( + "Invalid arguments for tool get-annotated-message", + ); + expect(annotated.text).toContain("messageType: Invalid option"); + expect(annotated.serialized).not.toContain(SECRET); + }); + + it("not in the gzip tool's private-address refusal, with masking on", async () => { + const s = await open(undefined); + const refusal = await callTool(s, "gzip-file-as-resource", { + name: "x.gz", + data: LOOPBACK_URL, + }); + expect(refusal.isError).toBe(true); + expect(refusal.text).toContain("not a public address"); + expect(refusal.serialized).not.toContain(SECRET); + }); + + it("not in the gzip tool's refusal even with GET_ENV_INCLUDE_SECRETS=1", async () => { + const s = await open("1"); + + // Control: the opt-in is in effect, so get-env returns the value as is. + const env = await s.client.callTool({ name: "get-env", arguments: {} }); + expect(JSON.parse(textOf(contentOf(env)[0])).OPENAI_API_KEY).toBe(SECRET); + + const refusal = await callTool(s, "gzip-file-as-resource", { + name: "x.gz", + data: LOOPBACK_URL, + }); + expect(refusal.isError).toBe(true); + expect(refusal.text).toContain("not a public address"); + expect(refusal.serialized).not.toContain(SECRET); + }); +}); From f4acaa5f7b30a477167a1a98c995dcaf47e96f15 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:22:49 -0500 Subject: [PATCH 03/76] fix(everything): fall back to the default on an unusable gzip limit GZIP_MAX_FETCH_SIZE and GZIP_MAX_FETCH_TIME_MILLIS were parsed with Number(...), so a value such as "10MB" became NaN: the size cap stopped applying and every fetch was aborted at once. A value that is not a whole number in range now falls back to the documented default, with a one-line warning on stderr (never stdout, which carries stdio framing). Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/gzip-unusable-limits.md | 5 + src/everything/README.md | 2 + .../__tests__/gzip-unusable-limits.test.ts | 171 ++++++++++++++++++ src/everything/docs/instructions.md | 2 +- src/everything/docs/structure.md | 5 +- src/everything/tools/gzip-file-as-resource.ts | 49 ++++- 6 files changed, 226 insertions(+), 8 deletions(-) create mode 100644 .changeset/gzip-unusable-limits.md create mode 100644 src/everything/__tests__/gzip-unusable-limits.test.ts diff --git a/.changeset/gzip-unusable-limits.md b/.changeset/gzip-unusable-limits.md new file mode 100644 index 0000000000..de7dcaa029 --- /dev/null +++ b/.changeset/gzip-unusable-limits.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-everything": patch +--- + +`gzip-file-as-resource`: a `GZIP_MAX_FETCH_SIZE` or `GZIP_MAX_FETCH_TIME_MILLIS` value that is not a whole number (such as `10MB`, an empty string or a negative) now falls back to the documented default, with a one-line warning on stderr, instead of silently removing the size cap and aborting every fetch at once. diff --git a/src/everything/README.md b/src/everything/README.md index 1689bd8b74..adf9ee2d28 100644 --- a/src/everything/README.md +++ b/src/everything/README.md @@ -39,6 +39,8 @@ The `gzip-file-as-resource` tool fetches the URL it is given, so these environme | `GZIP_ALLOWED_DOMAINS` | empty (any name) | Comma-separated host names; a host must be one of them or a subdomain of one. Checked on the caller's URL and on every redirect hop | | `GZIP_ALLOW_PRIVATE_IPS` | off | Set to `1` or `true` to allow loopback, private (RFC 1918), CGNAT, link-local (cloud metadata) and other non-public addresses | +`GZIP_MAX_FETCH_SIZE` takes a whole number of bytes, and `GZIP_MAX_FETCH_TIME_MILLIS` a whole number of milliseconds up to 2147483647, with no unit suffix. A value that is neither (an empty string, `10MB`, a negative or a fraction) is not used: the server writes a one-line warning to stderr and applies the default instead. + By default the tool refuses a URL whose host resolves to a non-public address, and follows at most five redirects, checking each hop the same way. An IPv6 address that wraps an IPv4 one (IPv4-mapped, IPv4-translated, or in the NAT64 prefix `64:ff9b::/96`) is judged by that IPv4, and any other IPv6 address outside global unicast (`2000::/3`) is refused. `GZIP_ALLOWED_DOMAINS` filters names, not addresses: a listed name that resolves to a private address is still refused unless `GZIP_ALLOW_PRIVATE_IPS` is set. The address is checked before the request and resolved again when it is made, so a DNS answer that changes in between (DNS rebinding) is not caught. `data:` URLs are not fetched, so neither check applies to them. ## Requirements diff --git a/src/everything/__tests__/gzip-unusable-limits.test.ts b/src/everything/__tests__/gzip-unusable-limits.test.ts new file mode 100644 index 0000000000..95dcaca7f6 --- /dev/null +++ b/src/everything/__tests__/gzip-unusable-limits.test.ts @@ -0,0 +1,171 @@ +/** + * Pins what `gzip-file-as-resource` does when `GZIP_MAX_FETCH_SIZE` or + * `GZIP_MAX_FETCH_TIME_MILLIS` holds a value that cannot be used as a limit + * (#5642): it falls back to the documented default (10 MiB, 30000 ms) and + * writes a one-line warning to stderr, never stdout, which carries the stdio + * transport's messages. Before the fix the value parsed to NaN, so the size + * cap silently stopped applying and every fetch timed out at once. + * + * The tool reads both variables once, when its module loads, so this file + * sets them, and spies on stdout and stderr, before it imports the server + * (vitest gives each test file its own module graph). The spies also keep the + * expected warnings off the console. The fixture is on loopback, so the file + * sets `GZIP_ALLOW_PRIVATE_IPS` too. `limitFromEnv`'s other unusable inputs + * are covered by calling it directly. + */ +import { createServer as createHttpServer, type Server } from "node:http"; +import { once } from "node:events"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, + type MockInstance, +} from "vitest"; +import type { Session } from "./harness.js"; + +const TEN_MIB = 10 * 1024 * 1024; + +let harness: typeof import("./harness.js"); +let limitFromEnv: typeof import("../tools/gzip-file-as-resource.js").limitFromEnv; +let http: Server; +let base: string; +let stderr: MockInstance; +let stdout: MockInstance; +// What the module wrote while it loaded, captured before any test runs. +let stderrAtLoad: string; +let stdoutAtLoad: string; + +function written(spy: MockInstance): string { + return spy.mock.calls.map((call) => String(call[0])).join(""); +} + +beforeAll(async () => { + vi.stubEnv("GZIP_MAX_FETCH_SIZE", "not-a-number"); + vi.stubEnv("GZIP_MAX_FETCH_TIME_MILLIS", "30s"); + vi.stubEnv("GZIP_ALLOW_PRIVATE_IPS", "1"); + stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + try { + harness = await import("./harness.js"); + ({ limitFromEnv } = await import("../tools/gzip-file-as-resource.js")); + } finally { + stderrAtLoad = written(stderr); + stdoutAtLoad = written(stdout); + stdout.mockRestore(); + } + + http = createHttpServer((req, res) => { + if (req.url === "/big") { + res.writeHead(200, { "content-length": String(TEN_MIB + 1) }); + res.end(Buffer.alloc(TEN_MIB + 1, 0x61)); + return; + } + if (req.url === "/slow") { + // Slower than the 1 ms a NaN timeout collapses to, far inside 30 s. + setTimeout(() => res.end("slow"), 200); + return; + } + res.end("small"); + }); + http.listen(0); + await once(http, "listening"); + const address = http.address(); + if (address === null || typeof address === "string") + throw new Error("no port"); + base = `http://127.0.0.1:${address.port}`; +}); + +afterAll(async () => { + stderr.mockRestore(); + vi.unstubAllEnvs(); + http.closeAllConnections(); + await new Promise((resolve) => http.close(resolve)); +}); + +const sessions: Session[] = []; + +afterEach(async () => { + await Promise.all(sessions.splice(0).map((s) => s.close())); +}); + +async function gzip(path: string, name: string) { + const s = await harness.connect(); + sessions.push(s); + return s.client.callTool({ + name: "gzip-file-as-resource", + arguments: { name, data: `${base}${path}` }, + }); +} + +describe("gzip-file-as-resource with unusable limit values", () => { + it("warns on stderr for each variable, naming the default it uses", () => { + expect(stderrAtLoad).toContain( + 'Warning: GZIP_MAX_FETCH_SIZE="not-a-number" is not a whole number from 0 to 9007199254740991; using the default, 10485760.\n', + ); + expect(stderrAtLoad).toContain( + 'Warning: GZIP_MAX_FETCH_TIME_MILLIS="30s" is not a whole number from 0 to 2147483647; using the default, 30000.\n', + ); + }); + + it("writes nothing to stdout, which the stdio transport owns", () => { + expect(stdoutAtLoad).toBe(""); + }); + + it("still fetches a small file (the tool itself works)", async () => { + const result = await gzip("/small", "small.txt.gz"); + expect(result.isError).toBeFalsy(); + }); + + it("refuses a fetch larger than the documented 10 MiB cap", async () => { + const result = await gzip("/big", "big.bin.gz"); + expect(result.isError).toBe(true); + expect(harness.textOf(harness.contentOf(result)[0])).toBe( + `Content-Length for ${base}/big exceeds max of ${TEN_MIB}: ${TEN_MIB + 1}`, + ); + }); + + it("gives a fetch the documented 30 s, not the 1 ms a NaN timeout means", async () => { + const result = await gzip("/slow", "slow.txt.gz"); + expect(result.isError).toBeFalsy(); + }); +}); + +describe("limitFromEnv", () => { + it.each([ + ["0", 0], + ["16", 16], + [" 150 ", 150], + ["2147483647", 2147483647], + ])("uses a whole number in range: %j", (raw, expected) => { + stderr.mockClear(); + expect(limitFromEnv("LIMIT", raw, 7, 2147483647)).toBe(expected); + expect(stderr).not.toHaveBeenCalled(); + }); + + it("uses the default, silently, when the variable is unset", () => { + stderr.mockClear(); + expect(limitFromEnv("LIMIT", undefined, 7)).toBe(7); + expect(stderr).not.toHaveBeenCalled(); + }); + + it.each(["", " ", "10MB", "-1", "1.5", "Infinity", "NaN", "2147483648"])( + "falls back to the default, with a warning, for %j", + (raw) => { + stderr.mockClear(); + expect(limitFromEnv("LIMIT", raw, 7, 2147483647)).toBe(7); + expect(written(stderr)).toBe( + `Warning: LIMIT=${JSON.stringify(raw)} is not a whole number from 0 to 2147483647; using the default, 7.\n`, + ); + }, + ); + + it("bounds a limit by MAX_SAFE_INTEGER when no maximum is given", () => { + stderr.mockClear(); + expect(limitFromEnv("LIMIT", "1e300", 7)).toBe(7); + expect(stderr).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/everything/docs/instructions.md b/src/everything/docs/instructions.md index ca5ca6bbba..68379ed1db 100644 --- a/src/everything/docs/instructions.md +++ b/src/everything/docs/instructions.md @@ -20,7 +20,7 @@ The server serves two protocol eras. A client on protocol version 2026-07-28 con ## 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` +- `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 `""`; 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 diff --git a/src/everything/docs/structure.md b/src/everything/docs/structure.md index 20f2317522..370b21488a 100644 --- a/src/everything/docs/structure.md +++ b/src/everything/docs/structure.md @@ -194,8 +194,9 @@ src/everything - returns an inline `resource` with the gzipped data. - The linked resource is a per-session resource at `demo://resource/session/` (`resources/session.ts`) for a 2025-era client, and a minted one at `demo://resource/minted//` (`resources/minted.ts`) for a 2026-07-28 client, with `mimeType: application/gzip`. - Environment controls: - - `GZIP_MAX_FETCH_SIZE` (bytes, default 10 MiB) - - `GZIP_MAX_FETCH_TIME_MILLIS` (ms, default 30000) + - `GZIP_MAX_FETCH_SIZE` (whole bytes, default 10 MiB) + - `GZIP_MAX_FETCH_TIME_MILLIS` (whole ms up to 2147483647, default 30000) + - A size or time value that is not such a whole number falls back to its default, with a one-line warning on stderr - `GZIP_ALLOWED_DOMAINS` (comma-separated name allowlist, checked on the caller's URL and on every redirect hop; empty means any name is allowed) - `GZIP_ALLOW_PRIVATE_IPS` (`1`/`true` to allow loopback, private, link-local and other non-public addresses; by default a host that resolves to one is refused, on every hop) - `simulate-research-query.ts` diff --git a/src/everything/tools/gzip-file-as-resource.ts b/src/everything/tools/gzip-file-as-resource.ts index 3d646f6b8f..3f5768d7d0 100644 --- a/src/everything/tools/gzip-file-as-resource.ts +++ b/src/everything/tools/gzip-file-as-resource.ts @@ -36,14 +36,53 @@ import { import type { ServerContext } from "../server/context.js"; import { RESOURCE_ICONS, TOOL_ICONS } from "../server/icons.js"; -// Maximum input file size - 10 MB default -const GZIP_MAX_FETCH_SIZE = Number( - process.env.GZIP_MAX_FETCH_SIZE ?? String(10 * 1024 * 1024), +// The longest delay setTimeout honors. A larger one is silently replaced +// with 1 ms, which would abort every fetch at once. +const MAX_TIMER_MILLIS = 2 ** 31 - 1; + +/** + * Reads a numeric limit from an environment variable's raw value (#5642). + * Unset means the default. A value that is not a whole number from 0 to + * `max` (an empty string, text such as "10MB", a negative, a fraction, + * Infinity) cannot be used as a limit: comparing against NaN is always + * false, so it would silently remove the cap. Such a value is replaced by + * the default, with a one-line warning on stderr, never stdout, which + * carries the stdio transport's messages. + * + * @param name The variable's name, for the warning. + * @param raw The variable's value, or undefined when it is unset. + * @param fallback The documented default. + * @param max The largest usable value. + * @returns The limit to apply. + */ +export function limitFromEnv( + name: string, + raw: string | undefined, + fallback: number, + max: number = Number.MAX_SAFE_INTEGER, +): number { + if (raw === undefined) return fallback; + const value = raw.trim() === "" ? NaN : Number(raw); + if (Number.isSafeInteger(value) && value >= 0 && value <= max) return value; + process.stderr.write( + `Warning: ${name}=${JSON.stringify(raw)} is not a whole number from 0 to ${max}; using the default, ${fallback}.\n`, + ); + return fallback; +} + +// Maximum input file size - 10 MiB default. +const GZIP_MAX_FETCH_SIZE = limitFromEnv( + "GZIP_MAX_FETCH_SIZE", + process.env.GZIP_MAX_FETCH_SIZE, + 10 * 1024 * 1024, ); // Maximum fetch time - 30 seconds default. -const GZIP_MAX_FETCH_TIME_MILLIS = Number( - process.env.GZIP_MAX_FETCH_TIME_MILLIS ?? String(30 * 1000), +const GZIP_MAX_FETCH_TIME_MILLIS = limitFromEnv( + "GZIP_MAX_FETCH_TIME_MILLIS", + process.env.GZIP_MAX_FETCH_TIME_MILLIS, + 30 * 1000, + MAX_TIMER_MILLIS, ); // Comma-separated list of allowed domains, matched by name on every request From 954ec0163d55a4f30288ff98a179e292753b678a Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:21 -0500 Subject: [PATCH 04/76] test(filesystem): pin the new oldText description in the schema snapshot Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/filesystem/__tests__/server-tools.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/filesystem/__tests__/server-tools.test.ts b/src/filesystem/__tests__/server-tools.test.ts index eadae875a4..2d3993bb99 100644 --- a/src/filesystem/__tests__/server-tools.test.ts +++ b/src/filesystem/__tests__/server-tools.test.ts @@ -273,7 +273,12 @@ describe("server identity and tool list", () => { properties: { oldText: { type: "string", - description: "Text to search for - must match exactly", + description: + "Text to search for. It matches the file's text exactly, except that line " + + "endings (LF or CRLF) never matter; when there is no exact match, a run of " + + "whole lines matches if each line is equal once leading and trailing " + + "whitespace is ignored, and newText then takes the file's indentation. " + + "Whitespace inside a line must match.", }, newText: { type: "string", From d104316e8e3b70402c60a395d076097a6aed8551 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:22 -0500 Subject: [PATCH 05/76] test(memory): pin what a save does when the graph file path is a symlink Reads follow the link to its target; a save's atomic rename replaces the link itself with a regular file holding the whole graph, and the link's former target is left byte-for-byte unchanged. Characterization only, no behavior change. POSIX only, like the other symlink tests in the suite. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .../__tests__/graph-path-symlink.test.ts | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/memory/__tests__/graph-path-symlink.test.ts diff --git a/src/memory/__tests__/graph-path-symlink.test.ts b/src/memory/__tests__/graph-path-symlink.test.ts new file mode 100644 index 0000000000..37391e0730 --- /dev/null +++ b/src/memory/__tests__/graph-path-symlink.test.ts @@ -0,0 +1,87 @@ +// Characterization tests for a graph file path that is itself a symlink +// (#5644), a routine setup when an operator points MEMORY_FILE_PATH at another +// volume or a backup location. The README promises atomic saves by rename and +// is silent on symlinks, so these pin what the server does today, driven +// through an SDK Client over an in-memory transport: reads follow the link to +// its target, and a save's rename lands on the path itself, replacing the link +// with a regular file that holds the whole graph and leaving the link's former +// target byte-for-byte unchanged. They pin current behavior and do not endorse +// it; whether a save should write through the link is a separate decision. +// POSIX only: creating a symlink on Windows needs privileges, as in +// persistence.test.ts. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import { call, connect, makeTempGraph, readFileText } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +const old = { name: "Old", entityType: "t", observations: [] }; +const added = { name: "New", entityType: "t", observations: [] }; + +describe.skipIf(process.platform === "win32")( + "memory server when the graph file path is a symlink", + () => { + let linkPath: string; + let targetPath: string; + let cleanup: () => Promise; + let conn: Connection | undefined; + + beforeEach(async () => { + let dir: string; + ({ dir, filePath: linkPath, cleanup } = await makeTempGraph()); + conn = undefined; + targetPath = path.join(dir, "real.jsonl"); + await fs.writeFile( + targetPath, + JSON.stringify({ type: "entity", ...old }) + "\n", + ); + await fs.symlink(targetPath, linkPath); + }); + + afterEach(async () => { + await conn?.close(); + await cleanup(); + }); + + async function entityNames(connection: Connection): Promise { + const { structuredContent } = await call(connection.client, "read_graph"); + const { entities } = structuredContent as { + entities: { name: string }[]; + }; + return entities.map((e) => e.name); + } + + it("reads the graph through the symlink and leaves the link in place", async () => { + conn = await connect(linkPath); + + expect(await entityNames(conn)).toEqual(["Old"]); + expect((await fs.lstat(linkPath)).isSymbolicLink()).toBe(true); + expect(await fs.readlink(linkPath)).toBe(targetPath); + }); + + it("replaces the symlink with a regular file on write and leaves the target untouched", async () => { + const targetBefore = await readFileText(targetPath); + conn = await connect(linkPath); + + const result = await call(conn.client, "create_entities", { + entities: [added], + }); + expect(result.isError).toBeFalsy(); + + // The rename lands on the path itself: the link is gone, and the path + // is a regular file holding the whole graph, old and new. + const stat = await fs.lstat(linkPath); + expect(stat.isSymbolicLink()).toBe(false); + expect(stat.isFile()).toBe(true); + expect(await entityNames(conn)).toEqual(["Old", "New"]); + + // A fresh server over the same path reads the same graph back. + await conn.close(); + conn = await connect(linkPath); + expect(await entityNames(conn)).toEqual(["Old", "New"]); + + // The link's former target was never written through it. + expect(await readFileText(targetPath)).toBe(targetBefore); + }); + }, +); From 9ff9867d58b54cde658149e754c32f9c04b9c343 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:37 -0500 Subject: [PATCH 06/76] docs(memory): say what happens to lines of the memory file the server cannot read Which line shapes are skipped, which of them log to stderr and which do not, that every save keeps them and they count toward MEMORY_MAX_FILE_BYTES, that no tool reaches them, and that the fix is a hand edit with the clients stopped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..2d32338f11 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -318,6 +318,17 @@ By default nothing caps the graph. Set `MEMORY_MAX_ENTITIES`, `MEMORY_MAX_RELATI - The delete tools are never refused, so a graph over a limit (one that grew before the limit was set, or lowered) can always be shrunk. While it is over, calls that would grow it further on that dimension are refused. - `MEMORY_MAX_FILE_BYTES` counts the bytes of the file as it would be saved, unreadable lines included, so it bounds the cost of each write directly. The counts are easier to reason about but do not bound how long each entity's observations grow. +#### Lines the server cannot read + +Each line of the memory file is expected to be one JSON object with `"type": "entity"` or `"type": "relation"` and the fields described under [Core Concepts](#core-concepts). The server reads the whole file on every tool call, and leaves any other non-blank line out of the graph it loads: a line that is not JSON, a JSON value that is not an object (a number, a string, `null`), a JSON array, an object whose `type` is missing or is neither `entity` nor `relation`, and an entity or relation that fails its schema (an entity with no `entityType`, an observation that is not a string, a relation with no `relationType`, say). + +- **Most skipped lines are logged to stderr, not all.** A line that is not JSON logs `Skipping malformed line in memory file`, a non-object value logs `Skipping non-object line in memory file`, and an entity or relation that fails its schema logs `Skipping invalid entity in memory file:` or `Skipping invalid relation in memory file:` followed by the fields at fault. A JSON array, and an object whose `type` is missing or unknown, are skipped without a message. The messages repeat each time the file is read, so on every tool call. +- **Skipped lines are kept.** Every save writes them back unchanged, after the graph's own lines, so a write never drops data the server could not read. Blank lines are not kept: a save removes them. +- **Skipped lines count toward `MEMORY_MAX_FILE_BYTES`**, since they are part of the file each save writes. +- **No tool can reach a skipped line.** `read_graph`, `search_nodes` and `open_nodes` do not show it. `delete_entities` and `delete_observations` report its name as not found, and `add_observations` and `create_relations` refuse it as an entity that does not exist. `create_entities` under the same name stores a second record beside the skipped line rather than replacing it. A skipped relation matches no `delete_relations` call, and stays in the file after the entities it names are deleted. + +**The only fix is to edit the file by hand.** Quit every MCP client using the memory file, so that no server writes it while you work, then correct or delete the line in a text editor and start the clients again. A stderr line from the list above, or a `not found` for an entity you can see in the file, is the sign to look. + # VS Code Installation Instructions For quick installation, use one of the one-click installation buttons below: From c26881969a089cef0489c4e9180228cb44f24c2a Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:41 -0500 Subject: [PATCH 07/76] test(memory): pin the neighbouring faces of three pinned invariants Adds protocol-level characterization tests for the sibling faces of rules already pinned elsewhere: delete_relations' exact match also rejects a space-padded relation type; entity identity is case-sensitive while search_nodes is case-insensitive; and observationCount agrees with delete_observations on the next read. Each request names every item once. Test-only; no behavior change. Proposed by @reservoir-cmyk in #5645. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/sibling-faces.test.ts | 115 +++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 src/memory/__tests__/sibling-faces.test.ts diff --git a/src/memory/__tests__/sibling-faces.test.ts b/src/memory/__tests__/sibling-faces.test.ts new file mode 100644 index 0000000000..f1b7842287 --- /dev/null +++ b/src/memory/__tests__/sibling-faces.test.ts @@ -0,0 +1,115 @@ +// Characterization tests for the neighbouring faces of invariants the memory +// server already pins on one face (#5645), driven through an SDK Client over +// an in-memory transport. Each case re-measures a pinned rule on its sibling: +// - delete_relations' exact-match rule is pinned for a different type +// (tools.test.ts); here it is a type padded with a space, which is not the +// same type, so nothing is deleted and the relation survives. +// - search_nodes' case-insensitivity is pinned on the read face +// (knowledge-graph.test.ts); here the write face's identity is shown to be +// case-sensitive, so "Test" and "test" coexist and one search finds both. +// The docs are silent on this asymmetry: it is characterization. +// - observationCount is computed at read time; here it is read right after +// delete_observations, so a stale total would show. +// Every request names each item once, so these hold whatever the server does +// with repeated items in one request. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import type { Client } from "@modelcontextprotocol/client"; +import { call, connect, makeTempGraph } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +describe("neighbouring faces of pinned invariants (#5645)", () => { + let conn: Connection; + let client: Client; + let cleanup: () => Promise; + + beforeEach(async () => { + const graph = await makeTempGraph(); + cleanup = graph.cleanup; + conn = await connect(graph.filePath); + client = conn.client; + }); + + afterEach(async () => { + await conn.close(); + await cleanup(); + }); + + // The structured result of a call that must succeed. + async function structured(name: string, args: Record = {}) { + const result = await call(client, name, args); + expect(result.isError).toBeFalsy(); + return result.structuredContent; + } + + it("delete_relations deletes nothing for a relation type padded with a space", async () => { + const a = { name: "A", entityType: "t", observations: [] }; + const b = { name: "B", entityType: "t", observations: [] }; + const knows = { from: "A", to: "B", relationType: "knows" }; + await structured("create_entities", { entities: [a, b] }); + await structured("create_relations", { relations: [knows] }); + + for (const padded of ["knows ", " knows"]) { + expect( + await structured("delete_relations", { + relations: [{ ...knows, relationType: padded }], + }), + ).toEqual({ + success: true, + message: "Deleted 0 of 1 relations. The rest matched nothing.", + }); + expect(await structured("read_graph")).toEqual({ + entities: [a, b], + relations: [knows], + }); + } + + expect( + await structured("delete_relations", { relations: [knows] }), + ).toEqual({ success: true, message: "Relations deleted successfully" }); + expect(await structured("read_graph")).toEqual({ + entities: [a, b], + relations: [], + }); + }); + + it("keeps 'Test' and 'test' as distinct entities, and a search in either case finds both", async () => { + const upper = { name: "Test", entityType: "T", observations: [] }; + const lower = { name: "test", entityType: "T", observations: [] }; + await structured("create_entities", { entities: [upper, lower] }); + + expect(await structured("read_graph")).toEqual({ + entities: [upper, lower], + relations: [], + }); + for (const query of ["test", "TEST"]) { + expect(await structured("search_nodes", { query })).toEqual({ + entities: [upper, lower], + relations: [], + }); + } + }); + + it("observationCount agrees with delete_observations on the next read", async () => { + await structured("create_entities", { + entities: [ + { name: "E", entityType: "t", observations: ["O1", "O2", "O3"] }, + ], + }); + expect( + await structured("delete_observations", { + deletions: [{ entityName: "E", observations: ["O1"] }], + }), + ).toEqual({ success: true, message: "Observations deleted successfully" }); + + expect(await structured("read_graph", { observationLimit: 0 })).toEqual({ + entities: [ + { name: "E", entityType: "t", observations: [], observationCount: 2 }, + ], + relations: [], + }); + expect(await structured("read_graph")).toEqual({ + entities: [{ name: "E", entityType: "t", observations: ["O2", "O3"] }], + relations: [], + }); + }); +}); From 9167dc56c9e68c355c6cf79e1eca48e120e9fb6f Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:51 -0500 Subject: [PATCH 08/76] fix(memory): store a repeated observation once in create_entities create_entities pushed the requested entities unchanged, so a string repeated within one entity's observations was stored twice, unlike add_observations (#5201), and delete_observations then reported deleting more than it was asked to. Dedupe each new entity's observations in place: skippedEntityNames tells created entities apart by identity, so mapped copies would report every entity as skipped. Closes #5653 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- ...y-create-entities-repeated-observations.md | 5 ++ src/memory/README.md | 1 + .../create-repeated-observations.test.ts | 72 +++++++++++++++++++ src/memory/index.ts | 6 ++ 4 files changed, 84 insertions(+) create mode 100644 .changeset/memory-create-entities-repeated-observations.md create mode 100644 src/memory/__tests__/create-repeated-observations.test.ts diff --git a/.changeset/memory-create-entities-repeated-observations.md b/.changeset/memory-create-entities-repeated-observations.md new file mode 100644 index 0000000000..91a0223528 --- /dev/null +++ b/.changeset/memory-create-entities-repeated-observations.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +`create_entities` now stores a string repeated within one entity's observations once, as `add_observations` does, so a later `delete_observations` reports the count it was asked for. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..56c4876829 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -71,6 +71,7 @@ Example: - `name` (string): Entity identifier - `entityType` (string): Type classification - `observations` (string[]): Associated observations + - A string repeated within one entity's `observations` is stored once, as `add_observations` does - Ignores entities with existing names (and repeats of a name earlier in the same call); their observations are not added - Returns the created entities. When any were skipped, the structured result also lists their names in `skipped`, and a second text item says which were skipped (use `add_observations` to extend an existing entity) diff --git a/src/memory/__tests__/create-repeated-observations.test.ts b/src/memory/__tests__/create-repeated-observations.test.ts new file mode 100644 index 0000000000..700096cad7 --- /dev/null +++ b/src/memory/__tests__/create-repeated-observations.test.ts @@ -0,0 +1,72 @@ +// Regression tests for #5653, driven through an SDK Client over an in-memory +// transport: create_entities stores a string repeated within one entity's +// observations once, as add_observations does since #5201. A stored repeat +// would otherwise make delete_observations report deleting more than it was +// asked to. The fix dedupes in place, so these tests also check that the +// skip report, which tells created entities apart by identity, still holds. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { call, connect, makeTempGraph, textOf } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +describe("create_entities with repeated observations (#5653)", () => { + let cleanup: () => Promise; + let conn: Connection; + + beforeEach(async () => { + const graph = await makeTempGraph(); + cleanup = graph.cleanup; + conn = await connect(graph.filePath); + }); + + afterEach(async () => { + await conn.close(); + await cleanup(); + }); + + async function observationsOf(name: string): Promise { + const result = await call(conn.client, "open_nodes", { names: [name] }); + const { entities } = result.structuredContent as { + entities: { observations: string[] }[]; + }; + return entities[0].observations; + } + + it("stores and returns an observation repeated in one entity once", async () => { + const result = await call(conn.client, "create_entities", { + entities: [ + { name: "A", entityType: "thing", observations: ["x", "y", "x"] }, + ], + }); + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + entities: [{ name: "A", entityType: "thing", observations: ["x", "y"] }], + }); + expect(await observationsOf("A")).toEqual(["x", "y"]); + }); + + it("lets delete_observations report the count it was asked for", async () => { + await call(conn.client, "create_entities", { + entities: [{ name: "A", entityType: "thing", observations: ["x", "x"] }], + }); + const result = await call(conn.client, "delete_observations", { + deletions: [{ entityName: "A", observations: ["x"] }], + }); + expect(result.isError).toBeUndefined(); + expect(textOf(result)).toBe("Observations deleted successfully"); + expect(await observationsOf("A")).toEqual([]); + }); + + it("still reports a skipped entity alongside a deduped one", async () => { + const result = await call(conn.client, "create_entities", { + entities: [ + { name: "A", entityType: "thing", observations: ["x", "x"] }, + { name: "A", entityType: "thing", observations: ["z"] }, + ], + }); + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + entities: [{ name: "A", entityType: "thing", observations: ["x"] }], + skipped: ["A"], + }); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..ae0c3edee1 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -1198,6 +1198,12 @@ export class KnowledgeGraphManager { // Also skip duplicates appearing earlier in this same batch !entities.slice(0, index).some((earlier) => earlier.name === e.name), ); + // A string repeated within one entity's observations is stored once, as + // add_observations does (#5201, #5653). In place, not mapped copies: + // skippedEntityNames tells created entities apart by identity. + for (const e of newEntities) { + e.observations = [...new Set(e.observations)]; + } graph.entities.push(...newEntities); // Only a call that adds something is held to the limits: re-saving can // grow an existing file that was not written in this exact form. From edb349e3cf443893df273538957cc504810ed940 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:24:42 -0500 Subject: [PATCH 09/76] fix(memory): report relations create_relations skipped create_relations returned a bare empty list for a relation that already exists, so an agent could not tell "already there" from "nothing happened". Mirror create_entities: list the skipped relations (existing, or repeated earlier in the same call) in an optional `skipped` field of structuredContent, add a text notice naming them, and say so in the tool description and README. Closes #5654 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-create-relations-skipped.md | 5 ++ src/memory/README.md | 3 +- src/memory/__tests__/tools.test.ts | 41 ++++++++++++++-- src/memory/__tests__/write-limits.test.ts | 5 +- src/memory/index.ts | 48 +++++++++++++++++-- 5 files changed, 92 insertions(+), 10 deletions(-) create mode 100644 .changeset/memory-create-relations-skipped.md diff --git a/.changeset/memory-create-relations-skipped.md b/.changeset/memory-create-relations-skipped.md new file mode 100644 index 0000000000..21e2c5f301 --- /dev/null +++ b/.changeset/memory-create-relations-skipped.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +`create_relations` now reports the relations it skipped because they already exist (or repeat an earlier relation in the same call): the structured result lists them in a new optional `skipped` array, a second text item names them, and the tool description says so. Skipped relations are still not added again ([#5654](https://github.com/modelcontextprotocol/servers/issues/5654)). diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..df5e96abda 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -81,7 +81,8 @@ Example: - `from` (string): Source entity name - `to` (string): Target entity name - `relationType` (string): Relationship type in active voice - - Skips duplicate relations + - Skips relations that already exist (and repeats of a relation earlier in the same call) + - Returns the created relations. When any were skipped, the structured result also lists them in `skipped`, and a second text item says which were skipped - Fails if either the source or target entity doesn't exist - **add_observations** diff --git a/src/memory/__tests__/tools.test.ts b/src/memory/__tests__/tools.test.ts index 8fc5cfeaff..725dbb4100 100644 --- a/src/memory/__tests__/tools.test.ts +++ b/src/memory/__tests__/tools.test.ts @@ -162,7 +162,7 @@ const expectedTools = [ name: "create_relations", title: "Create Relations", description: - "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice", + "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice. A relation already in the graph, or that repeats an earlier relation in the same call, is skipped; the result lists the skipped relations in `skipped`.", inputSchema: { type: "object", properties: { @@ -178,7 +178,10 @@ const expectedTools = [ }, outputSchema: { type: "object", - properties: { relations: { type: "array", items: relationItem(true) } }, + properties: { + relations: { type: "array", items: relationItem(true) }, + skipped: { type: "array", items: relationItem(true) }, + }, required: ["relations"], $schema: JSON_SCHEMA_2020_12, additionalProperties: false, @@ -653,20 +656,52 @@ describe("memory tools over the protocol", () => { ); }); - it("skips relations that already exist or repeat within the batch", async () => { + it("skips relations that already exist or repeat within the batch, and reports them (#5654)", async () => { await call(client, "create_relations", { relations: [aliceKnowsBob] }); const result = await call(client, "create_relations", { relations: [aliceKnowsBob, aliceWorksAtAcme, aliceWorksAtAcme], }); + expect(result.isError).toBeUndefined(); expect(result.structuredContent).toEqual({ relations: [aliceWorksAtAcme], + skipped: [aliceKnowsBob, aliceWorksAtAcme], }); + expect(result.content).toEqual([ + { type: "text", text: JSON.stringify([aliceWorksAtAcme], null, 2) }, + { + type: "text", + text: `Skipped 2 relations that already exist: Alice -[${aliceKnowsBob.relationType}]-> Bob, Alice -[${aliceWorksAtAcme.relationType}]-> ${aliceWorksAtAcme.to}. They are already in the graph, so nothing was added for them.`, + }, + ]); expect(await readGraph()).toEqual({ entities: [alice, bob, acme], relations: [aliceKnowsBob, aliceWorksAtAcme], }); }); + it("reports a repeated call's relation as skipped rather than returning a bare empty list (#5654)", async () => { + await call(client, "create_relations", { relations: [aliceKnowsBob] }); + const result = await call(client, "create_relations", { + relations: [aliceKnowsBob], + }); + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + relations: [], + skipped: [aliceKnowsBob], + }); + expect(result.content).toEqual([ + { type: "text", text: "[]" }, + { + type: "text", + text: `Skipped 1 relation that already exists: Alice -[${aliceKnowsBob.relationType}]-> Bob. It is already in the graph, so nothing was added for it.`, + }, + ]); + expect(await readGraph()).toEqual({ + entities: [alice, bob, acme], + relations: [aliceKnowsBob], + }); + }); + it("treats a different relation type between the same pair as new", async () => { const aliceManagesBob = { ...aliceKnowsBob, relationType: "manages" }; await call(client, "create_relations", { relations: [aliceKnowsBob] }); diff --git a/src/memory/__tests__/write-limits.test.ts b/src/memory/__tests__/write-limits.test.ts index 4e81d934a8..a9ea86705d 100644 --- a/src/memory/__tests__/write-limits.test.ts +++ b/src/memory/__tests__/write-limits.test.ts @@ -220,7 +220,10 @@ describe("write limits", () => { relations: [{ from: "A", to: "B", relationType: "knows" }], }); expect(repeat.isError).toBeUndefined(); - expect(repeat.structuredContent).toEqual({ relations: [] }); + expect(repeat.structuredContent).toEqual({ + relations: [], + skipped: [{ from: "A", to: "B", relationType: "knows" }], + }); }); }); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..90d1996275 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -180,6 +180,29 @@ export function skippedEntitiesNotice(skipped: string[]): string { ); } +// Requested relations that createRelations did not create: the relation +// already existed, or repeated an earlier one in the same batch (#5654). +// createRelations returns the requested relation objects themselves, so +// identity tells them apart, as it does for skippedEntityNames. +export function skippedRelations( + requested: Relation[], + created: Relation[], +): Relation[] { + return requested.filter((r) => !created.includes(r)); +} + +// Text telling the agent which relations create_relations skipped. +export function skippedRelationsNotice(skipped: Relation[]): string { + const one = skipped.length === 1; + const listed = skipped + .map((r) => `${r.from} -[${r.relationType}]-> ${r.to}`) + .join(", "); + return ( + `Skipped ${skipped.length} ${one ? "relation that already exists" : "relations that already exist"}: ` + + `${listed}. ${one ? "It is" : "They are"} already in the graph, so nothing was added for ${one ? "it" : "them"}.` + ); +} + // Opt-in ceilings on how large the write tools may grow the graph (#5525). // Every mutation reads the whole graph file and writes it back under the // cross-process lock, so its cost, and how long it holds the lock, grow @@ -1646,7 +1669,7 @@ export function createServer( { title: "Create Relations", description: - "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice", + "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice. A relation already in the graph, or that repeats an earlier relation in the same call, is skipped; the result lists the skipped relations in `skipped`.", inputSchema: z.object({ relations: z .array(RelationSchema) @@ -1656,6 +1679,8 @@ export function createServer( }), outputSchema: z.object({ relations: z.array(RelationSchema), + // Present only when at least one requested relation was skipped. + skipped: z.array(RelationSchema).optional(), }), annotations: { readOnlyHint: false, @@ -1667,11 +1692,24 @@ export function createServer( async ({ relations }) => { const result = await knowledgeGraphManager.createRelations(relations); notifyGraphUpdated(); + // Existing relations are ignored. Say so, as create_entities does: + // otherwise an empty result reads as nothing having happened (#5654). + const skipped = skippedRelations(relations, result); + const content = [ + { type: "text" as const, text: JSON.stringify(result, null, 2) }, + ]; + if (skipped.length > 0) { + content.push({ + type: "text" as const, + text: skippedRelationsNotice(skipped), + }); + } return { - content: [ - { type: "text" as const, text: JSON.stringify(result, null, 2) }, - ], - structuredContent: { relations: result }, + content, + structuredContent: + skipped.length > 0 + ? { relations: result, skipped } + : { relations: result }, }; }, ); From 2b64c89517c87398d61723a3e896c3b1022ae137 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:24:58 -0500 Subject: [PATCH 10/76] fix(memory): count a repeated delete request item once delete_relations and delete_observations compared the number of stored records removed with the raw request length, so a relation or observation listed twice reported "Deleted 1 of 2 ... The rest matched nothing" although both items matched the same record. Both now count distinct requested items: (from, to, relationType) for relations, keyed collision-free by JSON-encoding the three fields, and (entityName, observation) pairs for observations. The methods count distinct requested items that matched rather than records removed, so a requested item stored twice counts once and the message can never read "Deleted 2 of 1". The response shape and wording are unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-delete-repeated-items.md | 5 + src/memory/README.md | 4 +- src/memory/__tests__/tools.test.ts | 142 +++++++++++++++++++++ src/memory/index.ts | 65 ++++++++-- 4 files changed, 204 insertions(+), 12 deletions(-) create mode 100644 .changeset/memory-delete-repeated-items.md diff --git a/.changeset/memory-delete-repeated-items.md b/.changeset/memory-delete-repeated-items.md new file mode 100644 index 0000000000..a48f98e3a7 --- /dev/null +++ b/.changeset/memory-delete-repeated-items.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +`delete_relations` and `delete_observations` count a request item listed more than once as one item, so a repeated relation or observation no longer reports "Deleted 1 of 2" as if part of the deletion missed. A requested observation or relation stored more than once also counts once. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..e1ba22400f 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -106,7 +106,7 @@ Example: - Each object contains: - `entityName` (string): Target entity - `observations` (string[]): Observations to remove - - No error if an observation doesn't exist; the response reports how many were deleted + - No error if an observation doesn't exist; the response reports how many of the requested observations were deleted, counting an observation listed more than once for the same entity as one - **delete_relations** - Remove specific relations from the graph, keeping the entities they connect (to remove an entity itself, use `delete_entities`) @@ -116,7 +116,7 @@ Example: - `to` (string): Target entity name - `relationType` (string): Relationship type - A relation is deleted only when `from`, `to` and `relationType` all match a stored one exactly; read the stored `relationType` with `open_nodes` (or `search_nodes`) first if unsure - - No error if a relation doesn't exist; the response reports how many were deleted + - No error if a relation doesn't exist; the response reports how many of the requested relations were deleted, counting a relation listed more than once as one - **read_graph** - Read the entire knowledge graph diff --git a/src/memory/__tests__/tools.test.ts b/src/memory/__tests__/tools.test.ts index 8fc5cfeaff..c150b2264c 100644 --- a/src/memory/__tests__/tools.test.ts +++ b/src/memory/__tests__/tools.test.ts @@ -3,6 +3,7 @@ // sees today: the advertised tool list, each tool's text and // structured results, and the error results. A test that pins a known bug // cites its issue, so the PR that fixes it has a test to change. +import { promises as fs } from "fs"; import { describe, it, expect, beforeEach, afterEach } from "vitest"; import type { Client } from "@modelcontextprotocol/client"; import { call, connect, makeTempGraph, textOf } from "./helpers.js"; @@ -424,10 +425,12 @@ describe("memory tools over the protocol", () => { let conn: Connection; let client: Client; let cleanup: () => Promise; + let filePath: string; beforeEach(async () => { const graph = await makeTempGraph(); cleanup = graph.cleanup; + filePath = graph.filePath; conn = await connect(graph.filePath); client = conn.client; }); @@ -449,6 +452,24 @@ describe("memory tools over the protocol", () => { return (await call(client, "read_graph")).structuredContent; } + // Write the graph file directly, one JSON record per line, for stored + // states the tools themselves do not produce (duplicate records, say). + async function writeGraphFile(records: object[]) { + await fs.writeFile( + filePath, + records.map((r) => JSON.stringify(r)).join("\n") + "\n", + ); + } + + // The result every delete tool returns: the message as text and as + // structured content. + function deleteResult(message: string) { + return { + content: [{ type: "text", text: message }], + structuredContent: { success: true, message }, + }; + } + describe("server identity and tool list", () => { it("reports its name, the package version and its capabilities", async () => { expect(client.getServerVersion()).toEqual({ @@ -873,6 +894,69 @@ describe("memory tools over the protocol", () => { structuredContent: { success: true, message }, }); }); + + // #5655: a repeated request item matches the same stored observation, so + // it is one item, not a miss. + it("counts an observation repeated in one entry once", async () => { + const result = await call(client, "delete_observations", { + deletions: [ + { entityName: "Alice", observations: ["likes tea", "likes tea"] }, + ], + }); + expect(result).toEqual(deleteResult("Observations deleted successfully")); + expect(await call(client, "open_nodes", { names: ["Alice"] })).toEqual( + expect.objectContaining({ + structuredContent: { + entities: [{ ...alice, observations: ["works at Acme Corp"] }], + relations: [aliceKnowsBob, aliceWorksAtAcme], + }, + }), + ); + }); + + it("counts an observation repeated across entries for one entity once", async () => { + const result = await call(client, "delete_observations", { + deletions: [ + { entityName: "Alice", observations: ["likes tea"] }, + { entityName: "Alice", observations: ["likes tea"] }, + ], + }); + expect(result).toEqual(deleteResult("Observations deleted successfully")); + }); + + it("counts a repeated observation once next to one that is not there", async () => { + const result = await call(client, "delete_observations", { + deletions: [ + { + entityName: "Alice", + observations: ["likes tea", "likes tea", "never said"], + }, + ], + }); + expect(result).toEqual(deleteResult("Deleted 1 of 2 observations.")); + }); + + it("counts a requested observation stored twice once", async () => { + await writeGraphFile([ + { + type: "entity", + name: "Alice", + entityType: "person", + observations: ["likes tea", "likes tea", "works at Acme Corp"], + }, + ]); + expect( + await call(client, "delete_observations", { + deletions: [ + { entityName: "Alice", observations: ["likes tea", "never said"] }, + ], + }), + ).toEqual(deleteResult("Deleted 1 of 2 observations.")); + expect(await readGraph()).toEqual({ + entities: [{ ...alice, observations: ["works at Acme Corp"] }], + relations: [], + }); + }); }); describe("delete_relations", () => { @@ -918,6 +1002,64 @@ describe("memory tools over the protocol", () => { structuredContent: { success: true, message }, }); }); + + // #5655: a repeated request item matches the same stored relation, so it + // is one item, not a miss. + it("counts a relation repeated in the request once", async () => { + const result = await call(client, "delete_relations", { + relations: [aliceKnowsBob, { ...aliceKnowsBob }], + }); + expect(result).toEqual(deleteResult("Relations deleted successfully")); + expect(await readGraph()).toEqual({ + entities: [alice, bob, acme], + relations: [aliceWorksAtAcme], + }); + }); + + it("counts a repeated relation once next to one that matched nothing", async () => { + const result = await call(client, "delete_relations", { + relations: [ + aliceKnowsBob, + aliceKnowsBob, + { ...aliceKnowsBob, relationType: "likes" }, + ], + }); + expect(result).toEqual( + deleteResult("Deleted 1 of 2 relations. The rest matched nothing."), + ); + }); + + it("counts a requested relation stored twice once", async () => { + await writeGraphFile([ + { type: "entity", ...alice }, + { type: "entity", ...bob }, + { type: "relation", ...aliceKnowsBob }, + { type: "relation", ...aliceKnowsBob }, + ]); + expect( + await call(client, "delete_relations", { relations: [aliceKnowsBob] }), + ).toEqual(deleteResult("Relations deleted successfully")); + expect(await readGraph()).toEqual({ + entities: [alice, bob], + relations: [], + }); + }); + + it("tells relations apart whose fields would join to the same string", async () => { + const stored = { from: "x|y", to: "z", relationType: "t" }; + await writeGraphFile([ + { type: "entity", name: "x|y", entityType: "e", observations: [] }, + { type: "entity", name: "z", entityType: "e", observations: [] }, + { type: "relation", ...stored }, + ]); + expect( + await call(client, "delete_relations", { + relations: [stored, { from: "x", to: "y|z", relationType: "t" }], + }), + ).toEqual( + deleteResult("Deleted 1 of 2 relations. The rest matched nothing."), + ); + }); }); describe("read_graph", () => { diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..d605e4a8a5 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -1291,6 +1291,11 @@ export class KnowledgeGraphManager { }); } + // deletedCount is how many distinct requested (entityName, observation) + // pairs matched a stored observation, not how many stored records went: + // a pair repeated in the request counts once, and so does a pair that + // matched a stored duplicate (#5655). It never exceeds + // countDistinctObservations(deletions), which the tool compares it with. async deleteObservations( deletions: { entityName: string; observations: string[] }[], ): Promise<{ deletedCount: number; missingEntities: string[] }> { @@ -1301,11 +1306,14 @@ export class KnowledgeGraphManager { deletions.forEach((d) => { const entity = graph.entities.find((e) => e.name === d.entityName); if (entity) { - const before = entity.observations.length; + // A pair an earlier entry already removed is no longer stored, so + // it is not counted twice. + deletedCount += [...new Set(d.observations)].filter((o) => + entity.observations.includes(o), + ).length; entity.observations = entity.observations.filter( (o) => !d.observations.includes(o), ); - deletedCount += before - entity.observations.length; } else { missingEntities.push(d.entityName); } @@ -1315,12 +1323,20 @@ export class KnowledgeGraphManager { }); } + // deletedCount is how many distinct requested relations matched a stored + // one, not how many stored records went: a relation repeated in the + // request counts once, and so does one that matched a stored duplicate + // (#5655). It never exceeds countDistinctRelations(relations), which the + // tool compares it with. async deleteRelations( relations: Relation[], ): Promise<{ deletedCount: number }> { return this.withLock(async () => { const { graph, unreadable } = await this.loadGraphWithUnreadable(); - const before = graph.relations.length; + const stored = new Set(graph.relations.map(relationKey)); + const deletedCount = [...new Set(relations.map(relationKey))].filter( + (key) => stored.has(key), + ).length; graph.relations = graph.relations.filter( (r) => !relations.some( @@ -1331,7 +1347,7 @@ export class KnowledgeGraphManager { ), ); await this.saveGraph(graph, unreadable); - return { deletedCount: before - graph.relations.length }; + return { deletedCount }; }); } @@ -1470,6 +1486,37 @@ function limitObservations( })); } +// A relation's identity as one string, for Set lookups. JSON-encoding the +// three fields as an array cannot collide, whatever the names hold; joining +// them with a separator could ("a|b" + "c" against "a" + "b|c"). +function relationKey(r: Relation): string { + return JSON.stringify([r.from, r.to, r.relationType]); +} + +// How many distinct relations a delete_relations request names: the same +// relation listed twice is one request item, so it can match only once +// (#5655). +function countDistinctRelations(relations: Relation[]): number { + return new Set(relations.map(relationKey)).size; +} + +// How many distinct (entityName, observation) pairs a delete_observations +// request names, whether repeated inside one entry or across entries for the +// same entity (#5655). +function countDistinctObservations( + deletions: { entityName: string; observations: string[] }[], +): number { + const byEntity = new Map>(); + for (const d of deletions) { + const observations = byEntity.get(d.entityName) ?? new Set(); + d.observations.forEach((o) => observations.add(o)); + byEntity.set(d.entityName, observations); + } + let total = 0; + byEntity.forEach((observations) => (total += observations.size)); + return total; +} + // Zod schemas for entities and relations const EntitySchema = z.object({ name: z.string().describe("The name of the entity"), @@ -1802,10 +1849,7 @@ export function createServer( const { deletedCount, missingEntities } = await knowledgeGraphManager.deleteObservations(deletions); notifyGraphUpdated(); - const requested = deletions.reduce( - (total, d) => total + d.observations.length, - 0, - ); + const requested = countDistinctObservations(deletions); const message = deletedCount === requested ? "Observations deleted successfully" @@ -1847,10 +1891,11 @@ export function createServer( const { deletedCount } = await knowledgeGraphManager.deleteRelations(relations); notifyGraphUpdated(); + const requested = countDistinctRelations(relations); const message = - deletedCount === relations.length + deletedCount === requested ? "Relations deleted successfully" - : `Deleted ${deletedCount} of ${relations.length} relations. The rest matched nothing.`; + : `Deleted ${deletedCount} of ${requested} relations. The rest matched nothing.`; return { content: [{ type: "text" as const, text: message }], structuredContent: { success: true, message }, From 1616778406737639d9d833f2824fb21a64db7632 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:24:32 -0500 Subject: [PATCH 11/76] fix(filesystem): ship the root LICENSE in the npm package and correct the README license section The package.json says "SEE LICENSE IN LICENSE", but the tarball shipped no LICENSE, and the README said MIT only, contradicting the root LICENSE's MIT to Apache-2.0 transition terms. Commit a copy of the root LICENSE in src/filesystem (npm always packs a root LICENSE, whatever "files" says), and rewrite the README section to match it. pack:verify now fails a tarball missing the license file its manifest names, with the three packages #5700 fixes exempt, and a script test checks each package's packed file list and that the copy matches the root LICENSE. Closes #5639 Signed-off-by: cliffhall Co-Authored-By: Claude Opus 5.5 --- .changeset/filesystem-ship-license.md | 5 + docs/quality-gate.md | 4 +- scripts/pack-and-verify.mjs | 45 +++++- scripts/pack-and-verify.test.mjs | 96 +++++++++++- src/filesystem/LICENSE | 216 ++++++++++++++++++++++++++ src/filesystem/README.md | 8 +- 6 files changed, 369 insertions(+), 5 deletions(-) create mode 100644 .changeset/filesystem-ship-license.md create mode 100644 src/filesystem/LICENSE diff --git a/.changeset/filesystem-ship-license.md b/.changeset/filesystem-ship-license.md new file mode 100644 index 0000000000..77a174aa7d --- /dev/null +++ b/.changeset/filesystem-ship-license.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-filesystem": patch +--- + +Ship the repository's `LICENSE` in the npm package, which `package.json` already pointed at but the tarball left out, and correct the README's license section, which said MIT only, to describe the MIT to Apache-2.0 transition terms in that file. diff --git a/docs/quality-gate.md b/docs/quality-gate.md index bc959c26b9..e1df090e0b 100644 --- a/docs/quality-gate.md +++ b/docs/quality-gate.md @@ -195,7 +195,9 @@ covers: the repo-wide tooling and the guards that keep the gate itself honest. installed server. It catches what the boot smoke cannot, since the smoke runs the checkout: a file missing from the tarball, a dependency that only resolves inside the workspace. It also fails an npm tarball that ships a - test, a test helper or a test runner's config. It needs the network, so it is not a gate + test, a test helper or a test runner's config, and one that leaves out the + license file its `package.json` names (`SEE LICENSE IN LICENSE`; the + packages #5700 has yet to fix are exempt). It needs the network, so it is not a gate stage. `release.yml` runs it before anything publishes, and the `release` skill runs it by hand for the release ledger. - **`npm run format`** rewrites files, so it is something you run, not diff --git a/scripts/pack-and-verify.mjs b/scripts/pack-and-verify.mjs index c1b7c9497b..ecd13315c1 100644 --- a/scripts/pack-and-verify.mjs +++ b/scripts/pack-and-verify.mjs @@ -101,8 +101,10 @@ export function parseArgs(argv) { /** * What is wrong with an npm tarball's contents, judged from its manifest and - * file list alone: every `bin` target must be in it, and no test or test - * config file may be (#4930). Anything subtler (a module the entry point + * file list alone: every `bin` target must be in it, no test or test config + * file may be (#4930), and a license file the manifest names + * (`"license": "SEE LICENSE IN LICENSE"`) must be in it (#5639), unless the + * package is in `LICENSE_PENDING`. Anything subtler (a module the entry point * imports, a data file) is found by actually running the installed bin, which * is the next step. * @@ -124,6 +126,45 @@ export function tarballProblems(manifest, files) { ...files .filter(isTestFile) .map((f) => `${f} is a test file, which a package does not ship`), + ...licenseProblems(manifest, present), + ]; +} + +/** + * The npm packages that do not ship the license file their manifest names + * yet. The filesystem package published with `"license": "SEE LICENSE IN + * LICENSE"` and no LICENSE in its tarball (#5639); these three still do, and + * #5700 fixes them. The check passes them so that their releases are not + * blocked meanwhile. Remove a package from this list in the change that makes + * it ship the file: the script tests fail on a listed package that already + * does, so the list can only shrink. + */ +export const LICENSE_PENDING = new Set([ + "@modelcontextprotocol/server-everything", + "@modelcontextprotocol/server-memory", + "@modelcontextprotocol/server-sequential-thinking", +]); + +/** + * The license file a manifest points at, from the `SEE LICENSE IN ` + * form of its `license` field, or `null` when it names an SPDX expression or + * nothing. + * + * @param {{ license?: string }} manifest + * @returns {string | null} + */ +export function licenseFile(manifest) { + const match = /^SEE LICENSE IN (.+)$/.exec(manifest.license ?? ""); + return match ? match[1].trim() : null; +} + +/** The license file the manifest names, when the tarball lacks it. */ +function licenseProblems(manifest, present) { + const file = licenseFile(manifest); + if (!file || LICENSE_PENDING.has(manifest.name)) return []; + if (present.has(path.posix.normalize(file))) return []; + return [ + `package.json says "${manifest.license}", but ${file} is not in the tarball`, ]; } diff --git a/scripts/pack-and-verify.test.mjs b/scripts/pack-and-verify.test.mjs index 7bac8e1abe..fb2c179a44 100644 --- a/scripts/pack-and-verify.test.mjs +++ b/scripts/pack-and-verify.test.mjs @@ -2,29 +2,44 @@ // tarball check and where an installed command lives. The rest of the script // is `npm pack`, `npm install`, `uv build` and a real server boot, which need // the network and are exercised by running `npm run pack:verify` itself. -// Run via `npm run test:scripts`. +// One test is a guard on the repository as it stands (#5639): each npm +// package's file list, from an offline `npm pack --dry-run`, holds the license +// file its manifest names, with the same text as the root LICENSE. That runs +// in `validate:guards`, so a package that would publish without it fails +// before release rather than at it. Run via `npm run test:scripts`. import { test } from "node:test"; import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, + readFileSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; import { + LICENSE_PENDING, artifactDirProblem, consumerEnv, installedLaunch, isDistribution, isTestFile, + licenseFile, main, parseArgs, tarballProblems, } from "./pack-and-verify.mjs"; +import { SERVERS } from "./smoke-servers.mjs"; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); test("parseArgs separates server names from --out", () => { assert.deepEqual(parseArgs([]), { names: [], out: undefined }); @@ -88,6 +103,85 @@ test("a test or test-config file in the tarball is named (#4930)", () => { ); }); +test("a license file the manifest names must be in the tarball (#5639)", () => { + const manifest = { + name: "@scope/pkg", + bin: { cmd: "dist/index.js" }, + license: "SEE LICENSE IN LICENSE", + }; + assert.deepEqual(tarballProblems(manifest, ["dist/index.js", "LICENSE"]), []); + assert.deepEqual(tarballProblems(manifest, ["dist/index.js"]), [ + 'package.json says "SEE LICENSE IN LICENSE", but LICENSE is not in the tarball', + ]); + // An SPDX expression names no file, so there is nothing to look for. + assert.deepEqual( + tarballProblems({ ...manifest, license: "MIT" }, ["dist/index.js"]), + [], + ); + // A package still waiting on its fix (#5700) is passed meanwhile. + const [pending] = LICENSE_PENDING; + assert.deepEqual( + tarballProblems({ ...manifest, name: pending }, ["dist/index.js"]), + [], + ); +}); + +test("licenseFile reads the SEE LICENSE IN form, and only that", () => { + assert.equal(licenseFile({ license: "SEE LICENSE IN LICENSE" }), "LICENSE"); + assert.equal( + licenseFile({ license: "SEE LICENSE IN docs/LICENSE.txt" }), + "docs/LICENSE.txt", + ); + assert.equal(licenseFile({ license: "Apache-2.0" }), null); + assert.equal(licenseFile({}), null); +}); + +test("each npm package ships the root LICENSE its manifest names, unless pending", () => { + const rootLicense = readFileSync(path.join(repoRoot, "LICENSE"), "utf8"); + const npmServers = SERVERS.filter((s) => s.language === "ts"); + assert.ok(npmServers.length > 0, "no TypeScript servers found"); + const names = new Set(); + for (const server of npmServers) { + const pkgDir = path.join(repoRoot, "src", server.name); + const manifest = JSON.parse( + readFileSync(path.join(pkgDir, "package.json"), "utf8"), + ); + names.add(manifest.name); + const file = licenseFile(manifest); + assert.ok(file, `${manifest.name}: license is not "SEE LICENSE IN "`); + // What `npm pack` would put in the tarball, read without building it: + // `--ignore-scripts` skips the `prepare` build, and `--dry-run` writes + // nothing. The license file does not depend on the build. + const res = spawnSync( + "npm", + ["pack", "--dry-run", "--json", "--ignore-scripts"], + { cwd: pkgDir, encoding: "utf8", shell: process.platform === "win32" }, + ); + assert.equal(res.status, 0, `npm pack failed in ${pkgDir}: ${res.stderr}`); + const shipped = JSON.parse(res.stdout)[0].files.some( + (f) => path.posix.normalize(f.path) === path.posix.normalize(file), + ); + if (LICENSE_PENDING.has(manifest.name)) { + assert.ok( + !shipped, + `${manifest.name} now ships ${file}: remove it from LICENSE_PENDING`, + ); + continue; + } + assert.ok(shipped, `${manifest.name}: ${file} is not in its tarball`); + assert.equal( + readFileSync(path.join(pkgDir, file), "utf8"), + rootLicense, + `src/${server.name}/${file} differs from the root LICENSE: copy it again`, + ); + } + for (const pending of LICENSE_PENDING) + assert.ok( + names.has(pending), + `LICENSE_PENDING names ${pending}, which is not a package here`, + ); +}); + test("isTestFile matches tests, helpers and runner configs, nothing else", () => { for (const f of [ "dist/__tests__/helpers.js", diff --git a/src/filesystem/LICENSE b/src/filesystem/LICENSE new file mode 100644 index 0000000000..4a93985763 --- /dev/null +++ b/src/filesystem/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/src/filesystem/README.md b/src/filesystem/README.md index 7435ff3606..176f60e90f 100644 --- a/src/filesystem/README.md +++ b/src/filesystem/README.md @@ -603,4 +603,10 @@ docker build -t mcp/filesystem -f src/filesystem/Dockerfile . ## License -This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. +This server is distributed under the terms of the [`LICENSE`](LICENSE) file, a copy of the repository's root `LICENSE` that ships in the npm package. The Model Context Protocol project is moving from the MIT License to the Apache License, Version 2.0 (Apache-2.0), so those terms depend on the contribution: + +- New code and specification contributions are licensed under Apache-2.0, as are contributions whose authors have consented to relicensing. +- Contributions from authors who originally licensed their work under the MIT License and have not granted permission to relicense remain licensed under the MIT License. +- Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +The [`LICENSE`](LICENSE) file holds the full text of the Apache-2.0 and MIT licenses and the terms above; it, not this summary, is authoritative. From 90e20f77340eb9dcc1c1239128d91457b67d4e1a Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:25:50 -0500 Subject: [PATCH 12/76] fix(memory): fail every tool with an actionable error when the memory file's directory is missing When the directory holding MEMORY_FILE_PATH did not exist, reads reported an empty graph while every write failed with a raw ENOENT naming the internal .lock file. The README already promises that the server creates the memory file but not the directories above it, so keep that and make reads and writes agree: both now fail with one error naming the memory file and its directory, and pointing at MEMORY_FILE_PATH. A missing file in an existing directory is still an empty graph. Closes #5689 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-missing-directory-error.md | 5 + src/memory/README.md | 2 +- .../__tests__/missing-directory.test.ts | 158 ++++++++++++++++++ src/memory/index.ts | 44 ++++- 4 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 .changeset/memory-missing-directory-error.md create mode 100644 src/memory/__tests__/missing-directory.test.ts diff --git a/.changeset/memory-missing-directory-error.md b/.changeset/memory-missing-directory-error.md new file mode 100644 index 0000000000..fc59eb1baa --- /dev/null +++ b/.changeset/memory-missing-directory-error.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +When the directory holding `MEMORY_FILE_PATH` does not exist, every tool now fails with an error naming the memory file and its directory, instead of reads returning an empty graph while writes failed with a raw `ENOENT` on the internal `.lock` file. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..9c5a30b1a7 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -291,7 +291,7 @@ When `MEMORY_FILE_PATH` is not set and the server directory still holds a legacy **Set `MEMORY_FILE_PATH` to an absolute path you own**, such as `~/memory.jsonl`, as in the configuration above. The default `memory.jsonl` sits in the server's own directory, next to its code. Under `npx` or an npm install, that directory is inside a `node_modules` tree, which npm manages as its own: reinstalling or updating the server, or clearing the npx cache, can delete the file and the knowledge graph in it. A relative `MEMORY_FILE_PATH` resolves against that same directory, so it has the same problem. - When the memory file it resolves is inside a `node_modules` directory, the server prints a warning on stderr at startup naming the file; most clients show a server's stderr in its log. Move the file to the new path when you set the variable, or the server starts on an empty graph. -- The directory must already exist: the server creates the memory file, not the directories above it. +- The directory must already exist: the server creates the memory file, not the directories above it. While it is missing, every tool, read or write, and the `memory://knowledge-graph` resource fail with an error naming the memory file and its directory, rather than reads reporting an empty graph that no write could save to. Create the directory (no restart is needed) or point `MEMORY_FILE_PATH` at one that exists. A missing memory file in an existing directory is an empty graph, and the first write creates it. - The default stays where it is so that existing graphs keep loading. The [Docker](#docker) setup above keeps it in a named volume mounted over `/app/dist`, so the graph there survives restarts and draws no warning. Saves are atomic. Every write tool writes the whole graph to a temporary file in the same directory and renames it over the memory file, so a server stopped or killed mid-save leaves the previous graph intact rather than a half-written file. The file's permission bits are kept across the rename. The temporary file is always newly created by the save. Writes from several processes are serialized by a lock, described next. diff --git a/src/memory/__tests__/missing-directory.test.ts b/src/memory/__tests__/missing-directory.test.ts new file mode 100644 index 0000000000..5a179e1b3b --- /dev/null +++ b/src/memory/__tests__/missing-directory.test.ts @@ -0,0 +1,158 @@ +// Tests for a memory file whose directory does not exist (#5689). The server +// creates the memory file but never the directories above it, as its README +// says, so every tool, read or write, fails with the same actionable error +// naming MEMORY_FILE_PATH. Before, reads reported an empty graph while every +// write failed with a raw ENOENT naming the internal .lock file. Driven +// through an MCP client over an in-memory transport, so each test asserts on +// what a client sees. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import { call, connect, makeTempGraph, textOf } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +const alice = { name: "Alice", entityType: "person", observations: ["hi"] }; + +// Every tool, with arguments it accepts. A read and a write both have to fail +// the same way, so the whole list is checked rather than one of each. +const TOOLS: ReadonlyArray]> = [ + ["read_graph", {}], + ["search_nodes", { query: "Alice" }], + ["open_nodes", { names: ["Alice"] }], + ["create_entities", { entities: [alice] }], + [ + "create_relations", + { relations: [{ from: "Alice", to: "Bob", relationType: "knows" }] }, + ], + [ + "add_observations", + { observations: [{ entityName: "Alice", contents: ["x"] }] }, + ], + ["delete_entities", { entityNames: ["Alice"] }], + [ + "delete_observations", + { deletions: [{ entityName: "Alice", observations: ["hi"] }] }, + ], + [ + "delete_relations", + { relations: [{ from: "Alice", to: "Bob", relationType: "knows" }] }, + ], +]; + +describe("a memory file whose directory does not exist", () => { + let dir: string; + let cleanup: () => Promise; + let connection: Connection | undefined; + + beforeEach(async () => { + ({ dir, cleanup } = await makeTempGraph()); + }); + + afterEach(async () => { + await connection?.close(); + connection = undefined; + await cleanup(); + }); + + function expectedError(filePath: string): string { + return ( + `The directory for the memory file ${filePath} does not exist: ${path.dirname(filePath)}. ` + + "The server creates the memory file but not the directories above it. " + + "Create that directory, or set MEMORY_FILE_PATH to a file in a directory that exists." + ); + } + + it("fails every read and write tool with an error naming MEMORY_FILE_PATH", async () => { + const filePath = path.join(dir, "missing", "memory.jsonl"); + connection = await connect(filePath); + + for (const [name, args] of TOOLS) { + const result = await call(connection.client, name, args); + expect({ name, result }).toEqual({ + name, + result: { + content: [{ type: "text", text: expectedError(filePath) }], + isError: true, + }, + }); + expect(textOf(result)).not.toContain(".lock"); + } + // Nothing was created: not the directory, and not a lock file in it. + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("fails the knowledge-graph resource the same way", async () => { + const filePath = path.join(dir, "missing", "memory.jsonl"); + connection = await connect(filePath); + + await expect( + connection.client.readResource({ uri: "memory://knowledge-graph" }), + ).rejects.toThrow(expectedError(filePath)); + }); + + it("treats a file where the directory should be as a missing directory", async () => { + await fs.writeFile(path.join(dir, "not-a-dir"), ""); + const filePath = path.join(dir, "not-a-dir", "memory.jsonl"); + connection = await connect(filePath); + + const result = await call(connection.client, "create_entities", { + entities: [alice], + }); + expect(result).toEqual({ + content: [{ type: "text", text: expectedError(filePath) }], + isError: true, + }); + }); + + it("serves the graph once the directory is created, with no restart", async () => { + const filePath = path.join(dir, "later", "memory.jsonl"); + connection = await connect(filePath); + expect( + (await call(connection.client, "create_entities", { entities: [alice] })) + .isError, + ).toBe(true); + + await fs.mkdir(path.dirname(filePath)); + + expect( + (await call(connection.client, "create_entities", { entities: [alice] })) + .isError, + ).toBeUndefined(); + const graph = await call(connection.client, "read_graph"); + expect(graph.isError).toBeUndefined(); + expect(JSON.parse(textOf(graph))).toEqual({ + entities: [alice], + relations: [], + }); + }); + + it("still reads a missing file in an existing directory as an empty graph", async () => { + connection = await connect(path.join(dir, "memory.jsonl")); + + const result = await call(connection.client, "read_graph"); + expect(result.isError).toBeUndefined(); + expect(JSON.parse(textOf(result))).toEqual({ entities: [], relations: [] }); + }); + + // A directory that cannot be examined is not reported as missing: the + // stat error (EACCES here) reaches the client unchanged. Root reads through + // a mode-000 directory, so the case cannot be produced there. + it.skipIf(process.getuid?.() === 0)( + "passes through an error other than a missing directory", + async () => { + const locked = path.join(dir, "locked"); + await fs.mkdir(path.join(locked, "inner"), { recursive: true }); + await fs.chmod(locked, 0o000); + try { + connection = await connect(path.join(locked, "inner", "memory.jsonl")); + const result = await call(connection.client, "create_entities", { + entities: [alice], + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/^EACCES/); + } finally { + await fs.chmod(locked, 0o700); + } + }, + ); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..051dc411c0 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -912,8 +912,17 @@ export class KnowledgeGraphManager { private extraFields = new WeakMap>(); private async withLock(operation: () => Promise): Promise { - const locked = () => - withFileLock(`${this.memoryFilePath}.lock`, operation, this.lockOptions); + // The directory is checked before the lock is taken, since the lock file + // is created in it: a missing one would otherwise fail as a raw ENOENT + // naming the internal .lock path (#5689). + const locked = async () => { + await this.requireMemoryDirectory(); + return withFileLock( + `${this.memoryFilePath}.lock`, + operation, + this.lockOptions, + ); + }; const result = this.mutationQueue.then(locked, locked); // Always resolve the queue itself, even if this operation failed, so a // single failed mutation doesn't permanently wedge every call after it. @@ -925,6 +934,34 @@ export class KnowledgeGraphManager { return result; } + // Throw an actionable error when the directory that holds the memory file + // does not exist (#5689). The server creates the memory file, never the + // directories above it: a missing directory is far more often a mistyped + // MEMORY_FILE_PATH or an unmounted volume than a request to create one, and + // creating it would put the graph somewhere the user did not mean. Reads and + // writes both call this, so a read no longer reports an empty graph for a + // store that no write can ever reach. + private async requireMemoryDirectory(): Promise { + const directory = path.dirname(this.memoryFilePath); + let isDirectory: boolean; + try { + isDirectory = (await fs.stat(directory)).isDirectory(); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "ENOENT" && code !== "ENOTDIR") { + throw error; + } + isDirectory = false; + } + if (!isDirectory) { + throw new Error( + `The directory for the memory file ${this.memoryFilePath} does not exist: ${directory}. ` + + "The server creates the memory file but not the directories above it. " + + "Create that directory, or set MEMORY_FILE_PATH to a file in a directory that exists.", + ); + } + } + private async loadGraph(): Promise { return (await this.loadGraphWithUnreadable()).graph; } @@ -1009,6 +1046,9 @@ export class KnowledgeGraphManager { "code" in error && error.code === "ENOENT" ) { + // A missing file is an empty graph, but only in a directory a write + // can create it in (see requireMemoryDirectory). + await this.requireMemoryDirectory(); return { graph: { entities: [], relations: [] }, unreadable: [], From b076e507fddcd0b1635fd4fe2d218ef2541940e7 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:26:34 -0500 Subject: [PATCH 13/76] fix(memory): clear a crash-left lock guard by rename-aside, not by path Two processes clearing the same crash-left guard could remove a live guard a third took in between. The clearer now renames the guard aside, compares it with the file it judged (whose handle stays open, so its inode cannot be reused), and links a live guard back exclusively. The comment above guardPathOf() states the gap that remains. Closes #5624 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-guard-clear-race.md | 5 + src/memory/README.md | 2 +- src/memory/__tests__/guard-clearing.test.ts | 124 ++++++++++++++++++++ src/memory/index.ts | 61 +++++++++- 4 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 .changeset/memory-guard-clear-race.md create mode 100644 src/memory/__tests__/guard-clearing.test.ts diff --git a/.changeset/memory-guard-clear-race.md b/.changeset/memory-guard-clear-race.md new file mode 100644 index 0000000000..78f38c70b7 --- /dev/null +++ b/.changeset/memory-guard-clear-race.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +Clearing a lock guard (`.lock.break`) left by a crash no longer deletes it by path. It is renamed aside and checked to be the file judged stale, so when two servers clear the same crash-left guard at once, the second no longer removes a live guard a third server took in between (#5624). diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..16c6ecb92d 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -302,7 +302,7 @@ Each MCP client starts its own server process, so two clients using the same `ME - A server stopped mid-write by `SIGINT` or `SIGTERM` (Ctrl-C, `docker stop`, a client shutting it down), or exiting normally, removes the lock it holds before it exits, so the next writer does not wait on it. - A lock left behind by a server that crashed mid-write is removed automatically: at once if its process is known to have exited on the same machine, otherwise once it has gone 30 seconds without being refreshed (a server holding the lock refreshes it every 15 seconds while it works). Only one waiting server breaks a stale lock at a time, guarded by a momentary `.lock.break` file. It never deletes the lock where it stands: it renames it aside to a momentary `.lock..stale` file, checks that what it took is the very file it judged stale, and only then deletes it. A live lock that replaced the stale one in between is put straight back, untouched, and the breaker goes on waiting. -- The same momentary `.lock.break` file orders every hand-off of the lock, not only the breaking of a stale one. A server takes it to release its lock, and a server that has just created the lock waits until no `.lock.break` file is there, then checks the lock is still its own, before it writes. So a lock cannot be broken and taken over halfway through its holder's release, and a writer cannot start in the moment a live lock spends moved aside. A `.lock.break` file left by a crash is cleared once it is 30 seconds old, so it delays the next write by at most that long. This holds as long as no server stalls for 30 seconds in the middle of a hand-off. +- The same momentary `.lock.break` file orders every hand-off of the lock, not only the breaking of a stale one. A server takes it to release its lock, and a server that has just created the lock waits until no `.lock.break` file is there, then checks the lock is still its own, before it writes. So a lock cannot be broken and taken over halfway through its holder's release, and a writer cannot start in the moment a live lock spends moved aside. A `.lock.break` file left by a crash is cleared once it is 30 seconds old, so it delays the next write by at most that long. It is cleared the way a stale lock is broken: renamed aside to a momentary `.lock.break..stale` file and checked to be the very file judged stale, so a live `.lock.break` file another server took in its place is put back rather than deleted. This holds as long as no server stalls for 30 seconds in the middle of a hand-off. - Servers of different versions can share a memory file: the lock file, what it holds and the `.lock.break` file are the same in every version. A server at 2.2.1 or earlier takes the `.lock.break` file only to break a stale lock, so its own releases and acquisitions are not ordered this way, and the gaps described above stay open for that server (each needs a lock to go stale first). Upgrade every server sharing a file to close them. - A write that cannot get the lock within 60 seconds fails with a tool error rather than overwriting the file. - The lock relies on exclusive file creation, which local filesystems provide; a network filesystem that does not honour it cannot be shared safely this way. diff --git a/src/memory/__tests__/guard-clearing.test.ts b/src/memory/__tests__/guard-clearing.test.ts new file mode 100644 index 0000000000..983ff42829 --- /dev/null +++ b/src/memory/__tests__/guard-clearing.test.ts @@ -0,0 +1,124 @@ +// Tests for clearing a lock guard (`.break`) left by a crash (#5624). +// Two processes can find the same crash-left guard stale at once; the one +// that clears it second must not remove a live guard a third process took in +// between. Each interleaving is staged deterministically: the clearers run in +// turn, and the other processes' steps are made from inside fs spies, at the +// exact call where they would have to land: the second clearer's removal of +// the guard path (whether it renames or unlinks it), or its put-back. Kept apart +// from file-lock.test.ts so the guard-clearing cases change independently of +// the lock's own. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import { isGuardHeld } from "../index.js"; +import { makeTempGraph } from "./helpers.js"; + +const staleMs = 60_000; + +describe("clearing a guard left by a crash (#5624)", () => { + let dir: string; + let guardPath: string; + let cleanup: () => Promise; + + beforeEach(async () => { + ({ dir, cleanup } = await makeTempGraph()); + guardPath = path.join(dir, "memory.jsonl.lock.break"); + // The guard a crashed holder left behind: empty, as every guard is, and + // older than staleMs. + await fs.writeFile(guardPath, ""); + const longAgo = new Date(Date.now() - 2 * staleMs); + await fs.utimes(guardPath, longAgo, longAgo); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await cleanup(); + }); + + // Run stage once, just before the first call that removes the file at the + // guard path, by renaming it or by unlinking it: the moment a clearer that + // has judged the guard stale acts on that judgement. Returns whether it ran. + function beforeFirstRemoval(stage: () => Promise): () => boolean { + let staged = false; + const once = async (file: unknown): Promise => { + if (file === guardPath && !staged) { + staged = true; + await stage(); + } + }; + const realRename = fs.rename; + vi.spyOn(fs, "rename").mockImplementation(async (from, to) => { + await once(from); + return realRename(from, to); + }); + const realUnlink = fs.unlink; + vi.spyOn(fs, "unlink").mockImplementation(async (file) => { + await once(file); + return realUnlink(file); + }); + return () => staged; + } + + // Another process takes the guard, as tryTakeGuard does: an exclusive + // create. Its contents mark it, so the test can tell it from the stale one. + function takeGuard(owner: string): Promise { + return fs.writeFile(guardPath, owner, { flag: "wx" }); + } + + it("leaves a guard taken between two clearers' removals in place", async () => { + const staged = beforeFirstRemoval(async () => { + // Clearer B has judged the guard stale and is about to remove it. + // Before it does, clearer A, which judged the same guard, clears it, + // and process C takes a fresh guard at the same path. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + await expect(fs.access(guardPath)).rejects.toThrow(); + await takeGuard("C"); + }); + + // Clearer B. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + + expect(staged()).toBe(true); + expect(await fs.readFile(guardPath, "utf-8")).toBe("C"); + // C's guard is back under its own name, with no aside file left behind. + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock.break"]); + // And it is still judged live, so nobody clears it in its turn. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + expect(await fs.readFile(guardPath, "utf-8")).toBe("C"); + }); + + it("removes the stale guard once when two clearers find it at once", async () => { + const staged = beforeFirstRemoval(async () => { + // Clearer A gets there first; nobody takes the guard after it. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + }); + + // Clearer B finds the path empty and leaves it so. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + + expect(staged()).toBe(true); + expect(await fs.readdir(dir)).toEqual([]); + expect(await isGuardHeld(guardPath, staleMs)).toBe(false); + }); + + it("never puts a live guard back over one created while it was aside", async () => { + beforeFirstRemoval(async () => { + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + await takeGuard("C"); + }); + const realLink = fs.link; + vi.spyOn(fs, "link").mockImplementation(async (existing, target) => { + // Clearer B has taken C's guard aside by mistake. Process D takes the + // free path before B can put C's guard back. This is the gap the + // comment above guardPathOf() leaves: C's guard cannot go back without + // replacing D's, so D's is the one kept. + await takeGuard("D"); + return realLink(existing, target); + }); + + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + + expect(await fs.readFile(guardPath, "utf-8")).toBe("D"); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock.break"]); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..5a1da14104 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -352,9 +352,19 @@ async function isLockStale( // holder that stops refreshing it for staleMs is presumed dead. A lock // file can go no further without a lock the kernel releases itself, which // Node offers only through a native dependency. -// - A guard left by a crash is cleared by path. Two processes clearing the -// same one at once can remove a guard a third took in between, which -// leaves that third process unguarded for its few calls (#5624). +// - A guard left by a crash is never deleted where it stands +// (clearCrashLeftGuard): it is renamed aside and compared with the file +// judged stale, as a stale lock is, so two processes clearing the same one +// at once cannot remove a guard a third took in between (#5624). A live +// guard taken aside that way is put back with an exclusive link, which +// never replaces a guard a fourth process created at the path in that +// moment. That is the gap left: should a fourth create one there between +// the rename and the link, the third's guard cannot go back without +// replacing the fourth's, so it is dropped, and the third and fourth each +// run believing they hold the guard. It takes a crash inside a guarded +// section, two clearers of that guard at once, a third process taking it +// between them, and a fourth within the two calls after. A server from +// before #5624 still clears a guard by path, with the wider gap that had. // - A server older than this change takes the guard only to break a lock. It // releases without the guard and runs as soon as it has created the lock. // Sharing a memory file with one is safe in every way it was before (same @@ -381,7 +391,8 @@ function pause(retryMs: number): Promise { // Whether a guard stands at guardPath. One left by a crash (older than // staleMs) is cleared on the way, and still reported: the caller looks again. -async function isGuardHeld( +// Exported for tests, which drive two clearers of one guard in turn. +export async function isGuardHeld( guardPath: string, staleMs: number, ): Promise { @@ -399,15 +410,53 @@ async function isGuardHeld( throw error; } try { - if ((await judgeLock(handle, staleMs)).stale) { - await fs.unlink(guardPath).catch(ignoreError); + const judged = await judgeLock(handle, staleMs); + if (judged.stale) { + await clearCrashLeftGuard(guardPath, judged); } } finally { + // Closed only once the clearing is done: while the judged guard is open + // its inode number cannot be reused by a guard created after it, so the + // comparison in clearCrashLeftGuard cannot mistake one for the other. await handle.close(); } return true; } +// Remove the guard judged stale (left by a crash) from guardPath, without +// removing a guard that replaced it there. Another process clearing the same +// guard can have removed it already, and a third can have taken the guard +// since, so a removal by path could delete that live guard (#5624). Instead +// the file at guardPath is renamed aside to a name nobody else uses, which +// is atomic and takes whichever file stands there at that instant, and what +// was taken is compared with the file that was judged. A live guard taken by +// mistake is linked back to guardPath before its aside name is removed: a +// link is created exclusively, so it never replaces a guard created at the +// path in the meantime. What that leaves is described above guardPathOf(). +async function clearCrashLeftGuard( + guardPath: string, + judged: LockJudgement, +): Promise { + const asidePath = `${guardPath}.${randomBytes(8).toString("hex")}.stale`; + try { + await fs.rename(guardPath, asidePath); + } catch { + // Gone already (another process cleared it, or its holder dropped it), + // or it cannot be moved: either way the caller looks again. + return; + } + try { + const taken = await fs.stat(asidePath, { bigint: true }); + if (taken.dev !== judged.dev || taken.ino !== judged.ino) { + // Not the guard that was judged: one taken since. Put it back. + await fs.link(asidePath, guardPath).catch(ignoreError); + } + } finally { + // The aside name only: a guard put back keeps its name at guardPath. + await fs.unlink(asidePath).catch(ignoreError); + } +} + // Take the guard if it is free, returning whether it was taken. A guard that // is held is left to its holder, unless a crash left it: that one is cleared, // for the next attempt. From ac38a2c3036f2b5e6c919df51e203f9032aa029d Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:26:54 -0500 Subject: [PATCH 14/76] chore: ship the root LICENSE in the everything, memory and sequential-thinking packages Each package.json says "SEE LICENSE IN LICENSE", but their tarballs shipped no LICENSE, and each README said MIT only, contradicting the root LICENSE's MIT to Apache-2.0 transition terms. Commit a copy of the root LICENSE in each server directory, as #5639 does for filesystem, and rewrite each README's license section to match it. With every npm package now shipping its license file, LICENSE_PENDING is empty, so it goes, along with the exemption it carried in pack:verify and the script test. The Python servers are left for the maintainer decision #5700 asks for. Closes #5700 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/everything-ship-license.md | 5 + .changeset/memory-ship-license.md | 5 + .changeset/sequentialthinking-ship-license.md | 5 + docs/quality-gate.md | 4 +- scripts/pack-and-verify.mjs | 21 +- scripts/pack-and-verify.test.mjs | 25 +- src/everything/LICENSE | 216 ++++++++++++++++++ src/everything/README.md | 8 +- src/memory/LICENSE | 216 ++++++++++++++++++ src/memory/README.md | 8 +- src/sequentialthinking/LICENSE | 216 ++++++++++++++++++ src/sequentialthinking/README.md | 8 +- 12 files changed, 691 insertions(+), 46 deletions(-) create mode 100644 .changeset/everything-ship-license.md create mode 100644 .changeset/memory-ship-license.md create mode 100644 .changeset/sequentialthinking-ship-license.md create mode 100644 src/everything/LICENSE create mode 100644 src/memory/LICENSE create mode 100644 src/sequentialthinking/LICENSE diff --git a/.changeset/everything-ship-license.md b/.changeset/everything-ship-license.md new file mode 100644 index 0000000000..e45d9c8e9f --- /dev/null +++ b/.changeset/everything-ship-license.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-everything": patch +--- + +Ship the repository's `LICENSE` in the npm package, which `package.json` already pointed at but the tarball left out, and correct the README's license section, which said MIT only, to describe the MIT to Apache-2.0 transition terms in that file. diff --git a/.changeset/memory-ship-license.md b/.changeset/memory-ship-license.md new file mode 100644 index 0000000000..9ff1f51243 --- /dev/null +++ b/.changeset/memory-ship-license.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +Ship the repository's `LICENSE` in the npm package, which `package.json` already pointed at but the tarball left out, and correct the README's license section, which said MIT only, to describe the MIT to Apache-2.0 transition terms in that file. diff --git a/.changeset/sequentialthinking-ship-license.md b/.changeset/sequentialthinking-ship-license.md new file mode 100644 index 0000000000..3f7e2ec39b --- /dev/null +++ b/.changeset/sequentialthinking-ship-license.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-sequential-thinking": patch +--- + +Ship the repository's `LICENSE` in the npm package, which `package.json` already pointed at but the tarball left out, and correct the README's license section, which said MIT only, to describe the MIT to Apache-2.0 transition terms in that file. diff --git a/docs/quality-gate.md b/docs/quality-gate.md index e1df090e0b..483c32b63b 100644 --- a/docs/quality-gate.md +++ b/docs/quality-gate.md @@ -196,8 +196,8 @@ covers: the repo-wide tooling and the guards that keep the gate itself honest. runs the checkout: a file missing from the tarball, a dependency that only resolves inside the workspace. It also fails an npm tarball that ships a test, a test helper or a test runner's config, and one that leaves out the - license file its `package.json` names (`SEE LICENSE IN LICENSE`; the - packages #5700 has yet to fix are exempt). It needs the network, so it is not a gate + license file its `package.json` names (`SEE LICENSE IN LICENSE`). It needs + the network, so it is not a gate stage. `release.yml` runs it before anything publishes, and the `release` skill runs it by hand for the release ledger. - **`npm run format`** rewrites files, so it is something you run, not diff --git a/scripts/pack-and-verify.mjs b/scripts/pack-and-verify.mjs index ecd13315c1..594575e9b7 100644 --- a/scripts/pack-and-verify.mjs +++ b/scripts/pack-and-verify.mjs @@ -103,8 +103,8 @@ export function parseArgs(argv) { * What is wrong with an npm tarball's contents, judged from its manifest and * file list alone: every `bin` target must be in it, no test or test config * file may be (#4930), and a license file the manifest names - * (`"license": "SEE LICENSE IN LICENSE"`) must be in it (#5639), unless the - * package is in `LICENSE_PENDING`. Anything subtler (a module the entry point + * (`"license": "SEE LICENSE IN LICENSE"`) must be in it (#5639, #5700). + * Anything subtler (a module the entry point * imports, a data file) is found by actually running the installed bin, which * is the next step. * @@ -130,21 +130,6 @@ export function tarballProblems(manifest, files) { ]; } -/** - * The npm packages that do not ship the license file their manifest names - * yet. The filesystem package published with `"license": "SEE LICENSE IN - * LICENSE"` and no LICENSE in its tarball (#5639); these three still do, and - * #5700 fixes them. The check passes them so that their releases are not - * blocked meanwhile. Remove a package from this list in the change that makes - * it ship the file: the script tests fail on a listed package that already - * does, so the list can only shrink. - */ -export const LICENSE_PENDING = new Set([ - "@modelcontextprotocol/server-everything", - "@modelcontextprotocol/server-memory", - "@modelcontextprotocol/server-sequential-thinking", -]); - /** * The license file a manifest points at, from the `SEE LICENSE IN ` * form of its `license` field, or `null` when it names an SPDX expression or @@ -161,7 +146,7 @@ export function licenseFile(manifest) { /** The license file the manifest names, when the tarball lacks it. */ function licenseProblems(manifest, present) { const file = licenseFile(manifest); - if (!file || LICENSE_PENDING.has(manifest.name)) return []; + if (!file) return []; if (present.has(path.posix.normalize(file))) return []; return [ `package.json says "${manifest.license}", but ${file} is not in the tarball`, diff --git a/scripts/pack-and-verify.test.mjs b/scripts/pack-and-verify.test.mjs index fb2c179a44..e1b360cff8 100644 --- a/scripts/pack-and-verify.test.mjs +++ b/scripts/pack-and-verify.test.mjs @@ -2,7 +2,7 @@ // tarball check and where an installed command lives. The rest of the script // is `npm pack`, `npm install`, `uv build` and a real server boot, which need // the network and are exercised by running `npm run pack:verify` itself. -// One test is a guard on the repository as it stands (#5639): each npm +// One test is a guard on the repository as it stands (#5639, #5700): each npm // package's file list, from an offline `npm pack --dry-run`, holds the license // file its manifest names, with the same text as the root LICENSE. That runs // in `validate:guards`, so a package that would publish without it fails @@ -23,7 +23,6 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { - LICENSE_PENDING, artifactDirProblem, consumerEnv, installedLaunch, @@ -118,12 +117,6 @@ test("a license file the manifest names must be in the tarball (#5639)", () => { tarballProblems({ ...manifest, license: "MIT" }, ["dist/index.js"]), [], ); - // A package still waiting on its fix (#5700) is passed meanwhile. - const [pending] = LICENSE_PENDING; - assert.deepEqual( - tarballProblems({ ...manifest, name: pending }, ["dist/index.js"]), - [], - ); }); test("licenseFile reads the SEE LICENSE IN form, and only that", () => { @@ -136,17 +129,15 @@ test("licenseFile reads the SEE LICENSE IN form, and only that", () => { assert.equal(licenseFile({}), null); }); -test("each npm package ships the root LICENSE its manifest names, unless pending", () => { +test("each npm package ships the root LICENSE its manifest names", () => { const rootLicense = readFileSync(path.join(repoRoot, "LICENSE"), "utf8"); const npmServers = SERVERS.filter((s) => s.language === "ts"); assert.ok(npmServers.length > 0, "no TypeScript servers found"); - const names = new Set(); for (const server of npmServers) { const pkgDir = path.join(repoRoot, "src", server.name); const manifest = JSON.parse( readFileSync(path.join(pkgDir, "package.json"), "utf8"), ); - names.add(manifest.name); const file = licenseFile(manifest); assert.ok(file, `${manifest.name}: license is not "SEE LICENSE IN "`); // What `npm pack` would put in the tarball, read without building it: @@ -161,13 +152,6 @@ test("each npm package ships the root LICENSE its manifest names, unless pending const shipped = JSON.parse(res.stdout)[0].files.some( (f) => path.posix.normalize(f.path) === path.posix.normalize(file), ); - if (LICENSE_PENDING.has(manifest.name)) { - assert.ok( - !shipped, - `${manifest.name} now ships ${file}: remove it from LICENSE_PENDING`, - ); - continue; - } assert.ok(shipped, `${manifest.name}: ${file} is not in its tarball`); assert.equal( readFileSync(path.join(pkgDir, file), "utf8"), @@ -175,11 +159,6 @@ test("each npm package ships the root LICENSE its manifest names, unless pending `src/${server.name}/${file} differs from the root LICENSE: copy it again`, ); } - for (const pending of LICENSE_PENDING) - assert.ok( - names.has(pending), - `LICENSE_PENDING names ${pending}, which is not a package here`, - ); }); test("isTestFile matches tests, helpers and runner configs, nothing else", () => { diff --git a/src/everything/LICENSE b/src/everything/LICENSE new file mode 100644 index 0000000000..4a93985763 --- /dev/null +++ b/src/everything/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/src/everything/README.md b/src/everything/README.md index 1689bd8b74..be4a3ee0a6 100644 --- a/src/everything/README.md +++ b/src/everything/README.md @@ -209,4 +209,10 @@ The endpoint is `http://localhost:3001/mcp`. The image sets `HOST=0.0.0.0`, so t ## License -This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. +This server is distributed under the terms of the [`LICENSE`](LICENSE) file, a copy of the repository's root `LICENSE` that ships in the npm package. The Model Context Protocol project is moving from the MIT License to the Apache License, Version 2.0 (Apache-2.0), so those terms depend on the contribution: + +- New code and specification contributions are licensed under Apache-2.0, as are contributions whose authors have consented to relicensing. +- Contributions from authors who originally licensed their work under the MIT License and have not granted permission to relicense remain licensed under the MIT License. +- Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +The [`LICENSE`](LICENSE) file holds the full text of the Apache-2.0 and MIT licenses and the terms above; it, not this summary, is authoritative. diff --git a/src/memory/LICENSE b/src/memory/LICENSE new file mode 100644 index 0000000000..4a93985763 --- /dev/null +++ b/src/memory/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..eca62cda78 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -472,4 +472,10 @@ If the old volume holds only a legacy `memory.json`, copy `/old/memory.json` to ## License -This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. +This server is distributed under the terms of the [`LICENSE`](LICENSE) file, a copy of the repository's root `LICENSE` that ships in the npm package. The Model Context Protocol project is moving from the MIT License to the Apache License, Version 2.0 (Apache-2.0), so those terms depend on the contribution: + +- New code and specification contributions are licensed under Apache-2.0, as are contributions whose authors have consented to relicensing. +- Contributions from authors who originally licensed their work under the MIT License and have not granted permission to relicense remain licensed under the MIT License. +- Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +The [`LICENSE`](LICENSE) file holds the full text of the Apache-2.0 and MIT licenses and the terms above; it, not this summary, is authoritative. diff --git a/src/sequentialthinking/LICENSE b/src/sequentialthinking/LICENSE new file mode 100644 index 0000000000..4a93985763 --- /dev/null +++ b/src/sequentialthinking/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/src/sequentialthinking/README.md b/src/sequentialthinking/README.md index c0e7539ec3..c2ac961443 100644 --- a/src/sequentialthinking/README.md +++ b/src/sequentialthinking/README.md @@ -255,4 +255,10 @@ docker build -t mcp/sequentialthinking -f src/sequentialthinking/Dockerfile . ## License -This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. +This server is distributed under the terms of the [`LICENSE`](LICENSE) file, a copy of the repository's root `LICENSE` that ships in the npm package. The Model Context Protocol project is moving from the MIT License to the Apache License, Version 2.0 (Apache-2.0), so those terms depend on the contribution: + +- New code and specification contributions are licensed under Apache-2.0, as are contributions whose authors have consented to relicensing. +- Contributions from authors who originally licensed their work under the MIT License and have not granted permission to relicense remain licensed under the MIT License. +- Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +The [`LICENSE`](LICENSE) file holds the full text of the Apache-2.0 and MIT licenses and the terms above; it, not this summary, is authoritative. From e954ef48173679d2e6db6c41b7c6d5aa60679417 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:27:04 -0500 Subject: [PATCH 15/76] feat(git): describe every tool input property 21 of the 32 tool input properties had no description, so a model saw only their names. Add shared RepoPath and ContextLines aliases next to DEFAULT_CONTEXT_LINES, use them for every repo_path and context_lines, and describe git_diff.target, git_commit.message, git_add.files, git_create_branch.branch_name, git_checkout.branch_name and git_show.revision. A protocol-level test lists the tools and fails on any input property without a description; the tool-list snapshot is regenerated. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/git/src/mcp_server_git/server.py | 100 ++++++++++++++++++++---- src/git/tests/snapshots/list_tools.json | 21 +++++ src/git/tests/test_protocol.py | 13 +++ 3 files changed, 117 insertions(+), 17 deletions(-) diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 9c3b5606aa..20e8996f14 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -57,6 +57,19 @@ # Default number of context lines to show in diff output DEFAULT_CONTEXT_LINES = 3 +# The two parameters most tools share, described once so every tool's input +# schema tells the model what they are (#5647). +RepoPath = Annotated[str, Field(description="The path to the Git repository.")] +ContextLines = Annotated[ + int, + Field( + description=( + "Number of context lines to show around each change. " + f"Defaults to {DEFAULT_CONTEXT_LINES}." + ) + ), +] + class FlagInjectionError(BadName): """A flag-injection guard's rejection of a value starting with '-'. @@ -1980,7 +1993,7 @@ def open_repo(repo_path: str) -> git.Repo: description="Asks the model for a commit message for the staged changes", ) def commit_message( - repo_path: Annotated[str, Field(description="The path to the Git repository.")], + repo_path: RepoPath, ) -> str: with ( _GIT_LOCK, @@ -1999,7 +2012,7 @@ def commit_message( ), ) def summarize_changes( - repo_path: Annotated[str, Field(description="The path to the Git repository.")], + repo_path: RepoPath, target: Annotated[ str | None, Field( @@ -2025,7 +2038,7 @@ def summarize_changes( structured_output=False, ) @reports_failures - def status(repo_path: str) -> str: + def status(repo_path: RepoPath) -> str: return f"Repository status:\n{git_status(open_repo(repo_path))}" @server.tool( @@ -2036,7 +2049,7 @@ def status(repo_path: str) -> str: ) @reports_failures def diff_unstaged( - repo_path: str, context_lines: int = DEFAULT_CONTEXT_LINES + repo_path: RepoPath, context_lines: ContextLines = DEFAULT_CONTEXT_LINES ) -> str: diff = git_diff_unstaged(open_repo(repo_path), context_lines) return f"Unstaged changes:\n{diff}" @@ -2048,7 +2061,9 @@ def diff_unstaged( structured_output=False, ) @reports_failures - def diff_staged(repo_path: str, context_lines: int = DEFAULT_CONTEXT_LINES) -> str: + def diff_staged( + repo_path: RepoPath, context_lines: ContextLines = DEFAULT_CONTEXT_LINES + ) -> str: diff = git_diff_staged(open_repo(repo_path), context_lines) return f"Staged changes:\n{diff}" @@ -2060,7 +2075,18 @@ def diff_staged(repo_path: str, context_lines: int = DEFAULT_CONTEXT_LINES) -> s ) @reports_failures def diff( - repo_path: str, target: str, context_lines: int = DEFAULT_CONTEXT_LINES + repo_path: RepoPath, + target: Annotated[ + str, + Field( + description=( + "A branch, tag, commit SHA or relative revision (HEAD~1) " + "to diff the working tree against, or a revision range " + "(main..feature, main...feature) to diff between" + ) + ), + ], + context_lines: ContextLines = DEFAULT_CONTEXT_LINES, ) -> str: result = git_diff(open_repo(repo_path), target, context_lines) return f"Diff with {target}:\n{result}" @@ -2073,7 +2099,10 @@ def diff( ) @reports_failures @writes_objects - def commit(repo_path: str, message: str) -> str: + def commit( + repo_path: RepoPath, + message: Annotated[str, Field(description="The commit message")], + ) -> str: return git_commit(open_repo(repo_path), message, allowed_repository=repository) @server.tool( @@ -2084,7 +2113,19 @@ def commit(repo_path: str, message: str) -> str: ) @reports_failures @writes_objects - def add(repo_path: str, files: Annotated[list[str], Field(min_length=1)]) -> str: + def add( + repo_path: RepoPath, + files: Annotated[ + list[str], + Field( + min_length=1, + description=( + "Paths of the files to stage, relative to the repository " + "root or absolute inside it. ['.'] stages everything" + ), + ), + ], + ) -> str: return git_add(open_repo(repo_path), files) @server.tool( @@ -2095,7 +2136,7 @@ def add(repo_path: str, files: Annotated[list[str], Field(min_length=1)]) -> str ) @reports_failures @writes_objects - def reset(repo_path: str) -> str: + def reset(repo_path: RepoPath) -> str: return git_reset(open_repo(repo_path)) @server.tool( @@ -2115,7 +2156,7 @@ def reset(repo_path: str) -> str: ) @reports_failures def log( - repo_path: str, + repo_path: RepoPath, max_count: Annotated[ int, Field( @@ -2164,8 +2205,10 @@ def log( @reports_failures @writes_objects def create_branch( - repo_path: str, - branch_name: str, + repo_path: RepoPath, + branch_name: Annotated[ + str, Field(description="The name of the new branch to create") + ], base_branch: Annotated[ str | None, Field( @@ -2187,7 +2230,18 @@ def create_branch( ) @reports_failures @writes_objects - def checkout(repo_path: str, branch_name: str) -> str: + def checkout( + repo_path: RepoPath, + branch_name: Annotated[ + str, + Field( + description=( + "The branch to switch to. A tag, commit SHA or " + "remote-tracking branch is also accepted, and detaches HEAD" + ) + ), + ], + ) -> str: return git_checkout( open_repo(repo_path), branch_name, allowed_repository=repository ) @@ -2205,7 +2259,7 @@ def checkout(repo_path: str, branch_name: str) -> str: @reports_failures @writes_objects def merge( - repo_path: str, + repo_path: RepoPath, source_branch: Annotated[ str, Field( @@ -2236,7 +2290,19 @@ def merge( structured_output=False, ) @reports_failures - def show(repo_path: str, revision: str) -> str: + def show( + repo_path: RepoPath, + revision: Annotated[ + str, + Field( + description=( + "The commit to show: a branch, tag, commit SHA or relative " + "revision (HEAD~1). : shows a file's " + "contents or a directory's listing at that revision" + ) + ), + ], + ) -> str: return git_show(open_repo(repo_path), revision) @server.tool( @@ -2247,7 +2313,7 @@ def show(repo_path: str, revision: str) -> str: ) @reports_failures def branch( - repo_path: Annotated[str, Field(description="The path to the Git repository.")], + repo_path: RepoPath, branch_type: Annotated[ str, Field( @@ -2282,7 +2348,7 @@ def branch( ) @reports_failures def remote( - repo_path: Annotated[str, Field(description="The path to the Git repository.")], + repo_path: RepoPath, ) -> str: return git_remote(open_repo(repo_path)) diff --git a/src/git/tests/snapshots/list_tools.json b/src/git/tests/snapshots/list_tools.json index 79849cd1b0..3c9f5e3426 100644 --- a/src/git/tests/snapshots/list_tools.json +++ b/src/git/tests/snapshots/list_tools.json @@ -6,6 +6,7 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" } @@ -29,11 +30,13 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "context_lines": { "default": 3, + "description": "Number of context lines to show around each change. Defaults to 3.", "title": "Context Lines", "type": "integer" } @@ -57,11 +60,13 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "context_lines": { "default": 3, + "description": "Number of context lines to show around each change. Defaults to 3.", "title": "Context Lines", "type": "integer" } @@ -85,15 +90,18 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "target": { + "description": "A branch, tag, commit SHA or relative revision (HEAD~1) to diff the working tree against, or a revision range (main..feature, main...feature) to diff between", "title": "Target", "type": "string" }, "context_lines": { "default": 3, + "description": "Number of context lines to show around each change. Defaults to 3.", "title": "Context Lines", "type": "integer" } @@ -118,10 +126,12 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "message": { + "description": "The commit message", "title": "Message", "type": "string" } @@ -146,10 +156,12 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "files": { + "description": "Paths of the files to stage, relative to the repository root or absolute inside it. ['.'] stages everything", "items": { "type": "string" }, @@ -178,6 +190,7 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" } @@ -201,6 +214,7 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, @@ -257,10 +271,12 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "branch_name": { + "description": "The name of the new branch to create", "title": "Branch Name", "type": "string" }, @@ -298,10 +314,12 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "branch_name": { + "description": "The branch to switch to. A tag, commit SHA or remote-tracking branch is also accepted, and detaches HEAD", "title": "Branch Name", "type": "string" } @@ -326,6 +344,7 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, @@ -361,10 +380,12 @@ "inputSchema": { "properties": { "repo_path": { + "description": "The path to the Git repository.", "title": "Repo Path", "type": "string" }, "revision": { + "description": "The commit to show: a branch, tag, commit SHA or relative revision (HEAD~1). : shows a file's contents or a directory's listing at that revision", "title": "Revision", "type": "string" } diff --git a/src/git/tests/test_protocol.py b/src/git/tests/test_protocol.py index 82d3865ee0..6528ebbb55 100644 --- a/src/git/tests/test_protocol.py +++ b/src/git/tests/test_protocol.py @@ -111,6 +111,19 @@ async def test_list_tools_names_in_order(): ] +async def test_every_tool_input_property_has_a_description(): + # #5647: a property with no description shows the model only its name. + async with connect(None) as session: + tools = wire(await session.list_tools())["tools"] + missing = [ + f"{tool['name']}.{name}" + for tool in tools + for name, schema in tool["inputSchema"]["properties"].items() + if not schema.get("description") + ] + assert missing == [] + + # -------------------------------------------------------------------------- # Protocol-level errors common to every tool # -------------------------------------------------------------------------- From 73720f91cfeebecc9d0f4a5160cec6f9606dc74b Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:27:07 -0500 Subject: [PATCH 16/76] test(fetch): run subprocesses under stretched budgets in tests The Readability.js probe, npm install and extraction ran under their production timeouts in the test suite, so on a saturated machine a slow but healthy child was killed and unrelated tests failed on the wall clock. An autouse fixture now scales those budgets by 10 for every test; tests of the timeout path still set their own short timeouts. Closes #5658 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/fetch/tests/conftest.py | 16 ++++++++-- src/fetch/tests/harness.py | 29 +++++++++++++++++++ .../tests/test_readability_subprocess.py | 29 ++++++++++++++++++- 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/src/fetch/tests/conftest.py b/src/fetch/tests/conftest.py index ffab260023..2eb7f3f8d1 100644 --- a/src/fetch/tests/conftest.py +++ b/src/fetch/tests/conftest.py @@ -5,6 +5,18 @@ so this file re-exports them. """ -from .harness import node_readability, private_tempdir, python_readability, web +from .harness import ( + generous_subprocess_timeouts, + node_readability, + private_tempdir, + python_readability, + web, +) -__all__ = ["node_readability", "private_tempdir", "python_readability", "web"] +__all__ = [ + "generous_subprocess_timeouts", + "node_readability", + "private_tempdir", + "python_readability", + "web", +] diff --git a/src/fetch/tests/harness.py b/src/fetch/tests/harness.py index c9e2749dcb..785687f292 100644 --- a/src/fetch/tests/harness.py +++ b/src/fetch/tests/harness.py @@ -180,6 +180,35 @@ def private_tempdir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) +# How far the subprocess budgets are stretched for tests (#5658). +SUBPROCESS_TIMEOUT_SCALE = 10 + + +@pytest.fixture(autouse=True) +def generous_subprocess_timeouts(monkeypatch: pytest.MonkeyPatch) -> None: + """Stretch ``readability_js``'s production timeouts for every test. + + The real ``node -v`` probe, npm install and extraction run under budgets + sized for an idle machine (10 s, 120 s, 30 s). On a saturated one (a gate + run beside another worktree's build) a healthy child can outlast them, is + killed, and a test of something else entirely (stderr routing, + simplification) fails on the wall clock (#5658). Retries are forbidden, so + the budget is raised instead. A test of the timeout path itself sets its + own short timeout with ``monkeypatch.setattr`` in its body, which runs + after this autouse fixture and so overrides it. + """ + for name in ( + "VERSION_TIMEOUT_SECONDS", + "INSTALL_TIMEOUT_SECONDS", + "EXTRACT_TIMEOUT_SECONDS", + ): + monkeypatch.setattr( + readability_js, + name, + getattr(readability_js, name) * SUBPROCESS_TIMEOUT_SCALE, + ) + + async def raw_request( method: str, params: dict[str, Any] ) -> JSONRPCResponse | JSONRPCError: diff --git a/src/fetch/tests/test_readability_subprocess.py b/src/fetch/tests/test_readability_subprocess.py index c548032dba..b535bba6d2 100644 --- a/src/fetch/tests/test_readability_subprocess.py +++ b/src/fetch/tests/test_readability_subprocess.py @@ -31,7 +31,7 @@ import mcp_server_fetch.server as server_module from mcp_server_fetch import readability_js -from .harness import FakeWeb, connect +from .harness import SUBPROCESS_TIMEOUT_SCALE, FakeWeb, connect PAGE = "https://example.com/article" @@ -274,6 +274,33 @@ def run(argv: list[str], timeout: float, cwd: Path | None = None) -> Any: ] +# --- #5658: tests run the children under stretched budgets ------------------ + + +def test_children_run_under_the_stretched_test_budgets( + jsdir: Path, monkeypatch: pytest.MonkeyPatch, capfd: pytest.CaptureFixture[str] +) -> None: + # The autouse `generous_subprocess_timeouts` fixture keeps a loaded + # machine's slow but healthy child from being killed mid-test (#5658); + # this pins that the probe, the install and the extraction all get it. + monkeypatch.setattr(readability_js.shutil, "which", lambda name: f"/x/{name}") + timeouts: list[float] = [] + + def run(argv: list[str], timeout: float, cwd: Path | None = None) -> Any: + timeouts.append(timeout) + if argv[1] == "install": + install(jsdir) + # Extraction exits 1, so the call falls back without reading output. + code = 1 if argv[1].endswith("ExtractArticle.js") else 0 + return subprocess.CompletedProcess(argv, code, "v24.0.0\n", "") + + monkeypatch.setattr(readability_js, "_run", run) + assert readability_js.extract_article(ARTICLE) is None + scale = SUBPROCESS_TIMEOUT_SCALE + assert timeouts == [10.0 * scale, 120.0 * scale, 30.0 * scale] + assert "Readability.js failed (exit 1)" in capfd.readouterr().err + + # --- Each way Readability.js can be unavailable falls back ------------------- From f7adcea5f00cbbc2d1fb67f10b5f54c7845a3339 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:27:06 -0500 Subject: [PATCH 17/76] perf(memory): index the write methods' lookups with Set and Map 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 Signed-off-by: cliffhall --- .changeset/memory-write-lookups.md | 5 + src/memory/__tests__/write-lookups.test.ts | 422 +++++++++++++++++++++ src/memory/index.ts | 101 +++-- 3 files changed, 493 insertions(+), 35 deletions(-) create mode 100644 .changeset/memory-write-lookups.md create mode 100644 src/memory/__tests__/write-lookups.test.ts diff --git a/.changeset/memory-write-lookups.md b/.changeset/memory-write-lookups.md new file mode 100644 index 0000000000..e0225e38fc --- /dev/null +++ b/.changeset/memory-write-lookups.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +The write tools (`create_entities`, `create_relations`, `add_observations`, `delete_entities`, `delete_observations`, `delete_relations`) match requested items against the graph through Set and Map lookups instead of a scan per item, so large graphs and batches write much faster and hold the file lock for less time. Results, their order and every message are unchanged. diff --git a/src/memory/__tests__/write-lookups.test.ts b/src/memory/__tests__/write-lookups.test.ts new file mode 100644 index 0000000000..ed069edffa --- /dev/null +++ b/src/memory/__tests__/write-lookups.test.ts @@ -0,0 +1,422 @@ +// Pins that the write methods' Set/Map lookups (#5693) behave exactly as the +// linear scans they replaced: same results, same order, same messages, same +// graph afterwards. A seeded run of random writes is checked step by step +// against a reference model that keeps the old scanning code, and targeted +// protocol-level cases cover what the indexes could plausibly get wrong: +// relation keys whose fields contain a separator, a hand-edited file holding +// two entities with one name (only the first was ever matched), and +// create_entities telling skipped from created by object identity. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { promises as fs } from "fs"; +import { + KnowledgeGraphManager, + type Entity, + type KnowledgeGraph, + type Relation, +} from "../index.js"; +import { call, connect, makeTempGraph, type Connection } from "./helpers.js"; + +// The write methods as they were before #5693, over an in-memory graph. +class ScanningModel { + constructor(public graph: KnowledgeGraph) {} + + createEntities(entities: Entity[]): Entity[] { + const newEntities = entities.filter( + (e, index) => + !this.graph.entities.some((x) => x.name === e.name) && + !entities.slice(0, index).some((earlier) => earlier.name === e.name), + ); + this.graph.entities.push(...newEntities); + return newEntities; + } + + createRelations(relations: Relation[]): Relation[] { + const names = new Set(this.graph.entities.map((e) => e.name)); + relations.forEach((r) => { + if (!names.has(r.from)) { + throw new Error(`Entity with name ${r.from} not found`); + } + if (!names.has(r.to)) { + throw new Error(`Entity with name ${r.to} not found`); + } + }); + const same = (a: Relation, b: Relation) => + a.from === b.from && a.to === b.to && a.relationType === b.relationType; + const newRelations = relations.filter( + (r, index) => + !this.graph.relations.some((x) => same(x, r)) && + !relations.slice(0, index).some((earlier) => same(earlier, r)), + ); + this.graph.relations.push(...newRelations); + return newRelations; + } + + addObservations( + observations: { entityName: string; contents: string[] }[], + ): { entityName: string; addedObservations: string[] }[] { + return observations.map((o) => { + const entity = this.graph.entities.find((e) => e.name === o.entityName); + if (!entity) { + throw new Error(`Entity with name ${o.entityName} not found`); + } + const newObservations = [...new Set(o.contents)].filter( + (content) => !entity.observations.includes(content), + ); + entity.observations.push(...newObservations); + return { entityName: o.entityName, addedObservations: newObservations }; + }); + } + + deleteEntities(entityNames: string[]): { + deleted: string[]; + notFound: string[]; + } { + const present = new Set(this.graph.entities.map((e) => e.name)); + const deleted = entityNames.filter((name) => present.has(name)); + const notFound = entityNames.filter((name) => !present.has(name)); + this.graph.entities = this.graph.entities.filter( + (e) => !entityNames.includes(e.name), + ); + this.graph.relations = this.graph.relations.filter( + (r) => !entityNames.includes(r.from) && !entityNames.includes(r.to), + ); + return { deleted, notFound }; + } + + deleteObservations( + deletions: { entityName: string; observations: string[] }[], + ): { deletedCount: number; missingEntities: string[] } { + let deletedCount = 0; + const missingEntities: string[] = []; + deletions.forEach((d) => { + const entity = this.graph.entities.find((e) => e.name === d.entityName); + if (entity) { + const before = entity.observations.length; + entity.observations = entity.observations.filter( + (o) => !d.observations.includes(o), + ); + deletedCount += before - entity.observations.length; + } else { + missingEntities.push(d.entityName); + } + }); + return { deletedCount, missingEntities }; + } + + deleteRelations(relations: Relation[]): { deletedCount: number } { + const before = this.graph.relations.length; + this.graph.relations = this.graph.relations.filter( + (r) => + !relations.some( + (d) => + r.from === d.from && + r.to === d.to && + r.relationType === d.relationType, + ), + ); + return { deletedCount: before - this.graph.relations.length }; + } +} + +// mulberry32: a small seeded generator, so a failure replays exactly. +function seeded(seed: number): () => number { + let a = seed; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +// A small pool, so repeats within a batch and against the graph are common. +// The separator-bearing names would collide under a joined-string key. +const NAMES = ["a", "b", "a|b", "b|c", "c", "a\u0000b", ""]; +const TYPES = ["knows", "knows|a", "b"]; +const OBSERVATIONS = ["o1", "o2", "o3", "o1|o2"]; + +type Outcome = { value: unknown } | { error: string }; + +async function outcome(run: () => unknown): Promise { + try { + return { value: await run() }; + } catch (error) { + return { error: (error as Error).message }; + } +} + +function jsonl(graph: KnowledgeGraph): string { + return ( + [ + ...graph.entities.map((e) => JSON.stringify({ type: "entity", ...e })), + ...graph.relations.map((r) => JSON.stringify({ type: "relation", ...r })), + ].join("\n") + "\n" + ); +} + +// A hand-edited starting graph: "a" appears twice, and one relation is stored +// twice, neither of which the tools themselves would ever write. +function startingGraph(): KnowledgeGraph { + return { + entities: [ + { name: "a", entityType: "first", observations: ["o1", "o1"] }, + { name: "b", entityType: "t", observations: [] }, + { name: "a", entityType: "second", observations: ["o2"] }, + { name: "a|b", entityType: "t", observations: ["o3"] }, + ], + relations: [ + { from: "a", to: "b", relationType: "knows" }, + { from: "a", to: "b", relationType: "knows" }, + { from: "a|b", to: "b", relationType: "knows" }, + ], + }; +} + +describe("write lookups (#5693)", () => { + let tmp: Awaited>; + + beforeEach(async () => { + tmp = await makeTempGraph(); + }); + + afterEach(async () => { + await tmp.cleanup(); + }); + + it("matches the scanning implementation over a seeded run of writes", async () => { + await fs.writeFile(tmp.filePath, jsonl(startingGraph())); + const manager = new KnowledgeGraphManager(tmp.filePath); + const model = new ScanningModel(startingGraph()); + const random = seeded(5693); + const pick = (items: T[]): T => + items[Math.floor(random() * items.length)]; + const some = (make: () => T): T[] => + Array.from({ length: Math.floor(random() * 5) }, make); + // Distinct items only, where a repeat within one request is what #5653 + // and #5655 change: this test pins the lookups, not those behaviors. + const distinct = (make: () => T): T[] => { + const items = some(make); + return items.filter( + (item, i) => + items.findIndex( + (other) => JSON.stringify(other) === JSON.stringify(item), + ) === i, + ); + }; + const relation = (): Relation => ({ + from: pick(NAMES), + to: pick(NAMES), + relationType: pick(TYPES), + }); + + // What the run reached, so a change to the generator cannot quietly turn + // it into 300 no-ops. + const reached = new Set(); + for (let step = 0; step < 300; step++) { + const op = Math.floor(random() * 6); + // A call that throws saves nothing, so the model rolls back with it. + const snapshot = structuredClone(model.graph); + let ours: Outcome; + let theirs: Outcome; + if (op === 0) { + const batch = some(() => ({ + name: pick(NAMES), + entityType: pick(TYPES), + observations: distinct(() => pick(OBSERVATIONS)), + })); + const created = await manager.createEntities(batch); + // The result holds the requested objects themselves, in order. + for (const e of created) { + expect(batch).toContain(e); + } + ours = { value: created }; + theirs = await outcome(() => + model.createEntities(structuredClone(batch)), + ); + } else if (op === 1) { + // Repeats are kept here: skipping them is the dedup under test. + const batch = some(relation); + ours = await outcome(() => manager.createRelations(batch)); + theirs = await outcome(() => + model.createRelations(structuredClone(batch)), + ); + } else if (op === 2) { + const batch = some(() => ({ + entityName: pick(NAMES), + contents: some(() => pick(OBSERVATIONS)), + })); + ours = await outcome(() => manager.addObservations(batch)); + theirs = await outcome(() => + model.addObservations(structuredClone(batch)), + ); + } else if (op === 3) { + // Rarely, so the graph does not empty out early. + const batch = random() < 0.3 ? distinct(() => pick(NAMES)) : []; + ours = await outcome(() => manager.deleteEntities(batch)); + theirs = await outcome(() => + model.deleteEntities(structuredClone(batch)), + ); + } else if (op === 4) { + const batch = some(() => ({ + entityName: pick(NAMES), + observations: distinct(() => pick(OBSERVATIONS)), + })); + ours = await outcome(() => manager.deleteObservations(batch)); + theirs = await outcome(() => + model.deleteObservations(structuredClone(batch)), + ); + } else { + const batch = distinct(relation); + ours = await outcome(() => manager.deleteRelations(batch)); + theirs = await outcome(() => + model.deleteRelations(structuredClone(batch)), + ); + } + if ("error" in theirs) { + model.graph = snapshot; + reached.add(`${op}:error`); + } else if (JSON.stringify(model.graph) !== JSON.stringify(snapshot)) { + reached.add(`${op}:changed`); + } + expect(ours, `step ${step}, op ${op}`).toEqual(theirs); + expect(await manager.readGraph(), `step ${step}, op ${op}`).toEqual( + model.graph, + ); + } + expect([...reached].sort()).toEqual([ + "0:changed", + "1:changed", + "1:error", + "2:changed", + "2:error", + "3:changed", + "4:changed", + "5:changed", + ]); + }); + + describe("over the protocol", () => { + let conn: Connection; + + beforeEach(async () => { + await fs.writeFile(tmp.filePath, jsonl(startingGraph())); + conn = await connect(tmp.filePath); + }); + + afterEach(async () => { + await conn.close(); + }); + + async function graph(): Promise { + return (await call(conn.client, "read_graph")).structuredContent; + } + + it("keeps relations whose fields contain a separator apart", async () => { + await call(conn.client, "create_entities", { + entities: [ + { name: "b|c", entityType: "t", observations: [] }, + { name: "c", entityType: "t", observations: [] }, + ], + }); + // Joined with "|", the second would read as a repeat of the first. + const created = await call(conn.client, "create_relations", { + relations: [ + { from: "a|b", to: "c", relationType: "knows" }, + { from: "a", to: "b|c", relationType: "knows" }, + { from: "a|b", to: "c", relationType: "knows" }, + ], + }); + expect(created.structuredContent).toEqual({ + relations: [ + { from: "a|b", to: "c", relationType: "knows" }, + { from: "a", to: "b|c", relationType: "knows" }, + ], + }); + + const deleted = await call(conn.client, "delete_relations", { + relations: [{ from: "a", to: "b|c", relationType: "knows" }], + }); + expect(deleted.isError).toBeFalsy(); + expect(await graph()).toMatchObject({ + relations: [ + { from: "a", to: "b", relationType: "knows" }, + { from: "a", to: "b", relationType: "knows" }, + { from: "a|b", to: "b", relationType: "knows" }, + { from: "a|b", to: "c", relationType: "knows" }, + ], + }); + }); + + it("deletes every stored copy of a relation, in stored order", async () => { + await call(conn.client, "delete_relations", { + relations: [{ from: "a", to: "b", relationType: "knows" }], + }); + expect(await graph()).toMatchObject({ + relations: [{ from: "a|b", to: "b", relationType: "knows" }], + }); + }); + + it("adds and deletes observations on the first of two same-named entities", async () => { + await call(conn.client, "add_observations", { + observations: [ + { entityName: "a", contents: ["o2", "o1"] }, + // A second entry for the same entity sees what the first added. + { entityName: "a", contents: ["o2", "o3"] }, + ], + }); + expect(await graph()).toMatchObject({ + entities: [ + { + name: "a", + entityType: "first", + observations: ["o1", "o1", "o2", "o3"], + }, + { name: "b" }, + { name: "a", entityType: "second", observations: ["o2"] }, + { name: "a|b" }, + ], + }); + + await call(conn.client, "delete_observations", { + deletions: [{ entityName: "a", observations: ["o1", "o3"] }], + }); + expect(await graph()).toMatchObject({ + entities: [ + { name: "a", entityType: "first", observations: ["o2"] }, + { name: "b" }, + { name: "a", entityType: "second", observations: ["o2"] }, + { name: "a|b" }, + ], + }); + }); + + it("deletes every same-named entity and every relation touching one", async () => { + await call(conn.client, "delete_entities", { entityNames: ["a"] }); + expect(await graph()).toEqual({ + entities: [ + { name: "b", entityType: "t", observations: [] }, + { name: "a|b", entityType: "t", observations: ["o3"] }, + ], + relations: [{ from: "a|b", to: "b", relationType: "knows" }], + }); + }); + + it("reports stored names and in-batch repeats as skipped, in request order", async () => { + const result = await call(conn.client, "create_entities", { + entities: [ + { name: "c", entityType: "t", observations: ["kept"] }, + { name: "a", entityType: "t", observations: ["dropped"] }, + { name: "c", entityType: "t", observations: ["dropped"] }, + { name: "d", entityType: "t", observations: [] }, + ], + }); + expect(result.structuredContent).toEqual({ + entities: [ + { name: "c", entityType: "t", observations: ["kept"] }, + { name: "d", entityType: "t", observations: [] }, + ], + skipped: ["a", "c"], + }); + }); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..b80ef76f14 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -170,6 +170,29 @@ export function skippedEntityNames( return requested.filter((e) => !created.includes(e)).map((e) => e.name); } +// The write methods match against the loaded graph through these indexes +// rather than scanning it once per requested item (#5693). + +// A relation's identity as one string. JSON.stringify of the tuple is +// collision-free: entity names are arbitrary strings, so joining the three +// fields with any separator could make two different relations share a key. +function relationKey(r: Relation): string { + return JSON.stringify([r.from, r.to, r.relationType]); +} + +// Each name's FIRST entity, the one Array.prototype.find would return. A +// hand-edited file can hold two entities with one name, and only the first +// is ever matched by name. +function firstEntityByName(entities: Entity[]): Map { + const byName = new Map(); + for (const entity of entities) { + if (!byName.has(entity.name)) { + byName.set(entity.name, entity); + } + } + return byName; +} + // Text telling the agent which entities create_entities skipped. export function skippedEntitiesNotice(skipped: string[]): string { const one = skipped.length === 1; @@ -1190,14 +1213,18 @@ export class KnowledgeGraphManager { async createEntities(entities: Entity[]): Promise { return this.withLock(async () => { const { graph, unreadable, size } = await this.loadGraphWithUnreadable(); - const newEntities = entities.filter( - (e, index) => - !graph.entities.some( - (existingEntity) => existingEntity.name === e.name, - ) && - // Also skip duplicates appearing earlier in this same batch - !entities.slice(0, index).some((earlier) => earlier.name === e.name), - ); + // Seeded with the stored names, and grown as the batch is read, so a + // name repeating an earlier one in this same batch is skipped too. The + // filter keeps the requested objects themselves: skippedEntityNames + // tells created from skipped by identity. + const seen = new Set(graph.entities.map((e) => e.name)); + const newEntities = entities.filter((e) => { + if (seen.has(e.name)) { + return false; + } + seen.add(e.name); + return true; + }); graph.entities.push(...newEntities); // Only a call that adds something is held to the limits: re-saving can // grow an existing file that was not written in this exact form. @@ -1224,18 +1251,17 @@ export class KnowledgeGraphManager { } }); - const isSameRelation = (a: Relation, b: Relation) => - a.from === b.from && a.to === b.to && a.relationType === b.relationType; - const newRelations = relations.filter( - (r, index) => - !graph.relations.some((existingRelation) => - isSameRelation(existingRelation, r), - ) && - // Also skip duplicates appearing earlier in this same batch - !relations - .slice(0, index) - .some((earlier) => isSameRelation(earlier, r)), - ); + // As in createEntities: stored relations, then earlier ones in this + // same batch, are skipped. + const seen = new Set(graph.relations.map(relationKey)); + const newRelations = relations.filter((r) => { + const key = relationKey(r); + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; + }); graph.relations.push(...newRelations); // Held to the limits only when it adds something (see createEntities). await this.saveGraph( @@ -1252,17 +1278,26 @@ export class KnowledgeGraphManager { ): Promise<{ entityName: string; addedObservations: string[] }[]> { return this.withLock(async () => { const { graph, unreadable, size } = await this.loadGraphWithUnreadable(); + const entityByName = firstEntityByName(graph.entities); + // Each touched entity's observations as a Set, built on first use and + // kept in step with what is pushed, so a later entry for the same + // entity sees what an earlier one added. + const storedByName = new Map>(); const results = observations.map((o) => { - const entity = graph.entities.find((e) => e.name === o.entityName); + const entity = entityByName.get(o.entityName); if (!entity) { throw new Error(`Entity with name ${o.entityName} not found`); } + const known = + storedByName.get(o.entityName) ?? new Set(entity.observations); + storedByName.set(o.entityName, known); // A Set keeps the first occurrence of each string, so a repeat within // one call is stored and reported once (#5201). const newObservations = [...new Set(o.contents)].filter( - (content) => !entity.observations.includes(content), + (content) => !known.has(content), ); entity.observations.push(...newObservations); + newObservations.forEach((content) => known.add(content)); return { entityName: o.entityName, addedObservations: newObservations }; }); // Held to the limits only when it adds something (see createEntities). @@ -1280,11 +1315,10 @@ export class KnowledgeGraphManager { const present = new Set(graph.entities.map((e) => e.name)); const deleted = entityNames.filter((name) => present.has(name)); const notFound = entityNames.filter((name) => !present.has(name)); - graph.entities = graph.entities.filter( - (e) => !entityNames.includes(e.name), - ); + const toDelete = new Set(entityNames); + graph.entities = graph.entities.filter((e) => !toDelete.has(e.name)); graph.relations = graph.relations.filter( - (r) => !entityNames.includes(r.from) && !entityNames.includes(r.to), + (r) => !toDelete.has(r.from) && !toDelete.has(r.to), ); await this.saveGraph(graph, unreadable); return { deleted, notFound }; @@ -1298,12 +1332,14 @@ export class KnowledgeGraphManager { const { graph, unreadable } = await this.loadGraphWithUnreadable(); let deletedCount = 0; const missingEntities: string[] = []; + const entityByName = firstEntityByName(graph.entities); deletions.forEach((d) => { - const entity = graph.entities.find((e) => e.name === d.entityName); + const entity = entityByName.get(d.entityName); if (entity) { const before = entity.observations.length; + const toDelete = new Set(d.observations); entity.observations = entity.observations.filter( - (o) => !d.observations.includes(o), + (o) => !toDelete.has(o), ); deletedCount += before - entity.observations.length; } else { @@ -1321,14 +1357,9 @@ export class KnowledgeGraphManager { return this.withLock(async () => { const { graph, unreadable } = await this.loadGraphWithUnreadable(); const before = graph.relations.length; + const toDelete = new Set(relations.map(relationKey)); graph.relations = graph.relations.filter( - (r) => - !relations.some( - (delRelation) => - r.from === delRelation.from && - r.to === delRelation.to && - r.relationType === delRelation.relationType, - ), + (r) => !toDelete.has(relationKey(r)), ); await this.saveGraph(graph, unreadable); return { deletedCount: before - graph.relations.length }; From 1de964236b3b0b94619dfb9862185661f0ed07b3 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:28:25 -0500 Subject: [PATCH 18/76] docs: extend the GitHub pacing rule to expensive reads Rename AGENTS.md "Pacing GitHub writes" to "Pacing GitHub calls" and add that an expensive read (the whole-board listing, field-list) runs once per batch, that a retry after a refusal makes no expensive calls, and that the GraphQL quota is per account, with the Projects v2 REST endpoints as the core-quota fallback. board-ops gains board_list/issue_item for one listing per batch, the draft-card lookup reuses a listing it is given, and a REST section covers reading the board and setting Status or Priority when GraphQL is exhausted. issue-create and issue-triage reuse one listing too. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .claude/skills/board-ops/SKILL.md | 111 +++++++++++++++++++++++++-- .claude/skills/issue-create/SKILL.md | 6 +- .claude/skills/issue-triage/SKILL.md | 8 +- .claude/skills/pr-flow/SKILL.md | 2 +- AGENTS.md | 22 +++++- docs/contribution-model.md | 2 +- 6 files changed, 136 insertions(+), 15 deletions(-) diff --git a/.claude/skills/board-ops/SKILL.md b/.claude/skills/board-ops/SKILL.md index bb75edece9..f483cbe759 100644 --- a/.claude/skills/board-ops/SKILL.md +++ b/.claude/skills/board-ops/SKILL.md @@ -114,6 +114,41 @@ about the board's size; don't make the recipes depend on it being right. file, an incomplete dump is deleted, so that step fails on the missing file rather than running on partial data. +### One listing per batch + +The whole-board listing is the costliest read these recipes make (about 50 +GraphQL points), so **a batch takes it once and every lookup in the batch +reads that one result**, as `AGENTS.md` **Pacing GitHub calls** says. Never +re-list per item, and never re-list to test whether a refusal has lifted. + +```sh +# board_list → BOARD holds the complete listing, or is empty and the call fails. +board_list() { + BOARD=$(gh project item-list 43 --owner modelcontextprotocol --format json --limit 2000) || BOARD= + jq -e '(.items | length) == .totalCount' <<<"$BOARD" >/dev/null 2>&1 \ + || { echo "item-list incomplete or failed — raise --limit; not concluding anything" >&2 + BOARD=; return 1; } +} + +# issue_item → the item id of this repo's issue N in BOARD, or nothing. +# Arguments reach jq through --args, never as shell positional parameters (#5160). +issue_item() { + jq -r '($ARGS.positional[0] | tonumber) as $n | .items[] + | select(.content.type=="Issue" and .content.repository=="modelcontextprotocol/servers" + and .content.number==$n) | .id' --args "$@" <<<"$BOARD" +} + +board_list # once, at the start of the batch +``` + +Every lookup below that needs the listing runs `[ -n "$BOARD" ] || board_list` +first, so it reuses a listing it is given and fetches only when there is none. +A listing is a snapshot: it holds no card added after it was taken, so take a +fresh one for the next batch, not for the next item. For a batch of issues, +`issue_item` replaces the per-issue lookup in +[Move an existing card](#move-an-existing-card); for one issue, that lookup is +cheaper than a listing. + ## Recipes Every recipe below assumes `FIELDS` and `opt` from [IDs](#ids) are defined in @@ -263,20 +298,19 @@ finds the follow-up. ⚠️ **A draft card has no repository and no issue number**, so the issue-side lookup above cannot find one. Look it up by its **bracketed GHSA id** in the -full listing, checked for truncation, then feed that item id to `item-edit` or -`item-delete` exactly as usual: +complete listing from [One listing per batch](#one-listing-per-batch), then +feed that item id to `item-edit` or `item-delete` exactly as usual. Over +several advisories, run this block once per GHSA against the same `BOARD`: ```sh GHSA=GHSA-xxxx-yyyy-zzzz # the advisory's real id ITEM_ID= # never let an earlier lookup's id survive a failed one LOOKED= # set only by a lookup over a COMPLETE listing -BOARD=$(gh project item-list 43 --owner modelcontextprotocol --format json --limit 2000) -if jq -e '(.items | length) == .totalCount' <<<"$BOARD" >/dev/null; then +[ -n "$BOARD" ] || board_list # reuse the batch's listing; fetch only if there is none +if [ -n "$BOARD" ]; then ITEM_ID=$(jq -r --arg p "[$GHSA]" '.items[] | select(.content.type=="DraftIssue") | select(.content.title | startswith($p)) | .id' <<<"$BOARD") && LOOKED=1 [ -n "$ITEM_ID" ] || echo "no draft card titled [$GHSA] on #43" >&2 -else - echo "item-list incomplete or failed — raise --limit; not concluding anything" >&2 fi ``` @@ -299,6 +333,10 @@ fi # Then the two chained item-edit calls from "Add a card and set its fields". ``` +A card this creates is not in `BOARD`, which predates it, so a batch never +runs the lookup and create a second time for the same GHSA against one +listing: it would find nothing and create a duplicate. + **Convert** it to an issue when its fix is ready to merge, keeping its opaque title; a follow-up card converts only after the advisory is **published**. When each happens, and what the issue gets, is the `/security-advisory` flow. The web @@ -315,6 +353,63 @@ REPO_ID=$(gh api repos/modelcontextprotocol/servers --jq .node_id) || REPO_ID= The card keeps its place and its field values; the new issue takes the card's title and body. +## When GraphQL is exhausted: the REST endpoints + +The GraphQL quota is per account, so concurrent sessions can exhaust it +together (`AGENTS.md` **Pacing GitHub calls**). Then every `gh project` +command fails with `unknown owner type`, because its first owner lookup is +refused. Confirm it before doing anything else: + +```sh +gh api rate_limit --jq '.resources | {graphql, core}' +``` + +Projects v2 also has REST endpoints, which draw on the separate **core** +quota. They cover listing the fields and items, adding an issue, and setting +Status or Priority, under the same pacing. They do **not** cover editing a +draft card's body, which still needs GraphQL. REST uses **numeric** ids for +fields and items, not the `PVTSSF_…` / `PVTI_…` node ids above; option ids are +the same short ids `opt` returns. + +```sh +P=/orgs/modelcontextprotocol/projectsV2/43 +RFIELDS=$(gh api "$P/fields") || RFIELDS= # once per session, like FIELDS +# rfield → its numeric REST id; ropt