diff --git a/.claude/skills/local-dev/SKILL.md b/.claude/skills/local-dev/SKILL.md index 3872ca1446..852bfd5c44 100644 --- a/.claude/skills/local-dev/SKILL.md +++ b/.claude/skills/local-dev/SKILL.md @@ -88,9 +88,18 @@ node src/filesystem/dist/index.js --transport streamable-http /tmp/scratch # d (cd src/time && uv run mcp-server-time --transport streamable-http) ``` -Each one's endpoint is stateless for 2025-era clients (a fresh server per -request; GET and DELETE answer 405), so nothing the server asks of the client -mid-session (filesystem's Roots) reaches it over HTTP. +What a 2025-era client gets from that endpoint differs by language (#5593): + +- **`memory`, `filesystem`, `sequentialthinking` (TypeScript) are stateless**: a + fresh server per request, no `Mcp-Session-Id` on the `initialize` response, + and GET and DELETE answer 405. So nothing the server asks of the client + mid-session (filesystem's Roots) reaches it over HTTP. +- **`fetch`, `git`, `time` (Python) keep a session**, through the SDK's + Streamable HTTP app. `initialize` returns an `Mcp-Session-Id` header and + every later request must carry it: without it a POST, GET or DELETE answers + 400 "Missing session ID". With it, GET opens the session's stream and DELETE + ends the session, after which its id answers 404. A hand-written `curl` + probe therefore sends `initialize` first and passes the header on. ## Run the local package the way a user would @@ -173,7 +182,9 @@ fails its first step. ## Docker -Each server has a `Dockerfile`, and no gate builds them. The build context +Each server has a `Dockerfile`. The gate's `image-smoke` stage builds and +boots the image of each server a change touches (`npm run image-smoke -- --all` +for all seven; `docs/quality-gate.md`). The build context differs by language. The TypeScript images build from the **repo root**, because they copy the root `tsconfig.json`: `docker build -t mcp/ -f src//Dockerfile .`. The Python images diff --git a/.claude/skills/pr-flow/SKILL.md b/.claude/skills/pr-flow/SKILL.md index e64ac106dc..0c37bd0f4d 100644 --- a/.claude/skills/pr-flow/SKILL.md +++ b/.claude/skills/pr-flow/SKILL.md @@ -252,7 +252,7 @@ gh pr view "$PR" --repo modelcontextprotocol/servers \ ``` The link does **not** make the issue close on merge into `v2/main`; that is -still done by hand in step 9. +still done by hand in step 10. Then move the card to **In Review** (`/board-ops`). The PR itself never goes on the board. @@ -407,6 +407,108 @@ the PR shows why the loop ended. Merging is a maintainer's decision. Do not merge on your own initiative. +### Before the merge: catch up if `v2/main` moved + +The rule is in `AGENTS.md` **Issue-driven work style**: a PR is caught up and +re-tested before it merges when `v2/main` moved in a way that can interact +with it. CI here runs on **push**, on the branch's head commit, and the gate +ran in your worktree, so neither has seen anything that landed on `v2/main` +after the branch last took it in. GitHub's "no conflicts with the base branch" +compares text and tests nothing: #5564 and #5567 were each green and cleanly +mergeable, merged ten minutes apart, and left `v2/main` failing `ruff check` +(#5569). + +**1. List what the PR's head lacks.** From any checkout of this repo: + +```sh +PR= +git fetch origin v2/main "refs/pull/$PR/head" +HEAD_SHA=$(gh pr view "$PR" --repo modelcontextprotocol/servers \ + --json headRefOid --jq .headRefOid) + +# Commits on v2/main that the head does not hold. Nothing printed: the PR was +# tested on the current tip, so there is nothing to catch up. +git log --oneline "$HEAD_SHA..origin/v2/main" + +# The files each side changed since the two diverged. +LANDED=$(git diff --name-only "$HEAD_SHA...origin/v2/main") +MINE=$(git diff --name-only "origin/v2/main...$HEAD_SHA") + +# Check A: servers that both sides touched. +comm -12 <(grep -oE '^src/[^/]+/' <<<"$LANDED" | sort -u) \ + <(grep -oE '^src/[^/]+/' <<<"$MINE" | sort -u) + +# Check B: repository-wide configuration, on either side: a root manifest, +# lockfile, config file or dotfile, scripts/, or a workflow. +WIDE='^([^/]+\.(json|js|mjs|cjs|ts|toml|ya?ml)|\.[^/]+|scripts/.*|\.github/workflows/.*)$' +grep -E "$WIDE" <<<"$LANDED" | sed 's/^/landed: /' +grep -E "$WIDE" <<<"$MINE" | sed 's/^/mine: /' +``` + +**2. Decide.** + +| The listing shows | Then | +| --- | --- | +| No commits | Nothing to do. Merge on green CI | +| Commits, and checks A and B both print nothing | What landed cannot interact with the PR. No catch-up needed | +| Check A prints a server, or check B prints any path | **Catch up** (below) | +| Anything you are unsure of | **Catch up**. The checks are deliberately coarse, and a gate run is cheaper than a red `v2/main` | + +A server's own configuration (`pyproject.toml`, `uv.lock`, `tsconfig.json`, +`vitest.config.ts`) is inside its directory, so check A covers it: that is the +#5569 case, where a `requires-python` bump changed which lint rules applied to +code another PR was adding. + +**3. Catch up**, in the PR's worktree: + +```sh +git fetch origin v2/main +git merge --no-edit origin/v2/main +npm install # the merge may have moved package-lock.json +npm run local:gate && git push # the push runs only on a green gate +``` + +- **Merge, never rebase.** A rebase rewrites the commits that were reviewed, + outdates every review thread and needs a force-push. The merge commit is + exempt from the DCO check (step 3). +- **The gate runs on the merged tree before the push**, as before any push + (step 4), and a red gate pushes nothing. A red stage here is the interaction + this step exists to find: fix it on the branch, signed off, and run that + last line again. +- **Then wait for CI on the new head**, with one backgrounded command, as + `AGENTS.md` **Waiting on long-running work** says. The `sleep` gives the push + runs time to register; `--watch` on a head with no checks yet exits at once. + + ```sh + sleep 60; gh pr checks "$PR" --repo modelcontextprotocol/servers \ + --watch --interval 30; echo "EXIT=$?" + ``` + +- **A catch-up that merged without conflicts and passed the gate unchanged + needs no new Copilot round.** Nothing the PR adds changed. One that needed a + conflict resolved or a fix pushed changed the PR, so request a round (step 9). +- **If `v2/main` moves again before the merge, run step 1 again.** It costs + one fetch, and most of the time it prints nothing that interacts. + +**Fan-outs.** When several PRs for one server are open at once, a PR that +changes that server's **configuration** (a language floor, lint or compiler +settings, a dependency major) interacts with every one of them. Merge it +**last**, after catching it up on the others, or merge it first and catch up +and re-test each of the others after it. The open PRs that touch a server: + +```sh +gh pr list --repo modelcontextprotocol/servers --base v2/main --state open \ + --limit 200 --json number,title,files \ + --jq '.[] | select(any(.files[]; .path | startswith("src/fetch/"))) + | "\(.number) \(.title)"' +``` + +Nothing enforces this step: `v2/main`'s ruleset requires no status checks, so +it is done by hand by whoever merges. Whether a merge queue or a required +up-to-date check should take it over is #5588. + +### After the merge + **On merge into `v2/main`, close the issue by hand and move its card to Done**, since auto-close does not fire there: diff --git a/.claude/skills/pr-flow/evals/evals.json b/.claude/skills/pr-flow/evals/evals.json index 2fa6dacb38..e47e1011f5 100644 --- a/.claude/skills/pr-flow/evals/evals.json +++ b/.claude/skills/pr-flow/evals/evals.json @@ -23,6 +23,10 @@ "prompt": "My PR into v2/main just merged. What do I still need to do to close it out?", "expect": "pr-flow" }, + { + "prompt": "My PR is green and GitHub says it has no conflicts, but another PR for the same server merged into v2/main ten minutes ago. What do I have to do before it can merge?", + "expect": "pr-flow" + }, { "prompt": "What does this regex match? /^[a-z]+$/", "expect": null diff --git a/.claude/skills/pre-push-gate/SKILL.md b/.claude/skills/pre-push-gate/SKILL.md index 8231084a4f..76bd790e12 100644 --- a/.claude/skills/pre-push-gate/SKILL.md +++ b/.claude/skills/pre-push-gate/SKILL.md @@ -275,7 +275,7 @@ of the server's stderr. Re-run a subset with ### `interface-diff` -The last stage diffs the MCP interface (capabilities, tools, prompts, +This stage diffs the MCP interface (capabilities, tools, prompts, resources, resource templates) of each server the change touches, in this checkout's build, against the same server built from the merge-base with `origin/v2/main`, and prints one report per server. Each report says why that @@ -308,6 +308,39 @@ it compares against in CI, and why it is a script rather than an action, is in [`docs/quality-gate.md`](../../../docs/quality-gate.md) and the header of `scripts/interface-diff.mjs`. +### `image-smoke` + +The last stage builds the Docker image of each server the change touches, +boots it with `docker run -i`, lists its tools, and (for `everything` and +`memory`) stops it with `docker stop`. A change that touches no image prints +`nothing to build` and passes without Docker. What selects an image is in +[`docs/quality-gate.md`](../../../docs/quality-gate.md). A failure is +`image-smoke — FAIL ` and the reason: + +- **"no Docker daemon answered"**: the change touches an image and Docker is + not running. Start it and re-run; the stage never skips. +- **"`docker build …` failed"**, with the tail of the build log: the + Dockerfile no longer builds from this checkout. The usual causes are a file + the Dockerfile copies that moved or is excluded by its + `Dockerfile.dockerignore`, a lockfile out of step with a manifest + (`npm ci`, `uv sync --locked`), or, offline, a layer Docker has not cached. +- **"Connection closed"** or a timeout, with the container's stderr: the + image built but its entrypoint did not start the server. Run it by hand: + `docker run -i --rm mcp-image-smoke/:local`. +- **"tools/list does not include …"**: as for `smoke`; the tool the image is + checked for is in `IMAGES` in `scripts/image-smoke.mjs`. +- **"`docker stop` had to kill it"**: the server did not exit on the image's + stop signal. Check the Dockerfile's `STOPSIGNAL` and the server's signal + handlers. +- **"/data holds […] after the stop"**: `memory` left a lock or temporary + file behind, or lost the write. +- **A new Dockerfile fails `test:scripts`** with "every Dockerfile in the + repo has an image entry": add it to `IMAGES`. + +Re-run it on its own with `npm run image-smoke`, `-- --server ` for one +image, `-- --all` for all seven, or `-- --list` to see what it would select +and why. + ## Waiting on the lease A gate that starts with diff --git a/.claude/skills/project-structure/SKILL.md b/.claude/skills/project-structure/SKILL.md index 78e9bf9a3a..2937c0d955 100644 --- a/.claude/skills/project-structure/SKILL.md +++ b/.claude/skills/project-structure/SKILL.md @@ -24,7 +24,8 @@ entry point is `index.ts`, sources sit at the workspace root (there is no `src/` inside a server), tests are in `__tests__/`, and `tsc` writes `dist/`. Each has the same four config files: `package.json`, `tsconfig.json` (the build), `tsconfig.test.json` (the no-emit typecheck program, which also -includes the tests) and `vitest.config.ts`. +includes the tests) and `vitest.config.ts`. Each also has a `server.json`, its +MCP Registry entry, which carries no version: `release.yml` stamps it. | Server | Layout | Where its features are registered | | --- | --- | --- | @@ -66,6 +67,7 @@ in-process harness. src// ├── pyproject.toml dependencies, the console script, pytest and coverage config ├── uv.lock, .python-version +├── server.json the server's MCP Registry entry (no version: release.yml stamps it) ├── src/mcp_server_/ │ ├── __init__.py main(): the command-line flags, then asyncio.run(serve(...)) │ ├── __main__.py python -m mcp_server_ diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index e939551079..8c9506766b 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -216,7 +216,7 @@ Then, on the PR: (that fires `pull_request`; they run on `push`). If a status does not appear, dispatch its workflow by hand: `gh workflow run typescript.yml --ref changeset-release/v2/main` (or - `python.yml`, `dco.yml`, `everything-mcp-diff.yml`). + `python.yml`, `dco.yml`, `mcp-interface-diff.yml`). 3. **Read it**: each bump matches the semver policy in `RELEASING.md`, each `CHANGELOG.md` entry says what a user of the server needs to know, the consumed changeset files are deleted, and `package-lock.json` records the @@ -721,6 +721,12 @@ skip. Approve the packages whose build leg passed. One failed build leg does not hold the others back; that package is handled as a failed publish (`RELEASING.md` **When a publish fails**). +**One more approval arrives after the packages publish**: `Publish to the MCP +Registry`, which lists each published version in the MCP Registry. It cannot +be approved with the others, because it only starts once they finish, so come +back for it. Its failure does not touch the packages (`RELEASING.md` **The MCP +Registry**). + ## 6. After it publishes ```sh @@ -738,6 +744,16 @@ done A freshly published npm version can take a few minutes to appear. Query the exact version, as above, never `dist-tags`. +Then each server's MCP Registry entry at that version: 200 means listed. + +```sh +node scripts/mcp-registry-entries.mjs | jq -r '.[] | "\(.name) \(.version)"' | + while read -r name version; do + echo "$name $version $(curl -s -o /dev/null -w '%{http_code}' \ + "https://registry.modelcontextprotocol.io/v0/servers/${name/\//%2F}/versions/$version")" + done +``` + ### The first semver release only: deprecate the date-stamped versions The TypeScript packages were published with date-stamped versions (`2025.x`, diff --git a/.github/workflows/everything-mcp-diff.yml b/.github/workflows/everything-mcp-diff.yml deleted file mode 100644 index 3de61944a4..0000000000 --- a/.github/workflows/everything-mcp-diff.yml +++ /dev/null @@ -1,432 +0,0 @@ -# Tracks public interface changes to the MCP servers: how each server's tools, -# resources, prompts and capabilities evolve, so a reviewer sees the protocol -# surface a change moves without running anything (useful for SDK compliance -# validation and catching regressions). -# -# Contributed by @SamMorrowDrums in #3260 for the Everything server, adapted for -# v2/main in #4860, and extended to every server in #5428: -# -# - The check is `npm run interface-diff` (scripts/interface-diff.mjs), which -# drives the `mcp-server-diff` CLI, an exact-pinned root devDependency. The -# same script is a `local:gate` stage, and `scripts/lib/workflow-gate.test.mjs` -# requires every npm script a workflow runs to be one, so CI and the gate run -# the same check. No third-party action runs here. -# - A server is diffed only when the change touches it: its own directory, a -# package it resolves in the root lockfile, the root tsconfig (TypeScript -# servers), or the diff tooling itself (every server). A `paths` filter -# cannot say "the lockfile changed in a way that reaches this server", and -# almost every TypeScript PR rewrites the lockfile, so the workflow runs on -# every change and the `changes` job asks the script which servers to diff -# (`--list`, the same selection the gate makes). `diff` and `comment` fan out -# over that list, one matrix leg per server. -# - The base is chosen per event below rather than by the tool, whose default -# (the merge-base with origin/main) is the wrong base for PRs to v2/main. -# - Untrusted code (the PR's install, build and server, and the selection -# script) runs only in `changes` and `diff`, which hold a read-only token and -# no persisted credentials. Each sticky comment (one per server, found again -# by its marker) is posted by `comment`, which holds `pull-requests: write` -# and runs none of the PR's code, and only for PRs from this repository: a -# fork PR's token is read-only, so there the report is in the job summary and -# the `mcp-diff-report-` artifact. `pull_request_target` is -# deliberately not used, since it would run the fork's build next to a write -# token. If fork PRs need the comment too, the way is a separate -# `workflow_run` workflow that posts the artifact without checking anything -# out. The server names `comment` reads come from `changes`, which ran PR -# code, so it checks each against the known list before using it. -# -# A changed interface does not fail the run: the diff is information for the -# reviewer. A diff that cannot run (a base that does not build, a server that -# cannot be probed) does. -# -# A server's comment is left as it is when a later push stops touching that -# server; it then describes the last push that did. -# -# The version PRs are pushed and opened with the workflow token, whose events -# start no `pull_request` run here: GitHub holds each one as -# `action_required`, or fails it with no jobs (#5173). So the Version Packages -# and Prepare Python Release workflows dispatch this one on the PR's branch, as -# they do the CI workflows (#5110), and the `dispatch-status` jobs report the -# dispatched run on the PR as a commit status. -# -# The file keeps its `everything-` name although it diffs every server: GitHub -# dispatches only a workflow whose file exists on the default branch (`main`), -# and both version workflows dispatch this one by file name from `v2/main`, so -# renaming it here would break their dispatch until the next milestone merge. -# The rename is staged instead: `mcp-interface-diff.yml` lands on `main` first -# as a dispatch-only placeholder (#5463), then #5527 moves this file's contents -# there, switches the callers and deletes this file. -# -# See: https://github.com/modelcontextprotocol/inspector/issues/1034 -name: MCP Interface Diff - -on: - push: - branches: [main, v2/main] - # No branch filter: PRs to v2/main and to main both run, and so does a PR - # stacked on another PR's branch. The base is the PR's own base either way. - pull_request: - # A published Release (a milestone, tagged vX.Y.Z on main; see RELEASING.md) - # surfaces the cumulative interface delta since the previous Release, for - # each server that changed in between. This replaces #3260's - # `typescript-servers-*` tag trigger: those tags stopped in 2024, and no - # release since has used them. - release: - types: [published] - # Manual trigger: the branch chosen in "Use workflow from" is the head, and - # `compare_ref` any base. #3260 also took a `target_ref`, but a target that - # predates the interface-diff script has no `npm run interface-diff` to run, - # so the head is the dispatched branch instead. - workflow_dispatch: - inputs: - compare_ref: - description: "Base ref to compare against (commit SHA, tag, or branch; defaults to the merge-base with v2/main)" - required: false - default: "" - -permissions: - contents: read - -# Superseded runs on the same PR are cancelled. Every other run gets a group -# of its own: a group holds one running and one pending run, so a shared group -# would drop a push's run when two more queued behind it. -concurrency: - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - changes: - name: Choose the servers to diff - timeout-minutes: 10 - runs-on: ubuntu-latest - permissions: - contents: read - outputs: - base: ${{ steps.base.outputs.ref }} - servers: ${{ steps.list.outputs.servers }} - steps: - - name: Checkout repository - uses: actions/checkout@v6 - with: - # The base is found in history, so all of it is needed, tags - # included (the release base is the previous Release's tag). - fetch-depth: 0 - # The event's own commit (the merge commit for a PR), not a branch - # ref that a later push could move before this step runs. - ref: ${{ github.sha }} - persist-credentials: false - - # No install: the selection imports nothing outside Node. - - uses: actions/setup-node@v7 - with: - node-version: 24 - - - name: Choose the base to compare against - id: base - env: - EVENT: ${{ github.event_name }} - PR_BASE: ${{ github.event.pull_request.base.sha }} - BEFORE: ${{ github.event.before }} - INPUT_BASE: ${{ inputs.compare_ref }} - TAG: ${{ github.event.release.tag_name }} - PUBLISHED: ${{ github.event.release.published_at }} - REPO: ${{ github.repository }} - GH_TOKEN: ${{ github.token }} - run: | - case "$EVENT" in - # The checkout is the PR's merge commit, so its base tip is - # exactly what the PR changes. - pull_request) base="$PR_BASE" ;; - # The branch as it was before this push; a new branch has none. - push) - if [ -n "$BEFORE" ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then - base="$BEFORE" - else - base=$(git rev-parse HEAD^) - fi ;; - # The Release published just before this one (so a re-run of an - # older Release still compares against ITS predecessor). Not - # `git describe`: the date-stamped releases tagged commits that - # never reached main, so the nearest ancestor tag is years older - # than the last release. - release) - base=$(gh release list --repo "$REPO" --exclude-drafts --exclude-pre-releases --limit 50 \ - --json tagName,publishedAt \ - --jq "map(select(.tagName != \"$TAG\" and .publishedAt < \"$PUBLISHED\")) | sort_by(.publishedAt) | last | .tagName // empty") - if [ -z "$base" ]; then echo "no earlier Release to compare against" >&2; exit 1; fi ;; - workflow_dispatch) - if [ -n "$INPUT_BASE" ]; then - base="$INPUT_BASE" - else - base=$(git merge-base HEAD origin/v2/main) - fi ;; - *) echo "unexpected event: $EVENT" >&2; exit 1 ;; - esac - # Resolved to a SHA here, so every leg compares against the same - # commit even if a branch named as the base moves meanwhile. - base=$(git rev-parse --verify "$base^{commit}") - echo "Comparing against $base" - echo "ref=$base" >> "$GITHUB_OUTPUT" - - - name: List the servers the change touches - id: list - env: - BASE: ${{ steps.base.outputs.ref }} - run: | - # The reasons go to the log on stderr; stdout is the JSON list. - servers=$(npm run --silent interface-diff -- --base "$BASE" --list) - echo "Servers to diff: $servers" - echo "servers=$servers" >> "$GITHUB_OUTPUT" - { - if [ "$servers" = "[]" ]; then - echo "No server changed since \`$BASE\`; there is no interface to diff." - else - echo "Diffing: $(jq -r 'map("`" + .server + "`") | join(", ")' <<<"$servers")" - fi - } >> "$GITHUB_STEP_SUMMARY" - - diff: - name: Diff ${{ matrix.server }} - needs: changes - if: needs.changes.outputs.servers != '[]' - timeout-minutes: 15 - runs-on: ubuntu-latest - permissions: - contents: read - strategy: - # One server's broken diff must not hide another's report. - fail-fast: false - matrix: - include: ${{ fromJSON(needs.changes.outputs.servers) }} - steps: - - name: Checkout repository - uses: actions/checkout@v6 - with: - # The base is built from history. - fetch-depth: 0 - ref: ${{ github.sha }} - persist-credentials: false - - - uses: actions/setup-node@v7 - with: - node-version: 24 - cache: npm - - # A root `npm ci` runs every workspace's `prepare`, which builds it, so - # a TypeScript head build the diff probes exists after this step. It also - # installs `mcp-server-diff`, which every leg needs. - - name: Install dependencies and build - run: npm ci - - - name: Install uv - if: matrix.language == 'py' - uses: astral-sh/setup-uv@v7 - - # The diff probes a Python head with `uv run --no-sync`, so its - # environment is synced here, as the gate's `validate:py` does. - - name: Sync the Python server - if: matrix.language == 'py' - working-directory: src/${{ matrix.server }} - run: uv sync --locked - - - name: Diff the interface - env: - BASE: ${{ needs.changes.outputs.base }} - SERVER: ${{ matrix.server }} - run: npm run interface-diff -- --base "$BASE" --server "$SERVER" --report-dir mcp-diff-report - - - name: Write the job summary - if: always() - env: - SERVER: ${{ matrix.server }} - run: | - report="mcp-diff-report/$SERVER/report.md" - { - if [ -f "$report" ]; then - # A step summary holds at most 1 MiB. - head -c 900000 "$report" - if [ "$(wc -c < "$report")" -gt 900000 ]; then - echo "" - echo "_The report is truncated here; the full report is in the run's \`mcp-diff-report-$SERVER\` artifact._" - fi - else - echo "The interface diff produced no report; see the job log." - fi - echo "" - echo "---" - echo "" - echo "ℹ️ **Interpreting Results**" - echo "" - echo "These are reference servers, so a change to one's interface may indicate:" - echo "- New MCP protocol features being demonstrated" - echo "- Updated tool schemas or descriptions" - echo "- New resources, prompts, or capabilities" - echo "" - echo "Review changes to ensure they align with the intended protocol updates." - } >> "$GITHUB_STEP_SUMMARY" - - - name: Upload the report - if: always() - uses: actions/upload-artifact@v7 - with: - name: mcp-diff-report-${{ matrix.server }} - path: mcp-diff-report/ - if-no-files-found: ignore - - # A dispatched run's checks are left out of the status rollup a pull request - # reads, so on a dispatch these two jobs mirror the run onto the commit as a - # status, as in typescript.yml (whose comments hold the reasoning): pending - # at the start, then the result. Every other event skips both. Unlike - # typescript.yml's (#5223), the pending job also stays silent when a newer - # dispatched run exists, so a late or re-run older run cannot reset the - # newer run's result to pending, which its own result job would then leave. - dispatch-status-pending: - name: Report the dispatched run as pending - if: github.event_name == 'workflow_dispatch' - timeout-minutes: 5 - runs-on: ubuntu-latest - permissions: - statuses: write - # To look for a newer dispatched run of this workflow on the commit. - actions: read - steps: - - name: Set the commit status to pending - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_REPO: ${{ github.repository }} - run: | - # A re-run keeps its run ID, so a newer run means this one is - # superseded and the status is no longer its to set. - NEWER=$(gh run list --workflow everything-mcp-diff.yml --event workflow_dispatch \ - --commit "$GITHUB_SHA" --json databaseId \ - --jq "[.[] | select(.databaseId > $GITHUB_RUN_ID)] | length") || NEWER=0 - if [ "${NEWER:-0}" -gt 0 ]; then - echo "Superseded by a newer dispatched run, which reports instead" - exit 0 - fi - gh api "repos/$GITHUB_REPOSITORY/statuses/$GITHUB_SHA" \ - -f state=pending -f context="Interface diff (dispatched)" \ - -f description="Dispatched run in progress" \ - -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - - # `comment` runs only on `pull_request`, so on a dispatch it is skipped, - # which counts as passed, and so is `diff` when no server changed; the report - # is in the run's summary and artifacts. - dispatch-status: - name: Report the dispatched run's result - if: github.event_name == 'workflow_dispatch' && always() - needs: [dispatch-status-pending, changes, diff, comment] - timeout-minutes: 5 - runs-on: ubuntu-latest - permissions: - statuses: write - # To look for a newer dispatched run of this workflow on the commit. - actions: read - steps: - - name: Set the commit status to the run's result - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_REPO: ${{ github.repository }} - NEEDS: ${{ toJSON(needs) }} - run: | - # A run superseded by a newer dispatch on the same commit posts - # nothing, whatever its jobs' results: the newer run owns the status - # (#5178). A failed lookup counts as no newer run, so this run still - # reports: a stale status is better than one left pending. - NEWER=$(gh run list --workflow everything-mcp-diff.yml --event workflow_dispatch \ - --commit "$GITHUB_SHA" --json databaseId \ - --jq "[.[] | select(.databaseId > $GITHUB_RUN_ID)] | length") || NEWER=0 - if [ "${NEWER:-0}" -gt 0 ]; then - echo "Superseded by a newer dispatched run, which reports instead" - exit 0 - fi - if jq -e 'all(.[]; .result == "success" or .result == "skipped")' <<<"$NEEDS" >/dev/null; then - STATE=success DESCRIPTION="The diff ran; the report is in the run's summary" - elif jq -e 'any(.[]; .result == "failure")' <<<"$NEEDS" >/dev/null; then - STATE=failure DESCRIPTION="The diff could not run; open the run for details" - else - STATE=error DESCRIPTION="The run was cancelled; dispatch it again" - fi - gh api "repos/$GITHUB_REPOSITORY/statuses/$GITHUB_SHA" \ - -f state="$STATE" -f context="Interface diff (dispatched)" \ - -f description="$DESCRIPTION" \ - -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - - # Post (or update) one sticky PR comment per diffed server so reviewers can - # see the diff without navigating to the Actions tab, found again by its - # per-server marker and edited on each push. This job checks nothing out and - # runs none of the PR's code; it only reads the report the `diff` leg - # uploaded. Dependabot's PRs are same-repo but get a read-only token, so they - # are skipped like fork PRs and keep the job summary and the artifact. - comment: - name: Post the ${{ matrix.server }} diff on the PR - needs: [changes, diff] - if: >- - always() && - github.event_name == 'pull_request' && - github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.user.login != 'dependabot[bot]' && - needs.changes.result == 'success' && - needs.changes.outputs.servers != '[]' && - (needs.diff.result == 'success' || needs.diff.result == 'failure') - timeout-minutes: 5 - runs-on: ubuntu-latest - permissions: - pull-requests: write - strategy: - fail-fast: false - matrix: - include: ${{ fromJSON(needs.changes.outputs.servers) }} - steps: - # The list came from a job that ran the PR's code; only a known server - # name reaches an artifact name, a marker or a path below. - - name: Check the server name - env: - SERVER: ${{ matrix.server }} - run: | - case "$SERVER" in - everything|filesystem|memory|sequentialthinking|fetch|git|time) ;; - *) echo "::error::Not a known server: $SERVER"; exit 1 ;; - esac - - - name: Download the report - uses: actions/download-artifact@v8 - continue-on-error: true - with: - name: mcp-diff-report-${{ matrix.server }} - path: mcp-diff-report - - - name: Post / update sticky PR comment - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - PR: ${{ github.event.pull_request.number }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - SERVER: ${{ matrix.server }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - marker="" - report="mcp-diff-report/$SERVER/report.md" - { - echo "$marker" - if [ -f "$report" ]; then - # A comment holds at most 65536 characters. - head -c 60000 "$report" - if [ "$(wc -c < "$report")" -gt 60000 ]; then - echo "" - echo "_The report is truncated here; the full report is in the run's \`mcp-diff-report-$SERVER\` artifact._" - fi - else - echo "## \`$SERVER\`: MCP interface diff" - echo "" - echo "❌ The diff job produced no report; see the run's log." - fi - echo "" - echo "Updated by [this run]($RUN_URL) for \`$HEAD_SHA\`." - } > body.md - id=$(gh api --paginate "repos/$REPO/issues/$PR/comments" \ - --jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | .id" | head -n 1) - if [ -n "$id" ]; then - gh api -X PATCH "repos/$REPO/issues/comments/$id" -F body=@body.md > /dev/null - else - gh api "repos/$REPO/issues/$PR/comments" -F body=@body.md > /dev/null - fi diff --git a/.github/workflows/image-smoke.yml b/.github/workflows/image-smoke.yml new file mode 100644 index 0000000000..0931b56a39 --- /dev/null +++ b/.github/workflows/image-smoke.yml @@ -0,0 +1,144 @@ +# Builds and boots the Docker image of each server a change touches (#5598). +# +# Every server ships a Dockerfile, and before this workflow nothing built one: +# an image that no longer built, could not find its server, or had to be killed +# by `docker stop` reached a release unnoticed, and the release verification +# found it by hand. The check is `npm run image-smoke` +# (scripts/image-smoke.mjs, whose header holds what it asserts and why). The +# same script is a `local:gate` stage, as `scripts/lib/workflow-gate.test.mjs` +# requires of every npm script a workflow runs. +# +# - An image is built only when the change touches it: its server's directory, +# a root file it copies, a package it installs from the root lockfile, or +# the image tooling itself (every image). A `paths` filter cannot say "the +# lockfile changed in a way that reaches this server", so the workflow runs +# on every change and the `changes` job asks the script which images to +# build (`--list`, the same selection the gate makes). `image` fans out over +# that list, one matrix leg per image. This is the interface diff's shape +# (mcp-interface-diff.yml), for the same reasons. +# - The base is the PR's base, or the branch as it was before a push. +# - A manual run (`workflow_dispatch`) builds every image, changed or not: the +# way to check all seven on a branch, for a release verification or after a +# base image moves. +# - Untrusted code (the PR's Dockerfiles and the selection script) runs with a +# read-only token and no persisted credentials. No job here holds a +# credential, pushes an image or logs in to a registry. +# +# The version PRs are opened with the workflow token, whose events start no +# `pull_request` run here. They change version metadata only, and nothing +# dispatches this workflow for them: GitHub dispatches only a workflow whose +# file is on the default branch, which this one is not until a milestone merge. +name: Image smoke + +on: + push: + branches: [main, v2/main] + # No branch filter: PRs to v2/main and to main both run, and so does a PR + # stacked on another PR's branch. The base is the PR's own base either way. + pull_request: + workflow_dispatch: + +permissions: + contents: read + +# Superseded runs on the same PR are cancelled. Every other run gets a group +# of its own, so a push's run is never dropped behind two queued ones. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + changes: + name: Choose the images to build + timeout-minutes: 10 + runs-on: ubuntu-latest + outputs: + images: ${{ steps.list.outputs.images }} + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # The base is found in history, so all of it is needed. + fetch-depth: 0 + # The event's own commit (the merge commit for a PR), not a branch + # ref that a later push could move before this step runs. + ref: ${{ github.sha }} + persist-credentials: false + + # No install: the selection imports nothing outside Node. + - uses: actions/setup-node@v7 + with: + node-version: 24 + + - name: List the images the change touches + id: list + env: + EVENT: ${{ github.event_name }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + BEFORE: ${{ github.event.before }} + run: | + case "$EVENT" in + # The checkout is the PR's merge commit, so its base tip is + # exactly what the PR changes. + pull_request) base="$PR_BASE" ;; + # The branch as it was before this push; a new branch has none. + push) + if [ -n "$BEFORE" ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + base="$BEFORE" + else + base=$(git rev-parse HEAD^) + fi ;; + workflow_dispatch) base="" ;; + *) echo "unexpected event: $EVENT" >&2; exit 1 ;; + esac + # The reasons go to the log on stderr; stdout is the JSON list. + if [ -n "$base" ]; then + echo "Comparing against $base" + images=$(npm run --silent image-smoke -- --base "$base" --list) + else + images=$(npm run --silent image-smoke -- --all --list) + fi + echo "Images to build: $images" + echo "images=$images" >> "$GITHUB_OUTPUT" + { + if [ "$images" = "[]" ]; then + echo "The change touches no server's image; there is nothing to build." + else + echo "Building: $(jq -r 'map("`" + .server + "`") | join(", ")' <<<"$images")" + fi + } >> "$GITHUB_STEP_SUMMARY" + + image: + name: Image ${{ matrix.server }} + needs: changes + if: needs.changes.outputs.images != '[]' + # A cold build is about a minute; the slack is for a slow registry pull. + timeout-minutes: 20 + runs-on: ubuntu-latest + strategy: + # One image's failure must not hide another's verdict. + fail-fast: false + matrix: + include: ${{ fromJSON(needs.changes.outputs.images) }} + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + + # Only for the MCP client the smoke drives the container with, a root + # devDependency. The image builds from the checkout's source inside + # Docker, so no workspace is built here. + - name: Install dependencies + run: npm ci --ignore-scripts + + - name: Build, boot and stop the image + env: + SERVER: ${{ matrix.server }} + run: npm run image-smoke -- --server "$SERVER" diff --git a/.github/workflows/mcp-interface-diff.yml b/.github/workflows/mcp-interface-diff.yml index 4bda642ed5..e8ca5936e7 100644 --- a/.github/workflows/mcp-interface-diff.yml +++ b/.github/workflows/mcp-interface-diff.yml @@ -1,42 +1,435 @@ -# Placeholder for the MCP interface diff's future file name (#5463, Step 1 of -# a rename staged across a milestone merge). +# Tracks public interface changes to the MCP servers: how each server's tools, +# resources, prompts and capabilities evolve, so a reviewer sees the protocol +# surface a change moves without running anything (useful for SDK compliance +# validation and catching regressions). # -# The interface diff lives in `everything-mcp-diff.yml`, a name left over from -# when it diffed only the Everything server. GitHub dispatches a workflow only -# when its file exists on the default branch (`main`), and both version -# workflows (`version-packages.yml`, `prepare-python-release.yml`) dispatch -# the diff by file name from `v2/main`. Renaming it in one step on `v2/main` -# would break their dispatch until the next milestone merge. So the rename is -# staged: +# Contributed by @SamMorrowDrums in #3260 for the Everything server, adapted for +# v2/main in #4860, and extended to every server in #5428: # -# 1. This file ships to `main` in a milestone merge. It is a placeholder, not -# a copy of the diff: a dispatch resolves the file name on `main` but runs -# the file as it is on the dispatched ref, so a placeholder makes the name -# dispatchable as well as a copy would, without a second copy to keep in -# step meanwhile. It has only a `workflow_dispatch` trigger, so it never -# runs beside the real diff on a push or a pull request. -# 2. After that merge, #5527 (Step 2) moves `everything-mcp-diff.yml`'s -# contents here, switches the callers to this name, and deletes the old -# file. +# - The check is `npm run interface-diff` (scripts/interface-diff.mjs), which +# drives the `mcp-server-diff` CLI, an exact-pinned root devDependency. The +# same script is a `local:gate` stage, and `scripts/lib/workflow-gate.test.mjs` +# requires every npm script a workflow runs to be one, so CI and the gate run +# the same check. No third-party action runs here. +# - A server is diffed only when the change touches it: its own directory, a +# package it resolves in the root lockfile, the root tsconfig (TypeScript +# servers), or the diff tooling itself (every server). A `paths` filter +# cannot say "the lockfile changed in a way that reaches this server", and +# almost every TypeScript PR rewrites the lockfile, so the workflow runs on +# every change and the `changes` job asks the script which servers to diff +# (`--list`, the same selection the gate makes). `diff` and `comment` fan out +# over that list, one matrix leg per server. +# - The base is chosen per event below rather than by the tool, whose default +# (the merge-base with origin/main) is the wrong base for PRs to v2/main. +# - Untrusted code (the PR's install, build and server, and the selection +# script) runs only in `changes` and `diff`, which hold a read-only token and +# no persisted credentials. Each sticky comment (one per server, found again +# by its marker) is posted by `comment`, which holds `pull-requests: write` +# and runs none of the PR's code, and only for PRs from this repository: a +# fork PR's token is read-only, so there the report is in the job summary and +# the `mcp-diff-report-` artifact. `pull_request_target` is +# deliberately not used, since it would run the fork's build next to a write +# token. If fork PRs need the comment too, the way is a separate +# `workflow_run` workflow that posts the artifact without checking anything +# out. The server names `comment` reads come from `changes`, which ran PR +# code, so it checks each against the known list before using it. # -# Until then, nothing dispatches this file, and a manual dispatch only says -# where the diff is. -name: MCP Interface Diff (rename placeholder) +# A changed interface does not fail the run: the diff is information for the +# reviewer. A diff that cannot run (a base that does not build, a server that +# cannot be probed) does. +# +# A server's comment is left as it is when a later push stops touching that +# server; it then describes the last push that did. +# +# The version PRs are pushed and opened with the workflow token, whose events +# start no `pull_request` run here: GitHub holds each one as +# `action_required`, or fails it with no jobs (#5173). So the Version Packages +# and Prepare Python Release workflows dispatch this one on the PR's branch, as +# they do the CI workflows (#5110), and the `dispatch-status` jobs report the +# dispatched run on the PR as a commit status. +# +# The file was `everything-mcp-diff.yml` until #5527, a name left over from +# when it diffed only the Everything server. GitHub dispatches only a workflow +# whose file exists on the default branch (`main`), and both version workflows +# dispatch this one by file name from `v2/main`, so the rename was staged +# across a milestone merge: this name reached `main` first as a dispatch-only +# placeholder (#5463, in v2.5.0), and only then did #5527 move the diff here, +# switch the callers and delete the old file. Renaming it again takes the same +# two steps. `main` keeps its own `everything-mcp-diff.yml` until the next +# milestone merge deletes it there; nothing dispatches it, and `main` takes no +# other push or pull request in between. +# +# See: https://github.com/modelcontextprotocol/inspector/issues/1034 +name: MCP Interface Diff on: + push: + branches: [main, v2/main] + # No branch filter: PRs to v2/main and to main both run, and so does a PR + # stacked on another PR's branch. The base is the PR's own base either way. + pull_request: + # A published Release (a milestone, tagged vX.Y.Z on main; see RELEASING.md) + # surfaces the cumulative interface delta since the previous Release, for + # each server that changed in between. This replaces #3260's + # `typescript-servers-*` tag trigger: those tags stopped in 2024, and no + # release since has used them. + release: + types: [published] + # Manual trigger: the branch chosen in "Use workflow from" is the head, and + # `compare_ref` any base. #3260 also took a `target_ref`, but a target that + # predates the interface-diff script has no `npm run interface-diff` to run, + # so the head is the dispatched branch instead. workflow_dispatch: + inputs: + compare_ref: + description: "Base ref to compare against (commit SHA, tag, or branch; defaults to the merge-base with v2/main)" + required: false + default: "" permissions: contents: read +# Superseded runs on the same PR are cancelled. Every other run gets a group +# of its own: a group holds one running and one pending run, so a shared group +# would drop a push's run when two more queued behind it. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: - placeholder: - name: Point to the interface diff + changes: + name: Choose the servers to diff + timeout-minutes: 10 + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + base: ${{ steps.base.outputs.ref }} + servers: ${{ steps.list.outputs.servers }} + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # The base is found in history, so all of it is needed, tags + # included (the release base is the previous Release's tag). + fetch-depth: 0 + # The event's own commit (the merge commit for a PR), not a branch + # ref that a later push could move before this step runs. + ref: ${{ github.sha }} + persist-credentials: false + + # No install: the selection imports nothing outside Node. + - uses: actions/setup-node@v7 + with: + node-version: 24 + + - name: Choose the base to compare against + id: base + env: + EVENT: ${{ github.event_name }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + BEFORE: ${{ github.event.before }} + INPUT_BASE: ${{ inputs.compare_ref }} + TAG: ${{ github.event.release.tag_name }} + PUBLISHED: ${{ github.event.release.published_at }} + REPO: ${{ github.repository }} + GH_TOKEN: ${{ github.token }} + run: | + case "$EVENT" in + # The checkout is the PR's merge commit, so its base tip is + # exactly what the PR changes. + pull_request) base="$PR_BASE" ;; + # The branch as it was before this push; a new branch has none. + push) + if [ -n "$BEFORE" ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + base="$BEFORE" + else + base=$(git rev-parse HEAD^) + fi ;; + # The Release published just before this one (so a re-run of an + # older Release still compares against ITS predecessor). Not + # `git describe`: the date-stamped releases tagged commits that + # never reached main, so the nearest ancestor tag is years older + # than the last release. + release) + base=$(gh release list --repo "$REPO" --exclude-drafts --exclude-pre-releases --limit 50 \ + --json tagName,publishedAt \ + --jq "map(select(.tagName != \"$TAG\" and .publishedAt < \"$PUBLISHED\")) | sort_by(.publishedAt) | last | .tagName // empty") + if [ -z "$base" ]; then echo "no earlier Release to compare against" >&2; exit 1; fi ;; + workflow_dispatch) + if [ -n "$INPUT_BASE" ]; then + base="$INPUT_BASE" + else + base=$(git merge-base HEAD origin/v2/main) + fi ;; + *) echo "unexpected event: $EVENT" >&2; exit 1 ;; + esac + # Resolved to a SHA here, so every leg compares against the same + # commit even if a branch named as the base moves meanwhile. + base=$(git rev-parse --verify "$base^{commit}") + echo "Comparing against $base" + echo "ref=$base" >> "$GITHUB_OUTPUT" + + - name: List the servers the change touches + id: list + env: + BASE: ${{ steps.base.outputs.ref }} + run: | + # The reasons go to the log on stderr; stdout is the JSON list. + servers=$(npm run --silent interface-diff -- --base "$BASE" --list) + echo "Servers to diff: $servers" + echo "servers=$servers" >> "$GITHUB_OUTPUT" + { + if [ "$servers" = "[]" ]; then + echo "No server changed since \`$BASE\`; there is no interface to diff." + else + echo "Diffing: $(jq -r 'map("`" + .server + "`") | join(", ")' <<<"$servers")" + fi + } >> "$GITHUB_STEP_SUMMARY" + + diff: + name: Diff ${{ matrix.server }} + needs: changes + if: needs.changes.outputs.servers != '[]' + timeout-minutes: 15 + runs-on: ubuntu-latest + permissions: + contents: read + strategy: + # One server's broken diff must not hide another's report. + fail-fast: false + matrix: + include: ${{ fromJSON(needs.changes.outputs.servers) }} + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + # The base is built from history. + fetch-depth: 0 + ref: ${{ github.sha }} + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + + # A root `npm ci` runs every workspace's `prepare`, which builds it, so + # a TypeScript head build the diff probes exists after this step. It also + # installs `mcp-server-diff`, which every leg needs. + - name: Install dependencies and build + run: npm ci + + - name: Install uv + if: matrix.language == 'py' + uses: astral-sh/setup-uv@v7 + + # The diff probes a Python head with `uv run --no-sync`, so its + # environment is synced here, as the gate's `validate:py` does. + - name: Sync the Python server + if: matrix.language == 'py' + working-directory: src/${{ matrix.server }} + run: uv sync --locked + + - name: Diff the interface + env: + BASE: ${{ needs.changes.outputs.base }} + SERVER: ${{ matrix.server }} + run: npm run interface-diff -- --base "$BASE" --server "$SERVER" --report-dir mcp-diff-report + + - name: Write the job summary + if: always() + env: + SERVER: ${{ matrix.server }} + run: | + report="mcp-diff-report/$SERVER/report.md" + { + if [ -f "$report" ]; then + # A step summary holds at most 1 MiB. + head -c 900000 "$report" + if [ "$(wc -c < "$report")" -gt 900000 ]; then + echo "" + echo "_The report is truncated here; the full report is in the run's \`mcp-diff-report-$SERVER\` artifact._" + fi + else + echo "The interface diff produced no report; see the job log." + fi + echo "" + echo "---" + echo "" + echo "ℹ️ **Interpreting Results**" + echo "" + echo "These are reference servers, so a change to one's interface may indicate:" + echo "- New MCP protocol features being demonstrated" + echo "- Updated tool schemas or descriptions" + echo "- New resources, prompts, or capabilities" + echo "" + echo "Review changes to ensure they align with the intended protocol updates." + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload the report + if: always() + uses: actions/upload-artifact@v7 + with: + name: mcp-diff-report-${{ matrix.server }} + path: mcp-diff-report/ + if-no-files-found: ignore + + # A dispatched run's checks are left out of the status rollup a pull request + # reads, so on a dispatch these two jobs mirror the run onto the commit as a + # status, as in typescript.yml (whose comments hold the reasoning): pending + # at the start, then the result. Every other event skips both. Unlike + # typescript.yml's (#5223), the pending job also stays silent when a newer + # dispatched run exists, so a late or re-run older run cannot reset the + # newer run's result to pending, which its own result job would then leave. + dispatch-status-pending: + name: Report the dispatched run as pending + if: github.event_name == 'workflow_dispatch' + timeout-minutes: 5 + runs-on: ubuntu-latest + permissions: + statuses: write + # To look for a newer dispatched run of this workflow on the commit. + actions: read + steps: + - name: Set the commit status to pending + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + run: | + # A re-run keeps its run ID, so a newer run means this one is + # superseded and the status is no longer its to set. + NEWER=$(gh run list --workflow mcp-interface-diff.yml --event workflow_dispatch \ + --commit "$GITHUB_SHA" --json databaseId \ + --jq "[.[] | select(.databaseId > $GITHUB_RUN_ID)] | length") || NEWER=0 + if [ "${NEWER:-0}" -gt 0 ]; then + echo "Superseded by a newer dispatched run, which reports instead" + exit 0 + fi + gh api "repos/$GITHUB_REPOSITORY/statuses/$GITHUB_SHA" \ + -f state=pending -f context="Interface diff (dispatched)" \ + -f description="Dispatched run in progress" \ + -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + + # `comment` runs only on `pull_request`, so on a dispatch it is skipped, + # which counts as passed, and so is `diff` when no server changed; the report + # is in the run's summary and artifacts. + dispatch-status: + name: Report the dispatched run's result + if: github.event_name == 'workflow_dispatch' && always() + needs: [dispatch-status-pending, changes, diff, comment] timeout-minutes: 5 runs-on: ubuntu-latest + permissions: + statuses: write + # To look for a newer dispatched run of this workflow on the commit. + actions: read steps: - - name: Say where the interface diff runs + - name: Set the commit status to the run's result + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + NEEDS: ${{ toJSON(needs) }} + run: | + # A run superseded by a newer dispatch on the same commit posts + # nothing, whatever its jobs' results: the newer run owns the status + # (#5178). A failed lookup counts as no newer run, so this run still + # reports: a stale status is better than one left pending. + NEWER=$(gh run list --workflow mcp-interface-diff.yml --event workflow_dispatch \ + --commit "$GITHUB_SHA" --json databaseId \ + --jq "[.[] | select(.databaseId > $GITHUB_RUN_ID)] | length") || NEWER=0 + if [ "${NEWER:-0}" -gt 0 ]; then + echo "Superseded by a newer dispatched run, which reports instead" + exit 0 + fi + if jq -e 'all(.[]; .result == "success" or .result == "skipped")' <<<"$NEEDS" >/dev/null; then + STATE=success DESCRIPTION="The diff ran; the report is in the run's summary" + elif jq -e 'any(.[]; .result == "failure")' <<<"$NEEDS" >/dev/null; then + STATE=failure DESCRIPTION="The diff could not run; open the run for details" + else + STATE=error DESCRIPTION="The run was cancelled; dispatch it again" + fi + gh api "repos/$GITHUB_REPOSITORY/statuses/$GITHUB_SHA" \ + -f state="$STATE" -f context="Interface diff (dispatched)" \ + -f description="$DESCRIPTION" \ + -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + + # Post (or update) one sticky PR comment per diffed server so reviewers can + # see the diff without navigating to the Actions tab, found again by its + # per-server marker and edited on each push. This job checks nothing out and + # runs none of the PR's code; it only reads the report the `diff` leg + # uploaded. Dependabot's PRs are same-repo but get a read-only token, so they + # are skipped like fork PRs and keep the job summary and the artifact. + comment: + name: Post the ${{ matrix.server }} diff on the PR + needs: [changes, diff] + if: >- + always() && + github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.user.login != 'dependabot[bot]' && + needs.changes.result == 'success' && + needs.changes.outputs.servers != '[]' && + (needs.diff.result == 'success' || needs.diff.result == 'failure') + timeout-minutes: 5 + runs-on: ubuntu-latest + permissions: + pull-requests: write + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.changes.outputs.servers) }} + steps: + # The list came from a job that ran the PR's code; only a known server + # name reaches an artifact name, a marker or a path below. + - name: Check the server name + env: + SERVER: ${{ matrix.server }} + run: | + case "$SERVER" in + everything|filesystem|memory|sequentialthinking|fetch|git|time) ;; + *) echo "::error::Not a known server: $SERVER"; exit 1 ;; + esac + + - name: Download the report + uses: actions/download-artifact@v8 + continue-on-error: true + with: + name: mcp-diff-report-${{ matrix.server }} + path: mcp-diff-report + + - name: Post / update sticky PR comment + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + SERVER: ${{ matrix.server }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - echo "This file is a placeholder for a staged rename (#5463, #5527)." - echo "The MCP interface diff runs from .github/workflows/everything-mcp-diff.yml:" - echo " gh workflow run everything-mcp-diff.yml --ref " + marker="" + report="mcp-diff-report/$SERVER/report.md" + { + echo "$marker" + if [ -f "$report" ]; then + # A comment holds at most 65536 characters. + head -c 60000 "$report" + if [ "$(wc -c < "$report")" -gt 60000 ]; then + echo "" + echo "_The report is truncated here; the full report is in the run's \`mcp-diff-report-$SERVER\` artifact._" + fi + else + echo "## \`$SERVER\`: MCP interface diff" + echo "" + echo "❌ The diff job produced no report; see the run's log." + fi + echo "" + echo "Updated by [this run]($RUN_URL) for \`$HEAD_SHA\`." + } > body.md + id=$(gh api --paginate "repos/$REPO/issues/$PR/comments" \ + --jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | .id" | head -n 1) + if [ -n "$id" ]; then + gh api -X PATCH "repos/$REPO/issues/comments/$id" -F body=@body.md > /dev/null + else + gh api "repos/$REPO/issues/$PR/comments" -F body=@body.md > /dev/null + fi diff --git a/.github/workflows/prepare-python-release.yml b/.github/workflows/prepare-python-release.yml index a9e5b6c469..78dbb4e873 100644 --- a/.github/workflows/prepare-python-release.yml +++ b/.github/workflows/prepare-python-release.yml @@ -112,7 +112,7 @@ jobs: echo "Generated by the **Prepare Python Release** workflow. Nothing is published until a maintainer publishes a GitHub Release." echo echo "> [!NOTE]" - echo "> A push made with the workflow token starts no CI, so the workflow dispatched the TypeScript, Python, DCO and interface diff workflows on this branch. Their results show on this PR as the \`TypeScript (dispatched)\`, \`Python (dispatched)\`, \`DCO (dispatched)\` and \`Interface diff (dispatched)\` statuses. To run them again: \`gh workflow run python.yml --ref $BRANCH\` (and \`typescript.yml\`, \`dco.yml\`, \`everything-mcp-diff.yml\`)." + echo "> A push made with the workflow token starts no CI, so the workflow dispatched the TypeScript, Python, DCO and interface diff workflows on this branch. Their results show on this PR as the \`TypeScript (dispatched)\`, \`Python (dispatched)\`, \`DCO (dispatched)\` and \`Interface diff (dispatched)\` statuses. To run them again: \`gh workflow run python.yml --ref $BRANCH\` (and \`typescript.yml\`, \`dco.yml\`, \`mcp-interface-diff.yml\`)." } > "$RUNNER_TEMP/pr-body.md" # A second run on the same day force-updates the branch, and may # stamp a different set of packages; the open PR's body is rewritten @@ -132,6 +132,6 @@ jobs: # The push above starts no workflow (see the header), so CI is # dispatched on the branch explicitly, after a first run and a rerun # alike. - for workflow in typescript.yml python.yml dco.yml everything-mcp-diff.yml; do + for workflow in typescript.yml python.yml dco.yml mcp-interface-diff.yml; do gh workflow run "$workflow" --ref "$BRANCH" done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 55d108f780..6242ca489c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,6 +19,16 @@ # `id-token: write` and the `release` environment. No checkout, # no dependency install, no build. # +# AFTER THE PACKAGES, THE MCP REGISTRY (#3047). `publish-mcp-registry` lists +# each server in the official MCP Registry (registry.modelcontextprotocol.io) +# at the version just published. A registry entry is a `server.json` that +# points at a package, and the registry accepts one only for a package version +# that already exists on npm or PyPI and names the server itself (`mcpName`, +# or the README's `mcp-name:` marker), so the job runs after both sets of +# publish legs. What it registers comes from `detect-packages` +# (`scripts/mcp-registry-entries.mjs`), as a job output, and it is one more +# `release` environment deployment for a maintainer to approve. +# # The split is about what runs next to the OIDC token. Installing dependencies # runs their lifecycle scripts, and a build runs the toolchain; in a job that # can mint a publish credential, any of that code can publish. Here the only @@ -34,7 +44,8 @@ # the next release with no special handling, and one that did not change costs # a skipped leg. For npm the build leg decides (`npm-publish-guard.mjs`) and # uploads a `SKIP` marker instead of a tarball; for PyPI the registry decides -# at upload (`skip-existing`). +# at upload (`skip-existing`). The MCP Registry job asks the registry for each +# entry's version and publishes only the ones it does not have. # # The trigger is `release: published` and nothing else, so editing a # published Release's notes never re-runs publishing. A release event runs the @@ -44,7 +55,11 @@ # Authentication is OIDC trusted publishing on both registries: there are no # registry tokens. Each trusted publisher is bound to this workflow's filename # (`release.yml`) and the `release` environment, so the publish jobs must stay -# in this file and keep that environment. +# in this file and keep that environment. The MCP Registry takes the same kind +# of token (`mcp-publisher login github-oidc`) and grants the +# `io.github.modelcontextprotocol/*` namespace to any workflow in this +# organization: it is bound to neither the file nor the environment, so there +# the environment is the maintainer's approval and nothing else. # # Only a commit that is on `main` is published. A Release can be created for # any tag on any commit, and the environment approval shows a reviewer a tag @@ -73,7 +88,7 @@ concurrency: group: release queue: max -# Nothing in this workflow needs more than read access by default; the two +# Nothing in this workflow needs more than read access by default; the three # publish jobs add `id-token: write` for themselves. permissions: contents: read @@ -88,6 +103,7 @@ jobs: pypi_packages: ${{ steps.find-packages.outputs.pypi_packages }} npm_expected: ${{ steps.expected.outputs.npm_expected }} pypi_expected: ${{ steps.expected.outputs.pypi_expected }} + mcp_registry: ${{ steps.registry.outputs.mcp_registry }} steps: # On a release event the default ref is the release's tag: the exact # commit the maintainer released. Full history, for the check below. @@ -124,6 +140,14 @@ jobs: id: expected run: node scripts/release-manifest.mjs + # Each server's MCP Registry entry: its committed `server.json`, checked + # against the package it points at and stamped with that package's + # version. Read here for the same reason as the step above, and a + # problem with any entry stops the release before anything is built. + - name: Record each server's MCP Registry entry + id: registry + run: node scripts/mcp-registry-entries.mjs + build-npm: timeout-minutes: 15 needs: [detect-packages] @@ -476,3 +500,98 @@ jobs: with: packages-dir: dist skip-existing: true + + publish-mcp-registry: + timeout-minutes: 10 + needs: [detect-packages, publish-npm, publish-pypi] + # After the package publish legs, whatever their results: an entry is only + # accepted for a package version that is on npm or PyPI, so one package's + # failed leg fails that entry alone and the rest are still registered. + if: ${{ !cancelled() && needs.detect-packages.result == 'success' }} + name: Publish to the MCP Registry + # The registry does not look at the environment (see the header). It is + # here so that registering, like publishing, waits for a maintainer. + environment: release + permissions: + # Required for `mcp-publisher login github-oidc`. Like the other publish + # jobs, this one has no checkout and installs no dependency. + id-token: write + runs-on: ubuntu-latest + env: + # The registry's publisher CLI, pinned to one release and to the SHA-256 + # of that release's archive: a release asset can be replaced, and this + # binary runs next to the OIDC token. Bump both together, taking the + # digest from the release's asset list (RELEASING.md has the command). + MCP_PUBLISHER_VERSION: v1.8.9 + MCP_PUBLISHER_SHA256: 4d527ca8f1ced0394c962dc925c2a4a4addef441cbefd62501c875e9481823a8 + steps: + - name: Download the pinned mcp-publisher + run: | + ARCHIVE=mcp-publisher_linux_amd64.tar.gz + curl --fail --location --silent --show-error --output "$ARCHIVE" \ + "https://github.com/modelcontextprotocol/registry/releases/download/$MCP_PUBLISHER_VERSION/$ARCHIVE" + echo "$MCP_PUBLISHER_SHA256 $ARCHIVE" | sha256sum --check --strict - + tar -xzf "$ARCHIVE" mcp-publisher + + # One `entries//server.json` per server, and `plan.tsv` naming + # each for the shell below. An empty or unreadable output fails here: + # nothing is registered from a release that recorded no entries. + - name: Write the entries the released commit declares + env: + ENTRIES: ${{ needs.detect-packages.outputs.mcp_registry }} + run: | + node -e ' + const fs = require("fs"); + const entries = Object.entries(JSON.parse(process.env.ENTRIES)); + if (entries.length === 0) throw new Error("no MCP Registry entries were recorded"); + const plan = []; + for (const [dir, entry] of entries) { + const { name, version } = entry; + // These three reach a URL and a path in the next step. + if (!/^[a-z0-9-]+$/.test(dir)) throw new Error("unexpected server directory " + JSON.stringify(dir)); + if (typeof name !== "string" || !/^io\.github\.modelcontextprotocol\/[a-zA-Z0-9._-]+$/.test(name)) throw new Error("unexpected server name " + JSON.stringify(name)); + if (typeof version !== "string" || !/^[0-9A-Za-z.-]+$/.test(version)) throw new Error("unexpected version " + JSON.stringify(version)); + fs.mkdirSync("entries/" + dir, { recursive: true }); + fs.writeFileSync("entries/" + dir + "/server.json", JSON.stringify(entry, null, 2) + "\n"); + plan.push([dir, name, version].join("\t")); + } + fs.writeFileSync("plan.tsv", plan.join("\n") + "\n"); + ' + cat plan.tsv + + # The registry-diff guard for the MCP Registry: a version it already + # lists is skipped, not failed, and a published entry cannot be changed, + # so a re-run or a later release registers only what is missing. An + # answer that is neither "there" nor "not there" fails that entry rather + # than guessing. The token is asked for only when there is something to + # publish. One entry's failure does not stop the others; it fails the + # job at the end, and the next release (or a re-run) picks it up. + - name: Publish each entry the registry does not have + run: | + pending="" + failed=0 + while IFS="$(printf '\t')" read -r dir name version; do + url="https://registry.modelcontextprotocol.io/v0/servers/$(printf '%s' "$name" | sed 's|/|%2F|')/versions/$version" + code="$(curl -sS -o /dev/null -w '%{http_code}' "$url")" || code="no answer" + case "$code" in + 200) echo "$name@$version is already in the MCP Registry; nothing to publish." ;; + 404) pending="$pending $dir" ;; + *) + echo "::error::Could not tell whether $name@$version is in the MCP Registry ($code from $url)" + failed=1 + ;; + esac + done < plan.tsv + if [ -z "$pending" ]; then + exit "$failed" + fi + ./mcp-publisher login github-oidc + for dir in $pending; do + if ./mcp-publisher publish "entries/$dir/server.json"; then + echo "Registered src/$dir." + else + echo "::error::The MCP Registry refused the entry for src/$dir (see the output above). If its package failed to publish in this run, fix that first." + failed=1 + fi + done + exit "$failed" diff --git a/.github/workflows/version-packages.yml b/.github/workflows/version-packages.yml index 937ec2daa0..4805685692 100644 --- a/.github/workflows/version-packages.yml +++ b/.github/workflows/version-packages.yml @@ -91,6 +91,6 @@ jobs: PR: ${{ steps.changesets.outputs.pr-number }} run: | BRANCH=$(gh pr view "$PR" --json headRefName --jq .headRefName) - for workflow in typescript.yml python.yml dco.yml everything-mcp-diff.yml; do + for workflow in typescript.yml python.yml dco.yml mcp-interface-diff.yml; do gh workflow run "$workflow" --ref "$BRANCH" done diff --git a/AGENTS.md b/AGENTS.md index c090e1a5d0..a8b57a4cdf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,18 +53,18 @@ servers/ ├── .claude/skills/ On-demand procedures (see the Skills index above) ├── .claude/settings.json The SessionStart hook that checks this session's instructions are current ├── .changeset/ Pending changesets for the TypeScript servers, and the changesets config -├── scripts/ The pre-push gate (gate-lease, smoke-servers, validate-py, coverage-py, interface-diff), its guards (verify-*), +├── scripts/ The pre-push gate (gate-lease, smoke-servers, validate-py, coverage-py, interface-diff, image-smoke), its guards (verify-*), │ the skills tooling, release tooling (npm-publish-guard, prepare-python-release, -│ pack-and-verify, release-manifest, release-notes), and the issue-filing sweeps +│ pack-and-verify, release-manifest, mcp-registry-entries, release-notes), and the issue-filing sweeps │ (dependency-refresh, dependabot-alerts, sdk-watch), and the session-start │ instructions check (session-instructions-check) ├── docs/ Design documents; quality-gate.md is the gate's reference (stages, CI vs local, the lease); │ contribution-model.md holds the outside-PR backlog plan; ai-software-factory.md is the │ overview of how the rules, skills, gates and sweeps fit together -├── .github/workflows/ typescript.yml, python.yml (per-package CI), release.yml (publishes on a GitHub Release), +├── .github/workflows/ typescript.yml, python.yml (per-package CI), release.yml (publishes on a GitHub Release, then lists each server in the MCP Registry), │ version-packages.yml (the changesets PR), prepare-python-release.yml (the CalVer PR), -│ everything-mcp-diff.yml (each changed server's interface diff on PRs), -│ mcp-interface-diff.yml (a dispatch-only placeholder for that file's new name, #5463), +│ mcp-interface-diff.yml (each changed server's interface diff on PRs), +│ image-smoke.yml (each changed server's Docker image, built and booted), │ main-source.yml (a PR into main must bring nothing that is not on v2/main), │ and the scheduled sweeps that file issues: dependency-refresh.yml, dependabot-alerts.yml, sdk-watch.yml ├── .github/ISSUE_TEMPLATE/ Bug and feature issue forms; config.yml routes security and new servers away @@ -139,14 +139,17 @@ TypeScript workspace's per-file coverage gate), `validate:py` (each Python server's locked sync, `ruff check`, `ruff format --check`, pyright, pytest and build), `coverage:py` (each Python server's per-file coverage gate), `verify:skills:cli`, `smoke` (every server booted over each -transport it implements), and `interface-diff` (the MCP interface of each -server the change touches, diffed against the base it branched from). The stage-by-stage +transport it implements), `interface-diff` (the MCP interface of each +server the change touches, diffed against the base it branched from), and +`image-smoke` (the Docker image of each server the change touches, built, +booted and stopped; it needs a running Docker daemon when a change touches +one). The stage-by-stage reference, and what CI runs where, is [`docs/quality-gate.md`](./docs/quality-gate.md); diagnosing a red stage is the `pre-push-gate` skill. - **`npm run validate` and the per-package commands above are the inner loop, not a substitute.** They skip the other language, the pinned skills validator, - the boot smoke and the interface diff. + the boot smoke, the interface diff and the image smoke. - **Format before committing**: `npm run format` at the root (TypeScript), and `uv run --frozen ruff format .` in a Python server you changed. The gate only checks formatting; it never rewrites files. @@ -314,6 +317,15 @@ maintainer publishes a GitHub Release), never a side effect of a merge. - **A TypeScript server reports its version from its `package.json`** (the `SERVER_VERSION` its `version.ts` exports), never from a literal in the source: the version PR edits `package.json` only. +- **A server's `server.json` is its MCP Registry entry, and carries no + version.** `release.yml` stamps it from the manifest and registers it after + the package publishes (`scripts/mcp-registry-entries.mjs`). Its `name` is the + `mcpName` in the server's `package.json`, or the `mcp-name:` marker in a + Python server's `README.md`: the registry verifies the entry against the + published package, so the two change together, and the script tests fail + when they differ. **Never rename a registered server**: a published + entry cannot be edited, so the old name would stay behind as a separate + entry that nothing updates. ## Contributing @@ -600,6 +612,19 @@ here. declined finding that is worth doing gets its own issue, linked in the reply. The rule is under [Responding to code reviews](#responding-to-code-reviews). +- **Before a PR merges, it is caught up and re-tested if `v2/main` moved in a + way that can interact with it.** GitHub reporting no conflicts is not that + test: it compares text, and the gate and CI ran on the PR's head, which + holds nothing that landed on `v2/main` after the branch last took it in. Two + fetch PRs that were each green left `v2/main` red that way (#5569). What + landed **can interact** when it touches a server directory + (`src//`) the PR also touches, or when either side touches + repository-wide configuration: a root manifest, lockfile or configuration + file, `scripts/`, or `.github/workflows/`. When in doubt, re-test. Catching + up is a merge of `origin/v2/main` into the branch, never a rebase, then the + gate, a push, and green CI on the new head. `v2/main`'s ruleset requires no + status checks, so this is on whoever merges. The recipe is the `pr-flow` + skill (step 10). - **If new tasks are discovered during development, create issues** for them and put them on the board, rather than widening the current PR. diff --git a/RELEASING.md b/RELEASING.md index c4d16eff93..f505a0290f 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -39,7 +39,7 @@ node scripts/prepare-python-release.mjs # prints one "name: old -> new" line ### PRs opened by these workflows > [!NOTE] -> Both workflows push their PR's branch with the workflow token, and a push made with that token starts no workflow, so each one then dispatches the TypeScript, Python, DCO and MCP interface diff workflows on that branch (`workflow_dispatch` is the one event the token can start). A PR does not list dispatched checks, so each dispatched run also reports itself on the PR's head commit as a status: `TypeScript (dispatched)`, `Python (dispatched)`, `DCO (dispatched)` and `Interface diff (dispatched)`; wait for them to pass before merging. Closing and reopening the PR does not start the CI workflows: that fires `pull_request`, and those run on `push`. The token's `pull_request` events do not run DCO or the diff either: GitHub holds those runs as `action_required` (#5173), so the PR may also list them as pending or failed with no jobs; the `(dispatched)` statuses are the results. To run one again by hand: `gh workflow run typescript.yml --ref ` (or `python.yml`, `dco.yml`, `everything-mcp-diff.yml`). The Version Packages PR's body is rewritten on every push to `v2/main`, so it is linked to the release issue with `addCloseIssueReferences` (which lives outside the body), carries a `Part of #N` comment as its textual record, and gets `Part of #N` as its body's first line only immediately before it is merged. The Prepare Python Release PR keeps its `Closes #N` line and is linked to the release issue with `addCloseIssueReferences` too, as every PR into `v2/main` is. The repository setting **Settings → Actions → General → Allow GitHub Actions to create and approve pull requests** must be on, or the workflows fail at the step that opens the PR. +> Both workflows push their PR's branch with the workflow token, and a push made with that token starts no workflow, so each one then dispatches the TypeScript, Python, DCO and MCP interface diff workflows on that branch (`workflow_dispatch` is the one event the token can start). A PR does not list dispatched checks, so each dispatched run also reports itself on the PR's head commit as a status: `TypeScript (dispatched)`, `Python (dispatched)`, `DCO (dispatched)` and `Interface diff (dispatched)`; wait for them to pass before merging. Closing and reopening the PR does not start the CI workflows: that fires `pull_request`, and those run on `push`. The token's `pull_request` events do not run DCO or the diff either: GitHub holds those runs as `action_required` (#5173), so the PR may also list them as pending or failed with no jobs; the `(dispatched)` statuses are the results. To run one again by hand: `gh workflow run typescript.yml --ref ` (or `python.yml`, `dco.yml`, `mcp-interface-diff.yml`). The Version Packages PR's body is rewritten on every push to `v2/main`, so it is linked to the release issue with `addCloseIssueReferences` (which lives outside the body), carries a `Part of #N` comment as its textual record, and gets `Part of #N` as its body's first line only immediately before it is merged. The Prepare Python Release PR keeps its `Closes #N` line and is linked to the release issue with `addCloseIssueReferences` too, as every PR into `v2/main` is. The repository setting **Settings → Actions → General → Allow GitHub Actions to create and approve pull requests** must be on, or the workflows fail at the step that opens the PR. ## How publishing works @@ -51,6 +51,7 @@ Publishing is triggered by a maintainer **publishing a GitHub Release** whose ta | --- | --- | --- | | **Build** (`build-npm`, `build-pypi`) | No `id-token`, no environment | Installs dependencies, **runs the package's tests** (for Python, the whole `validate:py` chain: ruff, pyright, pytest), then runs **`pack:verify`**: it builds the tarball or wheel, installs it into an empty directory and boots the installed server. Uploads that verified artifact | | **Publish** (`publish-npm`, `publish-pypi`) | `id-token: write` and the `release` environment (a required reviewer must approve each deployment) | Downloads the artifact, checks that its name and version are the ones the released commit declares for that package, and hands it to the registry. No checkout, no dependency install, no build | +| **Register** (`publish-mcp-registry`, one job for all seven servers) | `id-token: write` and the `release` environment | After the publish jobs: lists each server in the [MCP Registry](https://registry.modelcontextprotocol.io/) at the version just published. No checkout, no dependency install, no action. See [The MCP Registry](#the-mcp-registry) | The split is about what runs next to the publish credential. Installing dependencies runs their lifecycle scripts, and a build runs a toolchain; in a job that can mint an OIDC token, any of that code could publish. Here the token only ever sits beside the registry client and SHA-pinned actions. Every action in the build and publish jobs is pinned to a commit SHA, enforced by `npm run verify:action-pins`. @@ -70,6 +71,24 @@ So a release publishes exactly the packages whose version moved, and a package w Because of those bindings, the publish jobs must stay in `release.yml` and keep the `release` environment. +### The MCP Registry + +Each server is also listed in the official [MCP Registry](https://registry.modelcontextprotocol.io/), where clients look servers up, under the name `io.github.modelcontextprotocol/server-`. A listing is not a package: it is a `server.json` that points at the npm or PyPI package, and the registry stores one per version. + +- **The entry is `src//server.json`, and it carries no version.** [`scripts/mcp-registry-entries.mjs`](scripts/mcp-registry-entries.mjs) stamps the version from `package.json` or `pyproject.toml` on the released commit, so the manifests stay the only place a version lives. It runs in `detect-packages`, and it fails the release before anything is built if an entry is malformed or disagrees with its package. The same check runs in the script tests, so a bad entry fails CI on the PR that introduces it. +- **The registry verifies the package, not this repository.** It accepts an entry only when the published package names the server: `mcpName` in `package.json` for npm, and an `mcp-name: ` marker in the README for PyPI. The current version of every package carries one. That is also why `publish-mcp-registry` runs after the publish jobs: the version it registers must already be on npm or PyPI. +- **Authentication is GitHub OIDC, with no token and no account.** `mcp-publisher login github-oidc` exchanges the job's OIDC token for the `io.github.modelcontextprotocol/*` namespace, which the registry grants to any workflow in this organization. The interactive `mcp-publisher login github` cannot publish to an organization namespace at all, so this job is the way these entries are published; do not register one from a laptop. +- **It is one more `release` environment approval**, and it arrives after the package publish jobs finish, so it is approved separately from them. The registry does not look at the environment; it is there so that registering, like publishing, waits for a maintainer. +- **A version the registry already lists is skipped, not failed**, so a re-run or a later release registers only what is missing. A published entry cannot be edited: a change to a title or description reaches the registry with the server's next version. +- **`mcp-publisher` is pinned** in the job's `env`, by release tag and by the SHA-256 of that release's Linux archive, which the job checks before unpacking it. To move to a newer release, change both together: + + ```bash + gh api repos/modelcontextprotocol/registry/releases/tags/ \ + --jq '.assets[] | select(.name == "mcp-publisher_linux_amd64.tar.gz") | .digest' + ``` + +When the job fails, the packages are already published and are unaffected. An entry the registry refused because its package's own publish leg failed is registered by re-running the job once that package is out (or by the next release). A registry outage is a re-run. The registry is in preview, so a change on its side that the pinned `mcp-publisher` cannot speak (an `invalid audience` error, say) is fixed by bumping the pin on `v2/main`; the entries it missed can only be registered from a later release, since a release runs the workflow as it is at its tag. + ## Cutting a release A release ships one **milestone**. The step-by-step procedure, with its commands, is the [`release` skill](.claude/skills/release/SKILL.md) (`/release`); this is its shape. @@ -84,7 +103,7 @@ A release ships one **milestone**. The step-by-step procedure, with its commands 3. **The merge PR** takes `v2/main` into `main`. It is a pure merge: its branch is `origin/v2/main` with no commits of its own, and the merged tree equals `origin/v2/main`'s. Its body starts with `Part of #`, not `Closes`, because `main` is the default branch and a closing keyword there would close the issue before anything is published. It is merged with a merge commit, never squashed. 4. **The release ledger** is linked from the merge PR. It records, for the merge branch's tree: `npm run local:gate`; `npm run pack:verify` for each package; each server-facing issue in the milestone exercised through a client; and a targeted probe for each issue with no client surface. The maintainers approve the merge on it. A finding is fixed on `v2/main` and merged in again, never committed to the merge branch. 5. **A maintainer publishes a GitHub Release** targeting the merge commit on `main` (the commit the ledger verified, chosen by SHA rather than by the branch name, which may have moved). [`scripts/release-notes.mjs`](scripts/release-notes.mjs) (`npm run release:notes`) writes the notes, one section per published package with its PRs and a Thanks section for the community members whose issues and advisories (`--advisory`) the release addresses and whose prototypes ship in it (`--thank`), and with `--draft` creates the draft Release under a tag named for the milestone (`vX.Y.Z`). The maintainer reads the draft and publishes it. The tag is a label, not a version. -6. **The build jobs run, then the maintainer approves the `release` environment deployments.** Each package publishes if its version is not on the registry yet; the rest skip cleanly. +6. **The build jobs run, then the maintainer approves the `release` environment deployments.** Each package publishes if its version is not on the registry yet; the rest skip cleanly. Once they finish, one more deployment asks for approval: `publish-mcp-registry`, which lists the published versions in the MCP Registry. 7. **The release issue is closed by hand**, and its card moves to Done. ## When a publish fails diff --git a/docs/quality-gate.md b/docs/quality-gate.md index 9dcee6551c..bc959c26b9 100644 --- a/docs/quality-gate.md +++ b/docs/quality-gate.md @@ -13,7 +13,7 @@ out; everything else points here. | --- | --- | --- | --- | | Inner loop | `npm run validate -w src/`, `npm run validate:py -- ` | Your machine | While iterating on one server | | Pre-push gate | `npm run local:gate` | Your machine, under a lease | Before every push | -| CI | `.github/workflows/typescript.yml`, `python.yml`, `everything-mcp-diff.yml`; `dco.yml`; `main-source.yml` | GitHub, on every push and pull request (`everything-mcp-diff.yml` diffs only the servers the change touches); `dco.yml` on pull requests only; `main-source.yml` on pull requests into `main` only, and not mirrored by a gate stage, since no local push targets `main` | Before merge | +| CI | `.github/workflows/typescript.yml`, `python.yml`, `mcp-interface-diff.yml`, `image-smoke.yml`; `dco.yml`; `main-source.yml` | GitHub, on every push and pull request (`mcp-interface-diff.yml` diffs, and `image-smoke.yml` builds, only the servers the change touches); `dco.yml` on pull requests only; `main-source.yml` on pull requests into `main` only, and not mirrored by a gate stage, since no local push targets `main` | Before merge | **`npm run local:gate` runs every check CI runs.** CI splits the same checks into parallel jobs on a fresh install; the gate runs them in sequence on your @@ -57,7 +57,8 @@ in this order, and the first failure stops the run. | 7 | `coverage:py` | Per Python server: `uv sync --locked`, then `uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json`; then **every file** in `coverage.json` must reach **90% on lines and 90% on branches** | `python.yml` → **Coverage \** (one leg each) | | 8 | `verify:skills:cli` | `claude plugin validate` on `.claude/skills`, at the pinned CLI version | `typescript.yml` → **Root guards** | | 9 | `smoke` | Every server boots over each transport it implements and answers one tool call | `typescript.yml` → **Boot smoke** | -| 10 | `interface-diff` | For each server the change touches, its MCP interface (capabilities, tools, prompts, resources, resource templates) in this checkout's build, diffed against the same server built from the base. It fails only when a diff cannot run; a changed interface is reported, not failed | `everything-mcp-diff.yml` → **Choose the servers to diff**, then **Diff \** (one leg each, and a PR comment each) | +| 10 | `interface-diff` | For each server the change touches, its MCP interface (capabilities, tools, prompts, resources, resource templates) in this checkout's build, diffed against the same server built from the base. It fails only when a diff cannot run; a changed interface is reported, not failed | `mcp-interface-diff.yml` → **Choose the servers to diff**, then **Diff \** (one leg each, and a PR comment each) | +| 11 | `image-smoke` | For each server the change touches, its Docker image: it builds, a client lists its tools over `docker run -i`, and `docker stop` ends `everything` and `memory` without killing them, `memory` leaving no lock file behind | `image-smoke.yml` → **Choose the images to build**, then **Image \** (one leg each) | Notes on the stages: @@ -100,9 +101,10 @@ Notes on the stages: when a server's environment is missing or behind its lockfile, since `uv sync --locked` then downloads packages (and the pinned interpreter, if `uv` does not have it); `coverage:py` begins with the same sync, which is a - no-op once `validate:py` has run; and `interface-diff` needs it for the - base's `npm ci` and `uv sync`. With warm caches those are the only stages that can fail - offline. + no-op once `validate:py` has run; `interface-diff` needs it for the + base's `npm ci` and `uv sync`; and `image-smoke` needs it for a build whose + layers Docker has not cached (base images, `npm ci`, `uv sync`, `apt-get`). + With warm caches those are the only stages that can fail offline. - **`smoke` launches what a user launches**: the built `dist/index.js` for a TypeScript server, the console script through `uv run --no-sync` for a Python one. stdio and Streamable HTTP for all seven; HTTP+SSE as well for @@ -133,6 +135,28 @@ Notes on the stages: `mcp-server-diff` changes. A change that touches no server diffs nothing and passes. `-- --server ` or `-- --all` diffs servers regardless, and `-- --list` prints the selection without diffing. +- **`image-smoke` needs a running Docker daemon, but only when the change + touches an image** (#5598). It selects as `interface-diff` does + (`selectImages` in `scripts/image-smoke.mjs`): a file under `src//`; + for a TypeScript server, the root `.npmrc` or `tsconfig.json`, which its + image copies, or a `package-lock.json` edit that changes a package the + server installs; and every image when the image tooling changes. A change + that touches none builds nothing and passes with no Docker at all. One that + does, with no daemon answering, **fails rather than skips**: start Docker + and re-run. It builds from the working tree, with the command each + Dockerfile documents (the repository root as the context for a TypeScript + server, the server's directory for a Python one), under the tag + `mcp-image-smoke/:local`, which each run reuses. A build with warm + layers takes a few seconds per image. `-- --server ` or `-- --all` + builds images regardless, and `-- --list` prints the selection without + building. In CI a manual run of `image-smoke.yml` builds all seven. +- **`image-smoke` asserts a clean stop only where an image has one**: + `everything` and `memory`, the two whose Dockerfiles declare a `STOPSIGNAL`. + A container Docker has to kill exits 137, and that fails. For `memory` it + also makes a write first and checks that the graph's directory holds the + graph and nothing else after the stop, so the lock #5485 removes on a + signal is gone. The other five images are killed at the timeout today + (#5611) and are not checked for it. - `python.yml` also has a **Build \** job per server that re-runs pyright and `uv build` and uploads the built distribution. It checks nothing stage 6 does not. diff --git a/package-lock.json b/package-lock.json index 01186d0bdf..aa81b65404 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5253,7 +5253,7 @@ }, "src/everything": { "name": "@modelcontextprotocol/server-everything", - "version": "2.3.1", + "version": "2.4.0", "license": "SEE LICENSE IN LICENSE", "dependencies": { "@modelcontextprotocol/node": "^2.1.1", @@ -5282,7 +5282,7 @@ }, "src/filesystem": { "name": "@modelcontextprotocol/server-filesystem", - "version": "2.4.0", + "version": "2.4.1", "license": "SEE LICENSE IN LICENSE", "dependencies": { "@modelcontextprotocol/node": "^2.1.1", @@ -5310,7 +5310,7 @@ }, "src/memory": { "name": "@modelcontextprotocol/server-memory", - "version": "2.2.1", + "version": "2.2.2", "license": "SEE LICENSE IN LICENSE", "dependencies": { "@modelcontextprotocol/node": "^2.1.1", diff --git a/package.json b/package.json index 979811b59b..b0e081e0b9 100644 --- a/package.json +++ b/package.json @@ -44,10 +44,11 @@ "verify:dco": "node scripts/verify-dco.mjs", "smoke": "node scripts/smoke-servers.mjs", "interface-diff": "node scripts/interface-diff.mjs", + "image-smoke": "node scripts/image-smoke.mjs", "pack:verify": "node scripts/pack-and-verify.mjs", "release:notes": "node scripts/release-notes.mjs", "local:gate": "node scripts/gate-lease.mjs npm run local:gate:stages", - "local:gate:stages": "npm run verify:install-fresh && npm run verify:dco && npm run validate && npm run coverage && npm run validate:py && npm run coverage:py && npm run verify:skills:cli && npm run smoke && npm run interface-diff" + "local:gate:stages": "npm run verify:install-fresh && npm run verify:dco && npm run validate && npm run coverage && npm run validate:py && npm run coverage:py && npm run verify:skills:cli && npm run smoke && npm run interface-diff && npm run image-smoke" }, "dependencies": { "@modelcontextprotocol/server-everything": "*", diff --git a/scripts/image-smoke.mjs b/scripts/image-smoke.mjs new file mode 100644 index 0000000000..cdfde5a4a8 --- /dev/null +++ b/scripts/image-smoke.mjs @@ -0,0 +1,657 @@ +#!/usr/bin/env node +// The image smoke (#5598): build the Docker image of each server a change +// touches, start it the way a client configuration does (`docker run -i`), +// and ask it for its tools over stdio. +// +// Why it exists: every server ships a `Dockerfile`, and until this script +// nothing built one. The boot smoke runs the checkout and `pack:verify` the +// publish artifact, so a Dockerfile that no longer builds, an image whose +// entrypoint cannot find the server, or a container that `docker stop` has to +// kill all passed every check and reached a release, where they were found by +// hand (the v2.5.0 release verification, #5572). +// +// What it checks, per image: +// +// 1. It builds, with the command its Dockerfile and README document: the +// repository root as the context for a TypeScript server (an npm +// workspace, whose lockfile is the root's), the server's own directory +// for a Python one. +// 2. It boots: an MCP client connects over the container's stdio, lists the +// tools, and finds the one the table names. +// 3. Where the table says the image stops on its own (`cleanStop`), +// `docker stop` ends it before Docker's timeout. A container Docker has +// to SIGKILL exits 137, and the server in it ran none of its cleanup. +// 4. For `memory`, whose cleanup removes the lock file a write holds +// (#5485): after a write and that stop, the graph's directory holds the +// graph and nothing else, so no lock or temporary save file was left. +// +// `cleanStop` is in the table, not read from the image's `STOPSIGNAL`: the +// regression worth catching is that line being dropped, which would also drop +// a check derived from it. The other five images do not stop on their own +// today (#5611), so nothing is asserted of them. +// +// Which images it builds is decided from the files changed since the base, +// as the interface diff decides which servers to diff: a server's own +// directory, the root files its image copies, a change to the packages it +// resolves in the root lockfile, or a change to this tooling (every image). +// The root `package.json` is copied into the TypeScript images too, but it is +// left out of the selection: almost every tooling change edits it (a new npm +// script), and the part of it an image depends on, `overrides`, reaches the +// image only through the lockfile, which is read. CI's `changes` job asks +// this script for the list (`--list`) and fans out one leg per image +// (`--server`); the gate runs it bare. Both go through the same selection. +// +// A change that touches no image builds nothing and needs no Docker. One that +// does needs a running Docker daemon, in the gate as in CI, and fails without +// one rather than skipping: a skipped check that prints a line nobody reads is +// how the gap this closes went unnoticed. A build with a cold layer cache +// also needs the network (base images, `npm ci`, `uv sync`, `apt-get`). +// +// The MCP client is imported only when an image is booted, so `--list` runs +// before any `npm ci`, as the interface diff's does. +// +// Usage: +// npm run image-smoke # base: merge-base with origin/v2/main +// npm run image-smoke -- --base # any commit, tag or branch +// npm run image-smoke -- --server # this image, changed or not (repeatable) +// npm run image-smoke -- --all # every image, changed or not +// npm run image-smoke -- --list # print the selected images as JSON; build nothing + +import { spawnSync } from "node:child_process"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { changesSince, resolveBase } from "./interface-diff.mjs"; +import { lockfileClosure } from "./lib/interface-diff-servers.mjs"; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); + +/** How long one MCP request may take, container start included. */ +export const REQUEST_TIMEOUT_MS = 120_000; + +/** The grace period `docker stop` gives a container: Docker's own default. */ +export const STOP_TIMEOUT_SECONDS = 10; + +/** What a container exits with when Docker had to SIGKILL it (128 + 9). */ +export const KILLED_EXIT_CODE = 137; + +/** + * Every server's image: how it is run for the boot, and what proves it is up. + * + * `args` are the server's arguments, after the image name. `env` is set with + * `docker run -e`. `tool` must be in `tools/list`. `cleanStop` says + * `docker stop` must end the container without killing it. `write` is a tool + * call made before the stop, and `leaves` the directory inside the container + * that must then hold exactly those files. + * + * Listed by hand, because the tool to look for is a fact about each server. + * `findUnlistedImages` keeps the list complete: a `src//Dockerfile` + * with no entry here fails the script tests. + */ +export const IMAGES = [ + { name: "everything", language: "ts", tool: "echo", cleanStop: true }, + { + name: "filesystem", + language: "ts", + // It refuses to start without an allowed directory; the image has /tmp. + args: ["/tmp"], + tool: "list_allowed_directories", + }, + { + name: "memory", + language: "ts", + // /data is the directory the image prepares for a graph kept outside + // dist; nothing is mounted over it, so the graph dies with the container. + env: { MEMORY_FILE_PATH: "/data/memory.jsonl" }, + tool: "read_graph", + cleanStop: true, + write: { + name: "create_entities", + arguments: { + entities: [ + { name: "image-smoke", entityType: "probe", observations: ["up"] }, + ], + }, + }, + leaves: { dir: "/data", files: ["memory.jsonl"] }, + }, + { name: "sequentialthinking", language: "ts", tool: "sequentialthinking" }, + { name: "fetch", language: "py", tool: "fetch" }, + { name: "git", language: "py", tool: "git_status" }, + { name: "time", language: "py", tool: "get_current_time" }, +]; + +/** Files whose change selects every image: this tooling itself. */ +export const TOOLING_PATHS = [ + "scripts/image-smoke.mjs", + ".github/workflows/image-smoke.yml", +]; + +/** Root files every TypeScript image copies, besides the manifests. */ +export const TS_WIDE_PATHS = [".npmrc", "tsconfig.json"]; + +/** + * The server directories under `srcDir` that hold a `Dockerfile` and that + * `IMAGES` does not list. + * + * @param {string} srcDir + * @param {{ name: string }[]} [images] + * @returns {string[]} + */ +export function findUnlistedImages(srcDir, images = IMAGES) { + const listed = new Set(images.map((i) => i.name)); + return readdirSync(srcDir, { withFileTypes: true }) + .filter( + (entry) => + entry.isDirectory() && + existsSync(path.join(srcDir, entry.name, "Dockerfile")), + ) + .map((entry) => entry.name) + .filter((name) => !listed.has(name)) + .sort(); +} + +/** + * Parse the command line. + * + * @param {string[]} argv + * @returns {{ base: string | null, servers: string[], all: boolean, + * list: boolean }} + */ +export function parseArgs(argv) { + const opts = { base: null, servers: [], all: false, list: false }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + const [flag, inline] = arg.startsWith("--") ? arg.split(/=(.*)/s) : [arg]; + const value = () => { + const v = inline ?? argv[++i]; + if (v === undefined || v === "") throw new Error(`${flag} needs a value`); + return v; + }; + const bare = () => { + if (inline !== undefined) throw new Error(`${flag} takes no value`); + return true; + }; + if (flag === "--base") opts.base = value(); + else if (flag === "--server") opts.servers.push(value()); + else if (flag === "--all") opts.all = bare(); + else if (flag === "--list") opts.list = bare(); + else throw new Error(`unknown argument: ${arg}`); + } + if (opts.all && opts.servers.length > 0) + throw new Error("--all and --server cannot be combined"); + const known = new Set(IMAGES.map((i) => i.name)); + const unknown = opts.servers.filter((s) => !known.has(s)); + // A typo must not read as "nothing to build, so it passed". + if (unknown.length > 0) + throw new Error( + `unknown server(s): ${unknown.join(", ")}. Known: ${[...known].join(", ")}.`, + ); + return opts; +} + +/** Whether two lockfile closures lock different packages. */ +function closuresDiffer(a, b) { + if (a.size !== b.size) return true; + for (const [location, print] of a) if (b.get(location) !== print) return true; + return false; +} + +/** + * The images a change can have broken, in `IMAGES` order, each with the + * reason it was selected. + * + * @param {{ changedFiles: string[], baseLock: object | null, + * headLock: object | null, images?: typeof IMAGES }} input + * `changedFiles` are repository-relative, `/`-separated paths. + * @returns {{ server: string, language: string, reason: string }[]} + */ +export function selectImages({ + changedFiles, + baseLock, + headLock, + images = IMAGES, +}) { + const changed = new Set(changedFiles); + const tooling = TOOLING_PATHS.find((p) => changed.has(p)); + const selected = []; + for (const { name, language } of images) { + const dir = `src/${name}/`; + const own = changedFiles.filter((f) => f.startsWith(dir)); + let reason = tooling ? `\`${tooling}\` (the image tooling) changed` : null; + if (!reason && own.length > 0) + reason = + own.length === 1 + ? `\`${own[0]}\` changed` + : `${own.length} files under \`${dir}\` changed`; + if (!reason && language === "ts") { + const wide = TS_WIDE_PATHS.find((p) => changed.has(p)); + if (wide) + reason = `\`${wide}\`, which every TypeScript image copies, changed`; + else if ( + changed.has("package-lock.json") && + closuresDiffer( + lockfileClosure(baseLock, `src/${name}`), + lockfileClosure(headLock, `src/${name}`), + ) + ) + reason = "`package-lock.json` changes a package it installs"; + } + if (reason) selected.push({ server: name, language, reason }); + } + return selected; +} + +/** + * The images a run covers, each with the reason: every one (`--all`), the + * named ones (`--server`), or else the ones the change touches. + * + * @param {ReturnType} opts + * @param {() => Parameters[0]} changes read lazily, so + * naming the images needs no git history + * @returns {{ server: string, language: string, reason: string }[]} + */ +export function chooseImages(opts, changes) { + const named = (reason, keep) => + IMAGES.filter(keep).map(({ name, language }) => ({ + server: name, + language, + reason, + })); + if (opts.all) return named("every image was asked for (`--all`)", () => true); + if (opts.servers.length > 0) + return named("it was named (`--server`)", (i) => + opts.servers.includes(i.name), + ); + return selectImages(changes()); +} + +/** + * The tag an image is built under. One per server, reused by every run, so + * the images do not pile up and one can be run by hand afterwards. A run never + * boots by this tag: another checkout's run can move it between this run's + * build and its boot, and the boot would then pass on that checkout's image. + * The boot uses the image ID the build wrote (`--iidfile`). + */ +export function imageTag(name) { + return `mcp-image-smoke/${name}:local`; +} + +/** + * How an image is built: `docker`'s arguments and the directory to run it in. + * These are the commands each Dockerfile and README give. + * + * @param {(typeof IMAGES)[number]} image + * @param {string} [root] + * @returns {{ args: string[], cwd: string }} + */ +export function buildCommand(image, root = repoRoot) { + const tag = imageTag(image.name); + return image.language === "ts" + ? { + args: ["build", "-f", `src/${image.name}/Dockerfile`, "-t", tag, "."], + cwd: root, + } + : { + args: ["build", "-t", tag, "."], + cwd: path.join(root, "src", image.name), + }; +} + +/** + * `docker`'s arguments for the boot: `run -i`, as a client configuration has + * it, under a name so the container can be stopped and inspected afterwards + * (hence no `--rm`; the check removes it). + * + * @param {(typeof IMAGES)[number]} image + * @param {string} container + * @param {string} [ref] the image to run: the ID this run built + * @returns {string[]} + */ +export function runArgs(image, container, ref = imageTag(image.name)) { + return [ + "run", + "-i", + "--name", + container, + ...Object.entries(image.env ?? {}).flatMap(([k, v]) => ["-e", `${k}=${v}`]), + ref, + ...(image.args ?? []), + ]; +} + +/** + * Why a stopped container's exit code fails the clean-stop check, or `null` + * when it passes. Any code but Docker's kill is the server's own exit: 0, or + * 128 plus the signal it handled. + * + * @param {number} exitCode + * @returns {string | null} + */ +export function judgeStop(exitCode) { + if (!Number.isInteger(exitCode)) + return "its exit code could not be read after `docker stop`"; + return exitCode === KILLED_EXIT_CODE + ? `\`docker stop\` had to kill it after ${STOP_TIMEOUT_SECONDS}s (exit ${KILLED_EXIT_CODE}): the server did not exit on the image's stop signal, so it ran none of its cleanup. Check the Dockerfile's STOPSIGNAL and the server's signal handlers.` + : null; +} + +/** + * Why the files a stopped container left fail the check, or `null`. + * + * @param {string[]} found + * @param {{ dir: string, files: string[] }} leaves + * @returns {string | null} + */ +export function judgeLeftovers(found, leaves) { + const want = [...leaves.files].sort(); + const got = [...found].sort(); + return got.length === want.length && got.every((f, i) => f === want[i]) + ? null + : `${leaves.dir} holds [${got.join(", ")}] after the stop, not exactly [${want.join(", ")}]: a write was lost, or a lock or temporary file was left behind.`; +} + +const tail = (text) => + (text ?? "").trim().split("\n").slice(-25).join("\n").trim(); + +/** Run `docker` to completion and hand back what happened; never throws. */ +function docker(args, cwd = repoRoot) { + const res = spawnSync("docker", args, { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + return { + status: res.error ? null : res.status, + stdout: res.stdout ?? "", + stderr: res.error ? String(res.error.message) : (res.stderr ?? ""), + }; +} + +/** This process's environment, as the string map the transport takes. */ +export function inheritedEnv(base = process.env) { + return Object.fromEntries( + Object.entries(base).filter(([, value]) => typeof value === "string"), + ); +} + +/** The signals that interrupt a run, and what a process they end exits with. */ +export const INTERRUPT_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 }; + +/** + * Connect an MCP client to a container started with `dockerArgs`. + * + * @param {string[]} dockerArgs + * @returns {Promise<{ listTools: () => Promise, + * callTool: (call: object) => Promise<{ isError: boolean, text: string }>, + * stderr: () => string, close: () => Promise }>} + */ +async function connect(dockerArgs) { + const { Client } = await import("@modelcontextprotocol/client"); + const { StdioClientTransport } = + await import("@modelcontextprotocol/client/stdio"); + const options = { timeout: REQUEST_TIMEOUT_MS }; + const client = new Client({ name: "image-smoke", version: "0.0.0" }); + const transport = new StdioClientTransport({ + command: "docker", + args: dockerArgs, + // The transport's default environment is a short allowlist that leaves + // out DOCKER_HOST, DOCKER_CONTEXT and the TLS settings, so `docker run` + // would reach a different daemon from the one `docker()` built on. + env: inheritedEnv(), + stderr: "pipe", + }); + let stderr = ""; + transport.stderr?.on("data", (chunk) => (stderr += chunk)); + const session = { + listTools: async () => + (await client.listTools(undefined, options)).tools.map((t) => t.name), + callTool: async (call) => { + const result = await client.callTool(call, options); + return { + isError: result.isError === true, + text: (result.content ?? []) + .filter((c) => c.type === "text") + .map((c) => c.text) + .join("\n"), + }; + }, + stderr: () => stderr, + close: () => client.close().catch(() => {}), + }; + try { + await client.connect(transport, options); + } catch (err) { + await session.close(); + throw new Error( + `${err?.message ?? err}${tail(stderr) ? `\n--- container stderr ---\n${tail(stderr)}` : ""}`, + { cause: err }, + ); + } + return session; +} + +/** + * Build, boot and stop one image. Resolves when it passes; rejects with the + * reason when it does not. Always removes the container it started. + * + * @param {(typeof IMAGES)[number]} image + * @param {{ docker?: typeof docker, connect?: typeof connect, + * log?: (line: string) => void, root?: string, + * proc?: Pick }} [deps] replaced + * in tests + */ +export async function checkImage(image, deps = {}) { + const run = deps.docker ?? docker; + const open = deps.connect ?? connect; + const log = deps.log ?? console.log; + const proc = deps.proc ?? process; + + const build = buildCommand(image, deps.root); + const scratch = mkdtempSync(path.join(tmpdir(), "mcp-image-smoke-")); + const iidFile = path.join(scratch, "image-id"); + let imageId; + try { + // The context (`.`) stays last; the ID file is how the boot below runs + // exactly what this build produced, whatever the shared tag points at. + const built = run( + [...build.args.slice(0, -1), "--iidfile", iidFile, "."], + build.cwd, + ); + if (built.status !== 0) + throw new Error( + `\`docker ${build.args.join(" ")}\` failed (${built.status ?? "could not run"}):\n${tail(built.stderr) || tail(built.stdout)}`, + ); + imageId = existsSync(iidFile) ? readFileSync(iidFile, "utf8").trim() : ""; + if (!imageId) + throw new Error( + `\`docker ${build.args.join(" ")}\` succeeded but wrote no image ID, so there is nothing to boot.`, + ); + } catch (err) { + rmSync(scratch, { recursive: true, force: true }); + throw err; + } + log( + `image-smoke — built ${imageTag(image.name)} (${imageId.replace(/^sha256:/, "").slice(0, 12)})`, + ); + + const container = `mcp-image-smoke-${image.name}-${process.pid}-${Date.now()}`; + let session; + // An interrupt (Ctrl-C, a cancelled gate) ends the process without running + // the `finally` below, and the container has no `--rm`, so it would be left + // behind, still running where the image ignores the signal `docker run` + // forwards. Remove it first, then exit as the signal would have. + const interrupts = Object.entries(INTERRUPT_EXIT_CODES).map( + ([signal, code]) => [ + signal, + () => { + run(["rm", "-f", container]); + proc.exit(code); + }, + ], + ); + for (const [signal, handler] of interrupts) proc.once(signal, handler); + try { + session = await open(runArgs(image, container, imageId)); + try { + const tools = await session.listTools(); + if (!tools.includes(image.tool)) + throw new Error( + `tools/list does not include \`${image.tool}\` (got: ${tools.join(", ")})`, + ); + if (image.write) { + const result = await session.callTool(image.write); + if (result.isError) + throw new Error( + `\`${image.write.name}\` returned an error result: ${result.text}`, + ); + } + } catch (err) { + const stderr = tail(session.stderr()); + throw new Error( + `${err?.message ?? err}${stderr ? `\n--- container stderr ---\n${stderr}` : ""}`, + { cause: err }, + ); + } + log(`image-smoke — booted; tools/list has \`${image.tool}\``); + + if (image.cleanStop) { + const stopped = run([ + "stop", + "-t", + String(STOP_TIMEOUT_SECONDS), + container, + ]); + if (stopped.status !== 0) + throw new Error(`\`docker stop\` failed:\n${tail(stopped.stderr)}`); + const inspected = run([ + "inspect", + "-f", + "{{.State.ExitCode}}", + container, + ]); + const exitCode = + inspected.status === 0 ? Number(inspected.stdout.trim()) : NaN; + const verdict = judgeStop(exitCode); + if (verdict) throw new Error(verdict); + log(`image-smoke — stopped on its own (exit ${exitCode})`); + } + + if (image.leaves) { + const left = path.join(scratch, "left"); + mkdirSync(left); + // `docker cp` reads a stopped container's filesystem; `/.` copies the + // directory's contents rather than the directory. + const copied = run(["cp", `${container}:${image.leaves.dir}/.`, left]); + if (copied.status !== 0) + throw new Error( + `could not read ${image.leaves.dir} from the stopped container:\n${tail(copied.stderr)}`, + ); + const verdict = judgeLeftovers(readdirSync(left), image.leaves); + if (verdict) throw new Error(verdict); + log( + `image-smoke — ${image.leaves.dir} holds only ${image.leaves.files.join(", ")}`, + ); + } + } finally { + await session?.close(); + run(["rm", "-f", container]); + for (const [signal, handler] of interrupts) proc.off(signal, handler); + rmSync(scratch, { recursive: true, force: true }); + } +} + +/** + * @param {string[]} [argv] + * @param {{ changes?: () => Parameters[0], + * docker?: typeof docker, check?: typeof checkImage }} [deps] replaced in + * tests + * @returns {Promise} the exit code + */ +export async function main(argv = process.argv.slice(2), deps = {}) { + let opts; + try { + opts = parseArgs(argv); + } catch (err) { + console.error(`image-smoke — ${err.message}`); + return 2; + } + + let selected; + try { + selected = chooseImages( + opts, + deps.changes ?? (() => changesSince(resolveBase(opts.base))), + ); + } catch (err) { + console.error(`image-smoke — ${err.message}`); + return 1; + } + for (const s of selected) + console.error(`image-smoke — ${s.server}: selected because ${s.reason}`); + + if (opts.list) { + console.log( + JSON.stringify( + selected.map(({ server, language }) => ({ server, language })), + ), + ); + return 0; + } + if (selected.length === 0) { + console.log( + "image-smoke — the change touches no server's image; nothing to build.", + ); + return 0; + } + + const run = deps.docker ?? docker; + const daemon = run(["version", "--format", "{{.Server.Version}}"]); + if (daemon.status !== 0) { + console.error( + `image-smoke — FAIL no Docker daemon answered (\`docker version\`: ${tail(daemon.stderr) || "no output"}).\n` + + `The change touches ${selected.map((s) => s.server).join(", ")}, so ${selected.length === 1 ? "its image has" : "their images have"} to build and boot before it is pushed. Start Docker and run \`npm run image-smoke\` again.`, + ); + return 1; + } + + const check = deps.check ?? checkImage; + const failures = []; + for (const { server } of selected) { + const image = IMAGES.find((i) => i.name === server); + const started = Date.now(); + console.log(`image-smoke — ${server} …`); + try { + await check(image, { docker: deps.docker }); + console.log(`image-smoke — ok ${server} (${Date.now() - started}ms)`); + } catch (err) { + failures.push(server); + console.error(`image-smoke — FAIL ${server}\n${err?.message ?? err}\n`); + } + } + + if (failures.length > 0) { + console.error( + `image-smoke — ${failures.length} of ${selected.length} failed: ${failures.join(", ")}`, + ); + return 1; + } + console.log( + `image-smoke — OK (${selected.length} image${selected.length === 1 ? "" : "s"} built and booted)`, + ); + return 0; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) + process.exit(await main()); diff --git a/scripts/image-smoke.test.mjs b/scripts/image-smoke.test.mjs new file mode 100644 index 0000000000..c9ead7aabd --- /dev/null +++ b/scripts/image-smoke.test.mjs @@ -0,0 +1,626 @@ +// Tests for the image smoke (#5598). Building and booting the images is what +// `npm run image-smoke` itself does, as a gate stage and in CI, so it is not +// repeated here. What is pinned is what a green run could otherwise hide: a +// Dockerfile missing from the table, a change that selects no image when it +// should, a typo'd name passing as "nothing to build", the build and run +// commands drifting from the documented ones, a killed container read as a +// clean stop, and a missing Docker daemon read as a pass. `checkImage` and +// `main` are driven with a fake `docker` and a fake MCP session. +// Run via `npm run test:scripts`. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { + IMAGES, + INTERRUPT_EXIT_CODES, + KILLED_EXIT_CODE, + TOOLING_PATHS, + buildCommand, + checkImage, + chooseImages, + findUnlistedImages, + imageTag, + inheritedEnv, + judgeLeftovers, + judgeStop, + main, + parseArgs, + runArgs, + selectImages, +} from "./image-smoke.mjs"; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); +const byName = (name) => IMAGES.find((i) => i.name === name); +const names = (selected) => selected.map((s) => s.server); +const noLocks = { baseLock: null, headLock: null }; + +/** Run `fn` with the console silenced, handing back what it printed. */ +async function quietly(t, fn) { + const lines = []; + for (const method of ["log", "error"]) + t.mock.method(console, method, (line) => lines.push(String(line))); + const result = await fn(); + return { result, output: lines.join("\n") }; +} + +test("every Dockerfile in the repo has an image entry", () => { + assert.deepEqual(findUnlistedImages(path.join(repoRoot, "src")), []); + assert.equal(IMAGES.length, 7); +}); + +test("findUnlistedImages names a Dockerfile the table lacks", (t) => { + const src = mkdtempSync(path.join(tmpdir(), "image-smoke-src-")); + t.after(() => rmSync(src, { recursive: true, force: true })); + for (const [dir, file] of [ + ["time", "Dockerfile"], + ["newserver", "Dockerfile"], + ["nodocker", "package.json"], + ]) { + mkdirSync(path.join(src, dir)); + writeFileSync(path.join(src, dir, file), ""); + } + assert.deepEqual(findUnlistedImages(src), ["newserver"]); +}); + +test("an image that declares a stop signal is checked for a clean stop", () => { + // The table, not the Dockerfile, decides what is asserted, so a deleted + // STOPSIGNAL cannot delete the check with it. This pins the other + // direction: an image that gains a STOPSIGNAL gains the check in the same + // change. Today that is `everything` and `memory`; the rest are #5611. + const declared = IMAGES.filter((image) => + /^STOPSIGNAL\s/m.test( + readFileSync( + path.join(repoRoot, "src", image.name, "Dockerfile"), + "utf8", + ), + ), + ).map((image) => image.name); + assert.deepEqual(declared, ["everything", "memory"]); + for (const name of declared) assert.equal(byName(name).cleanStop, true, name); +}); + +test("parseArgs reads every flag, in either spelling", () => { + const defaults = { base: null, servers: [], all: false, list: false }; + assert.deepEqual(parseArgs([]), defaults); + assert.deepEqual(parseArgs(["--base", "abc", "--list"]), { + ...defaults, + base: "abc", + list: true, + }); + assert.deepEqual(parseArgs(["--server", "git", "--server=time"]), { + ...defaults, + servers: ["git", "time"], + }); + assert.deepEqual(parseArgs(["--all"]), { ...defaults, all: true }); +}); + +test("parseArgs refuses an unknown flag or server, or a missing value", () => { + assert.throws(() => parseArgs(["--push"]), /unknown argument/); + assert.throws(() => parseArgs(["--base"]), /--base needs a value/); + assert.throws(() => parseArgs(["--all=yes"]), /--all takes no value/); + assert.throws(() => parseArgs(["--all", "--server", "git"]), /combined/); + // A typo must not read as "nothing to build". + assert.throws(() => parseArgs(["--server", "tyme"]), /unknown server/); +}); + +test("a change under a server's directory selects that image only", () => { + const selected = selectImages({ + changedFiles: ["src/memory/Dockerfile", "README.md"], + ...noLocks, + }); + assert.deepEqual(names(selected), ["memory"]); + assert.match(selected[0].reason, /src\/memory\/Dockerfile/); + assert.match( + selectImages({ + changedFiles: ["src/git/a.py", "src/git/b.py"], + ...noLocks, + })[0].reason, + /2 files under `src\/git\/`/, + ); +}); + +test("a change that touches no image selects none", () => { + assert.deepEqual( + selectImages({ + changedFiles: ["AGENTS.md", "package.json", "scripts/smoke-servers.mjs"], + ...noLocks, + }), + [], + ); +}); + +test("a root file the TypeScript images copy selects the four of them", () => { + for (const file of [".npmrc", "tsconfig.json"]) + assert.deepEqual( + names(selectImages({ changedFiles: [file], ...noLocks })), + ["everything", "filesystem", "memory", "sequentialthinking"], + file, + ); +}); + +test("the tooling's own files select every image", () => { + for (const file of TOOLING_PATHS) { + assert.ok(existsOnDisk(file), `${file} must exist`); + const selected = selectImages({ changedFiles: [file], ...noLocks }); + assert.equal(selected.length, IMAGES.length, file); + assert.match(selected[0].reason, /image tooling/); + } +}); + +function existsOnDisk(file) { + try { + readFileSync(path.join(repoRoot, file)); + return true; + } catch { + return false; + } +} + +test("a lockfile change selects only the images that install the changed package", () => { + const lock = (zodVersion) => ({ + packages: { + "": { workspaces: ["src/*"] }, + "src/memory": { dependencies: { zod: "^4" } }, + "src/filesystem": { dependencies: { minimatch: "^11" } }, + "node_modules/zod": { version: zodVersion }, + "node_modules/minimatch": { version: "11.0.1" }, + }, + }); + const changedFiles = ["package-lock.json"]; + assert.deepEqual( + names( + selectImages({ + changedFiles, + baseLock: lock("4.0.0"), + headLock: lock("4.0.1"), + }), + ), + ["memory"], + ); + // A rewrite that reaches no server's packages selects nothing. + assert.deepEqual( + selectImages({ + changedFiles, + baseLock: lock("4.0.0"), + headLock: lock("4.0.0"), + }), + [], + ); +}); + +test("chooseImages: --all, --server, or the change, read only when needed", () => { + const never = () => assert.fail("the change must not be read"); + assert.equal(chooseImages(parseArgs(["--all"]), never).length, IMAGES.length); + assert.deepEqual( + names(chooseImages(parseArgs(["--server", "time"]), never)), + ["time"], + ); + assert.deepEqual( + names( + chooseImages(parseArgs([]), () => ({ + changedFiles: ["src/fetch/uv.lock"], + ...noLocks, + })), + ), + ["fetch"], + ); +}); + +test("an image builds with the command its Dockerfile documents", () => { + // TypeScript: the repository root is the context. Python: the server's + // directory is. + assert.deepEqual(buildCommand(byName("memory"), "/repo"), { + args: [ + "build", + "-f", + "src/memory/Dockerfile", + "-t", + "mcp-image-smoke/memory:local", + ".", + ], + cwd: "/repo", + }); + assert.deepEqual(buildCommand(byName("git"), "/repo"), { + args: ["build", "-t", "mcp-image-smoke/git:local", "."], + cwd: path.join("/repo", "src", "git"), + }); + for (const image of IMAGES) { + const dockerfile = readFileSync( + path.join(repoRoot, "src", image.name, "Dockerfile"), + "utf8", + ); + // The TypeScript Dockerfiles say so themselves; keep the table honest. + assert.equal( + dockerfile.includes(`-f src/${image.name}/Dockerfile`), + image.language === "ts", + image.name, + ); + } +}); + +test("an image is run the way a client runs it: `docker run -i`, stdio", () => { + assert.deepEqual(runArgs(byName("filesystem"), "c1"), [ + "run", + "-i", + "--name", + "c1", + "mcp-image-smoke/filesystem:local", + "/tmp", + ]); + assert.deepEqual(runArgs(byName("memory"), "c2"), [ + "run", + "-i", + "--name", + "c2", + "-e", + "MEMORY_FILE_PATH=/data/memory.jsonl", + "mcp-image-smoke/memory:local", + ]); +}); + +test("judgeStop fails only a container Docker killed, or one it cannot read", () => { + assert.equal(judgeStop(0), null); + assert.equal(judgeStop(130), null); + assert.equal(judgeStop(143), null); + assert.match(judgeStop(KILLED_EXIT_CODE), /had to kill it/); + assert.match(judgeStop(NaN), /could not be read/); +}); + +test("judgeLeftovers wants exactly the files named", () => { + const leaves = { dir: "/data", files: ["memory.jsonl"] }; + assert.equal(judgeLeftovers(["memory.jsonl"], leaves), null); + assert.match( + judgeLeftovers(["memory.jsonl", "memory.jsonl.lock"], leaves), + /memory\.jsonl\.lock/, + ); + assert.match(judgeLeftovers([], leaves), /a write was lost/); +}); + +/** + * A fake `docker` that records each call and answers from `answers`, keyed by + * the subcommand; anything unlisted succeeds with no output. `cp` writes + * `files` into its destination, as the real one copies a directory out. + */ +function fakeDocker(answers = {}, files = ["memory.jsonl"]) { + const calls = []; + const docker = (args, cwd) => { + calls.push({ args, cwd }); + // A build that succeeds writes the ID of what it built. + if (args[0] === "build" && (answers.build?.status ?? 0) === 0) + writeFileSync( + args[args.indexOf("--iidfile") + 1], + answers.imageId ?? "sha256:built-here\n", + ); + if (args[0] === "cp" && answers.cp === undefined) + for (const file of files) writeFileSync(path.join(args[2], file), ""); + return { status: 0, stdout: "", stderr: "", ...answers[args[0]] }; + }; + return { docker, calls, ran: () => calls.map((c) => c.args[0]) }; +} + +/** A fake MCP session over a container. */ +function fakeSession({ tools, isError = false } = {}) { + const state = { closed: 0, called: [] }; + const connect = async () => ({ + listTools: async () => tools, + callTool: async (call) => { + state.called.push(call.name); + return { isError, text: "refused" }; + }, + stderr: () => "server stderr line", + close: async () => void (state.closed += 1), + }); + return { connect, state }; +} + +const quiet = { log: () => {} }; + +test("checkImage builds, boots, stops and reads back memory's directory", async () => { + const { docker, calls, ran } = fakeDocker({ + inspect: { stdout: "130\n" }, + }); + const { connect, state } = fakeSession({ tools: ["read_graph"] }); + await checkImage(byName("memory"), { + docker, + connect, + root: "/repo", + ...quiet, + }); + assert.deepEqual(ran(), ["build", "stop", "inspect", "cp", "rm"]); + assert.equal(calls[0].cwd, "/repo"); + const container = calls[1].args.at(-1); + assert.match(container, /^mcp-image-smoke-memory-/); + assert.match(calls[3].args[1], /:\/data\/\.$/); + assert.deepEqual(calls[4].args, ["rm", "-f", container]); + assert.deepEqual(state.called, ["create_entities"]); + assert.equal(state.closed, 1); +}); + +test("checkImage boots the image it built, by ID, not whatever the tag points at", async () => { + // Another checkout's run can retag `mcp-image-smoke/:local` between + // this run's build and its boot. + const { docker, calls } = fakeDocker(); + let booted; + const connect = async (args) => { + booted = args; + return fakeSessionFor(["get_current_time"]); + }; + await checkImage(byName("time"), { docker, connect, ...quiet }); + assert.deepEqual(calls[0].args.slice(0, 3), [ + "build", + "-t", + "mcp-image-smoke/time:local", + ]); + assert.equal(calls[0].args.at(-3), "--iidfile"); + assert.equal(calls[0].args.at(-1), "."); + assert.equal(booted.at(-1), "sha256:built-here"); + assert.ok(!booted.includes("mcp-image-smoke/time:local")); +}); + +test("checkImage fails a build that reports no image ID", async () => { + const { docker, ran } = fakeDocker({ imageId: "" }); + const { connect } = fakeSession({ tools: [] }); + await assert.rejects( + checkImage(byName("time"), { docker, connect, ...quiet }), + /wrote no image ID/, + ); + assert.deepEqual(ran(), ["build"]); +}); + +test("checkImage does not stop-check an image the table does not say stops", async () => { + const { docker, ran } = fakeDocker(); + const { connect } = fakeSession({ tools: ["get_current_time"] }); + await checkImage(byName("time"), { docker, connect, ...quiet }); + assert.deepEqual(ran(), ["build", "rm"]); +}); + +test("checkImage fails an image that does not build, and starts nothing", async () => { + const { docker, ran } = fakeDocker({ + build: { status: 1, stderr: "ERROR: failed to solve" }, + }); + const { connect, state } = fakeSession({ tools: [] }); + await assert.rejects( + checkImage(byName("git"), { docker, connect, ...quiet }), + /docker build -t mcp-image-smoke\/git:local \.` failed \(1\):\nERROR: failed to solve/, + ); + assert.deepEqual(ran(), ["build"]); + assert.equal(state.closed, 0); +}); + +test("checkImage fails an image whose server does not list its tool, with its stderr", async () => { + const { docker, ran } = fakeDocker(); + const { connect, state } = fakeSession({ tools: ["other"] }); + await assert.rejects( + checkImage(byName("everything"), { docker, connect, ...quiet }), + /tools\/list does not include `echo` \(got: other\)\n--- container stderr ---\nserver stderr line/, + ); + // The container is removed and the session closed all the same. + assert.deepEqual(ran(), ["build", "rm"]); + assert.equal(state.closed, 1); +}); + +test("checkImage fails an image whose container never answers", async () => { + const { docker, ran } = fakeDocker(); + const connect = async () => { + throw new Error("Connection closed"); + }; + await assert.rejects( + checkImage(byName("fetch"), { docker, connect, ...quiet }), + /Connection closed/, + ); + assert.deepEqual(ran(), ["build", "rm"]); +}); + +test("checkImage fails a write the server refuses", async () => { + const { docker } = fakeDocker(); + const { connect } = fakeSession({ tools: ["read_graph"], isError: true }); + await assert.rejects( + checkImage(byName("memory"), { docker, connect, ...quiet }), + /`create_entities` returned an error result: refused/, + ); +}); + +test("checkImage fails a container Docker had to kill", async () => { + const { docker, ran } = fakeDocker({ + inspect: { stdout: `${KILLED_EXIT_CODE}\n` }, + }); + const { connect } = fakeSession({ tools: ["echo"] }); + await assert.rejects( + checkImage(byName("everything"), { docker, connect, ...quiet }), + /had to kill it/, + ); + assert.deepEqual(ran(), ["build", "stop", "inspect", "rm"]); +}); + +test("checkImage fails when the stop, the inspect or the copy cannot run", async () => { + const { connect } = fakeSession({ tools: ["read_graph"] }); + for (const [answers, message] of [ + [ + { stop: { status: 1, stderr: "no such container" } }, + /docker stop` failed/, + ], + [{ inspect: { status: 1 } }, /exit code could not be read/], + [ + { inspect: { stdout: "0" }, cp: { status: 1, stderr: "denied" } }, + /could not read \/data from the stopped container:\ndenied/, + ], + ]) + await assert.rejects( + checkImage(byName("memory"), { + docker: fakeDocker(answers).docker, + connect, + ...quiet, + }), + message, + ); +}); + +test("checkImage fails memory when a lock file outlives the stop", async () => { + const { docker } = fakeDocker({ inspect: { stdout: "130" } }, [ + "memory.jsonl", + "memory.jsonl.lock", + ]); + const { connect } = fakeSession({ tools: ["read_graph"] }); + await assert.rejects( + checkImage(byName("memory"), { docker, connect, ...quiet }), + /memory\.jsonl\.lock/, + ); +}); + +test("main: a bad argument exits 2", async (t) => { + const { result, output } = await quietly(t, () => main(["--nope"])); + assert.equal(result, 2); + assert.match(output, /unknown argument/); +}); + +test("main: a change that cannot be read exits 1", async (t) => { + const { result, output } = await quietly(t, () => + main([], { + changes: () => { + throw new Error("origin/v2/main is not available"); + }, + }), + ); + assert.equal(result, 1); + assert.match(output, /origin\/v2\/main is not available/); +}); + +test("main --list prints the selection as JSON and touches no Docker", async (t) => { + const { docker, calls } = fakeDocker(); + const { result, output } = await quietly(t, () => + main(["--list"], { + docker, + changes: () => ({ changedFiles: ["src/time/Dockerfile"], ...noLocks }), + }), + ); + assert.equal(result, 0); + assert.match(output, /\[\{"server":"time","language":"py"\}\]/); + assert.equal(calls.length, 0); +}); + +test("main: a change that touches no image passes without Docker", async (t) => { + const { docker, calls } = fakeDocker({ version: { status: 1 } }); + const { result, output } = await quietly(t, () => + main([], { + docker, + changes: () => ({ changedFiles: ["README.md"], ...noLocks }), + }), + ); + assert.equal(result, 0); + assert.match(output, /nothing to build/); + assert.equal(calls.length, 0); +}); + +test("main: a selected image with no Docker daemon fails; it is never skipped", async (t) => { + const checked = []; + const { result, output } = await quietly(t, () => + main(["--server", "git", "--server", "time"], { + docker: fakeDocker({ + version: { status: 1, stderr: "Cannot connect to the Docker daemon" }, + }).docker, + check: async (image) => void checked.push(image.name), + }), + ); + assert.equal(result, 1); + assert.match(output, /no Docker daemon answered/); + assert.match(output, /Cannot connect to the Docker daemon/); + assert.match(output, /git, time, so their images have/); + assert.deepEqual(checked, []); +}); + +test("main checks every selected image, and one failure does not stop the rest", async (t) => { + const checked = []; + const deps = (failing) => ({ + docker: fakeDocker().docker, + check: async (image) => { + checked.push(image.name); + if (failing.includes(image.name)) throw new Error("did not build"); + }, + }); + const failed = await quietly(t, () => main(["--all"], deps(["memory"]))); + assert.equal(failed.result, 1); + assert.equal(checked.length, IMAGES.length); + assert.match(failed.output, /FAIL {2}memory\ndid not build/); + assert.match(failed.output, /1 of 7 failed: memory/); + + const passed = await quietly(t, () => main(["--server", "time"], deps([]))); + assert.equal(passed.result, 0); + assert.match(passed.output, /OK \(1 image built and booted\)/); +}); + +test("the container is started with this process's whole environment", () => { + // DOCKER_HOST and DOCKER_CONTEXT choose the daemon; the transport's default + // environment drops them, so the boot would miss the daemon the build used. + assert.deepEqual( + inheritedEnv({ DOCKER_HOST: "tcp://x:1", PATH: "/bin", GONE: undefined }), + { DOCKER_HOST: "tcp://x:1", PATH: "/bin" }, + ); +}); + +test("an interrupt removes the container and exits as the signal would", async () => { + for (const [signal, code] of Object.entries(INTERRUPT_EXIT_CODES)) { + const { docker, calls } = fakeDocker(); + const proc = Object.assign(new EventEmitter(), { + exited: [], + exit(n) { + this.exited.push(n); + }, + }); + let interrupted; + const connect = async (args) => { + // The container is up; the interrupt arrives mid-boot. + interrupted = args[args.indexOf("--name") + 1]; + proc.emit(signal); + return fakeSessionFor(["get_current_time"]); + }; + await checkImage(byName("time"), { docker, connect, proc, ...quiet }); + assert.deepEqual(proc.exited, [code], signal); + assert.deepEqual(calls[1].args, ["rm", "-f", interrupted], signal); + // Normal completion unregisters both handlers. + for (const name of Object.keys(INTERRUPT_EXIT_CODES)) + assert.equal(proc.listenerCount(name), 0, name); + } +}); + +test("a failed check unregisters its interrupt handlers too", async () => { + const proc = Object.assign(new EventEmitter(), { exit() {} }); + const { connect } = fakeSession({ tools: ["other"] }); + await assert.rejects( + checkImage(byName("time"), { + docker: fakeDocker().docker, + connect, + proc, + ...quiet, + }), + ); + assert.equal(proc.listenerCount("SIGINT"), 0); + assert.equal(proc.listenerCount("SIGTERM"), 0); +}); + +/** A bare session that lists `tools`. */ +function fakeSessionFor(tools) { + return { + listTools: async () => tools, + callTool: async () => ({ isError: false, text: "" }), + stderr: () => "", + close: async () => {}, + }; +} + +test("imageTag is one fixed tag per server", () => { + assert.equal(imageTag("time"), "mcp-image-smoke/time:local"); +}); diff --git a/scripts/interface-diff.mjs b/scripts/interface-diff.mjs index 4b21fd10f3..1575347c30 100644 --- a/scripts/interface-diff.mjs +++ b/scripts/interface-diff.mjs @@ -24,7 +24,7 @@ // `scripts/lib/workflow-gate.test.mjs` derives that from the npm scripts a // workflow invokes. A check behind an action is invisible to it; a check // behind `npm run interface-diff` is enforced by it. CI -// (`everything-mcp-diff.yml`) and the gate run this same file. +// (`mcp-interface-diff.yml`) and the gate run this same file. // - The tool comes in as an exact-pinned root devDependency, so it is held // by `package-lock.json`'s integrity hash, the way every other npm // dependency here is, and no third-party action runs in CI at all. @@ -325,8 +325,11 @@ function run(command, args, cwd, env) { const git = (...args) => run("git", args, repoRoot).trim(); -/** The commit to compare against, as a full SHA. */ -function resolveBase(base) { +/** + * The commit to compare against, as a full SHA. Exported for the image smoke + * (`scripts/image-smoke.mjs`), which selects from the same change. + */ +export function resolveBase(base) { if (base) return git("rev-parse", "--verify", `${base}^{commit}`); try { git("rev-parse", "--verify", DEFAULT_BASE_BRANCH); @@ -342,9 +345,10 @@ function resolveBase(base) { * What changed between `sha` and this checkout as it stands: the files * (committed, staged, unstaged and untracked alike, since the head probed is * the working tree's build, both sides of a rename included) and the root - * lockfile on each side (`null` where there is none). + * lockfile on each side (`null` where there is none). Exported for the image + * smoke, as `resolveBase` is. */ -function changesSince(sha) { +export function changesSince(sha) { // NUL-delimited, so a path holding a non-ASCII character, a tab or a // newline comes back as written rather than C-quoted (`"src/time/…`), which // would match no server's directory. diff --git a/scripts/lib/interface-diff-servers.mjs b/scripts/lib/interface-diff-servers.mjs index 82596d7fde..a3abe13d51 100644 --- a/scripts/lib/interface-diff-servers.mjs +++ b/scripts/lib/interface-diff-servers.mjs @@ -1,7 +1,7 @@ // The servers the MCP interface diff covers, how each is started for it, and // which of them a change touches (#5428). // -// Two things live here, both shared by CI (`everything-mcp-diff.yml`) and the +// Two things live here, both shared by CI (`mcp-interface-diff.yml`) and the // pre-push gate through `scripts/interface-diff.mjs`, so the two always agree // on what to diff: // @@ -68,7 +68,7 @@ export const TOOLING_PATHS = [ "scripts/interface-diff.mjs", "scripts/lib/interface-diff-servers.mjs", "scripts/lib/win-shell-args.mjs", - ".github/workflows/everything-mcp-diff.yml", + ".github/workflows/mcp-interface-diff.yml", ]; /** Root files every TypeScript server's build reads. */ diff --git a/scripts/lib/workflow-gate.test.mjs b/scripts/lib/workflow-gate.test.mjs index c08ae56186..9aa870ccf1 100644 --- a/scripts/lib/workflow-gate.test.mjs +++ b/scripts/lib/workflow-gate.test.mjs @@ -393,6 +393,7 @@ describe("the gate's name", () => { "verify:skills:cli", "smoke", "interface-diff", + "image-smoke", ]) { it(`runs \`${stage}\``, () => { assert.ok( diff --git a/scripts/mcp-registry-entries.mjs b/scripts/mcp-registry-entries.mjs new file mode 100644 index 0000000000..71d07be141 --- /dev/null +++ b/scripts/mcp-registry-entries.mjs @@ -0,0 +1,306 @@ +#!/usr/bin/env node +// Each server's entry for the official MCP Registry +// (registry.modelcontextprotocol.io), for `release.yml` (#3047). +// +// A registry entry is a `server.json`: the server's registry name, a title and +// description, and the package a client installs to run it. Each server keeps +// its own at `src//server.json`. +// +// THE COMMITTED FILE CARRIES NO VERSION, and this script adds it. The registry +// requires one, and it must be the version of a package that is already on npm +// or PyPI. But a version in this repository changes only in a version PR, +// which edits `package.json` or `pyproject.toml` and nothing else +// (`AGENTS.md`, **Versions**). A version written into `server.json` as well +// would be a second copy for those PRs to keep in step, and a stale one would +// register an entry pointing at the wrong package. So the manifest stays the +// only place a version lives, and the entry is stamped from it at release +// time, on the released commit. +// +// The registry accepts an entry only when the package itself names the server: +// `mcpName` in a published `package.json`, or an `mcp-name: ` marker in +// the README a PyPI project publishes as its description. Those were added +// when the issue was filed and are in every published package. A committed +// entry that disagreed with them would be refused at release time, long after +// the change that broke it merged, so `entryProblems` checks each entry against +// its package here, and the script tests run it against the repository as it +// stands (`npm run test:scripts`, part of `validate:guards`). +// +// Like `release-manifest.mjs`, this runs in `detect-packages`, with nothing +// installed and no third-party import, and its result reaches the publish job +// as a job output: the job that holds the OIDC credential takes what to +// register from the released source, not from a file a build job wrote. +// +// Under GitHub Actions it writes one step output, `mcp_registry`: a JSON +// object keyed by the server's directory under `src/`, each value the complete +// `server.json` to publish. It always prints the same JSON to stdout. Any +// problem with any entry fails the run and writes nothing. + +import { appendFileSync, existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { expectedPackages } from "./release-manifest.mjs"; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); + +/** The `server.json` schema the entries are written against. */ +export const SCHEMA_URL = + "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json"; + +/** + * The registry grants a namespace to whoever proves they own it. A workflow in + * this organization proves `io.github.modelcontextprotocol/*` with its OIDC + * token, and no other, so an entry outside it could never be published. + */ +export const NAMESPACE = "io.github.modelcontextprotocol/"; + +const REPOSITORY_URL = "https://github.com/modelcontextprotocol/servers"; + +// The registry's own limits (the schema's `maxLength`s). An over-long +// description is its most common rejection. +const MAX_DESCRIPTION = 100; +const MAX_TITLE = 100; +const NAME_PATTERN = /^[a-zA-Z0-9.-]+\/[a-zA-Z0-9._-]+$/; + +/** + * The server name a README claims with an `mcp-name:` marker, as the registry + * reads it: the token after the marker, ended by whitespace, an HTML tag or a + * comment close. + * + * @param {string} readme + * @returns {string | undefined} + */ +export function readmeMarker(readme) { + const match = /mcp-name:[ \t]*([^\s<]+?)(?=\s|<|-->|$)/.exec(readme); + return match?.[1]; +} + +/** + * Pure: what is wrong with one server's committed entry. + * + * @param {object} server + * @param {string} server.dir the server's directory under `src/` + * @param {"npm" | "pypi"} server.registryType + * @param {string} server.packageName the name its manifest publishes under + * @param {string | undefined} server.marker the server name its package claims + * @param {unknown} server.entry the parsed `server.json` + * @returns {string[]} one message per problem; empty when the entry is sound + */ +export function entryProblems({ + dir, + registryType, + packageName, + marker, + entry, +}) { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) + return ["is not a JSON object"]; + const problems = []; + const { name, title, description, repository, packages } = entry; + + if (entry.$schema !== SCHEMA_URL) + problems.push(`\`$schema\` must be ${SCHEMA_URL}`); + + if (typeof name !== "string" || !NAME_PATTERN.test(name)) + problems.push("`name` must be `/`"); + else if (!name.startsWith(NAMESPACE)) + problems.push( + `\`name\` must start with \`${NAMESPACE}\`, the only namespace this repository's workflows can publish to`, + ); + if (marker === undefined) + problems.push( + registryType === "npm" + ? "its package.json has no `mcpName`, which the registry reads to verify the package" + : "its README has no `mcp-name:` marker, which the registry reads to verify the package", + ); + else if (name !== marker) + problems.push( + `\`name\` is ${JSON.stringify(name)} but the package claims ${JSON.stringify(marker)} (${registryType === "npm" ? "`mcpName` in package.json" : "the `mcp-name:` marker in README.md"}); the registry refuses an entry whose package names another server`, + ); + + if (typeof title !== "string" || title === "" || title.length > MAX_TITLE) + problems.push(`\`title\` must be 1 to ${MAX_TITLE} characters`); + if ( + typeof description !== "string" || + description === "" || + description.length > MAX_DESCRIPTION + ) + problems.push( + `\`description\` must be 1 to ${MAX_DESCRIPTION} characters${typeof description === "string" ? ` (it is ${description.length})` : ""}`, + ); + + if ("version" in entry) + problems.push( + "`version` must not be committed: it is stamped from the package manifest at release time", + ); + + if ( + repository?.url !== REPOSITORY_URL || + repository?.source !== "github" || + repository?.subfolder !== `src/${dir}` + ) + problems.push( + `\`repository\` must be { url: ${REPOSITORY_URL}, source: github, subfolder: src/${dir} }`, + ); + + if ("remotes" in entry) + problems.push( + "`remotes` is not supported: these servers are installed as packages", + ); + + if (!Array.isArray(packages) || packages.length !== 1) { + problems.push("`packages` must hold exactly one package"); + return problems; + } + const [pkg] = packages; + if (pkg === null || typeof pkg !== "object") { + problems.push("`packages[0]` is not an object"); + return problems; + } + if (pkg.registryType !== registryType) + problems.push(`\`packages[0].registryType\` must be \`${registryType}\``); + if (pkg.identifier !== packageName) + problems.push( + `\`packages[0].identifier\` must be the published package, \`${packageName}\``, + ); + if ("version" in pkg) + problems.push( + "`packages[0].version` must not be committed: it is stamped from the package manifest at release time", + ); + if ("registryBaseUrl" in pkg) + problems.push( + "`packages[0].registryBaseUrl` must be left out: the registry accepts only the public npm and PyPI registries, which are the defaults", + ); + if (pkg.transport?.type !== "stdio") + problems.push( + "`packages[0].transport.type` must be `stdio`, the transport every server starts in by default", + ); + return problems; +} + +/** + * Pure: the entry to publish, with the package's version in both places the + * registry reads it. `version` goes after `description`, where the registry's + * own examples put it; nothing else moves. + * + * @param {Record} entry a committed entry `entryProblems` passed + * @param {string} version + * @returns {Record} + */ +export function stampEntry(entry, version) { + const stamped = {}; + for (const [key, value] of Object.entries(entry)) { + if (key === "packages") + stamped.packages = value.map((pkg) => ({ + registryType: pkg.registryType, + identifier: pkg.identifier, + version, + ...pkg, + })); + else stamped[key] = value; + if (key === "description") stamped.version = version; + } + return stamped; +} + +/** + * Every server's entry, stamped, or the problems that stop any from being + * published. + * + * @param {string} [root] the repository root + * @returns {{ entries: Record>, problems: string[] }} + */ +export function registryEntries(root = repoRoot) { + const { npm, pypi } = expectedPackages(root); + const servers = [ + ...Object.entries(npm).map(([dir, pkg]) => ({ + dir, + registryType: "npm", + pkg, + })), + ...Object.entries(pypi).map(([dir, pkg]) => ({ + dir, + registryType: "pypi", + pkg, + })), + ].sort((a, b) => a.dir.localeCompare(b.dir)); + + const entries = {}; + const problems = []; + for (const { dir, registryType, pkg } of servers) { + const serverDir = path.join(root, "src", dir); + const file = path.join(serverDir, "server.json"); + const label = `src/${dir}/server.json`; + if (!existsSync(file)) { + problems.push( + `${label} is missing: every published server has a registry entry`, + ); + continue; + } + let entry; + try { + entry = JSON.parse(readFileSync(file, "utf8")); + } catch (err) { + problems.push(`${label} does not parse: ${err.message}`); + continue; + } + const found = entryProblems({ + dir, + registryType, + packageName: pkg.name, + marker: packageMarker(serverDir, registryType), + entry, + }); + if (found.length > 0) { + for (const problem of found) problems.push(`${label}: ${problem}`); + continue; + } + entries[dir] = stampEntry(entry, pkg.version); + } + return { entries, problems }; +} + +/** The server name a package claims, read the way the registry will read it. */ +function packageMarker(serverDir, registryType) { + if (registryType === "npm") { + const { mcpName } = JSON.parse( + readFileSync(path.join(serverDir, "package.json"), "utf8"), + ); + return typeof mcpName === "string" ? mcpName : undefined; + } + // Every Python server's `pyproject.toml` declares `readme = "README.md"`, + // which is what PyPI serves as the project description. + const readme = path.join(serverDir, "README.md"); + return existsSync(readme) + ? readmeMarker(readFileSync(readme, "utf8")) + : undefined; +} + +/** + * @param {object} [options] + * @param {string} [options.root] + * @param {NodeJS.ProcessEnv} [options.env] + * @returns {number} the exit code + */ +export function main({ root = repoRoot, env = process.env } = {}) { + const { entries, problems } = registryEntries(root); + if (problems.length > 0) { + console.error( + `mcp-registry-entries: ${problems.length} problem(s) with the MCP Registry entries:\n`, + ); + for (const problem of problems) console.error(` ${problem}`); + return 1; + } + console.log(JSON.stringify(entries, null, 2)); + if (env.GITHUB_OUTPUT) + appendFileSync( + env.GITHUB_OUTPUT, + `mcp_registry=${JSON.stringify(entries)}\n`, + ); + return 0; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) + process.exit(main()); diff --git a/scripts/mcp-registry-entries.test.mjs b/scripts/mcp-registry-entries.test.mjs new file mode 100644 index 0000000000..66f2a3e657 --- /dev/null +++ b/scripts/mcp-registry-entries.test.mjs @@ -0,0 +1,483 @@ +// Tests for `mcp-registry-entries.mjs` (#3047): the rule each committed +// `server.json` must meet, the version stamp, the README marker as the +// registry reads it, and the entries of the repository as it stands. The last +// is the guard: an entry that disagrees with its package fails here, in +// `validate:guards`, instead of at release time. Run via +// `npm run test:scripts`. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + NAMESPACE, + SCHEMA_URL, + entryProblems, + main, + readmeMarker, + registryEntries, + stampEntry, +} from "./mcp-registry-entries.mjs"; +import { expectedPackages } from "./release-manifest.mjs"; + +const NAME = `${NAMESPACE}server-demo`; + +/** A committed entry that meets every rule, for an npm server in `src/demo`. */ +function soundEntry() { + return { + $schema: SCHEMA_URL, + name: NAME, + title: "Demo", + description: "A demonstration server", + repository: { + url: "https://github.com/modelcontextprotocol/servers", + source: "github", + subfolder: "src/demo", + }, + packages: [ + { + registryType: "npm", + identifier: "@modelcontextprotocol/server-demo", + transport: { type: "stdio" }, + }, + ], + }; +} + +/** The problems with `entry` as the npm server in `src/demo`. */ +function problemsWith(entry, overrides = {}) { + return entryProblems({ + dir: "demo", + registryType: "npm", + packageName: "@modelcontextprotocol/server-demo", + marker: NAME, + entry, + ...overrides, + }); +} + +test("entry: a sound entry has no problems", () => { + assert.deepEqual(problemsWith(soundEntry()), []); +}); + +test("entry: something that is not an object is refused outright", () => { + for (const entry of [null, [], "server", 3]) + assert.deepEqual(problemsWith(entry), ["is not a JSON object"]); +}); + +const defects = [ + { + name: "another schema", + edit: (e) => (e.$schema = "https://example.com/server.schema.json"), + expect: /`\$schema` must be/, + }, + { + name: "a name that is not namespace/server", + edit: (e) => (e.name = "server-demo"), + marker: "server-demo", + expect: /`name` must be `\/`/, + }, + { + name: "a name outside the namespace the workflow can prove", + edit: (e) => (e.name = "io.modelcontextprotocol/demo"), + marker: "io.modelcontextprotocol/demo", + expect: /must start with `io\.github\.modelcontextprotocol\/`/, + }, + { + name: "a name the package does not claim", + edit: (e) => (e.name = `${NAMESPACE}server-other`), + expect: + /the package claims "io\.github\.modelcontextprotocol\/server-demo"/, + }, + { + name: "no title", + edit: (e) => delete e.title, + expect: /`title` must be 1 to 100 characters/, + }, + { + name: "a description over the registry's limit", + edit: (e) => (e.description = "x".repeat(101)), + expect: /`description` must be 1 to 100 characters \(it is 101\)/, + }, + { + name: "an empty description", + edit: (e) => (e.description = ""), + expect: /`description` must be 1 to 100 characters \(it is 0\)/, + }, + { + name: "no description", + edit: (e) => delete e.description, + expect: /`description` must be 1 to 100 characters$/, + }, + { + name: "a committed version", + edit: (e) => (e.version = "1.0.0"), + expect: /`version` must not be committed/, + }, + { + name: "a repository pointing at another folder", + edit: (e) => (e.repository.subfolder = "src/other"), + expect: /`repository` must be .*subfolder: src\/demo/, + }, + { + name: "no repository", + edit: (e) => delete e.repository, + expect: /`repository` must be/, + }, + { + name: "a remote", + edit: (e) => + (e.remotes = [{ type: "streamable-http", url: "https://example.com" }]), + expect: /`remotes` is not supported/, + }, + { + name: "no packages", + edit: (e) => delete e.packages, + expect: /`packages` must hold exactly one package/, + }, + { + name: "two packages", + edit: (e) => e.packages.push({ ...e.packages[0] }), + expect: /`packages` must hold exactly one package/, + }, + { + name: "a package that is not an object", + edit: (e) => (e.packages = [null]), + expect: /`packages\[0\]` is not an object/, + }, + { + name: "the wrong package registry", + edit: (e) => (e.packages[0].registryType = "pypi"), + expect: /`packages\[0\]\.registryType` must be `npm`/, + }, + { + name: "another package's identifier", + edit: (e) => (e.packages[0].identifier = "left-pad"), + expect: + /must be the published package, `@modelcontextprotocol\/server-demo`/, + }, + { + name: "a committed package version", + edit: (e) => (e.packages[0].version = "1.0.0"), + expect: /`packages\[0\]\.version` must not be committed/, + }, + { + name: "a registry base URL", + edit: (e) => (e.packages[0].registryBaseUrl = "https://npm.example.com"), + expect: /`packages\[0\]\.registryBaseUrl` must be left out/, + }, + { + name: "a transport other than stdio", + edit: (e) => (e.packages[0].transport = { type: "sse" }), + expect: /`packages\[0\]\.transport\.type` must be `stdio`/, + }, + { + name: "no transport", + edit: (e) => delete e.packages[0].transport, + expect: /`packages\[0\]\.transport\.type` must be `stdio`/, + }, +]; + +// `marker` is what the package claims: by default the sound name, so a case +// that edits the name says what the package claims alongside it. +for (const { name, edit, expect, marker = NAME } of defects) + test(`entry: ${name} is a problem`, () => { + const entry = soundEntry(); + edit(entry); + const problems = problemsWith(entry, { marker }); + assert.equal(problems.length, 1, problems.join("\n")); + assert.match(problems[0], expect); + }); + +test("entry: a package with no marker is a problem, named per registry", () => { + assert.match( + problemsWith(soundEntry(), { marker: undefined })[0], + /its package\.json has no `mcpName`/, + ); + const entry = soundEntry(); + entry.packages[0].registryType = "pypi"; + assert.match( + problemsWith(entry, { registryType: "pypi", marker: undefined })[0], + /its README has no `mcp-name:` marker/, + ); +}); + +test("entry: a PyPI mismatch names the README marker", () => { + const entry = soundEntry(); + entry.packages[0].registryType = "pypi"; + assert.match( + problemsWith(entry, { + registryType: "pypi", + marker: `${NAMESPACE}server-other`, + })[0], + /the `mcp-name:` marker in README\.md/, + ); +}); + +test("entry: every problem is reported, not only the first", () => { + const entry = soundEntry(); + entry.version = "1.0.0"; + entry.description = ""; + entry.packages[0].identifier = "left-pad"; + assert.equal(problemsWith(entry).length, 3); +}); + +test("marker: read from a comment, plain text, or ahead of a tag", () => { + assert.equal(readmeMarker(`# T\n\n\n`), NAME); + assert.equal(readmeMarker(``), NAME); + assert.equal(readmeMarker(`mcp-name: ${NAME}\n`), NAME); + assert.equal(readmeMarker(`mcp-name: ${NAME}`), NAME); + assert.equal(readmeMarker(`

mcp-name: ${NAME}

`), NAME); +}); + +test("marker: a README without one has none", () => { + assert.equal(readmeMarker("# A server\n\nNo marker here.\n"), undefined); +}); + +test("stamp: the version lands after the description and in the package", () => { + const stamped = stampEntry(soundEntry(), "1.2.3"); + assert.deepEqual(Object.keys(stamped), [ + "$schema", + "name", + "title", + "description", + "version", + "repository", + "packages", + ]); + assert.equal(stamped.version, "1.2.3"); + assert.deepEqual(stamped.packages, [ + { + registryType: "npm", + identifier: "@modelcontextprotocol/server-demo", + version: "1.2.3", + transport: { type: "stdio" }, + }, + ]); +}); + +test("stamp: the committed entry is left as it was", () => { + const entry = soundEntry(); + stampEntry(entry, "1.2.3"); + assert.deepEqual(entry, soundEntry()); +}); + +test("repository: every published server has a sound entry at its manifest's version", () => { + const { entries, problems } = registryEntries(); + assert.deepEqual(problems, []); + const { npm, pypi } = expectedPackages(); + const packages = { ...npm, ...pypi }; + assert.deepEqual(Object.keys(entries).sort(), Object.keys(packages).sort()); + for (const [dir, entry] of Object.entries(entries)) { + assert.equal(entry.version, packages[dir].version, dir); + assert.equal(entry.packages[0].version, packages[dir].version, dir); + assert.equal(entry.packages[0].identifier, packages[dir].name, dir); + } +}); + +test("repository: filesystem's entry asks for its allowed directories", () => { + // Without them a 2026-07-28 client starts the server with an empty + // allow-list, so an entry a client builds its launch command from must say + // they are needed, and that there can be several. + const [pkg] = registryEntries().entries.filesystem.packages; + assert.equal(pkg.version, expectedPackages().npm.filesystem.version); + assert.equal(pkg.packageArguments.length, 1); + const [argument] = pkg.packageArguments; + assert.equal(argument.type, "positional"); + assert.equal(argument.format, "filepath"); + assert.equal(argument.isRequired, true); + assert.equal(argument.isRepeated, true); +}); + +test("repository: no two servers share a registry name", () => { + const names = Object.values(registryEntries().entries).map((e) => e.name); + assert.equal(new Set(names).size, names.length); +}); + +/** + * A repository root holding one npm server and one PyPI server, each with a + * sound entry, for the tests to break. + * + * @returns {string} the root; the caller removes it + */ +function fixture() { + const root = mkdtempSync(path.join(tmpdir(), "mcp-registry-")); + const npmDir = path.join(root, "src", "demo"); + mkdirSync(npmDir, { recursive: true }); + writeFileSync( + path.join(npmDir, "package.json"), + JSON.stringify({ + name: "@modelcontextprotocol/server-demo", + version: "1.2.3", + mcpName: NAME, + }), + ); + writeFileSync(path.join(npmDir, "server.json"), JSON.stringify(soundEntry())); + const pyDir = path.join(root, "src", "pydemo"); + mkdirSync(pyDir, { recursive: true }); + writeFileSync( + path.join(pyDir, "pyproject.toml"), + '[project]\nname = "mcp-server-pydemo"\nversion = "2026.1.2"\n', + ); + writeFileSync( + path.join(pyDir, "README.md"), + `# Demo\n\n\n`, + ); + const pyEntry = soundEntry(); + pyEntry.name = `${NAMESPACE}server-pydemo`; + pyEntry.repository.subfolder = "src/pydemo"; + pyEntry.packages[0] = { + registryType: "pypi", + identifier: "mcp-server-pydemo", + transport: { type: "stdio" }, + }; + writeFileSync(path.join(pyDir, "server.json"), JSON.stringify(pyEntry)); + return root; +} + +/** Run `main` with the console captured, so expected errors stay off it. */ +function runMain(options) { + const lines = { out: [], err: [] }; + const { log, error } = console; + console.log = (line) => lines.out.push(line); + console.error = (line) => lines.err.push(line); + try { + return { code: main(options), ...lines }; + } finally { + console.log = log; + console.error = error; + } +} + +test("fixture: both registries' entries are stamped from their manifests", () => { + const root = fixture(); + try { + const { entries, problems } = registryEntries(root); + assert.deepEqual(problems, []); + assert.equal(entries.demo.version, "1.2.3"); + assert.equal(entries.pydemo.version, "2026.1.2"); + assert.equal(entries.pydemo.packages[0].version, "2026.1.2"); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("fixture: a server with no entry is a problem", () => { + const root = fixture(); + try { + rmSync(path.join(root, "src", "demo", "server.json")); + const { entries, problems } = registryEntries(root); + assert.deepEqual(Object.keys(entries), ["pydemo"]); + assert.match(problems[0], /^src\/demo\/server\.json is missing/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("fixture: an entry that is not JSON is a problem", () => { + const root = fixture(); + try { + writeFileSync(path.join(root, "src", "demo", "server.json"), "{ nope"); + const { problems } = registryEntries(root); + assert.match(problems[0], /^src\/demo\/server\.json does not parse/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("fixture: a package.json whose mcpName is gone is a problem", () => { + const root = fixture(); + try { + writeFileSync( + path.join(root, "src", "demo", "package.json"), + JSON.stringify({ + name: "@modelcontextprotocol/server-demo", + version: "1.2.3", + mcpName: 7, + }), + ); + const { problems } = registryEntries(root); + assert.match(problems[0], /package\.json has no `mcpName`/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("fixture: a Python server whose README is gone, or lost its marker, is a problem", () => { + const root = fixture(); + try { + const readme = path.join(root, "src", "pydemo", "README.md"); + writeFileSync(readme, "# Demo\n"); + assert.match( + registryEntries(root).problems[0], + /README has no `mcp-name:` marker/, + ); + rmSync(readme); + assert.match( + registryEntries(root).problems[0], + /README has no `mcp-name:` marker/, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("main: prints the entries and writes the step output", () => { + const root = fixture(); + try { + const output = path.join(root, "github-output"); + writeFileSync(output, ""); + const { code, out } = runMain({ root, env: { GITHUB_OUTPUT: output } }); + assert.equal(code, 0); + const printed = JSON.parse(out.join("\n")); + assert.deepEqual(Object.keys(printed), ["demo", "pydemo"]); + const written = readFileSync(output, "utf8"); + assert.match(written, /^mcp_registry=\{.*\}\n$/); + assert.deepEqual( + JSON.parse(written.slice("mcp_registry=".length)), + printed, + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("main: outside GitHub Actions it only prints", () => { + const root = fixture(); + try { + const { code, out } = runMain({ root, env: {} }); + assert.equal(code, 0); + assert.equal(out.length, 1); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("main: a problem fails the run and writes no output", () => { + const root = fixture(); + try { + const output = path.join(root, "github-output"); + writeFileSync(output, ""); + const file = path.join(root, "src", "demo", "server.json"); + const entry = soundEntry(); + entry.version = "9.9.9"; + writeFileSync(file, JSON.stringify(entry)); + const { code, out, err } = runMain({ + root, + env: { GITHUB_OUTPUT: output }, + }); + assert.equal(code, 1); + assert.deepEqual(out, []); + assert.match(err.join("\n"), /src\/demo\/server\.json: `version` must not/); + assert.equal(readFileSync(output, "utf8"), ""); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/release-mcp-registry.test.mjs b/scripts/release-mcp-registry.test.mjs new file mode 100644 index 0000000000..637dabe43d --- /dev/null +++ b/scripts/release-mcp-registry.test.mjs @@ -0,0 +1,385 @@ +// Regression tests for `release.yml`'s `publish-mcp-registry` job (#3047). +// +// The job lists each server in the official MCP Registry after its package is +// published. It holds an OIDC credential and has no checkout, so, as with the +// dist-tag choice (release-dist-tag.test.mjs), what decides which entries are +// published is shell inside the workflow file, and it runs only when a Release +// is published. These tests read the steps out of the workflow and run THAT +// text, with `curl` and `mcp-publisher` replaced by stubs: nothing here +// reaches the registry or authenticates to it. +// +// They pin what must not regress silently: +// - an entry the registry already lists is skipped, and no token is asked +// for when nothing is missing; +// - an answer that is neither 200 nor 404 fails that entry without +// publishing it, and without stopping the others; +// - one refused entry does not stop the rest, and fails the job; +// - an empty or malformed job output registers nothing; +// - the job's shape: the credential, the environment, its place after the +// package publish legs, no action and no checkout, and a publisher binary +// pinned by version and checksum, verified before it is unpacked. +// +// The steps' shell is bash, so those tests are skipped where there is none. +// Run via `npm run test:scripts`. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { + chmodSync, + 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 { parse } from "yaml"; +import { registryEntries } from "./mcp-registry-entries.mjs"; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); + +const WRITE_STEP = "Write the entries the released commit declares"; +const PUBLISH_STEP = "Publish each entry the registry does not have"; +const DOWNLOAD_STEP = "Download the pinned mcp-publisher"; + +function workflow() { + return parse( + readFileSync( + path.join(repoRoot, ".github", "workflows", "release.yml"), + "utf8", + ), + ); +} + +/** The `publish-mcp-registry` job, as the workflow file declares it. */ +function registryJob() { + const job = workflow().jobs["publish-mcp-registry"]; + assert.ok(job, "release.yml has no publish-mcp-registry job"); + return job; +} + +function step(name) { + const found = registryJob().steps.find((s) => s.name === name); + assert.ok(found, `publish-mcp-registry has no \`${name}\` step`); + return found; +} + +const hasBash = + process.platform !== "win32" && + spawnSync("bash", ["-c", "exit 0"]).status === 0; + +const A = "io.github.modelcontextprotocol/server-a"; +const B = "io.github.modelcontextprotocol/server-b"; +const C = "io.github.modelcontextprotocol/server-c"; + +/** Three entries, in the shape `detect-packages` hands over. */ +function threeEntries() { + return { + a: { name: A, version: "1.0.0", packages: [] }, + b: { name: B, version: "2026.1.2", packages: [] }, + c: { name: C, version: "3.0.0", packages: [] }, + }; +} + +/** + * Run the write step and then the publish step in a scratch directory. + * + * `curl` is a stub that answers each registry lookup from `answers`, keyed by + * the server's name: an HTTP status to print, or `"fail"` to exit non-zero the + * way curl does when it cannot connect. `mcp-publisher` is a stub that logs + * each call and fails a `publish` of any directory in `refuse`. + * + * @param {object} options + * @param {string} [options.entries] the `mcp_registry` output, as text + * @param {Record} [options.answers] + * @param {string[]} [options.refuse] + * @returns {{ write: number | null, publish: number | null, calls: string[], lookups: string[], stdout: string, stderr: string, dir: (file: string) => string | undefined }} + */ +function run({ + entries = JSON.stringify(threeEntries()), + answers = {}, + refuse = [], +} = {}) { + const dir = mkdtempSync(path.join(tmpdir(), "mcp-registry-job-")); + try { + const bin = path.join(dir, "bin"); + mkdirSync(bin); + const lookups = path.join(dir, "lookups.log"); + const calls = path.join(dir, "calls.log"); + // The URL is curl's last argument. The name in it is `%2F`-encoded. + const cases = Object.entries(answers) + .map(([name, answer]) => { + const pattern = `*/v0/servers/${name.replace("/", "%2F")}/versions/*`; + return answer === "fail" + ? ` ${pattern}) printf '000'; exit 7 ;;` + : ` ${pattern}) printf '${answer}' ;;`; + }) + .join("\n"); + writeFileSync( + path.join(bin, "curl"), + `#!/bin/sh\nfor url; do :; done\necho "$url" >> "${lookups}"\ncase "$url" in\n${cases}\n *) printf '404' ;;\nesac\n`, + ); + chmodSync(path.join(bin, "curl"), 0o755); + const refused = refuse + .map((d) => ` "publish entries/${d}/server.json") exit 1 ;;`) + .join("\n"); + writeFileSync( + path.join(dir, "mcp-publisher"), + `#!/bin/sh\necho "$*" >> "${calls}"\ncase "$*" in\n${refused}\n *) exit 0 ;;\nesac\n`, + ); + chmodSync(path.join(dir, "mcp-publisher"), 0o755); + + const env = { + ...process.env, + PATH: `${bin}${path.delimiter}${process.env.PATH}`, + ENTRIES: entries, + }; + const options = { cwd: dir, encoding: "utf8", env }; + const write = spawnSync( + "bash", + ["-e", "-c", step(WRITE_STEP).run], + options, + ); + const publish = + write.status === 0 + ? spawnSync("bash", ["-e", "-c", step(PUBLISH_STEP).run], options) + : { status: null, stdout: "", stderr: "" }; + const lines = (file) => + existsSync(file) + ? readFileSync(file, "utf8").split("\n").filter(Boolean) + : []; + const files = new Map( + ["plan.tsv", "entries/a/server.json"].map((f) => [ + f, + existsSync(path.join(dir, f)) + ? readFileSync(path.join(dir, f), "utf8") + : undefined, + ]), + ); + return { + write: write.status, + publish: publish.status, + calls: lines(calls), + lookups: lines(lookups), + stdout: write.stdout + publish.stdout, + stderr: write.stderr + publish.stderr, + dir: (file) => files.get(file), + }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +const bashTest = (name, fn) => test(name, { skip: !hasBash }, fn); + +bashTest("write: one server.json per entry, and a plan naming each", () => { + const result = run(); + assert.equal(result.write, 0, result.stderr); + assert.equal( + result.dir("plan.tsv"), + `a\t${A}\t1.0.0\nb\t${B}\t2026.1.2\nc\t${C}\t3.0.0\n`, + ); + assert.deepEqual( + JSON.parse(result.dir("entries/a/server.json")), + threeEntries().a, + ); +}); + +bashTest("write: the entries the repository records pass its checks", () => { + const { entries, problems } = registryEntries(); + assert.deepEqual(problems, []); + const result = run({ entries: JSON.stringify(entries) }); + assert.equal(result.write, 0, result.stderr); + assert.equal( + result.dir("plan.tsv").trim().split("\n").length, + Object.keys(entries).length, + ); +}); + +for (const [name, entries] of [ + ["an empty output", ""], + ["an output with no entries", "{}"], + ["an output that is not JSON", "{ nope"], + [ + "a directory that would leave entries/", + JSON.stringify({ "../x": { name: A, version: "1.0.0" } }), + ], + [ + "a name outside this organization's namespace", + JSON.stringify({ a: { name: "io.github.someone/else", version: "1.0.0" } }), + ], + ["an entry with no name", JSON.stringify({ a: { version: "1.0.0" } })], + ["an entry with no version", JSON.stringify({ a: { name: A } })], + [ + "a version that would change the lookup URL", + JSON.stringify({ a: { name: A, version: "1.0.0/../../x" } }), + ], +]) + bashTest(`write: ${name} registers nothing`, () => { + const result = run({ entries }); + assert.notEqual(result.write, 0); + assert.equal(result.publish, null); + assert.deepEqual(result.calls, []); + assert.deepEqual(result.lookups, []); + }); + +bashTest("publish: every missing entry is published, after one login", () => { + const result = run(); + assert.equal(result.publish, 0, result.stderr); + assert.deepEqual(result.calls, [ + "login github-oidc", + "publish entries/a/server.json", + "publish entries/b/server.json", + "publish entries/c/server.json", + ]); + assert.deepEqual(result.lookups, [ + "https://registry.modelcontextprotocol.io/v0/servers/io.github.modelcontextprotocol%2Fserver-a/versions/1.0.0", + "https://registry.modelcontextprotocol.io/v0/servers/io.github.modelcontextprotocol%2Fserver-b/versions/2026.1.2", + "https://registry.modelcontextprotocol.io/v0/servers/io.github.modelcontextprotocol%2Fserver-c/versions/3.0.0", + ]); +}); + +bashTest("publish: an entry the registry already lists is skipped", () => { + const result = run({ answers: { [B]: "200" } }); + assert.equal(result.publish, 0, result.stderr); + assert.deepEqual(result.calls, [ + "login github-oidc", + "publish entries/a/server.json", + "publish entries/c/server.json", + ]); + assert.match( + result.stdout, + /server-b@2026\.1\.2 is already in the MCP Registry/, + ); +}); + +bashTest("publish: with nothing missing, no token is asked for", () => { + const result = run({ answers: { [A]: "200", [B]: "200", [C]: "200" } }); + assert.equal(result.publish, 0, result.stderr); + assert.deepEqual(result.calls, []); +}); + +for (const [name, answer] of [ + ["a server error", "500"], + ["a rate limit", "429"], + ["a redirect", "302"], + ["no answer at all", "fail"], +]) + bashTest(`publish: ${name} fails that entry without publishing it`, () => { + const result = run({ answers: { [B]: answer } }); + assert.equal(result.publish, 1); + assert.deepEqual(result.calls, [ + "login github-oidc", + "publish entries/a/server.json", + "publish entries/c/server.json", + ]); + assert.match( + result.stdout, + /::error::Could not tell whether .*server-b@2026\.1\.2 is in the MCP Registry/, + ); + }); + +bashTest( + "publish: unreadable answers and nothing missing still fail, with no login", + () => { + const result = run({ answers: { [A]: "200", [B]: "503", [C]: "200" } }); + assert.equal(result.publish, 1); + assert.deepEqual(result.calls, []); + }, +); + +bashTest( + "publish: one refused entry does not stop the rest, and fails the job", + () => { + const result = run({ refuse: ["a"] }); + assert.equal(result.publish, 1); + assert.deepEqual(result.calls, [ + "login github-oidc", + "publish entries/a/server.json", + "publish entries/b/server.json", + "publish entries/c/server.json", + ]); + assert.match( + result.stdout, + /::error::The MCP Registry refused the entry for src\/a/, + ); + assert.match(result.stdout, /Registered src\/b\./); + }, +); + +test("shape: the job holds the credential and waits for the release environment", () => { + const job = registryJob(); + assert.deepEqual(job.permissions, { "id-token": "write" }); + assert.equal(job.environment, "release"); + assert.equal(typeof job["timeout-minutes"], "number"); +}); + +test("shape: it runs after both sets of package publish legs, whatever their result", () => { + const job = registryJob(); + assert.deepEqual([...job.needs].sort(), [ + "detect-packages", + "publish-npm", + "publish-pypi", + ]); + assert.match(job.if, /!cancelled\(\)/); + assert.match(job.if, /needs\.detect-packages\.result == 'success'/); +}); + +test("shape: it runs no action, so no checkout and no dependency install", () => { + for (const s of registryJob().steps) { + assert.equal(s.uses, undefined, `step \`${s.name}\` uses an action`); + assert.doesNotMatch(s.run, /\bnpm (ci|install|i)\b|\bnpx\b|\bpip\b|\buv\b/); + } +}); + +test("shape: the entries come from detect-packages, as a job output", () => { + const detect = workflow().jobs["detect-packages"]; + assert.equal( + detect.outputs.mcp_registry, + "${{ steps.registry.outputs.mcp_registry }}", + ); + const record = detect.steps.find((s) => s.id === "registry"); + assert.ok(record, "detect-packages has no step with id `registry`"); + assert.equal(record.run, "node scripts/mcp-registry-entries.mjs"); + assert.equal( + step(WRITE_STEP).env.ENTRIES, + "${{ needs.detect-packages.outputs.mcp_registry }}", + ); +}); + +test("shape: the publisher is pinned by release and checksum, verified before it is unpacked", () => { + const job = registryJob(); + assert.match(job.env.MCP_PUBLISHER_VERSION, /^v\d+\.\d+\.\d+$/); + assert.match(job.env.MCP_PUBLISHER_SHA256, /^[a-f0-9]{64}$/); + const { run: script } = step(DOWNLOAD_STEP); + assert.match( + script, + /github\.com\/modelcontextprotocol\/registry\/releases\/download\/\$MCP_PUBLISHER_VERSION\//, + ); + assert.doesNotMatch(script, /releases\/latest/); + const check = script.indexOf("sha256sum --check --strict"); + const unpack = script.indexOf("tar -xzf"); + assert.ok(check !== -1, "the download step no longer checks the archive"); + assert.ok( + check < unpack, + "the archive must be checked before it is unpacked", + ); + assert.match(script, /\$MCP_PUBLISHER_SHA256 {2}\$ARCHIVE/); +}); + +test("shape: the download comes first, and the only login is github-oidc", () => { + const steps = registryJob().steps; + assert.equal(steps[0].name, DOWNLOAD_STEP); + const logins = steps.flatMap( + (s) => s.run.match(/mcp-publisher login \S+/g) ?? [], + ); + assert.deepEqual(logins, ["mcp-publisher login github-oidc"]); + for (const s of steps) assert.doesNotMatch(s.run, /secrets\./); +}); diff --git a/scripts/version-pr-ci.test.mjs b/scripts/version-pr-ci.test.mjs index 31bd4ed19c..c8667c0f25 100644 --- a/scripts/version-pr-ci.test.mjs +++ b/scripts/version-pr-ci.test.mjs @@ -4,7 +4,7 @@ // The Version Packages and Prepare Python Release workflows push their PR // branches with the workflow token, which starts no workflow (GitHub holds a // `pull_request` run as `action_required`), so they dispatch `typescript.yml`, -// `python.yml`, `dco.yml` and `everything-mcp-diff.yml` on the branch instead. A dispatched run's checks are left out of the +// `python.yml`, `dco.yml` and `mcp-interface-diff.yml` on the branch instead. A dispatched run's checks are left out of the // status rollup a pull request reads, so each dispatched workflow also mirrors // its run onto the commit as a status. Both version workflows run only from `v2/main`, so nothing // exercises this path before a release needs it; if any link here breaks, @@ -17,6 +17,7 @@ import { spawnSync } from "node:child_process"; import { chmodSync, mkdtempSync, + readdirSync, readFileSync, rmSync, writeFileSync, @@ -48,7 +49,7 @@ const CI = [ trigger: "pull_request", }, { - file: "everything-mcp-diff.yml", + file: "mcp-interface-diff.yml", context: "Interface diff (dispatched)", trigger: "pull_request", }, @@ -63,7 +64,7 @@ const VERSION_WORKFLOWS = [ "typescript.yml", "python.yml", "dco.yml", - "everything-mcp-diff.yml", + "mcp-interface-diff.yml", ], }, { @@ -73,7 +74,7 @@ const VERSION_WORKFLOWS = [ "typescript.yml", "python.yml", "dco.yml", - "everything-mcp-diff.yml", + "mcp-interface-diff.yml", ], }, ]; @@ -258,17 +259,34 @@ test("RELEASING.md names the statuses a version PR is merged on", () => { assert.doesNotMatch(releasing, /Close and reopen the PR to run CI/); }); -// #5463 (Step 1 of a staged rename): `mcp-interface-diff.yml` exists so the -// name is on `main` before #5527 (Step 2) points the version workflows at it. -// Until then it must not run beside the real diff on a push or a pull -// request, and nothing may dispatch it yet: the version workflows keep -// dispatching `everything-mcp-diff.yml` (pinned in VERSION_WORKFLOWS above). -test("mcp-interface-diff.yml is a dispatch-only placeholder until Step 2", () => { - const wf = workflow("mcp-interface-diff.yml"); - assert.deepEqual(Object.keys(wf.on), ["workflow_dispatch"]); - for (const { file } of VERSION_WORKFLOWS) +// #5527 (Step 2 of the rename staged in #5463): the interface diff lives in +// `mcp-interface-diff.yml`, and the old `everything-mcp-diff.yml` is gone. A +// leftover copy would run a second diff on every push and pull request, and a +// leftover reference would dispatch, or list the runs of, a workflow that no +// longer exists on `v2/main`: `gh workflow run` fails the version workflow's +// step, and a `gh run list` on a missing workflow reads as "no newer run". +test("the interface diff is mcp-interface-diff.yml, and the old name is gone", () => { + const dir = path.join(repoRoot, ".github/workflows"); + const files = readdirSync(dir); + assert.ok(!files.includes("everything-mcp-diff.yml"), "the old file"); + // Comment lines may name the old file (this workflow's header records the + // rename); nothing a runner executes may. + for (const file of files) { + const live = readFileSync(path.join(dir, file), "utf8") + .split("\n") + .filter((line) => !line.trimStart().startsWith("#")) + .join("\n"); assert.ok( - !read(`.github/workflows/${file}`).includes("mcp-interface-diff.yml"), - `${file} does not dispatch the placeholder yet`, + !live.includes("everything-mcp-diff.yml"), + `${file} names the old file`, ); + } + // The real diff, not the Step 1 placeholder: it runs on every event the + // old file did. + assert.deepEqual(Object.keys(workflow("mcp-interface-diff.yml").on).sort(), [ + "pull_request", + "push", + "release", + "workflow_dispatch", + ]); }); diff --git a/src/everything/CHANGELOG.md b/src/everything/CHANGELOG.md index 1ce679f52a..d64be167f5 100644 --- a/src/everything/CHANGELOG.md +++ b/src/everything/CHANGELOG.md @@ -1,5 +1,13 @@ # @modelcontextprotocol/server-everything +## 2.4.0 + +### Minor Changes + +- [#5652](https://github.com/modelcontextprotocol/servers/pull/5652) [`21f18cb`](https://github.com/modelcontextprotocol/servers/commit/21f18cb4c695893f644d29ec512edf9e4d41c9df) [@cliffhall](https://github.com/cliffhall) - Serve the Events extension (`io.modelcontextprotocol/events`, SEP-3415) on protocol version 2026-07-28: `events/list`, `events/poll` and `events/stream`, with a replayable `clock-tick` event type (poll and push) and an emit-only `custom-event` (push), raised by the new `trigger-event` tool. Webhook delivery is not offered. + +- [#5630](https://github.com/modelcontextprotocol/servers/pull/5630) [`a1137b8`](https://github.com/modelcontextprotocol/servers/commit/a1137b8e3be028baa193e4c03d396c6e78ec78ef) [@cliffhall](https://github.com/cliffhall) - The Streamable HTTP transport now evicts a 2025-era session that has been idle for 30 minutes: one with no request in flight and no stream open. Until now a session whose client never sent a DELETE stayed in memory, with its server instance, for the life of the process. An evicted session's next request is answered `404 Session not found`, the spec's signal for the client to initialize again. Set the new `SESSION_IDLE_TIMEOUT_MILLIS` environment variable to change the timeout, or to `0` to keep sessions until their client ends them. 2026-07-28 clients have no sessions and are unaffected. Thanks to [Pierpaolo1223](https://github.com/Pierpaolo1223) for the report and the measurements in [#5558](https://github.com/modelcontextprotocol/servers/issues/5558). + ## 2.3.1 ### Patch Changes diff --git a/src/everything/README.md b/src/everything/README.md index 0d597af143..1689bd8b74 100644 --- a/src/everything/README.md +++ b/src/everything/README.md @@ -23,7 +23,7 @@ The `get-env` tool returns the server's environment variables, but masks the val The server serves both protocol eras, over stdio and Streamable HTTP, from one process: -- **2026-07-28** clients connect with `server/discover`, send their protocol version, identity and capabilities with each request, and have no session. The server demonstrates the revision's new features for them: multi-round-trip requests (`input_required`) with `requestState`, `subscriptions/listen` change notifications, per-request log levels, cache hints (`ttlMs` / `cacheScope`), the tasks extension (`io.modelcontextprotocol/tasks`) under the `extensions` capability, and `x-mcp-header` with JSON Schema 2020-12 tool schemas. +- **2026-07-28** clients connect with `server/discover`, send their protocol version, identity and capabilities with each request, and have no session. The server demonstrates the revision's new features for them: multi-round-trip requests (`input_required`) with `requestState`, `subscriptions/listen` change notifications, per-request log levels, cache hints (`ttlMs` / `cacheScope`), the tasks (`io.modelcontextprotocol/tasks`) and events (`io.modelcontextprotocol/events`, poll and push delivery) extensions under the `extensions` capability, and `x-mcp-header` with JSON Schema 2020-12 tool schemas. - **2025-era** clients connect with the `initialize` handshake, as before. Elicitation, sampling and roots are served to them from the same multi-round-trip handlers through the SDK's legacy shim. Roots, sampling and logging are deprecated as of 2026-07-28 and stay available, labelled deprecated. [Server Features](docs/features.md) marks which era each feature belongs to. @@ -133,6 +133,9 @@ Both HTTP transports (Streamable HTTP and HTTP+SSE) listen on the loopback inter | --- | --- | --- | | `PORT` | `3001` | The port the HTTP transport listens on | | `HOST` | `127.0.0.1` | The address it binds; `0.0.0.0` (or `::`) for every interface | +| `SESSION_IDLE_TIMEOUT_MILLIS` | `1800000` (30 minutes) | Streamable HTTP only: how long a 2025-era session may sit idle before the server ends it; `0` never ends one | + +A 2025-era Streamable HTTP session normally ends when its client sends a `DELETE`. One whose client goes away without doing so is ended by the server once it has been idle for `SESSION_IDLE_TIMEOUT_MILLIS`: its server instance is closed and its timers and subscriptions are released. Idle means no request in flight and no stream open, so a client that keeps its `GET` stream open, or is waiting on a long tool call, is never timed out; the clock starts when the session's last response closes, and idle sessions are looked for every tenth of the timeout (no less than a second and no more than a minute apart), so one is ended that much late at most. A request for a session the server has ended is answered `404 Not Found` (`Session not found`), which is the [specification's signal](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management) for the client to start a new session with a fresh `initialize`. Set a short timeout to exercise that path in a client under test, or `0` to keep every session until its client ends it. A value that is not a non-negative number is ignored in favor of the default. 2026-07-28 clients have no sessions, and an HTTP+SSE session ends when its stream's connection closes, so neither is affected. Both HTTP transports (Streamable HTTP and HTTP+SSE) accept browser requests only from a localhost origin: an `Origin` header whose host is `localhost`, `127.0.0.1` or `[::1]`, on any port, such as the MCP Inspector's. A request carrying any other `Origin` is refused with `403 Forbidden`. Clients that send no `Origin` header, which is every non-browser client, are unaffected. diff --git a/src/everything/__tests__/events.test.ts b/src/everything/__tests__/events.test.ts new file mode 100644 index 0000000000..f2d3d3d129 --- /dev/null +++ b/src/everything/__tests__/events.test.ts @@ -0,0 +1,808 @@ +/** + * Protocol-level tests for the Events extension (`io.modelcontextprotocol/events`, + * SEP-3415) on protocol version 2026-07-28 (#5651). + * + * The SDK client has no Events helpers, so every test drives the server with + * raw JSON-RPC through `connectRaw`, which records the notifications a push + * stream sends. The clock is faked: `clock-tick` occurrences are computed from + * it, and a push stream's heartbeat and tick timers run on it, so the tests + * step time instead of waiting for it and need no retries. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; +import { + connect, + connectRaw, + type RawSession, + type Session, +} from "./harness.js"; +import { + DEFAULT_HEARTBEAT_MS, + EVENTS_EXTENSION, + MAX_HEARTBEAT_MS, + MAX_STREAMS, + MIN_HEARTBEAT_MS, + PushStream, + RETAINED_TICKS, + SUBSCRIPTION_ID_META_KEY, + TICK_PERIOD_MS, + resetEvents, +} from "../server/events.js"; + +type Json = Record; + +/** The client declares the extension, as the spec says it MAY. */ +const CAPABILITIES = { extensions: { [EVENTS_EXTENSION]: {} } }; + +/** The tick that has just happened when each test starts. */ +const HEAD = 360_000_003; +/** Each test starts this far into the tick period after HEAD. */ +const OFFSET_MS = 2_000; + +const cursor = (tick: number) => `clock-tick:${tick}`; + +const open: Array<{ close: () => Promise }> = []; + +async function raw(): Promise { + const session = await connectRaw(CAPABILITIES); + open.push(session); + return session; +} + +async function legacy(): Promise { + const session = await connect(); + open.push(session); + return session; +} + +/** Let queued messages cross the in-memory transport. */ +const settle = () => vi.advanceTimersByTimeAsync(0); + +/** The notifications with this method, and their params. */ +function sent(session: RawSession, method: string): Json[] { + return session.notifications + .filter((n) => n.method === method) + .map((n) => n.params as Json); +} + +/** The `events/*` notifications, as `[method, params]` pairs. */ +function eventNotifications(session: RawSession): Array<[string, Json]> { + return session.notifications + .filter((n) => String(n.method).startsWith("notifications/events/")) + .map((n) => [String(n.method), n.params as Json]); +} + +/** The error of a response that must fail. */ +async function errorOf( + session: RawSession, + method: string, + params: Json = {}, +): Promise { + const response = await session.request(method, params); + expect(response.result).toBeUndefined(); + return response.error as Json; +} + +/** The text of a tools/call result. */ +function textOfCall(result: Json): string { + return (result.content as Array<{ text: string }>)[0].text; +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + vi.setSystemTime(HEAD * TICK_PERIOD_MS + OFFSET_MS); +}); + +afterEach(async () => { + for (const session of open.splice(0)) await session.close(); + resetEvents(); + vi.useRealTimers(); +}); + +describe("discovery", () => { + it("advertises the extension in server/discover", async () => { + const session = await raw(); + const discover = await session.result("server/discover"); + expect( + (discover.capabilities as { extensions: Json }).extensions, + ).toMatchObject({ [EVENTS_EXTENSION]: {} }); + }); + + it("lists both event types with their delivery modes and schemas", async () => { + const session = await raw(); + const list = await session.result("events/list"); + expect(list.resultType).toBe("complete"); + expect(list.nextCursor).toBeUndefined(); + const events = list.events as Json[]; + expect(events.map((e) => [e.name, e.delivery])).toEqual([ + ["clock-tick", ["poll", "push"]], + ["custom-event", ["push"]], + ]); + const [clockTick, customEvent] = events; + expect(clockTick.inputSchema).toMatchObject({ + type: "object", + properties: { + everyNth: { type: "integer", default: 1 }, + label: { type: "string" }, + }, + additionalProperties: false, + }); + expect(clockTick.payloadSchema).toMatchObject({ + type: "object", + properties: { tick: { type: "integer" }, label: { type: "string" } }, + required: ["tick"], + }); + expect(clockTick.inputSchema).not.toHaveProperty("$schema"); + expect(customEvent.inputSchema).toMatchObject({ + properties: { + minSeverity: { enum: ["info", "warning", "error"], default: "info" }, + }, + }); + expect(customEvent.payloadSchema).toMatchObject({ + required: ["message", "severity"], + }); + }); + + it("refuses an events/list cursor it never minted", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/list", { cursor: "page-2" }), + ).toMatchObject({ code: -32602 }); + }); + + it("does not serve events/* to a 2025-era client (-32601)", async () => { + const session = await legacy(); + expect(session.client.getServerCapabilities()?.extensions).toBeUndefined(); + await expect( + session.client.request( + { method: "events/list", params: {} }, + z.looseObject({}), + ), + ).rejects.toMatchObject({ code: -32601 }); + }); + + it("offers no webhook delivery: events/subscribe and events/unsubscribe are not served", async () => { + const session = await raw(); + const params = { name: "clock-tick", arguments: {} }; + expect(await errorOf(session, "events/subscribe", params)).toMatchObject({ + code: -32601, + }); + expect(await errorOf(session, "events/unsubscribe", params)).toMatchObject({ + code: -32601, + }); + }); +}); + +describe("events/poll", () => { + it("bootstraps with a null cursor: no events and the current position", async () => { + const session = await raw(); + for (const params of [{ cursor: null }, {}]) { + const poll = await session.result("events/poll", { + name: "clock-tick", + ...params, + }); + expect(poll).toMatchObject({ + resultType: "complete", + events: [], + cursor: cursor(HEAD), + truncated: false, + hasMore: false, + nextPollMs: TICK_PERIOD_MS - OFFSET_MS, + }); + } + }); + + it("replays the ticks after the cursor, each with a stable eventId", async () => { + const session = await raw(); + const poll = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 2), + }); + expect(poll.events).toEqual([ + { + eventId: `tick-${HEAD - 1}`, + name: "clock-tick", + timestamp: new Date((HEAD - 1) * TICK_PERIOD_MS).toISOString(), + data: { tick: HEAD - 1 }, + }, + { + eventId: `tick-${HEAD}`, + name: "clock-tick", + timestamp: new Date(HEAD * TICK_PERIOD_MS).toISOString(), + data: { tick: HEAD }, + }, + ]); + expect(poll).toMatchObject({ + cursor: cursor(HEAD), + truncated: false, + hasMore: false, + }); + + // Polling again from the returned cursor finds nothing new until the + // next tick, and then exactly that tick. + const quiet = await session.result("events/poll", { + name: "clock-tick", + cursor: poll.cursor, + }); + expect(quiet.events).toEqual([]); + vi.advanceTimersByTime(TICK_PERIOD_MS); + const next = await session.result("events/poll", { + name: "clock-tick", + cursor: poll.cursor, + }); + expect((next.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD + 1}`, + ]); + }); + + it("caps a batch at maxEvents and reports the backlog with hasMore", async () => { + const session = await raw(); + const first = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 5), + maxEvents: 2, + }); + expect((first.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD - 4}`, + `tick-${HEAD - 3}`, + ]); + expect(first).toMatchObject({ + cursor: cursor(HEAD - 3), + hasMore: true, + nextPollMs: 0, + }); + + const rest = await session.result("events/poll", { + name: "clock-tick", + cursor: first.cursor, + maxEvents: 10, + }); + expect((rest.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD - 2}`, + `tick-${HEAD - 1}`, + `tick-${HEAD}`, + ]); + expect(rest).toMatchObject({ cursor: cursor(HEAD), hasMore: false }); + }); + + it("filters with everyNth and transforms with label", async () => { + const session = await raw(); + // HEAD - 8 and HEAD - 3 are the multiples of 5 in the last ten ticks. + const poll = await session.result("events/poll", { + name: "clock-tick", + arguments: { everyNth: 5, label: "five" }, + cursor: cursor(HEAD - 10), + }); + expect(poll.events).toEqual([ + expect.objectContaining({ data: { tick: HEAD - 8, label: "five" } }), + expect.objectContaining({ data: { tick: HEAD - 3, label: "five" } }), + ]); + // The cursor advances past ticks the filter skipped. + expect(poll).toMatchObject({ cursor: cursor(HEAD), hasMore: false }); + + // hasMore counts only ticks that would be delivered. + const capped = await session.result("events/poll", { + name: "clock-tick", + arguments: { everyNth: 5 }, + cursor: cursor(HEAD - 10), + maxEvents: 1, + }); + expect(capped).toMatchObject({ cursor: cursor(HEAD - 8), hasMore: true }); + }); + + it("replays at most the retained ticks, and says it skipped some", async () => { + const session = await raw(); + const poll = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 500), + maxEvents: 200, + }); + const events = poll.events as Json[]; + expect(events).toHaveLength(RETAINED_TICKS); + expect(events[0].eventId).toBe(`tick-${HEAD - RETAINED_TICKS + 1}`); + expect(poll).toMatchObject({ truncated: true, hasMore: false }); + }); + + it("returns at most 100 events however large maxEvents is, and 50 by default", async () => { + const session = await raw(); + const large = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 150), + maxEvents: 1_000, + }); + expect(large.events as Json[]).toHaveLength(100); + const byDefault = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 90), + }); + expect(byDefault.events as Json[]).toHaveLength(50); + expect(byDefault.hasMore).toBe(true); + }); + + it("starts no earlier than maxAgeMs, and says so when that skips events", async () => { + const session = await raw(); + // now - 12 s falls 2 s after tick HEAD - 2's start, so replay starts there. + const poll = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 10), + maxAgeMs: 12_000, + }); + expect((poll.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD - 2}`, + `tick-${HEAD - 1}`, + `tick-${HEAD}`, + ]); + expect(poll.truncated).toBe(true); + + // A floor older than the cursor skips nothing. + const wide = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 2), + maxAgeMs: 3_600_000, + }); + expect(wide).toMatchObject({ truncated: false }); + expect(wide.events as Json[]).toHaveLength(2); + + // maxAgeMs is ignored with a null cursor, which already means now. + const fresh = await session.result("events/poll", { + name: "clock-tick", + cursor: null, + maxAgeMs: 0, + }); + expect(fresh).toMatchObject({ events: [], truncated: false }); + }); + + it("refuses a cursor it never minted", async () => { + const session = await raw(); + for (const bad of ["garbage", cursor(HEAD + 1), "clock-tick:-1"]) { + expect( + await errorOf(session, "events/poll", { + name: "clock-tick", + cursor: bad, + }), + ).toMatchObject({ code: -32602, message: expect.stringContaining(bad) }); + } + }); + + it("answers an unknown event type with NotFound (-32023)", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/poll", { name: "no-such-event" }), + ).toEqual({ + code: -32023, + message: "Unknown event type: no-such-event", + data: { kind: "event" }, + }); + }); + + it("answers a delivery mode the type does not offer with Unsupported (-32026)", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/poll", { name: "custom-event" }), + ).toMatchObject({ + code: -32026, + data: { feature: "deliveryMode", value: "poll" }, + }); + }); + + it("answers arguments that do not match the inputSchema with InvalidParams", async () => { + const session = await raw(); + for (const args of [{ bogus: 1 }, { everyNth: 0 }, { label: 7 }]) { + expect( + await errorOf(session, "events/poll", { + name: "clock-tick", + arguments: args, + }), + ).toMatchObject({ code: -32602 }); + } + }); +}); + +describe("events/stream: clock-tick", () => { + it("confirms, replays, delivers each tick and heartbeats in between, all tagged with the request id", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + cursor: cursor(HEAD - 2), + heartbeatMs: 2_000, + arguments: { label: "push" }, + }); + const id = session.lastRequestId(); + await settle(); + + // active first, then the replayed backlog. + expect(eventNotifications(session)).toEqual([ + [ + "notifications/events/active", + { + cursor: cursor(HEAD - 2), + truncated: false, + heartbeatMs: 2_000, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ], + [ + "notifications/events/event", + expect.objectContaining({ + eventId: `tick-${HEAD - 1}`, + data: { tick: HEAD - 1, label: "push" }, + cursor: cursor(HEAD - 1), + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }), + ], + [ + "notifications/events/event", + expect.objectContaining({ + eventId: `tick-${HEAD}`, + cursor: cursor(HEAD), + }), + ], + ]); + + // 2 s of silence brings a heartbeat carrying the position checked up to. + await vi.advanceTimersByTimeAsync(2_000); + expect(sent(session, "notifications/events/heartbeat")).toEqual([ + { cursor: cursor(HEAD), _meta: { [SUBSCRIPTION_ID_META_KEY]: id } }, + ]); + + // The next tick arrives on time. + await vi.advanceTimersByTimeAsync(1_000); + expect(sent(session, "notifications/events/event").at(-1)).toMatchObject({ + eventId: `tick-${HEAD + 1}`, + cursor: cursor(HEAD + 1), + }); + }); + + it("starts from now with a null cursor, and advances the heartbeat cursor over filtered ticks", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + heartbeatMs: 1_000, + arguments: { everyNth: 1_000 }, + }); + await settle(); + expect(sent(session, "notifications/events/active")).toEqual([ + expect.objectContaining({ cursor: cursor(HEAD), truncated: false }), + ]); + await vi.advanceTimersByTimeAsync(TICK_PERIOD_MS * 2); + expect(sent(session, "notifications/events/event")).toEqual([]); + expect(sent(session, "notifications/events/heartbeat").at(-1)).toEqual( + expect.objectContaining({ cursor: cursor(HEAD + 2) }), + ); + }); + + it("replays no more than the retained ticks when its timer fires late, and reports the gap", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + heartbeatMs: MAX_HEARTBEAT_MS, + }); + await settle(); + // The process sleeps through 1000 ticks: the clock jumps, and the tick + // timer fires once, late. + // (Faking the clock moves Date but not the timer queue, so the jump is + // set short by the time left until the timer is due.) + const untilDue = TICK_PERIOD_MS - OFFSET_MS; + vi.setSystemTime((HEAD + 1_000) * TICK_PERIOD_MS + OFFSET_MS - untilDue); + await vi.advanceTimersByTimeAsync(untilDue); + expect(sent(session, "notifications/events/active")).toEqual([ + expect.objectContaining({ cursor: cursor(HEAD), truncated: false }), + expect.objectContaining({ + cursor: cursor(HEAD + 1_000 - RETAINED_TICKS), + truncated: true, + heartbeatMs: MAX_HEARTBEAT_MS, + }), + ]); + const events = sent(session, "notifications/events/event"); + expect(events).toHaveLength(RETAINED_TICKS); + expect(events[0].eventId).toBe(`tick-${HEAD + 1_000 - RETAINED_TICKS + 1}`); + }); + + it("reports a cursor outside the retained window as truncated on active", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + cursor: cursor(HEAD - 1_000), + }); + await settle(); + expect(sent(session, "notifications/events/active")).toEqual([ + expect.objectContaining({ + cursor: cursor(HEAD - RETAINED_TICKS), + truncated: true, + heartbeatMs: DEFAULT_HEARTBEAT_MS, + }), + ]); + expect(sent(session, "notifications/events/event")).toHaveLength( + RETAINED_TICKS, + ); + }); + + it("clamps the suggested heartbeat interval to the server's bounds", async () => { + const session = await raw(); + for (const heartbeatMs of [1, 10_000_000]) { + void session.request("events/stream", { + name: "clock-tick", + heartbeatMs, + }); + } + await settle(); + expect( + sent(session, "notifications/events/active").map((p) => p.heartbeatMs), + ).toEqual([MIN_HEARTBEAT_MS, MAX_HEARTBEAT_MS]); + }); + + it("stops delivering when the client cancels, and sends no response", async () => { + const session = await raw(); + const response = vi.fn(); + void session + .request("events/stream", { name: "clock-tick", heartbeatMs: 1_000 }) + .then(response); + const id = session.lastRequestId(); + await settle(); + await session.notify("notifications/cancelled", { requestId: id }); + await settle(); + const count = session.notifications.length; + await vi.advanceTimersByTimeAsync(TICK_PERIOD_MS * 3); + expect(session.notifications).toHaveLength(count); + expect(response).not.toHaveBeenCalled(); + }); + + it("refuses an invalid subscription with an error and opens no stream", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/stream", { + name: "clock-tick", + arguments: { everyNth: "often" }, + }), + ).toMatchObject({ code: -32602 }); + expect( + await errorOf(session, "events/stream", { + name: "clock-tick", + cursor: "garbage", + }), + ).toMatchObject({ code: -32602 }); + expect( + await errorOf(session, "events/stream", { name: "nope" }), + ).toMatchObject({ code: -32023 }); + expect(eventNotifications(session)).toEqual([]); + }); +}); + +describe("events/stream: custom-event and trigger-event", () => { + it("delivers what trigger-event raises, filtered by minSeverity, with a null cursor", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "custom-event", + arguments: { minSeverity: "warning" }, + heartbeatMs: 5_000, + }); + const id = session.lastRequestId(); + await settle(); + expect(sent(session, "notifications/events/active")).toEqual([ + { + cursor: null, + truncated: false, + heartbeatMs: 5_000, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ]); + + const info = await session.call("trigger-event", { message: "quiet" }); + expect(textOfCall(info)).toBe( + "Sent custom-event (info) to 1 open custom-event stream", + ); + await session.call("trigger-event", { + message: "loud", + severity: "warning", + }); + await settle(); + const events = sent(session, "notifications/events/event"); + expect(events).toEqual([ + { + eventId: expect.stringMatching(/^custom-[0-9a-f-]{36}$/), + name: "custom-event", + timestamp: new Date().toISOString(), + data: { message: "loud", severity: "warning" }, + cursor: null, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ]); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sent(session, "notifications/events/heartbeat")).toEqual([ + { cursor: null, _meta: { [SUBSCRIPTION_ID_META_KEY]: id } }, + ]); + }); + + it("reaches streams opened through another connection", async () => { + const listener = await raw(); + const caller = await raw(); + void listener.request("events/stream", { name: "custom-event" }); + void listener.request("events/stream", { name: "custom-event" }); + await settle(); + const result = await caller.call("trigger-event", {}); + expect(textOfCall(result)).toBe( + "Sent custom-event (info) to 2 open custom-event streams", + ); + await settle(); + // One occurrence: the same eventId and timestamp on every subscription. + const [first, second] = sent(listener, "notifications/events/event"); + expect(second.eventId).toBe(first.eventId); + expect(second.timestamp).toBe(first.timestamp); + expect(second._meta).not.toEqual(first._meta); + + // A second call is a new occurrence. + await caller.call("trigger-event", {}); + await settle(); + expect(sent(listener, "notifications/events/event")[2].eventId).not.toBe( + first.eventId, + ); + }); + + it("sends a recoverable error and keeps the stream open", async () => { + const session = await raw(); + void session.request("events/stream", { name: "custom-event" }); + await settle(); + const result = await session.call("trigger-event", { + kind: "error", + message: "upstream 503", + }); + expect(textOfCall(result)).toBe( + "Sent notifications/events/error to 1 open custom-event stream", + ); + await settle(); + expect(sent(session, "notifications/events/error")).toEqual([ + expect.objectContaining({ + error: { + code: -32603, + message: "UpstreamError", + data: { reason: "upstream 503" }, + }, + }), + ]); + await session.call("trigger-event", {}); + await settle(); + expect(sent(session, "notifications/events/event")).toHaveLength(1); + }); + + it("terminates the subscription and ends the stream with an empty result", async () => { + const session = await raw(); + const stream = session.request("events/stream", { name: "custom-event" }); + const id = session.lastRequestId(); + await settle(); + const result = await session.call("trigger-event", { + kind: "terminate", + message: "access revoked", + }); + expect(textOfCall(result)).toBe( + "Sent notifications/events/terminated to 1 open custom-event stream", + ); + expect(sent(session, "notifications/events/terminated")).toEqual([ + { + error: { + code: -32024, + message: "Forbidden", + data: { reason: "access revoked" }, + }, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ]); + const response = await stream; + expect(response.result).toMatchObject({ + resultType: "complete", + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }); + + // The subscription is gone. + const after = await session.call("trigger-event", {}); + expect(textOfCall(after)).toBe( + "Sent custom-event (info) to 0 open custom-event streams", + ); + }); + + it("closes a connection's streams when the connection ends", async () => { + const listener = await raw(); + const caller = await raw(); + void listener.request("events/stream", { name: "custom-event" }); + await settle(); + await listener.close(); + expect(textOfCall(await caller.call("trigger-event", {}))).toBe( + "Sent custom-event (info) to 0 open custom-event streams", + ); + }); +}); + +describe("stream limit", () => { + it(`refuses stream ${MAX_STREAMS + 1} with ResourceExhausted (-32025), and frees a slot when one ends`, async () => { + const holder = await raw(); + for (let i = 0; i < MAX_STREAMS; i++) { + void holder.request("events/stream", { name: "custom-event" }); + } + await settle(); + const session = await raw(); + expect( + await errorOf(session, "events/stream", { name: "clock-tick" }), + ).toEqual({ + code: -32025, + message: `The server already has ${MAX_STREAMS} event streams open, its limit`, + data: { limit: "streams", max: MAX_STREAMS }, + }); + + await holder.close(); + void session.request("events/stream", { name: "clock-tick" }); + await settle(); + expect(sent(session, "notifications/events/active")).toHaveLength(1); + }); +}); + +describe("PushStream", () => { + it("ends when a send fails, and sends nothing after", async () => { + const notify = vi.fn().mockRejectedValue(new Error("connection gone")); + const stream = new PushStream({ id: 9, notify }, 1_000, () => null); + const released = vi.fn(); + stream.onClose(released); + stream.send("notifications/events/active", { cursor: null }); + await stream.ended(); + expect(stream.isClosed).toBe(true); + expect(released).toHaveBeenCalledOnce(); + expect(notify).toHaveBeenCalledOnce(); + + // Closed for good: no further sends, no heartbeat, no second release. + stream.send("notifications/events/event", {}); + stream.close(); + await vi.advanceTimersByTimeAsync(5_000); + expect(notify).toHaveBeenCalledOnce(); + expect(released).toHaveBeenCalledOnce(); + }); + + /** A notify whose sends stay pending until released, one at a time. */ + function slowNotify() { + const pending: Array<() => void> = []; + const notify = vi.fn( + () => new Promise((resolve) => pending.push(resolve)), + ); + const release = async () => { + pending.shift()?.(); + await settle(); + }; + return { notify, release }; + } + + it("drops what is still queued when it ends abruptly", async () => { + const { notify, release } = slowNotify(); + const stream = new PushStream({ id: 1, notify }, 1_000, () => null); + stream.send("notifications/events/event", { n: 1 }); + stream.send("notifications/events/event", { n: 2 }); + stream.send("notifications/events/event", { n: 3 }); + await settle(); + stream.abort(); + await release(); + await stream.ended(); + expect(notify).toHaveBeenCalledOnce(); + }); + + it("drops what is still queued after a failed send", async () => { + const notify = vi + .fn() + .mockRejectedValueOnce(new Error("connection gone")) + .mockResolvedValue(undefined); + const stream = new PushStream({ id: 1, notify }, 1_000, () => null); + stream.send("notifications/events/event", { n: 1 }); + stream.send("notifications/events/event", { n: 2 }); + await stream.ended(); + expect(notify).toHaveBeenCalledOnce(); + }); + + it("sends what is already queued when it ends gracefully", async () => { + const { notify, release } = slowNotify(); + const stream = new PushStream({ id: 1, notify }, 1_000, () => null); + stream.send("notifications/events/terminated", { n: 1 }); + stream.send("notifications/events/terminated", { n: 2 }); + await settle(); + stream.close(); + await release(); + await release(); + await stream.ended(); + expect(notify).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/everything/__tests__/harness.ts b/src/everything/__tests__/harness.ts index baab1c4a38..461045dd05 100644 --- a/src/everything/__tests__/harness.ts +++ b/src/everything/__tests__/harness.ts @@ -19,7 +19,10 @@ * `connectRaw()` serves the same way to a raw JSON-RPC peer that puts the * 2026-07-28 envelope on each request, for what the SDK client hides or * refuses: the wire fields it consumes (`resultType`, the cache fields), a - * tampered `requestState`, and task handles. + * tampered `requestState`, task handles, and the Events extension's methods, + * which the SDK client has no helpers for. It records every notification the + * server sends and can send notifications of its own (`notifications/cancelled` + * ends an `events/stream`). * * `connectModern()` serves a 2026-07-28 client: it hands the factory to the * SDK's `serveStdio` entry over the in-memory pair, as the stdio transport @@ -207,6 +210,12 @@ export type RawSession = { call: (name: string, args?: Json) => Promise; /** The result of a `tasks/get`. */ get: (taskId: string) => Promise; + /** Send a notification, with the 2026-07-28 envelope. */ + notify: (method: string, params?: Json) => Promise; + /** Every notification the server has sent, in order. */ + notifications: Json[]; + /** The JSON-RPC id of the request sent last. */ + lastRequestId: () => number; close: () => Promise; }; @@ -226,31 +235,32 @@ export async function connectRaw(capabilities: Json): Promise { { transport: serverTransport }, ); const waiting = new Map void>(); + const notifications: Json[] = []; peer.onmessage = (message) => { if ("id" in message && typeof message.id === "number") { waiting.get(message.id)?.(message); + } else if ("method" in message) { + notifications.push({ ...message }); } }; await peer.start(); let nextId = 1; + const envelope = (params: Json): Json => ({ + ...params, + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": capabilities, + ...(params._meta as Json | undefined), + }, + }); const request = (method: string, params: Json = {}) => { const id = nextId++; return new Promise((resolve) => { waiting.set(id, (m) => resolve({ ...m })); - void peer.send({ - jsonrpc: "2.0", - id, - method, - params: { - ...params, - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": capabilities, - ...(params._meta as Json | undefined), - }, - }, - }); + // The in-memory send settles at once; a failure surfaces as the + // response never arriving, which fails the awaiting test. + void peer.send({ jsonrpc: "2.0", id, method, params: envelope(params) }); }); }; const result = async (method: string, params: Json = {}) => { @@ -263,6 +273,10 @@ export async function connectRaw(capabilities: Json): Promise { result, call: (name, args = {}) => result("tools/call", { name, arguments: args }), get: (taskId) => result("tasks/get", { taskId }), + notify: (method, params = {}) => + peer.send({ jsonrpc: "2.0", method, params: envelope(params) }), + notifications, + lastRequestId: () => nextId - 1, close: async () => { await handle.close(); for (const cleanup of cleanups) cleanup(); diff --git a/src/everything/__tests__/idle-sessions.test.ts b/src/everything/__tests__/idle-sessions.test.ts new file mode 100644 index 0000000000..b4729891ef --- /dev/null +++ b/src/everything/__tests__/idle-sessions.test.ts @@ -0,0 +1,180 @@ +/** + * The timing of idle-session eviction (#5558), with fake timers and no HTTP: + * what `SESSION_IDLE_TIMEOUT_MILLIS` is read as, that a session is evicted + * once, only after it has had no open response for the timeout, and that a + * timeout of 0 and `stop()` both end the watching. A response is an + * `EventEmitter` here, since "close" is all the module listens for. What + * eviction does to a real session is in `streamable-http.test.ts`. + */ +import { EventEmitter } from "node:events"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + DEFAULT_SESSION_IDLE_TIMEOUT_MILLIS, + sessionIdleTimeoutMillis, + watchIdleSessions, +} from "../transports/idle-sessions.js"; + +describe("sessionIdleTimeoutMillis", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("defaults to 30 minutes", () => { + expect(DEFAULT_SESSION_IDLE_TIMEOUT_MILLIS).toBe(1_800_000); + expect(sessionIdleTimeoutMillis(undefined)).toBe(1_800_000); + }); + + it("reads SESSION_IDLE_TIMEOUT_MILLIS from the environment", () => { + vi.stubEnv("SESSION_IDLE_TIMEOUT_MILLIS", "5000"); + expect(sessionIdleTimeoutMillis()).toBe(5000); + }); + + it("takes a number of milliseconds, and 0 as disabled", () => { + expect(sessionIdleTimeoutMillis("60000")).toBe(60_000); + expect(sessionIdleTimeoutMillis(" 250 ")).toBe(250); + expect(sessionIdleTimeoutMillis("0")).toBe(0); + }); + + it.each(["", " ", "-1", "soon", "Infinity"])( + "falls back to the default for %j", + (value) => { + expect(sessionIdleTimeoutMillis(value)).toBe( + DEFAULT_SESSION_IDLE_TIMEOUT_MILLIS, + ); + }, + ); +}); + +describe("watchIdleSessions", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("evicts a session once, after it has been idle for the timeout", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(5000, evict); + idle.add("a"); + vi.advanceTimersByTime(4999); + expect(evict).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(evict).toHaveBeenCalledExactlyOnceWith("a"); + vi.advanceTimersByTime(60_000); + expect(evict).toHaveBeenCalledOnce(); + idle.stop(); + }); + + it("keeps a session with an open response, and times it from when the response closes", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(5000, evict); + idle.add("active"); + idle.add("abandoned"); + const stream = new EventEmitter(); + const call = new EventEmitter(); + idle.hold("active", stream); + idle.hold("active", call); + vi.advanceTimersByTime(5000); + expect(evict).toHaveBeenCalledExactlyOnceWith("abandoned"); + + // One of two responses closing leaves the session in use. + call.emit("close"); + vi.advanceTimersByTime(60_000); + expect(evict).toHaveBeenCalledOnce(); + + // The clock starts when the last one closes, not when it opened. + stream.emit("close"); + vi.advanceTimersByTime(4999); + expect(evict).toHaveBeenCalledOnce(); + vi.advanceTimersByTime(1); + expect(evict).toHaveBeenLastCalledWith("active"); + expect(evict).toHaveBeenCalledTimes(2); + idle.stop(); + }); + + it("restarts a session's clock on each request", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(5000, evict); + idle.add("a"); + for (let i = 0; i < 4; i++) { + vi.advanceTimersByTime(4000); + const res = new EventEmitter(); + idle.hold("a", res); + res.emit("close"); + } + expect(evict).not.toHaveBeenCalled(); + idle.stop(); + }); + + it("does not evict a session that was removed, or hold one it does not watch", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(5000, evict); + idle.add("ended"); + idle.remove("ended"); + const res = new EventEmitter(); + idle.hold("unknown", res); + expect(res.listenerCount("close")).toBe(0); + vi.advanceTimersByTime(60_000); + expect(evict).not.toHaveBeenCalled(); + idle.stop(); + }); + + it("looks for idle sessions every tenth of the timeout", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(50_000, evict); + // Idle from 2 s in: past the timeout at 52 s, and seen at the 55 s look. + vi.advanceTimersByTime(2000); + idle.add("a"); + vi.advanceTimersByTime(52_999); + expect(evict).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(evict).toHaveBeenCalledExactlyOnceWith("a"); + idle.stop(); + }); + + it("looks at least every minute, however long the timeout", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(30 * 60_000, evict); + vi.advanceTimersByTime(60_000); + idle.add("a"); + // Idle from 1:00, so past the timeout at 31:00, the next look. + vi.advanceTimersByTime(30 * 60_000 - 1); + expect(evict).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(evict).toHaveBeenCalledExactlyOnceWith("a"); + idle.stop(); + }); + + it("looks no more often than once a second when the timeout is shorter", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(10, evict); + idle.add("a"); + vi.advanceTimersByTime(999); + expect(evict).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(evict).toHaveBeenCalledExactlyOnceWith("a"); + idle.stop(); + }); + + it("never evicts, and runs no timer, when the timeout is 0", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(0, evict); + expect(vi.getTimerCount()).toBe(0); + idle.add("a"); + vi.advanceTimersByTime(24 * 60 * 60 * 1000); + expect(evict).not.toHaveBeenCalled(); + idle.stop(); + }); + + it("stops looking once stopped", () => { + const evict = vi.fn(); + const idle = watchIdleSessions(5000, evict); + idle.add("a"); + idle.stop(); + expect(vi.getTimerCount()).toBe(0); + vi.advanceTimersByTime(60_000); + expect(evict).not.toHaveBeenCalled(); + }); +}); diff --git a/src/everything/__tests__/modern.test.ts b/src/everything/__tests__/modern.test.ts index 6de89b020c..160c1a18ad 100644 --- a/src/everything/__tests__/modern.test.ts +++ b/src/everything/__tests__/modern.test.ts @@ -13,7 +13,7 @@ * roots.test.ts), `requestState` carried across the multi-step tool's * rounds on both eras, with retries after missing or bad input, and the * SDK refusing an embedded request whose capability the request did not - * declare (-32021) or a tampered state (-32602). + * declare (-32021) or a tampered or expired state (-32602). * - Per-request log levels (`trigger-log-messages`) against the 2025-era * session level. * - Change notifications (`trigger-list-changed`, `trigger-resource-update`) @@ -336,6 +336,35 @@ describe("multi-round-trip requests on 2026-07-28", () => { requestState: expect.any(String), }); }); + + it("refuses an untampered requestState with -32602 once its 600-second TTL has passed", async () => { + // Freeze the clock before the state is minted, so only the test moves it. + vi.useFakeTimers({ toFake: ["Date"] }); + raw = await connectRaw({ elicitation: {} }); + const mintedAt = Date.now(); + const first = await raw.call("trigger-multi-step-elicitation"); + const answerTheName = { + name: "trigger-multi-step-elicitation", + arguments: {}, + requestState: (first as { requestState: string }).requestState, + inputResponses: { + name: { action: "accept", content: { name: "Ada" } }, + }, + }; + + // Inside the TTL the state is accepted, so the refusal below is the + // expiry and nothing else about this continuation. + vi.setSystemTime(mintedAt + 599_000); + expect(await raw.result("tools/call", answerTheName)).toMatchObject({ + resultType: "input_required", + inputRequests: { color: { method: "elicitation/create" } }, + }); + + // Past it, the same state is refused: only the clock has moved. + vi.setSystemTime(mintedAt + 601_000); + const response = await raw.request("tools/call", answerTheName); + expect(response.error).toMatchObject({ code: -32602 }); + }); }); describe("trigger-multi-step-elicitation", () => { diff --git a/src/everything/__tests__/registrations.test.ts b/src/everything/__tests__/registrations.test.ts index 463632df63..855eb7e704 100644 --- a/src/everything/__tests__/registrations.test.ts +++ b/src/everything/__tests__/registrations.test.ts @@ -105,6 +105,7 @@ describe("Registration Index Files", () => { "simulate-research-query", "trigger-sampling-request-async", "trigger-elicitation-request-async", + "trigger-event", ]); }); diff --git a/src/everything/__tests__/stdio.test.ts b/src/everything/__tests__/stdio.test.ts index d6889d9a34..c746100b93 100644 --- a/src/everything/__tests__/stdio.test.ts +++ b/src/everything/__tests__/stdio.test.ts @@ -66,6 +66,7 @@ describe("stdio transport", () => { expect(client.getProtocolEra()).toBe("modern"); expect(client.getServerCapabilities()?.extensions).toEqual({ "io.modelcontextprotocol/tasks": {}, + "io.modelcontextprotocol/events": {}, }); const result = await client.callTool({ name: "echo", diff --git a/src/everything/__tests__/streamable-http.test.ts b/src/everything/__tests__/streamable-http.test.ts index 7a4043654a..61bd68f883 100644 --- a/src/everything/__tests__/streamable-http.test.ts +++ b/src/everything/__tests__/streamable-http.test.ts @@ -18,6 +18,13 @@ * A browser request is served only from a localhost origin: the tests pin * that a foreign `Origin` is refused with a 403 and no CORS grant at every * route, preflights included, and that a localhost one is served. + * + * A 2025-era session left idle is evicted (#5558): the "idle sessions" block + * serves an app with a five-second idle timeout and moves a fake clock past + * it (only `setInterval` and `Date` are faked, so the HTTP round trips stay + * real), pinning that the abandoned session is closed, cleaned up and then + * answered 404 while one with an open stream is left alone. The timing rules + * themselves are in `idle-sessions.test.ts`. */ import type { Server } from "node:http"; import { once } from "node:events"; @@ -604,6 +611,156 @@ describe("shutdown", () => { }); }); +describe("idle sessions (#5558)", () => { + const IDLE = 5000; + const ping = { jsonrpc: "2.0", id: 7, method: "ping" }; + + /** Replace the default app with one whose sessions idle out after `timeout`. */ + async function serveWithIdleTimeout(timeout: number) { + await new Promise((resolve) => http.close(resolve)); + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval", "Date"] }); + app = createApp({ sessionIdleTimeoutMillis: timeout }); + http = app.app.listen(0, "127.0.0.1"); + await once(http, "listening"); + const address = http.address(); + if (address === null || typeof address === "string") + throw new Error("no port"); + mcp = `http://127.0.0.1:${address.port}/mcp`; + } + + afterEach(() => { + vi.useRealTimers(); + }); + + it("evicts an abandoned session and releases what it held, leaving one with an open stream alone", async () => { + await serveWithIdleTimeout(IDLE); + const timers = vi.getTimerCount(); + + // The abandoned session starts a timer of its own, then goes quiet. + const abandoned = await rawInitialize(); + const toggled = await post( + { + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { name: "toggle-simulated-logging", arguments: {} }, + }, + abandoned.sessionId, + ); + await toggled.text(); + expect(vi.getTimerCount()).toBe(timers + 1); + + // The active session keeps its standalone stream open and sends nothing. + const active = await rawInitialize(); + const controller = new AbortController(); + const stream = await fetch(mcp, { + headers: { + accept: "text/event-stream", + "mcp-session-id": active.sessionId, + "mcp-protocol-version": "2025-11-25", + }, + signal: controller.signal, + }); + expect(stream.status).toBe(200); + const timersBeforeEviction = vi.getTimerCount(); + + vi.advanceTimersByTime(IDLE); + await vi.waitFor(() => + expect(log).toHaveBeenCalledWith( + `Transport closed for session ${abandoned.sessionId}, removing from transports map`, + ), + ); + expect(log).toHaveBeenCalledWith( + `Session ${abandoned.sessionId} idle for ${IDLE} ms, closing it`, + ); + // Its cleanup ran: the simulated-logging timer is gone. + expect(vi.getTimerCount()).toBe(timersBeforeEviction - 1); + const evicted = await post(ping, abandoned.sessionId); + expect(evicted.status).toBe(404); + expect(await evicted.json()).toEqual({ ...SESSION_NOT_FOUND, id: 7 }); + + // The session with the open stream was idle just as long, and is served. + const kept = await post(ping, active.sessionId); + expect(kept.status).toBe(200); + await kept.text(); + expect(log).not.toHaveBeenCalledWith( + `Session ${active.sessionId} idle for ${IDLE} ms, closing it`, + ); + + // Once its stream closes it is idle too, and is evicted in its turn. + controller.abort(); + await vi.waitFor(() => { + vi.advanceTimersByTime(IDLE); + expect(log).toHaveBeenCalledWith( + `Transport closed for session ${active.sessionId}, removing from transports map`, + ); + }); + expect((await post(ping, active.sessionId)).status).toBe(404); + }); + + it("keeps a session that is still being used", async () => { + await serveWithIdleTimeout(IDLE); + const { sessionId } = await rawInitialize(); + for (let i = 0; i < 3; i++) { + vi.advanceTimersByTime(IDLE - 1000); + const response = await post(ping, sessionId); + expect(response.status).toBe(200); + await response.text(); + } + expect(log).not.toHaveBeenCalledWith( + `Session ${sessionId} idle for ${IDLE} ms, closing it`, + ); + }); + + it("evicts nothing when the timeout is 0", async () => { + await serveWithIdleTimeout(0); + expect(vi.getTimerCount()).toBe(0); + const { sessionId } = await rawInitialize(); + vi.advanceTimersByTime(24 * 60 * 60 * 1000); + const response = await post(ping, sessionId); + expect(response.status).toBe(200); + await response.text(); + }); + + it("logs an idle session that fails to close, and evicts it at a later look", async () => { + await serveWithIdleTimeout(IDLE); + const { sessionId } = await rawInitialize(); + const failure = new Error("close failed"); + vi.spyOn( + NodeStreamableHTTPServerTransport.prototype, + "close", + ).mockRejectedValueOnce(failure); + vi.advanceTimersByTime(IDLE); + await vi.waitFor(() => + expect(log).toHaveBeenCalledWith( + `Error closing idle session ${sessionId}:`, + failure, + ), + ); + // The failed close left the session in place, and still served. + const held = await post(ping, sessionId); + expect(held.status).toBe(200); + await held.text(); + + // It is watched again, so the next timeout closes it for real. + await vi.waitFor(() => { + vi.advanceTimersByTime(IDLE); + expect(log).toHaveBeenCalledWith( + `Transport closed for session ${sessionId}, removing from transports map`, + ); + }); + expect((await post(ping, sessionId)).status).toBe(404); + }); + + it("stops looking for idle sessions on shutdown", async () => { + vi.spyOn(process, "exit").mockImplementation(() => undefined as never); + await serveWithIdleTimeout(IDLE); + expect(vi.getTimerCount()).toBe(1); + await app.shutdown(); + expect(vi.getTimerCount()).toBe(0); + }); +}); + describe("startStreamableHttpServer", () => { afterEach(() => { vi.doUnmock("../transports/listen.js"); diff --git a/src/everything/docs/features.md b/src/everything/docs/features.md index 9b0474b53c..78047a5e92 100644 --- a/src/everything/docs/features.md +++ b/src/everything/docs/features.md @@ -24,6 +24,7 @@ Each feature below is marked **both**, **2026-07-28** or **2025-era**. Roots, sa | Change notifications | on a `subscriptions/listen` stream the client opened | unsolicited, or after `resources/subscribe` | | Log level | per request, `_meta` `io.modelcontextprotocol/logLevel` (none named: no logs) | per session, `logging/setLevel` | | Tasks | the `io.modelcontextprotocol/tasks` extension | not served | +| Events | the `io.modelcontextprotocol/events` extension (poll and push) | not served (`-32601`) | | Cache hints | `ttlMs` / `cacheScope` on lists, reads and `server/discover` | not sent | | `x-mcp-header` | mirrored into `Mcp-Param-*` headers over Streamable HTTP | not mirrored | @@ -47,6 +48,7 @@ Each feature below is marked **both**, **2026-07-28** or **2025-era**. Roots, sa - `trigger-elicitation-request-async` (tools/trigger-elicitation-request-async.ts), **2026-07-28**: Runs as a task whose `input_required` status carries a form elicitation; the client answers with `tasks/update` and the task completes with a summary. Needs a client that declares the tasks extension and form-mode elicitation. - `trigger-list-changed` (tools/trigger-list-changed.ts), **both**: Sends `notifications//list_changed` for `tools`, `prompts` or `resources`: on 2026-07-28 to each `subscriptions/listen` stream that asked for that list, on a 2025-era connection unsolicited. - `trigger-log-messages` (tools/trigger-log-messages.ts), **both**, deprecated: Sends one log message at each level during the call. A 2026-07-28 request gets those at or above the level its `_meta` names (none if it names none); a 2025-era client those at or above its `logging/setLevel` level. +- `trigger-event` (tools/trigger-event.ts), **2026-07-28**: Raises the events extension's `custom-event` on every open `events/stream` subscribed to it, with a `message` and a `severity` (`info`, `warning` or `error`) each stream filters by its `minSeverity`. With `kind: "error"` it sends a recoverable `notifications/events/error` instead and the streams stay open; with `kind: "terminate"` it sends `notifications/events/terminated` (`-32024` Forbidden) and ends them. Reports how many streams it reached. - `trigger-long-running-operation` (tools/trigger-long-running-operation.ts), **both**: Simulates a multi-step operation over a given `duration` and number of `steps`; reports progress via `notifications/progress` when a `progressToken` is provided by the client. Honors cancellation: a cancelled call clears its timer and sends no further progress. - `trigger-multi-step-elicitation` (tools/trigger-multi-step-elicitation.ts), **both**: Asks for a name, then for a favorite color addressed by that name, carrying the first answer to the second round in `requestState`. The state is HMAC-signed and expires after ten minutes; a tampered or expired one is refused with `-32602`. A blank name or a color that is not a choice is asked again. Needs form-mode elicitation. - `trigger-resource-update` (tools/trigger-resource-update.ts), **both**: Sends `notifications/resources/updated` for a URI: on 2026-07-28 to each listen stream whose `resourceSubscriptions` name it, on a 2025-era connection once the client has subscribed to it. @@ -102,3 +104,21 @@ Logging is deprecated as of 2026-07-28 (SEP-2577) and remains available on both A task tool called by a client whose request does not declare the extension, or the capability its task asks for input with (`sampling` for `trigger-sampling-request-async`, form-mode `elicitation` for `trigger-elicitation-request-async`), is refused with `-32021` (missing required client capability), naming what is missing in `data.requiredCapabilities`; so is a `tasks/*` request from a client without the extension. An unknown or expired task, and a `tasks/update` whose answers exceed 64 KiB serialized (counted in UTF-8 bytes), are refused with `-32602`. A `tasks/cancel` is acknowledged whatever the task's status (cancellation is cooperative), and a finished task stays as it ended. An update's answers to requests that are not outstanding (never issued, already answered, or sent while the task is not waiting for input) are ignored, as the extension asks. Each input request a task makes has its own key, never reused once answered, so a request asked again after an answer that does not fit gets a new key (`form-2`, `sampling-2`). The process keeps at most 100 tasks, each until its TTL; at that limit a new task is refused with a tool error. The task id is a server-minted UUID, so a task lives across requests (each 2026-07-28 HTTP request is served by a fresh server instance) and is reached only through its handle. A task's progress is computed from the clock when it is read, so nothing runs in the background. The 2025-11-25 core task methods (`tasks/result`, `tasks/list`, task-augmented requests) are not served: SDK v2 removed the experimental layer they were built on. + +## Events + +**2026-07-28.** The server implements the server side of the [events extension](https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx) (`io.modelcontextprotocol/events`, SEP-3415, Beta), advertised under `capabilities.extensions` in `server/discover` with no `listChanged`, since its event types never change. A client lists the event types with `events/list` and receives their occurrences (`{eventId, name, timestamp, data, cursor}`) by poll or push. Two synthetic event types cover the extension's two cursor models: + +| Event type | Delivery | Cursor | Arguments | Payload | +| --- | --- | --- | --- | --- | +| `clock-tick` | `poll`, `push` | replayable: `clock-tick:`; the last 100 ticks can be replayed | `everyNth` (filter, default 1), `label` (copied into the payload) | `tick`, `label` | +| `custom-event` | `push` | always `null`: emit-only, no history | `minSeverity` (filter: `info`, `warning` or `error`) | `message`, `severity` | + +`clock-tick` fires every 5 seconds: tick *k* happens at *k* × 5 s since the Unix epoch, so every occurrence is computed from the clock and its `eventId` (`tick-`) is the same on every subscription and every replay. `custom-event` fires when the `trigger-event` tool is called, through a process-wide bus, so a stream opened through one connection (or one HTTP request) sees an event raised through another. + +- `events/poll` (`clock-tick` only): a `null` or absent cursor starts from now (no events, the current cursor). A cursor replays the ticks after it, at most `maxEvents` (default 50, at most 100) at a time, with `hasMore: true` and `nextPollMs: 0` while a backlog remains; otherwise `nextPollMs` is the time to the next tick (at least 1 s). Replay starts no earlier than `now - maxAgeMs` or the oldest retained tick, and `truncated: true` says when either skipped events. +- `events/stream`: one long-lived request per subscription. It sends `notifications/events/active` first (the starting cursor, `truncated`, and the granted `heartbeatMs`: the client's suggestion clamped to 1–60 s, 30 s by default), then the replayed backlog and each new occurrence as `notifications/events/event`, and `notifications/events/heartbeat` with the cursor checked up to whenever the granted interval passes without another message. Every notification carries the request's id in `_meta["io.modelcontextprotocol/subscriptionId"]`. If the stream's tick timer fires late (the process was suspended, or the clock jumped), it replays no more than the 100 retained ticks and first sends a fresh `active` with `truncated: true`. A `custom-event` raised once arrives with the same `eventId` and `timestamp` on every stream it matches. Cancelling the request (`notifications/cancelled` on stdio, closing the HTTP response) ends the stream, drops any notifications still queued and releases its timers; when the server ends it (after `trigger-event` terminates it) the request answers with an empty result. The process holds at most 100 streams; past that a new one is refused with `-32025` (ResourceExhausted). +- Errors: an unknown event type is `-32023` (NotFound, `data.kind: "event"`); a delivery mode the type does not offer (polling `custom-event`) is `-32026` (Unsupported, `data: {feature: "deliveryMode", value}`); arguments that do not match the type's `inputSchema`, or a cursor the server never minted, are `-32602`. An invalid subscription gets its error before any stream opens. +- Webhook delivery is not offered: the extension requires an authenticated principal for `events/subscribe` and `events/unsubscribe`, and this server has none, so both answer `-32601`. + +Over Streamable HTTP the extension asks clients to send `Mcp-Name: ` on `events/poll` and `events/stream`. The SDK's server checks that header only for the core methods and `tasks/*` today, so a mismatched `Mcp-Name` on an `events/*` request is not refused yet. diff --git a/src/everything/docs/how-it-works.md b/src/everything/docs/how-it-works.md index 6059ac215d..fa4aafd46e 100644 --- a/src/everything/docs/how-it-works.md +++ b/src/everything/docs/how-it-works.md @@ -35,6 +35,14 @@ - Serves the tasks extension (`io.modelcontextprotocol/tasks`) on 2026-07-28: `tasks/get`, `tasks/update` and `tasks/cancel`, with explicit schemas. - `createTask(behavior, options)` stores a task under a minted UUID and returns the `tools/call` result that hands its handle to the client (`resultType: "task"`). A task's `behavior` works out its state from the clock (`stateAt`) and takes the client's answers (`receive`), so nothing runs in the background. Tasks past their TTL are dropped when the store is next touched. +# Events + +### Module: `server/events.ts` + +- Serves the events extension (`io.modelcontextprotocol/events`) on 2026-07-28: `events/list`, `events/poll` and `events/stream`, with explicit schemas. Webhook delivery is not offered. +- `clock-tick` is computed from the clock (tick *k* at *k* × 5 s), so a poll or a replaying stream needs no stored history. `custom-event` is raised by `trigger-event` through `emitCustomEvent`, a process-wide bus every open `custom-event` stream listens on. +- A `PushStream` sends one stream's notifications in order, tagged with the request id, re-arms the heartbeat after each, and ends on cancellation, on termination, on a failed send, or when its server instance is cleaned up. An abrupt end (cancellation, a failed send, cleanup) drops what is still queued; a termination sends it first. + ## Resource Subscriptions ### Module: `resources/subscriptions.ts` diff --git a/src/everything/docs/instructions.md b/src/everything/docs/instructions.md index 5c853824d7..ca5ca6bbba 100644 --- a/src/everything/docs/instructions.md +++ b/src/everything/docs/instructions.md @@ -8,6 +8,7 @@ Follow them to use, extend, and troubleshoot the server safely and effectively. The server serves two protocol eras. A client on protocol version 2026-07-28 connects with `server/discover` and sends its capabilities with each request; a 2025-era client connects with `initialize`. Some tools exist on one era only, so trust your `tools/list`: - 2026-07-28 only: `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async`, which run as tasks on the `io.modelcontextprotocol/tasks` extension and need a client that declares it; `trigger-sampling-request-async` also needs `sampling`, and `trigger-elicitation-request-async` form-mode `elicitation`. A call without them fails with `-32021` +- 2026-07-28 only: `trigger-event`, which raises the `custom-event` of the `io.modelcontextprotocol/events` extension on open `events/stream` subscriptions - 2025-era only (deprecated): `toggle-simulated-logging` and `toggle-subscriber-updates` ## Cross-Feature Relationships diff --git a/src/everything/docs/startup.md b/src/everything/docs/startup.md index e93a85577b..f35f348b84 100644 --- a/src/everything/docs/startup.md +++ b/src/everything/docs/startup.md @@ -34,6 +34,7 @@ - **Streamable HTTP**: one `/mcp` endpoint for both eras. - **2026-07-28**: a session-less **POST** carrying the per-request `_meta` envelope is served by the SDK's `createMcpHandler`, which builds a fresh server per request with `createServer({ era: "modern", publish })`. There are no sessions. Change notifications are published on the handler's subscription bus (`publish`), which reaches every open `subscriptions/listen` stream. - **2025 era**: everything else, classified by the SDK's `isLegacyRequest`, keeps the sessionful wiring: a server per session, created on the `initialize` **POST**, with **GET** for the standalone SSE stream and **DELETE** to end the session. Transports are stored by `sessionId`, an event store makes streams resumable, and the session's `cleanup()` runs when it closes. Sessionful serving keeps the server-to-client channel the legacy shim needs for elicitation, sampling and roots. + - A 2025-era session with no request in flight and no stream open for `SESSION_IDLE_TIMEOUT_MILLIS` (default 30 minutes; `0` disables it) is closed by the server, as if its client had sent the DELETE; its next request is answered `404`. - A session-less POST's body is parsed once (up to 4 MiB) to classify it and serve it. - **SSE** and **Streamable HTTP** bind their port (`PORT`, default `3001`) through `listenOrExit()` in `transports/listen.ts`. - The listening line is printed only once the port is bound. @@ -48,7 +49,7 @@ - `logging: {}` - `prompts: { listChanged: true }` - `resources: { subscribe: true, listChanged: true }` - - `extensions: { "io.modelcontextprotocol/tasks": {} }` (2026-07-28 only) + - `extensions: { "io.modelcontextprotocol/tasks": {}, "io.modelcontextprotocol/events": {} }` (2026-07-28 only) - **Server Instructions** - Loaded from the docs folder (`instructions.md`). - **Options** @@ -56,7 +57,7 @@ - The `requestState` verifier for multi-round tools (`roundStateCodec`). - **Registrations** - Builds a per-instance **context** (`server/context.ts`): the era, where change notifications go, the 2025-era resource subscriptions, and a cleanup registry. - - Registers **tools** via `registerTools(server, context)`, and then by era: `registerModernTools` and the tasks extension (`server/tasks.ts`) for 2026-07-28; `registerLegacyTools` now and `registerConditionalTools` once the client has initialized, for the 2025 era. + - Registers **tools** via `registerTools(server, context)`, and then by era: `registerModernTools` and the tasks and events extensions (`server/tasks.ts`, `server/events.ts`) for 2026-07-28; `registerLegacyTools` now and `registerConditionalTools` once the client has initialized, for the 2025 era. - Registers **resources** via `registerResources(server, context)`. - Registers **prompts** via `registerPrompts(server)`. - **Other Request Handlers** (2025 era) diff --git a/src/everything/docs/structure.md b/src/everything/docs/structure.md index 440702593f..20f2317522 100644 --- a/src/everything/docs/structure.md +++ b/src/everything/docs/structure.md @@ -37,6 +37,7 @@ src/everything ├── server │ ├── index.ts │ ├── context.ts + │ ├── events.ts │ ├── icons.ts │ ├── logging.ts │ ├── roots.ts @@ -59,6 +60,7 @@ src/everything │ ├── toggle-subscriber-updates.ts │ ├── trigger-elicitation-request-async.ts │ ├── trigger-elicitation-request.ts + │ ├── trigger-event.ts │ ├── trigger-list-changed.ts │ ├── trigger-log-messages.ts │ ├── trigger-long-running-operation.ts @@ -68,6 +70,7 @@ src/everything │ ├── trigger-sampling-request.ts │ └── trigger-url-elicitation.ts └── transports + ├── idle-sessions.ts ├── in-memory-event-store.ts ├── listen.ts ├── sse.ts @@ -156,6 +159,8 @@ src/everything - Exposes `{ server, cleanup }` to the chosen transport. Cleanup stops any running intervals in the server when the connection ends. - `context.ts` - The per-instance context features receive: the era, the change publisher, the 2025-era subscriptions and a cleanup registry. +- `events.ts` + - 2026-07-28: the server side of the events extension (`events/list`, `events/poll`, `events/stream`), its two event types (`clock-tick`, `custom-event`) and the process-wide bus `trigger-event` raises `custom-event` on. - `icons.ts` - The light- and dark-themed icon pairs (SEP-973) attached to the server info and to every tool, prompt, resource and resource template, one pair per kind, as inline SVG `data:` URIs. - `logging.ts` @@ -201,6 +206,8 @@ src/everything - 2026-07-28: registers a `trigger-elicitation-request-async` tool that runs as a task waiting in `input_required` for a form elicitation. - `trigger-list-changed.ts` - Registers a `trigger-list-changed` tool that publishes a tools, prompts or resources list change. +- `trigger-event.ts` + - 2026-07-28: registers a `trigger-event` tool that raises `custom-event` on the open `events/stream` subscriptions, or sends them a recoverable error or a termination. - `trigger-log-messages.ts` - Registers a `trigger-log-messages` tool that sends one log message per level, filtered by the request's or session's log level. - `trigger-multi-step-elicitation.ts` @@ -228,6 +235,9 @@ src/everything ### `transports/` +- `idle-sessions.ts` + - `watchIdleSessions(timeoutMillis, evict)`: decides when a 2025-era Streamable HTTP session has been idle too long. A request counts as activity until its response closes, so an open stream or a running call keeps its session; `evict` is called once for a session with no open response for the timeout. + - `sessionIdleTimeoutMillis()`: reads `SESSION_IDLE_TIMEOUT_MILLIS` (default 30 minutes; `0` disables eviction). - `in-memory-event-store.ts` - `InMemoryEventStore`: the Streamable HTTP transport's event store for resumability. Replays only the events of the stream a `Last-Event-ID` belongs to, and reports an unknown event ID as having no stream, so the SDK refuses the resume. - `listen.ts` @@ -250,4 +260,5 @@ src/everything - 2025 era: POST (JSON‑RPC), GET (SSE stream), and DELETE (session termination) using `NodeStreamableHTTPServerTransport` from `@modelcontextprotocol/node`. - Uses an `InMemoryEventStore` for resumable sessions and tracks transports by `sessionId`. - Answers a request for an unknown or ended `Mcp-Session-Id` with `404 Not Found`, and closes every open session on `SIGINT`. + - Closes a session that has been idle for `SESSION_IDLE_TIMEOUT_MILLIS` (`idle-sessions.ts`), which removes it and runs its `cleanup()` as a DELETE does. - Connects a fresh server instance on initialization POST and reuses the transport for subsequent requests. diff --git a/src/everything/package.json b/src/everything/package.json index 9d2155fc3f..609c624687 100644 --- a/src/everything/package.json +++ b/src/everything/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/server-everything", - "version": "2.3.1", + "version": "2.4.0", "description": "MCP server that exercises all the features of the MCP protocol", "license": "SEE LICENSE IN LICENSE", "mcpName": "io.github.modelcontextprotocol/server-everything", diff --git a/src/everything/server.json b/src/everything/server.json new file mode 100644 index 0000000000..fb4fc8e123 --- /dev/null +++ b/src/everything/server.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-everything", + "title": "Everything", + "description": "Reference server that exercises every MCP feature: tools, resources, prompts, sampling and more", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/everything" + }, + "packages": [ + { + "registryType": "npm", + "identifier": "@modelcontextprotocol/server-everything", + "transport": { + "type": "stdio" + } + } + ] +} diff --git a/src/everything/server/events.ts b/src/everything/server/events.ts new file mode 100644 index 0000000000..a94c91f6bd --- /dev/null +++ b/src/everything/server/events.ts @@ -0,0 +1,720 @@ +// The server side of the Events extension (`io.modelcontextprotocol/events`, +// SEP-3415) on the 2026-07-28 revision (#5651). +// +// A client lists the server's event types with `events/list`, then receives +// their occurrences by polling (`events/poll`) or over a long-lived push +// stream (`events/stream`). The SDK has no server implementation of the +// extension yet (modelcontextprotocol/typescript-sdk#3209), so this module is +// one, built on the SDK's custom request handlers, as `tasks.ts` is for Tasks. +// +// Two synthetic event types cover the extension's two cursor models without +// an upstream service: +// - `clock-tick` (poll and push) is replayable. Tick k happens at k × the +// tick period since the Unix epoch, so every occurrence can be computed +// from the clock and its cursor is just the tick index. Nothing is stored, +// which matters because on the 2026-07-28 HTTP path every request gets a +// fresh server instance. Only the last RETAINED_TICKS ticks can be +// replayed, which gives `truncated: true` a real trigger. +// - `custom-event` (push only) is emit-only. The `trigger-event` tool raises +// it on a process-wide bus, so a stream served by one instance sees an event +// raised through another. It has no history, so its cursor is always null. +// +// Webhook delivery (`events/subscribe`, `events/unsubscribe`) is not offered: +// the extension requires an authenticated principal for it, and this server +// has none, so those methods are left unregistered and answer -32601. The +// extension is served on 2026-07-28 only; a 2025-era client gets -32601 for +// every `events/*` method. + +import { randomUUID } from "node:crypto"; +import { + McpServer, + ProtocolError, + ProtocolErrorCode, + type ServerContext as RequestContext, +} from "@modelcontextprotocol/server"; +import { z } from "zod"; +import type { ServerContext } from "./context.js"; + +/** The extension's identifier, as declared in `capabilities.extensions`. */ +export const EVENTS_EXTENSION = "io.modelcontextprotocol/events"; + +/** The `_meta` key that ties a push notification to its `events/stream`. */ +export const SUBSCRIPTION_ID_META_KEY = + "io.modelcontextprotocol/subscriptionId"; + +/** The extension's error codes (its Error Handling table). */ +export const EventsErrorCode = { + NotFound: -32023, + Forbidden: -32024, + ResourceExhausted: -32025, + Unsupported: -32026, +} as const; + +/** How often `clock-tick` fires. */ +export const TICK_PERIOD_MS = 5_000; + +/** How many past ticks a `clock-tick` cursor can replay. */ +export const RETAINED_TICKS = 100; + +/** The most events one `events/poll` returns, and its default. */ +export const MAX_POLL_EVENTS = 100; +const DEFAULT_POLL_EVENTS = 50; + +/** The bounds and default of a push stream's heartbeat interval. */ +export const MIN_HEARTBEAT_MS = 1_000; +export const MAX_HEARTBEAT_MS = 60_000; +export const DEFAULT_HEARTBEAT_MS = 30_000; + +/** The shortest `nextPollMs` the server suggests when it has no backlog. */ +const MIN_POLL_INTERVAL_MS = 1_000; + +/** + * The most push streams the process holds open at once. Each is a long-lived + * request with a timer, so without a cap a client could open them until the + * process runs out of memory; past it, a new stream is refused with + * ResourceExhausted. + */ +export const MAX_STREAMS = 100; + +const Severity = z.enum(["info", "warning", "error"]); +type Severity = z.infer; +const SEVERITY_RANK: Record = { + info: 0, + warning: 1, + error: 2, +}; + +const ClockTickArguments = z.strictObject({ + everyNth: z + .number() + .int() + .min(1) + .max(1000) + .default(1) + .describe("A filter: deliver only ticks whose index is a multiple of this"), + label: z + .string() + .max(100) + .optional() + .describe("A transform: copied into each delivered payload as `label`"), +}); + +const ClockTickPayload = z.object({ + tick: z.number().int().describe("The tick's index since the Unix epoch"), + label: z.string().optional().describe("The subscription's `label` argument"), +}); + +const CustomEventArguments = z.strictObject({ + minSeverity: Severity.default("info").describe( + "A filter: deliver only events at this severity or above", + ), +}); + +const CustomEventPayload = z.object({ + message: z.string().describe("The message passed to trigger-event"), + severity: Severity.describe("The severity passed to trigger-event"), +}); + +type Delivery = "poll" | "push"; + +/** One event type this server offers. */ +type EventType = { + name: string; + description: string; + delivery: Delivery[]; + arguments: z.ZodType; + payload: z.ZodType; +}; + +const EVENT_TYPES: EventType[] = [ + { + name: "clock-tick", + description: `Fires every ${TICK_PERIOD_MS / 1000} seconds. Replayable: a cursor can resume up to ${RETAINED_TICKS} ticks back.`, + delivery: ["poll", "push"], + arguments: ClockTickArguments, + payload: ClockTickPayload, + }, + { + name: "custom-event", + description: + "Fires when the trigger-event tool is called. Emit-only: it has no history, so its cursor is always null.", + delivery: ["push"], + arguments: CustomEventArguments, + payload: CustomEventPayload, + }, +]; + +/** A JSON Schema for `schema`, without the `$schema` dialect marker. */ +function jsonSchema( + schema: z.ZodType, + io: "input" | "output", +): Record { + const { $schema: _dialect, ...rest } = z.toJSONSchema(schema, { io }); + return rest; +} + +/** The descriptors `events/list` returns. */ +function descriptors(): Record[] { + return EVENT_TYPES.map((type) => ({ + name: type.name, + description: type.description, + delivery: type.delivery, + inputSchema: jsonSchema(type.arguments, "input"), + payloadSchema: jsonSchema(type.payload, "output"), + })); +} + +/** The event type named `name`, or NotFound. */ +function findType(name: string): EventType { + const type = EVENT_TYPES.find((t) => t.name === name); + if (!type) { + throw new ProtocolError( + EventsErrorCode.NotFound, + `Unknown event type: ${name}`, + { kind: "event" }, + ); + } + return type; +} + +/** Refuse a delivery mode the event type does not offer. */ +function requireDelivery(type: EventType, mode: Delivery): void { + if (!type.delivery.includes(mode)) { + throw new ProtocolError( + EventsErrorCode.Unsupported, + `Event type ${type.name} does not support ${mode} delivery`, + { feature: "deliveryMode", value: mode }, + ); + } +} + +/** Parse a subscription's arguments against the type's schema. */ +function parseArguments( + schema: T, + name: string, + args: unknown, +): z.infer { + const parsed = schema.safeParse(args ?? {}); + if (!parsed.success) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + `Invalid arguments for event type ${name}: ${z.prettifyError(parsed.error)}`, + ); + } + return parsed.data; +} + +// --------------------------------------------------------------------------- +// clock-tick: positions, cursors and replay +// --------------------------------------------------------------------------- + +const CURSOR_PREFIX = "clock-tick:"; + +/** The index of the latest tick that has happened at `now`. */ +function headAt(now: number): number { + return Math.floor(now / TICK_PERIOD_MS); +} + +function formatCursor(tick: number): string { + return `${CURSOR_PREFIX}${tick}`; +} + +/** The tick a cursor names, or InvalidParams for one this server never minted. */ +function parseCursor(cursor: string, head: number): number { + const match = /^clock-tick:(\d{1,15})$/.exec(cursor); + const tick = match ? Number(match[1]) : NaN; + if (!Number.isSafeInteger(tick) || tick > head) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + `Invalid cursor for clock-tick: ${cursor}`, + ); + } + return tick; +} + +/** + * Where delivery starts for a subscription: the first tick to check, and + * whether ticks after the client's cursor were skipped to get there. + * + * A null (or absent) cursor means "start from now": nothing is replayed and + * `maxAgeMs` is ignored. Otherwise replay starts after the cursor, but no + * earlier than `now - maxAgeMs` or the oldest retained tick, and moving past + * the cursor for either reason is reported as `truncated`. + */ +function startFor( + cursor: string | null | undefined, + maxAgeMs: number | undefined, + now: number, +): { from: number; truncated: boolean } { + const head = headAt(now); + if (cursor === null || cursor === undefined) { + return { from: head + 1, truncated: false }; + } + const after = parseCursor(cursor, head) + 1; + let from = Math.max(after, head - RETAINED_TICKS + 1); + if (maxAgeMs !== undefined) { + from = Math.max(from, Math.ceil((now - maxAgeMs) / TICK_PERIOD_MS)); + } + return { from, truncated: from > after }; +} + +type ClockTickArgs = z.infer; + +function tickMatches(tick: number, args: ClockTickArgs): boolean { + return tick % args.everyNth === 0; +} + +/** One `clock-tick` occurrence, without its cursor. */ +function tickOccurrence( + tick: number, + args: ClockTickArgs, +): Record { + return { + eventId: `tick-${tick}`, + name: "clock-tick", + timestamp: new Date(tick * TICK_PERIOD_MS).toISOString(), + data: { tick, ...(args.label !== undefined && { label: args.label }) }, + }; +} + +// --------------------------------------------------------------------------- +// custom-event: the process-wide bus +// --------------------------------------------------------------------------- + +/** What `trigger-event` asks the open `custom-event` streams to do. */ +export type CustomEventSignal = + | { kind: "event"; message: string; severity: Severity } + | { kind: "error"; message: string } + | { kind: "terminate"; message: string }; + +/** + * A signal as the bus hands it to each stream: an event carries the identity + * and time minted once for it, so every subscription it matches receives the + * same `eventId` and `timestamp`, as the extension requires of one occurrence. + */ +type BusMessage = + | (Extract & { + eventId: string; + timestamp: string; + }) + | Exclude; + +/** Every open `custom-event` stream, across every server instance. */ +const customListeners = new Set<(message: BusMessage) => void>(); + +/** + * Hand a signal to every open `custom-event` stream, and return how many there + * were. Each stream applies its own `minSeverity` filter to an event. + */ +export function emitCustomEvent(signal: CustomEventSignal): number { + const message: BusMessage = + signal.kind === "event" + ? { + ...signal, + eventId: `custom-${randomUUID()}`, + timestamp: new Date().toISOString(), + } + : signal; + // Copied first: a terminate closes each stream, which removes its listener. + const listeners = [...customListeners]; + for (const listener of listeners) listener(message); + return listeners.length; +} + +/** How many push streams are open in the process. */ +let openStreams = 0; + +/** Forget every open stream. For tests. */ +export function resetEvents(): void { + customListeners.clear(); + openStreams = 0; +} + +// --------------------------------------------------------------------------- +// Push streams +// --------------------------------------------------------------------------- + +type Json = Record; + +/** What a push stream needs of the `events/stream` request it serves. */ +type StreamRequest = Pick; + +/** + * One open `events/stream`: sends its notifications in order, keeps the + * heartbeat going whenever nothing else has been sent for the granted + * interval, and resolves `done` when it ends. Exported for its unit tests, + * which cover the failed send no in-process transport can produce. + */ +export class PushStream { + readonly done: Promise; + private finish!: () => void; + private chain: Promise = Promise.resolve(); + private heartbeat?: NodeJS.Timeout; + private readonly cleanups: Array<() => void> = []; + private closed = false; + /** Set by an abrupt end: notifications still queued are dropped. */ + private discarding = false; + + /** Whether the stream has ended. */ + get isClosed(): boolean { + return this.closed; + } + + constructor( + private readonly request: StreamRequest, + private readonly heartbeatMs: number, + private readonly cursor: () => string | null, + ) { + this.done = new Promise((resolve) => (this.finish = resolve)); + } + + /** The `_meta` every notification on this stream carries. */ + get meta(): Json { + return { [SUBSCRIPTION_ID_META_KEY]: this.request.id }; + } + + /** Queue a notification, and restart the heartbeat interval. */ + send(method: string, params: Json): void { + if (this.closed) return; + this.armHeartbeat(); + const notification = { method, params: { ...params, _meta: this.meta } }; + this.chain = this.chain + .then(() => + this.discarding ? undefined : this.request.notify(notification), + ) + // A send fails only when the connection is gone, so the stream is too. + .catch(() => this.abort()); + } + + /** Run `fn` when the stream ends. */ + onClose(fn: () => void): void { + this.cleanups.push(fn); + } + + /** + * End the stream abruptly (the client cancelled, a send failed, or the + * connection ended): release it, and send nothing still queued, since the + * extension says delivery stops at cancellation. + */ + abort(): void { + this.discarding = true; + this.close(); + } + + /** + * End the stream gracefully: release it, but send what is already queued + * (a `terminated` goes out before the final result). Safe to call more than + * once. + */ + close(): void { + if (this.closed) return; + this.closed = true; + clearTimeout(this.heartbeat); + for (const fn of this.cleanups.splice(0)) fn(); + this.finish(); + } + + /** Wait for the stream to end and for its last notification to be sent. */ + async ended(): Promise { + await this.done; + await this.chain; + } + + private armHeartbeat(): void { + clearTimeout(this.heartbeat); + this.heartbeat = setTimeout( + () => + this.send("notifications/events/heartbeat", { cursor: this.cursor() }), + this.heartbeatMs, + ); + } +} + +/** Run a `clock-tick` subscription on `stream` until it closes. */ +function runClockTick( + stream: PushStream, + args: ClockTickArgs, + start: { from: number; truncated: boolean }, + heartbeatMs: number, + position: { checked: number }, +): void { + stream.send("notifications/events/active", { + cursor: formatCursor(position.checked), + truncated: start.truncated, + heartbeatMs, + }); + + let timer: NodeJS.Timeout | undefined; + // Deliver every tick up to now that has not been checked yet (the replayed + // backlog, on the first call), then wait for the next one. + const catchUp = () => { + const head = headAt(Date.now()); + // A timer that fires late (the process was suspended, or the clock jumped + // forward) replays no more than a new stream would, and reports the gap + // as the extension asks: a fresh `active` with `truncated: true`. + const oldest = head - RETAINED_TICKS + 1; + if (position.checked + 1 < oldest) { + position.checked = oldest - 1; + stream.send("notifications/events/active", { + cursor: formatCursor(position.checked), + truncated: true, + heartbeatMs, + }); + } + for (let tick = position.checked + 1; tick <= head; tick++) { + position.checked = tick; + if (tickMatches(tick, args)) { + stream.send("notifications/events/event", { + ...tickOccurrence(tick, args), + cursor: formatCursor(tick), + }); + } + } + timer = setTimeout( + catchUp, + (position.checked + 1) * TICK_PERIOD_MS - Date.now(), + ); + }; + stream.onClose(() => clearTimeout(timer)); + catchUp(); +} + +/** Run a `custom-event` subscription on `stream` until it closes. */ +function runCustomEvent( + stream: PushStream, + args: z.infer, + heartbeatMs: number, +): void { + stream.send("notifications/events/active", { + cursor: null, + truncated: false, + heartbeatMs, + }); + const listener = (signal: BusMessage) => { + switch (signal.kind) { + case "event": + if (SEVERITY_RANK[signal.severity] >= SEVERITY_RANK[args.minSeverity]) { + stream.send("notifications/events/event", { + eventId: signal.eventId, + name: "custom-event", + timestamp: signal.timestamp, + data: { message: signal.message, severity: signal.severity }, + cursor: null, + }); + } + break; + case "error": + stream.send("notifications/events/error", { + error: { + code: ProtocolErrorCode.InternalError, + message: "UpstreamError", + data: { reason: signal.message }, + }, + }); + break; + case "terminate": + stream.send("notifications/events/terminated", { + error: { + code: EventsErrorCode.Forbidden, + message: "Forbidden", + data: { reason: signal.message }, + }, + }); + stream.close(); + break; + } + }; + customListeners.add(listener); + stream.onClose(() => customListeners.delete(listener)); +} + +// --------------------------------------------------------------------------- +// The methods +// --------------------------------------------------------------------------- + +const Cursor = z.string().nullable().optional(); + +const ListParams = z.object({ + cursor: z.string().optional().describe("A pagination cursor"), +}); + +const SubscriptionParams = { + name: z.string().describe("The event type to subscribe to"), + arguments: z + .record(z.string(), z.unknown()) + .optional() + .describe("The subscription's arguments, per the type's inputSchema"), + cursor: Cursor.describe("Where to resume; null means start from now"), + maxAgeMs: z + .number() + .int() + .nonnegative() + .optional() + .describe("Do not replay events older than this many milliseconds"), +}; + +const PollParams = z.object({ + ...SubscriptionParams, + maxEvents: z + .number() + .int() + .min(1) + .optional() + .describe("The most events to return"), +}); + +const StreamParams = z.object({ + ...SubscriptionParams, + heartbeatMs: z + .number() + .int() + .positive() + .optional() + .describe("The suggested heartbeat interval"), +}); + +const LooseResult = z.looseObject({}); + +/** + * Serve the extension's methods on a 2026-07-28 server: `events/list`, + * `events/poll` and `events/stream`. + * + * @param {McpServer} server - The 2026-07-28 server to serve them on. + * @param {ServerContext} context - The instance's context, whose cleanup + * closes the streams it still has open. + */ +export function registerEventsExtension( + server: McpServer, + context: ServerContext, +): void { + const streams = new Set(); + context.onCleanup(() => { + for (const stream of streams) stream.abort(); + }); + + server.server.setRequestHandler( + "events/list", + { params: ListParams, result: LooseResult }, + async ({ cursor }) => { + // Every type fits on one page, so no cursor was ever minted. + if (cursor !== undefined) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + `Invalid cursor for events/list: ${cursor}`, + ); + } + return { events: descriptors() }; + }, + ); + + server.server.setRequestHandler( + "events/poll", + { params: PollParams, result: LooseResult }, + async (params) => { + const type = findType(params.name); + requireDelivery(type, "poll"); + // Only clock-tick offers poll. + const args = parseArguments( + ClockTickArguments, + type.name, + params.arguments, + ); + const now = Date.now(); + const head = headAt(now); + const start = startFor(params.cursor, params.maxAgeMs, now); + const maxEvents = Math.min( + params.maxEvents ?? DEFAULT_POLL_EVENTS, + MAX_POLL_EVENTS, + ); + + const events: Json[] = []; + let checked = start.from - 1; + while (checked < head && events.length < maxEvents) { + checked++; + if (tickMatches(checked, args)) { + events.push(tickOccurrence(checked, args)); + } + } + let hasMore = false; + for (let tick = checked + 1; tick <= head && !hasMore; tick++) { + hasMore = tickMatches(tick, args); + } + return { + events, + cursor: formatCursor(checked), + truncated: start.truncated, + hasMore, + nextPollMs: hasMore + ? 0 + : Math.max(MIN_POLL_INTERVAL_MS, (head + 1) * TICK_PERIOD_MS - now), + }; + }, + ); + + server.server.setRequestHandler( + "events/stream", + { params: StreamParams, result: LooseResult }, + async (params, ctx) => { + const type = findType(params.name); + requireDelivery(type, "push"); + const heartbeatMs = Math.min( + MAX_HEARTBEAT_MS, + Math.max(MIN_HEARTBEAT_MS, params.heartbeatMs ?? DEFAULT_HEARTBEAT_MS), + ); + + // Validate everything before the stream opens: an invalid subscription + // is answered with an error and no stream. + let run: (stream: PushStream) => void; + let cursor: () => string | null; + if (type.name === "clock-tick") { + const args = parseArguments( + ClockTickArguments, + type.name, + params.arguments, + ); + const start = startFor(params.cursor, params.maxAgeMs, Date.now()); + const position = { checked: start.from - 1 }; + cursor = () => formatCursor(position.checked); + run = (stream) => + runClockTick(stream, args, start, heartbeatMs, position); + } else { + const args = parseArguments( + CustomEventArguments, + type.name, + params.arguments, + ); + cursor = () => null; + run = (stream) => runCustomEvent(stream, args, heartbeatMs); + } + if (openStreams >= MAX_STREAMS) { + throw new ProtocolError( + EventsErrorCode.ResourceExhausted, + `The server already has ${MAX_STREAMS} event streams open, its limit`, + { limit: "streams", max: MAX_STREAMS }, + ); + } + + const stream = new PushStream(ctx.mcpReq, heartbeatMs, cursor); + openStreams++; + streams.add(stream); + stream.onClose(() => { + openStreams--; + streams.delete(stream); + }); + // Cancellation (notifications/cancelled on stdio, an abort on HTTP) + // ends the stream and releases its timers and listener. + const signal = ctx.mcpReq.signal; + const abort = () => stream.abort(); + signal.addEventListener("abort", abort, { once: true }); + stream.onClose(() => signal.removeEventListener("abort", abort)); + // An already-aborted signal never fires its abort event, so check it. + /* v8 ignore next -- the SDK dispatches no request it has already seen cancelled */ + if (signal.aborted) stream.abort(); + else run(stream); + await stream.ended(); + // The final frame, when the server ends the stream; the SDK sends no + // response to a request the client cancelled. + return { _meta: stream.meta }; + }, + ); +} diff --git a/src/everything/server/index.ts b/src/everything/server/index.ts index fb8a531423..cfa3c157b4 100644 --- a/src/everything/server/index.ts +++ b/src/everything/server/index.ts @@ -17,7 +17,8 @@ // - 2026-07-28: there is no `initialize`, and each request carries the // client's capabilities in its `_meta`, so the capability-gated tools are // registered up front and the SDK refuses an embedded request the client -// did not declare (-32021). The tasks extension is served here only. +// did not declare (-32021). The tasks and events extensions are served here +// only. import { createRequestStateCodec, @@ -33,6 +34,7 @@ import { } from "../tools/index.js"; import { registerResources, readInstructions } from "../resources/index.js"; import { registerPrompts } from "../prompts/index.js"; +import { EVENTS_EXTENSION, registerEventsExtension } from "./events.js"; import { guardTaskTools, registerTasksExtension, @@ -148,9 +150,13 @@ export const createServer = ( // eras: 2025-era clients set the level with `logging/setLevel`, // 2026-07-28 clients per request in `_meta`. logging: {}, - // The tasks extension (`io.modelcontextprotocol/tasks`) is - // advertised on 2026-07-28 only, where it is served. - ...(era === "modern" && { extensions: { [TASKS_EXTENSION]: {} } }), + // The tasks (`io.modelcontextprotocol/tasks`) and events + // (`io.modelcontextprotocol/events`) extensions are advertised on + // 2026-07-28 only, where they are served. Events sends no + // list_changed notifications: its event types never change. + ...(era === "modern" && { + extensions: { [TASKS_EXTENSION]: {}, [EVENTS_EXTENSION]: {} }, + }), }, instructions, cacheHints: CACHE_HINTS, @@ -185,9 +191,11 @@ export const createServer = ( if (era === "modern") { // Each request carries the client's capabilities, so the tools that need - // one are registered up front, along with the tasks extension. + // one are registered up front, along with the tasks and events + // extensions. registerModernTools(server, context); registerTasksExtension(server); + registerEventsExtension(server, context); } else { registerLegacyTools(server, context); setSubscriptionHandlers(server, context.subscribed); diff --git a/src/everything/tools/index.ts b/src/everything/tools/index.ts index 361cd67bcb..55b8d4c361 100644 --- a/src/everything/tools/index.ts +++ b/src/everything/tools/index.ts @@ -9,7 +9,8 @@ // - `registerModernTools`: 2026-07-28 clients. Their capabilities arrive with // each request, so the capability-gated tools are registered up front and the // SDK refuses an embedded request the client did not declare (-32021); the -// task tools are served only here, on the tasks extension. +// task tools are served only here, on the tasks extension, and so is +// `trigger-event`, which drives the events extension. import { McpServer } from "@modelcontextprotocol/server"; import type { ServerContext } from "../server/context.js"; @@ -29,6 +30,7 @@ import { registerToggleSimulatedLoggingTool } from "./toggle-simulated-logging.j import { registerToggleSubscriberUpdatesTool } from "./toggle-subscriber-updates.js"; import { registerTriggerElicitationRequestAsyncTool } from "./trigger-elicitation-request-async.js"; import { registerTriggerElicitationRequestTool } from "./trigger-elicitation-request.js"; +import { registerTriggerEventTool } from "./trigger-event.js"; import { registerTriggerListChangedTool } from "./trigger-list-changed.js"; import { registerTriggerLogMessagesTool } from "./trigger-log-messages.js"; import { registerTriggerLongRunningOperationTool } from "./trigger-long-running-operation.js"; @@ -108,7 +110,8 @@ export const registerConditionalTools = ( /** * Register the tools a 2026-07-28 client gets beyond the common ones: the - * capability-gated tools, registered up front, and the task tools. + * capability-gated tools, registered up front, the task tools, and the + * events extension's trigger-event. * @param server * @param context */ @@ -124,4 +127,5 @@ export const registerModernTools = ( registerSimulateResearchQueryTool(server); registerTriggerSamplingRequestAsyncTool(server); registerTriggerElicitationRequestAsyncTool(server); + registerTriggerEventTool(server); }; diff --git a/src/everything/tools/trigger-event.ts b/src/everything/tools/trigger-event.ts new file mode 100644 index 0000000000..b3777b74c3 --- /dev/null +++ b/src/everything/tools/trigger-event.ts @@ -0,0 +1,85 @@ +// The `trigger-event` tool: raises the Events extension's `custom-event` on +// every open push stream subscribed to it (#5651), so a client can watch an +// event arrive on `events/stream` when it asks for one. +// +// Besides an ordinary event, it can make the streams report a recoverable +// upstream failure (`notifications/events/error`, the stream stays open) or +// end their subscriptions (`notifications/events/terminated`), the two +// non-event outcomes a push subscriber has to handle. The extension is served +// on 2026-07-28 only, so the tool is too. + +import { McpServer, CallToolResult } from "@modelcontextprotocol/server"; +import { z } from "zod"; +import { emitCustomEvent } from "../server/events.js"; +import { TOOL_ICONS } from "../server/icons.js"; + +// Tool input schema +const TriggerEventSchema = z.object({ + kind: z + .enum(["event", "error", "terminate"]) + .default("event") + .describe( + "event: deliver a custom-event occurrence; error: send notifications/events/error and keep the " + + "streams open; terminate: send notifications/events/terminated and close the streams", + ), + message: z + .string() + .min(1) + .max(500) + .default("Hello from trigger-event") + .describe( + "The event's message, or the reason given for an error or termination", + ), + severity: z + .enum(["info", "warning", "error"]) + .default("info") + .describe( + "The event's severity, matched against each stream's minSeverity (kind event only)", + ), +}); + +// Tool configuration +const name = "trigger-event"; +const config = { + title: "Trigger Event Tool", + description: + "Raises the Events extension's custom-event on every open events/stream subscribed to it. " + + "With kind error it sends a recoverable notifications/events/error instead, and with kind " + + "terminate it ends those subscriptions with notifications/events/terminated.", + inputSchema: TriggerEventSchema, + icons: TOOL_ICONS, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, +}; + +/** + * Registers the 'trigger-event' tool. + * + * @param {McpServer} server - The McpServer instance where the tool will be registered. + */ +export const registerTriggerEventTool = (server: McpServer) => { + server.registerTool(name, config, async (args): Promise => { + const { kind, message, severity } = TriggerEventSchema.parse(args); + const streams = emitCustomEvent( + kind === "event" ? { kind, message, severity } : { kind, message }, + ); + const what = + kind === "event" + ? `custom-event (${severity})` + : kind === "error" + ? "notifications/events/error" + : "notifications/events/terminated"; + return { + content: [ + { + type: "text", + text: `Sent ${what} to ${streams} open custom-event stream${streams === 1 ? "" : "s"}`, + }, + ], + }; + }); +}; diff --git a/src/everything/transports/idle-sessions.ts b/src/everything/transports/idle-sessions.ts new file mode 100644 index 0000000000..930455a61e --- /dev/null +++ b/src/everything/transports/idle-sessions.ts @@ -0,0 +1,128 @@ +// Idle-session eviction for the Streamable HTTP transport's 2025-era sessions +// (#5558). +// +// A 2025-era session holds a server instance, a transport and an event store +// until its client ends it with a DELETE. A client that initializes and then +// goes away never does, so without this every abandoned session stayed in +// memory for the life of the process. The spec lets a server end a session at +// any time, after which it answers that session id with 404 and the client +// starts a new one, so an idle session is closed after a timeout. +// +// "Idle" means no request in flight and no stream open: every request served +// for a session is held as activity until its response closes, so a session +// with an open SSE stream, or a tool call still running, is never evicted +// however long it has been quiet. The clock starts when the last response +// closes. +// +// This module only decides when; the transport manager supplies what evicting +// means (closing the session's transport). It is kept apart from +// `streamableHttp.ts` so the timing can be tested with fake timers and no +// HTTP. The HTTP+SSE transport needs none of this: its session is its +// `GET /sse` stream, and it is cleaned up when that stream's socket closes. + +/** How long a session may sit idle before it is evicted, by default: 30 minutes. */ +export const DEFAULT_SESSION_IDLE_TIMEOUT_MILLIS = 30 * 60 * 1000; + +/** + * Idle sessions are looked for every tenth of the timeout, so one is evicted + * at most a tenth late, but no less often than this ... + */ +const MAX_SWEEP_INTERVAL_MILLIS = 60 * 1000; + +/** ... and no more often than this, however short the timeout. */ +const MIN_SWEEP_INTERVAL_MILLIS = 1000; + +/** + * The idle timeout `SESSION_IDLE_TIMEOUT_MILLIS` asks for, in milliseconds: + * `0` disables eviction, and anything that is not a non-negative number + * (unset, empty, negative, not a number) means the default. + */ +export function sessionIdleTimeoutMillis( + value: string | undefined = process.env.SESSION_IDLE_TIMEOUT_MILLIS, +): number { + const millis = Number(value?.trim() || NaN); + return Number.isFinite(millis) && millis >= 0 + ? millis + : DEFAULT_SESSION_IDLE_TIMEOUT_MILLIS; +} + +/** The part of a response this module needs: to learn when it has closed. */ +export type ClosableResponse = { + once(event: "close", listener: () => void): unknown; +}; + +/** The sessions being watched for idleness. */ +export type IdleSessions = { + /** Start watching a session; it is idle from now. */ + add(sessionId: string): void; + /** Count a request as the session's activity until its response closes. */ + hold(sessionId: string, res: ClosableResponse): void; + /** Stop watching a session that has ended. */ + remove(sessionId: string): void; + /** Stop looking for idle sessions, for shutdown. */ + stop(): void; +}; + +type Activity = { + /** Requests whose responses are still open. */ + open: number; + /** When `open` last reached zero. */ + idleSince: number; +}; + +/** + * Watch sessions for idleness, calling `evict` once for each session that has + * had no open response for `timeoutMillis`. A session is checked on a timer + * (unref'd, so it never keeps the process alive) that fires every tenth of + * the timeout, kept between a second and a minute, so it is evicted within + * one such interval after its timeout. A `timeoutMillis` of `0` disables + * eviction: no timer runs and nothing is ever evicted. + */ +export function watchIdleSessions( + timeoutMillis: number, + evict: (sessionId: string) => void, +): IdleSessions { + const sessions = new Map(); + + const sweep = () => { + const now = Date.now(); + for (const [sessionId, activity] of [...sessions]) { + if (activity.open === 0 && now - activity.idleSince >= timeoutMillis) { + sessions.delete(sessionId); + evict(sessionId); + } + } + }; + + const timer = + timeoutMillis > 0 + ? setInterval( + sweep, + Math.max( + MIN_SWEEP_INTERVAL_MILLIS, + Math.min(timeoutMillis / 10, MAX_SWEEP_INTERVAL_MILLIS), + ), + ).unref() + : undefined; + + return { + add(sessionId) { + sessions.set(sessionId, { open: 0, idleSince: Date.now() }); + }, + hold(sessionId, res) { + const activity = sessions.get(sessionId); + if (!activity) return; + activity.open++; + res.once("close", () => { + activity.open--; + activity.idleSince = Date.now(); + }); + }, + remove(sessionId) { + sessions.delete(sessionId); + }, + stop() { + clearInterval(timer); + }, + }; +} diff --git a/src/everything/transports/streamableHttp.ts b/src/everything/transports/streamableHttp.ts index d5b9ac9510..003f4b9cae 100644 --- a/src/everything/transports/streamableHttp.ts +++ b/src/everything/transports/streamableHttp.ts @@ -20,6 +20,10 @@ // classified by the SDK's own `isLegacyRequest`, from a body parsed once and // handed to whichever side serves it. // +// A 2025-era session whose client never ends it is evicted once it has been +// idle for `SESSION_IDLE_TIMEOUT_MILLIS` (#5558); `idle-sessions.ts` holds the +// reasoning and decides when, and this file closes the transport. +// // `createApp()` builds the Express app without binding a port or installing a // signal handler (#4854), so a test can serve it on a free port, drive it with // a real client, and call its shutdown handler directly; each app has its own @@ -44,6 +48,10 @@ import { randomUUID } from "node:crypto"; import cors from "cors"; import { bindHost, hostAndPort, listenOrExit } from "./listen.js"; import { InMemoryEventStore } from "./in-memory-event-store.js"; +import { + sessionIdleTimeoutMillis, + watchIdleSessions, +} from "./idle-sessions.js"; /** The most bytes of a refused POST's body read to find its request id. */ const MAX_ID_BODY_BYTES = 64 * 1024; @@ -126,6 +134,16 @@ function bodyError( } } +/** What `createApp()` can be told; the launcher passes nothing. */ +export type StreamableHttpAppOptions = { + /** + * How long a 2025-era session may sit idle before it is evicted, in + * milliseconds; `0` disables eviction. Defaults to what + * `SESSION_IDLE_TIMEOUT_MILLIS` asks for. + */ + sessionIdleTimeoutMillis?: number; +}; + /** The Streamable HTTP app, and the handler the launcher installs for SIGINT. */ export type StreamableHttpApp = { app: Express; @@ -135,10 +153,12 @@ export type StreamableHttpApp = { /** * Build the Streamable HTTP transport's Express app: Origin validation, CORS, * the `/mcp` POST, GET and DELETE routes, the map from session id to - * transport that they share, the 2026-07-28 handler, and the shutdown handler - * that closes them. + * transport that they share, the eviction of idle sessions from it, the + * 2026-07-28 handler, and the shutdown handler that closes them. */ -export function createApp(): StreamableHttpApp { +export function createApp( + options: StreamableHttpAppOptions = {}, +): StreamableHttpApp { const app = express(); // A browser page may reach this server only from a localhost origin. The // SDK's guard answers any other Origin with a 403 before a route or the @@ -191,6 +211,27 @@ export function createApp(): StreamableHttpApp { NodeStreamableHTTPServerTransport >(); + // A session nobody has used for the idle timeout is closed, which runs its + // onclose below, so it is removed and cleaned up as a DELETE would have. + // Its next request is answered 404, the client's signal to initialize again. + const idleTimeoutMillis = + options.sessionIdleTimeoutMillis ?? sessionIdleTimeoutMillis(); + const idle = watchIdleSessions(idleTimeoutMillis, (sessionId) => { + console.log( + `Session ${sessionId} idle for ${idleTimeoutMillis} ms, closing it`, + ); + transports + .get(sessionId) + ?.close() + .catch((error: unknown) => { + console.log(`Error closing idle session ${sessionId}:`, error); + // The session is still held, so watch it again: it is tried again + // after another timeout rather than kept for good. (If it did end, + // that later look finds no transport and just forgets it.) + idle.add(sessionId); + }); + }); + // A session-less POST's body is parsed once, to classify it and serve it. // A POST with a session id is a 2025-era session's, and its transport reads // the body itself. @@ -236,6 +277,7 @@ export function createApp(): StreamableHttpApp { // This avoids race conditions where requests might come in before the session is stored console.log(`Session initialized with ID: ${sessionId}`); transports.set(sessionId, transport); + idle.add(sessionId); }, }); @@ -247,6 +289,7 @@ export function createApp(): StreamableHttpApp { `Transport closed for session ${sid}, removing from transports map`, ); transports.delete(sid); + idle.remove(sid); cleanup(); } }; @@ -264,6 +307,8 @@ export function createApp(): StreamableHttpApp { // Handle the request with existing transport - no need to reconnect // The existing transport is already connected to the server + // (a request in flight keeps its session from being evicted as idle) + idle.hold(sessionId, res); await transport.handleRequest(req, res); } catch (error) { console.log("Error handling MCP request:", error); @@ -309,6 +354,8 @@ export function createApp(): StreamableHttpApp { console.log(`Establishing new SSE stream for session ${sessionId}`); } + // The session is in use for as long as this stream stays open + idle.hold(sessionId, res); const transport = transports.get(sessionId); await transport!.handleRequest(req, res); }); @@ -359,6 +406,9 @@ export function createApp(): StreamableHttpApp { const shutdown = async () => { console.log("Shutting down server..."); + // Stop looking for idle sessions: every session is closed below + idle.stop(); + // End the 2026-07-28 requests and subscription streams in flight await modern.close(); diff --git a/src/fetch/README.md b/src/fetch/README.md index c051833aec..545e04ca52 100644 --- a/src/fetch/README.md +++ b/src/fetch/README.md @@ -185,9 +185,12 @@ Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace By default, the server will obey a websites robots.txt file if the request came from the model (via a tool), but not if the request was user initiated (via a prompt). Every redirect hop of a tool fetch is checked against the robots.txt of -the host it leads to, the same way as the requested URL. A path is matched against the rules both as it is spelled and -as an origin typically resolves it (`%2F` and `%2E` decoded, repeated slashes merged, `.` and `..` segments removed), -and the fetch is refused if either is disallowed, so `//private` or `/x/../private` cannot get past `Disallow: /private`. +the host it leads to, the same way as the requested URL. A path is matched against the rules as it is spelled, as an +origin typically resolves it (`%2F` and `%2E` decoded, repeated slashes merged, `.` and `..` segments removed), as an +origin with Windows path semantics resolves it (the same, with a backslash or `%5C` also read as a separator), and as a +servlet container resolves it (the same, with a `;` parameter dropped from each segment). The fetch is refused if any +of these is disallowed, so +`//private`, `/x/../private`, `/x%5C..%5Cprivate` or `/x/..;/private` cannot get past `Disallow: /private`. Matching stays case-sensitive, as RFC 9309 specifies. If the robots.txt request fails to connect, or is answered with 401, 403 or a server error (5xx), the tool refuses the fetch rather than reading the response as rules (RFC 9309 treats a 5xx robots.txt as complete disallow); any other 4xx is treated as no rules. This can be disabled by adding the diff --git a/src/fetch/pyproject.toml b/src/fetch/pyproject.toml index 95a6ec077b..2ca92809d6 100644 --- a/src/fetch/pyproject.toml +++ b/src/fetch/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mcp-server-fetch" -version = "2026.11.18" +version = "2026.11.27" description = "A Model Context Protocol server providing tools to fetch and convert web content for usage by LLMs" readme = "README.md" requires-python = ">=3.11.5" diff --git a/src/fetch/server.json b/src/fetch/server.json new file mode 100644 index 0000000000..931d14a9d2 --- /dev/null +++ b/src/fetch/server.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-fetch", + "title": "Fetch", + "description": "Fetches web content and converts it to Markdown for an LLM to read", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/fetch" + }, + "packages": [ + { + "registryType": "pypi", + "identifier": "mcp-server-fetch", + "transport": { + "type": "stdio" + } + } + ] +} diff --git a/src/fetch/src/mcp_server_fetch/server.py b/src/fetch/src/mcp_server_fetch/server.py index 696459e620..54c269a6b1 100644 --- a/src/fetch/src/mcp_server_fetch/server.py +++ b/src/fetch/src/mcp_server_fetch/server.py @@ -721,6 +721,9 @@ def handle_starttag( _ENCODED_SLASH = re.compile("%2f", re.IGNORECASE) _ENCODED_DOT = re.compile("%2e", re.IGNORECASE) _REPEATED_SLASHES = re.compile("/{2,}") +# A backslash, literal or escaped, which some origins (IIS, Windows-backed +# servers) read as a path separator. +_BACKSLASH = re.compile(r"\\|%5c", re.IGNORECASE) def _remove_dot_segments(path: str) -> str: @@ -742,7 +745,9 @@ def _remove_dot_segments(path: str) -> str: return "/" + "/".join(resolved) + trailing -def _resolved_path_url(url: str) -> str: +def _resolved_path_url( + url: str, *, backslash_separator: bool = False, drop_parameters: bool = False +) -> str: """``url`` with its path spelled the way a typical origin resolves it. robots.txt rules match the path a crawler requests, but an origin such as @@ -751,9 +756,21 @@ def _resolved_path_url(url: str) -> str: repeated slashes merged and dot segments removed before rules are matched against it, as well as against the path as spelled. The query is kept as it is, and matching stays case-sensitive (RFC 9309 2.2.2). + + Origins with other path semantics are covered by further spellings, each + matched in addition to the others rather than in place of one, so each + only ever adds refusals: with ``backslash_separator`` a backslash (literal + or ``%5C``) is a separator, as on IIS; with ``drop_parameters`` a ``;`` + path parameter is dropped from each segment, as in a Java servlet + container. They are separate spellings because no origin is assumed to + do both. """ parts = urlsplit(url) path = _ENCODED_DOT.sub(".", _ENCODED_SLASH.sub("/", parts.path)) + if backslash_separator: + path = _BACKSLASH.sub("/", path) + if drop_parameters: + path = "/".join(segment.split(";", 1)[0] for segment in path.split("/")) path = _remove_dot_segments(_REPEATED_SLASHES.sub("/", path)) return urlunsplit(parts._replace(path=path)) @@ -804,12 +821,15 @@ async def check_may_autonomously_fetch_url( line for line in robot_txt.splitlines() if not line.strip().startswith("#") ) robot_parser = Protego.parse(processed_robot_txt) - # Refused when either spelling of the path is disallowed: resolving the + # Refused when any spelling of the path is disallowed: resolving the # path only ever adds refusals. - if not ( - robot_parser.can_fetch(url, user_agent) - and robot_parser.can_fetch(_resolved_path_url(url), user_agent) - ): + spellings = ( + url, + _resolved_path_url(url), + _resolved_path_url(url, backslash_separator=True), + _resolved_path_url(url, drop_parameters=True), + ) + if not all(robot_parser.can_fetch(spelling, user_agent) for spelling in spellings): raise ToolError( f"The sites robots.txt ({robot_txt_url}), specifies that autonomous fetching of this page is not allowed, " f"{user_agent}\n" diff --git a/src/fetch/tests/test_protocol.py b/src/fetch/tests/test_protocol.py index 5529f0d047..e618b6d5b1 100644 --- a/src/fetch/tests/test_protocol.py +++ b/src/fetch/tests/test_protocol.py @@ -475,6 +475,14 @@ async def test_ignore_robots_txt_skips_the_check(web: FakeWeb) -> None: "/%2e/private", "/x/%2E%2E/private", "//private//report", + # An origin that reads a backslash as a separator (IIS) serves + # /private for these. + "/public%5c..%5cprivate", + "/public%5C..%5Cprivate", + # A servlet container drops ;parameters from each segment first. + "/public/..;/private", + "/public;x/..;y/private", + "/;x/private", ], ) async def test_robots_disallow_matches_the_resolved_path( @@ -503,6 +511,11 @@ async def test_robots_disallow_matches_the_resolved_path( "/x/..%2Fprivate", "/x/%2e%2e//private", "/x//%2e%2e/private", + # A redirect carries a literal backslash as it is, where a tool + # argument would have it read as a separator first. + "/public\\..\\private", + "/public%5c..%5cprivate", + "/public/..;/private", ], ) async def test_redirect_to_a_disallowed_path_spelled_otherwise_is_refused( @@ -528,6 +541,8 @@ async def test_redirect_to_a_disallowed_path_spelled_otherwise_is_refused( "/pri%20vate", # Matching stays case-sensitive (RFC 9309 2.2.2). "//Private", + "/public%5cprivate", + "/public;private", ], ) async def test_robots_allows_a_path_that_resolves_outside_the_rule( @@ -543,6 +558,44 @@ async def test_robots_allows_a_path_that_resolves_outside_the_rule( assert web.urls() == [ROBOTS, url] +async def test_robots_disallow_still_matches_the_dot_resolved_spelling( + web: FakeWeb, +) -> None: + # Dropping ;parameters is matched in addition to the dot-resolved + # spelling, so a rule naming a parameter still refuses a path that only + # resolves to it once its dot segments are removed. + url = "https://example.com/x/%2e%2e/a;b" + web.add(ROBOTS, plain("User-agent: *\nDisallow: /a;b")) + web.add(url, plain("private-page")) + async with connect() as (session, _): + result = await call(session, {"url": url}) + assert wire(result)["isError"] is True + assert "private-page" not in text_of(result) + assert web.urls() == [ROBOTS] + + +@pytest.mark.parametrize( + ("rule", "path"), + [ + # An origin that reads a backslash as a separator keeps ;parameters, + # and one that drops ;parameters keeps backslashes. + ("/a;b", "/x%5c..%5ca;b"), + ("/a%5Cb", "/x/..;/a%5Cb"), + ], +) +async def test_robots_disallow_matches_each_resolution_on_its_own( + web: FakeWeb, rule: str, path: str +) -> None: + url = f"https://example.com{path}" + web.add(ROBOTS, plain(f"User-agent: *\nDisallow: {rule}")) + web.add(url, plain("private-page")) + async with connect() as (session, _): + result = await call(session, {"url": url}) + assert wire(result)["isError"] is True + assert "private-page" not in text_of(result) + assert web.urls() == [ROBOTS] + + async def test_robots_disallow_still_matches_the_literal_spelling( web: FakeWeb, ) -> None: diff --git a/src/fetch/uv.lock b/src/fetch/uv.lock index 6a2c8ad414..8a48c1d80d 100644 --- a/src/fetch/uv.lock +++ b/src/fetch/uv.lock @@ -829,7 +829,7 @@ wheels = [ [[package]] name = "mcp-server-fetch" -version = "2026.11.18" +version = "2026.11.27" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, diff --git a/src/filesystem/CHANGELOG.md b/src/filesystem/CHANGELOG.md index c48aaf6ccc..193f87c06a 100644 --- a/src/filesystem/CHANGELOG.md +++ b/src/filesystem/CHANGELOG.md @@ -1,5 +1,15 @@ # @modelcontextprotocol/server-filesystem +## 2.4.1 + +### Patch Changes + +- [#5618](https://github.com/modelcontextprotocol/servers/pull/5618) [`37a1f2f`](https://github.com/modelcontextprotocol/servers/commit/37a1f2f8dd72a6912969ac990f556422caa801fa) [@cliffhall](https://github.com/cliffhall) - `move_file` now refuses to move a directory into itself with `Cannot move a directory into itself: is inside `, instead of reporting `Parent directory does not exist` for a destination directory that does exist. + +- [#5622](https://github.com/modelcontextprotocol/servers/pull/5622) [`062b32a`](https://github.com/modelcontextprotocol/servers/commit/062b32a52fb8d6bfab96ae7085aeca6bae06eade) [@cliffhall](https://github.com/cliffhall) - On Windows, `list_directory`, `list_directory_with_sizes`, `directory_tree` and `search_files` now check the directory they list before and after reading it: its path must have no junction or symlink on it and must name the same directory both times, or the call is refused with "Access denied - a directory on the path changed during the operation". A directory swapped for a junction after the path was validated is no longer listed. A swap made and undone while the directory is being read is still not detected; the README's "Limit on Windows" entry says what holds. macOS and Linux are unchanged. + +- [#5620](https://github.com/modelcontextprotocol/servers/pull/5620) [`731abb0`](https://github.com/modelcontextprotocol/servers/commit/731abb0a1ea3e5dc0075c0ff95f0e21a27691b50) [@cliffhall](https://github.com/cliffhall) - `search_files` no longer answers a search that matched nothing with a bare `No matches found`. The result still begins with those words, and now names the pattern and the directory searched, says the pattern is a case-sensitive glob over names relative to that directory (never file contents), and, for a pattern with no `**`, suggests the `**/` form that reaches subdirectories. + ## 2.4.0 ### Minor Changes diff --git a/src/filesystem/README.md b/src/filesystem/README.md index 0335ff5551..7435ff3606 100644 --- a/src/filesystem/README.md +++ b/src/filesystem/README.md @@ -128,7 +128,7 @@ The server's directory access control follows this flow: - A path is checked and then used, so on macOS and Linux each write, each read of a file's content or metadata, and each directory listing (`list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`) acts from inside the directory that was checked. If a directory on the path is replaced in between, the call is refused with "Access denied - a directory on the path changed during the operation" rather than following the replacement. A listing therefore needs to enter the directory it lists: a directory the server can read but not enter (read permission without execute) is refused with `EACCES`, as an unreadable one is - On Windows, a path naming an NTFS alternate data stream (`file.txt:stream`, `file.txt::$DATA`) is refused with "Access denied - NTFS alternate data stream paths are not supported", even inside an allowed directory: a colon is accepted only as a drive letter's (`C:\`, `\\?\C:\`). A stream holds data that no directory listing or diff of the file shows. On macOS and Linux a colon is an ordinary file-name character and is not refused - On Windows, a path any of whose components is a reserved device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, in any case and with or without an extension, such as `NUL.txt`) is refused with "Access denied - Windows reserved device names ... are not supported", and one any of whose components ends in a dot or a space (`file.txt.`, `dir \file.txt`) with "Access denied - Windows path components ending in a dot or a space are not supported". Windows opens the device rather than a file in the directory, and strips trailing dots and spaces so the name refers to a different file. `.` and `..` are not affected. On macOS and Linux these are ordinary file names and are not refused - - **Limit on Windows: a parent directory swapped during an operation.** A path is checked and then used, and a directory on it could be replaced in between. On Linux and macOS the server anchors every write, and every read of a file's content or metadata, to the directory it validated, so a directory replaced with a symlink after the check cannot redirect the operation. **On Windows it cannot do that, and the operation is not protected**: a second local process that can already write inside an allowed directory can replace a parent directory with a junction (or a directory symlink) between the server's check and its open, and so redirect a read or a write outside the allowed directories. The server still checks the final component there (a write refuses a symlink or junction at the file's own name, and the file opened must be the one the directory holds at that name afterwards), which narrows the window without closing it + - **Limit on Windows: a parent directory swapped during an operation.** A path is checked and then used, and a directory on it could be replaced in between. On Linux and macOS the server anchors every write, every read of a file's content or metadata, and every directory listing, to the directory it validated, so a directory replaced with a symlink after the check cannot redirect the operation. **On Windows it cannot do that, and the operation is not protected**: a second local process that can already write inside an allowed directory can replace a parent directory with a junction (or a directory symlink) between the server's check and its open, and so redirect a read, a write or a directory listing outside the allowed directories. The server still checks the final component there (a write refuses a symlink or junction at the file's own name, and the file opened must be the one the directory holds at that name afterwards), which narrows the window without closing it. A directory listing (`list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`) is checked on both sides of the read instead: before and after it, the listed path must have no junction or symlink on it and must name the same directory, or the call is refused with "Access denied - a directory on the path changed during the operation". That refuses a replacement still in place when the read starts or when it ends. One made and undone in between is not detected, and returns the entry names of the directory it pointed to, so this too narrows the window without closing it - **What it takes**: a concurrent local process with write access inside an allowed directory, winning a race against the server. No tool of this server creates a junction or a symlink, so it cannot be set up through the server alone - **Guidance**: on Windows, do not allow a directory that untrusted local processes or users can write to - **Why it is not fixed**: closing the window needs opens relative to a directory handle, which Node does not expose, so it would take native code, and that is out of scope for a reference server ([#5260](https://github.com/modelcontextprotocol/servers/issues/5260)). It may be revisited when Node ships a stable built-in FFI under this package's `engines` floor @@ -256,6 +256,9 @@ Files inside the allowed directories are also [resources](https://modelcontextpr - `source` (string) - `destination` (string) - Fails if destination exists + - A directory cannot be moved into itself: a destination inside the source + directory fails with `Cannot move a directory into itself: + is inside `, and nothing is moved - Across filesystems (the source and destination on different mounts or disks), a regular file is moved by copying it to a newly created destination, with its permissions and modification time, and then removing @@ -297,6 +300,10 @@ Files inside the allowed directories are also [resources](https://modelcontextpr entirely. - Glob-style pattern matching - Returns full paths to matches + - When nothing matches, the result begins `No matches found` and goes on to + name the pattern and the directory searched and to say how the pattern is + read. For a pattern with no `**`, which only matches at one depth, it also + suggests the `**/` form that matches at any depth - Bounded: see [Slow and very large trees](#slow-and-very-large-trees) - A subdirectory that cannot be read (no permission, say) is skipped, and the result says so: after the matches, a note that the search is incomplete diff --git a/src/filesystem/__tests__/exclude-glob-prunes-dir.test.ts b/src/filesystem/__tests__/exclude-glob-prunes-dir.test.ts index c520bacbb6..00c3d899ea 100644 --- a/src/filesystem/__tests__/exclude-glob-prunes-dir.test.ts +++ b/src/filesystem/__tests__/exclude-glob-prunes-dir.test.ts @@ -140,7 +140,7 @@ describe('excludePatterns ending in "/**" (#5445)', () => { excludePatterns: ["**/node_modules/**"], }); expect(result.isError).toBeFalsy(); - expect(textOf(result)).toBe("No matches found"); + expect(textOf(result)).toMatch(/^No matches found for pattern /); }); it("directory_tree does not list the excluded directory, even as empty", async () => { diff --git a/src/filesystem/__tests__/list-anchored-windows.test.ts b/src/filesystem/__tests__/list-anchored-windows.test.ts new file mode 100644 index 0000000000..176977a7ed --- /dev/null +++ b/src/filesystem/__tests__/list-anchored-windows.test.ts @@ -0,0 +1,180 @@ +// The Windows listing check (#5600): readDirectoryInPlace cannot anchor a +// listing on Windows (the working directory is a path string there), so it +// checks the listed directory before and after the read: the path must +// resolve to itself, with no junction or symlink on it, and must name the +// same directory both times (pinned-directory.ts). +// +// These tests run that branch on every host. On Windows (the CI Windows leg) +// it runs for real, against real junctions. Elsewhere process.platform is +// set to "win32", which is all the branch reads; the filesystem stays the +// host's, so the swaps are real there too, and the coverage gate (which runs +// on Linux) sees the branch. +// +// A swap staged from inside the read can be refused by the host: Windows will +// not rename a directory a process is in, and the server is in the listed +// directory. So those tests assert what must hold either way: the entries +// returned are never the outside directory's, and a swap that did happen is +// refused. The protocol-level tests of a swap staged before the listing are +// in list-anchored.test.ts, and run on Windows too. + +import fsSync from "fs"; +import path from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { readDirectoryInPlace } from "../pinned-directory.js"; +import { makeTempDir } from "./helpers.js"; + +const OUTSIDE_NAME = "OUTSIDE-NAME-CANARY.txt"; +const INSIDE_NAME = "inside-marker.txt"; +const DIRECTORY_CHANGED = + /Access denied - a directory on the path changed during the operation/; + +const realPlatform = process.platform; + +let dir: string; +let outside: string; +let middle: string; +let listed: string; + +beforeEach(async () => { + dir = await makeTempDir("mcp-fs-list-win-"); + outside = await makeTempDir("mcp-fs-list-win-outside-"); + middle = path.join(dir, "middle"); + listed = path.join(middle, "listed"); + fsSync.mkdirSync(listed, { recursive: true }); + fsSync.writeFileSync(path.join(listed, INSIDE_NAME), "inside"); + // The outside tree mirrors the inside one, so a swapped parent still leads + // to a real directory named "listed". + fsSync.mkdirSync(path.join(outside, "listed")); + fsSync.writeFileSync(path.join(outside, OUTSIDE_NAME), "outside"); + fsSync.writeFileSync(path.join(outside, "listed", OUTSIDE_NAME), "outside"); + Object.defineProperty(process, "platform", { value: "win32" }); +}); + +afterEach(() => { + vi.restoreAllMocks(); + Object.defineProperty(process, "platform", { value: realPlatform }); + fsSync.rmSync(dir, { recursive: true, force: true }); + fsSync.rmSync(outside, { recursive: true, force: true }); +}); + +/** A junction on Windows, which needs no privilege; a symlink elsewhere. */ +function link(target: string, at: string): void { + fsSync.symlinkSync(target, at, "junction"); +} + +/** Run `swap` on the first readdirSync, before the real read; say if it ran. */ +function swapDuringRead(swap: () => void): { swapped: () => boolean } { + const realReaddirSync = fsSync.readdirSync.bind(fsSync) as ( + target: fsSync.PathLike, + options: { withFileTypes: true }, + ) => fsSync.Dirent[]; + let attempted = false; + let swapped = false; + vi.spyOn(fsSync, "readdirSync").mockImplementation((( + target: fsSync.PathLike, + options: { withFileTypes: true }, + ) => { + if (!attempted) { + attempted = true; + try { + swap(); + swapped = true; + } catch { + // The host refused the swap (see the header); nothing changed. + } + } + return realReaddirSync(target, options); + }) as typeof fsSync.readdirSync); + return { swapped: () => swapped }; +} + +/** List `listed`; the names it returned, or the refusal it threw. */ +function listNames(): { names?: string[]; refusal?: string } { + try { + return { names: readDirectoryInPlace(listed).map((entry) => entry.name) }; + } catch (error) { + return { refusal: (error as Error).message }; + } +} + +describe("the Windows listing check", () => { + it("lists a directory nothing was swapped on, naming it as the parent", () => { + const entries = readDirectoryInPlace(listed); + expect(entries.map((entry) => entry.name)).toEqual([INSIDE_NAME]); + expect(entries[0].parentPath).toBe(listed); + expect(entries[0].isFile()).toBe(true); + }); + + it("refuses a directory that is now a link to one outside", () => { + fsSync.renameSync(listed, path.join(middle, "listed-real")); + link(outside, listed); + const { names, refusal } = listNames(); + expect(names).toBeUndefined(); + expect(refusal).toMatch(DIRECTORY_CHANGED); + }); + + it("refuses a directory whose parent is now a link to one outside", () => { + // The last component is a real directory, the outside tree's "listed", so + // only the path's real location shows the swap. + fsSync.renameSync(middle, path.join(dir, "middle-real")); + link(outside, middle); + const { names, refusal } = listNames(); + expect(names).toBeUndefined(); + expect(refusal).toMatch(DIRECTORY_CHANGED); + }); + + it("never returns the outside entries when the directory is swapped for a link during the read", () => { + const { swapped } = swapDuringRead(() => { + fsSync.renameSync(listed, path.join(middle, "listed-real")); + link(outside, listed); + }); + const { names, refusal } = listNames(); + expect(names ?? []).not.toContain(OUTSIDE_NAME); + if (swapped()) { + expect(refusal).toMatch(DIRECTORY_CHANGED); + } else { + expect(names).toEqual([INSIDE_NAME]); + } + }); + + it("never returns the outside entries when a parent is swapped for a link during the read", () => { + const { swapped } = swapDuringRead(() => { + fsSync.renameSync(middle, path.join(dir, "middle-real")); + link(outside, middle); + }); + const { names, refusal } = listNames(); + expect(names ?? []).not.toContain(OUTSIDE_NAME); + if (swapped()) { + expect(refusal).toMatch(DIRECTORY_CHANGED); + } else { + expect(names).toEqual([INSIDE_NAME]); + } + }); + + it("refuses when another directory takes the name during the read", () => { + // No link anywhere, so only the identity shows it is not the directory + // the first check saw. + const { swapped } = swapDuringRead(() => { + fsSync.renameSync(listed, path.join(middle, "listed-real")); + fsSync.mkdirSync(listed); + }); + const { names, refusal } = listNames(); + if (swapped()) { + expect(refusal).toMatch(DIRECTORY_CHANGED); + } else { + expect(names).toEqual([INSIDE_NAME]); + } + }); + + it.skipIf(realPlatform === "win32")( + "is not applied off Windows, where the listing is anchored", + () => { + Object.defineProperty(process, "platform", { value: realPlatform }); + const lstat = vi.spyOn(fsSync, "lstatSync"); + expect(readDirectoryInPlace(listed).map((entry) => entry.name)).toEqual([ + INSIDE_NAME, + ]); + expect(lstat).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/src/filesystem/__tests__/list-anchored.test.ts b/src/filesystem/__tests__/list-anchored.test.ts index 1f8b8e4f93..72cbddd624 100644 --- a/src/filesystem/__tests__/list-anchored.test.ts +++ b/src/filesystem/__tests__/list-anchored.test.ts @@ -6,6 +6,10 @@ // is swapped for a symlink to a directory outside the allowed one. Each // listing must then refuse rather than return the outside directory's entry // names. Before listings were anchored, each of these returned them. +// +// They run on Windows too (#5600), where the swap is a junction, which needs +// no privilege, and the refusal comes from the check made around the read +// rather than from an anchor (list-anchored-windows.test.ts). import fs from "fs/promises"; import fsSync from "fs"; @@ -52,16 +56,19 @@ afterEach(async () => { await fs.rm(outside, { recursive: true, force: true }); }); -/** Swap `flip` for a symlink to `outside`, once, right after it is realpath'd. */ +/** + * Swap `flip` for a link to `outside`, once, right after it is realpath'd. + * "junction" picks the link type on Windows and is ignored elsewhere. + */ function swapAfterRealpath(): void { const realRealpath = fs.realpath.bind(fs); let swapped = false; vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => { const resolved = await realRealpath(p, opts); - if (!swapped && p === flip) { + if (!swapped && String(p).toLowerCase() === flip.toLowerCase()) { swapped = true; fsSync.renameSync(flip, flipReal); - fsSync.symlinkSync(outside, flip); + fsSync.symlinkSync(outside, flip, "junction"); } return resolved; }); @@ -70,44 +77,41 @@ function swapAfterRealpath(): void { const DIRECTORY_CHANGED = /Access denied - a directory on the path changed during the operation/; -describe.skipIf(process.platform === "win32")( - "a listed directory swapped for a symlink after validation", - () => { - it.each([ - ["list_directory", {}], - ["list_directory_with_sizes", {}], - ["directory_tree", {}], - ["search_files", { pattern: "**" }], - ])("%s does not list through it", async (tool, extra) => { - swapAfterRealpath(); - const result = await call(client, tool, { path: flip, ...extra }); - expect(result.isError).toBe(true); - expect(textOf(result)).toMatch(DIRECTORY_CHANGED); - expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME); - }); +describe("a listed directory swapped for a link after validation", () => { + it.each([ + ["list_directory", {}], + ["list_directory_with_sizes", {}], + ["directory_tree", {}], + ["search_files", { pattern: "**" }], + ])("%s does not list through it", async (tool, extra) => { + swapAfterRealpath(); + const result = await call(client, tool, { path: flip, ...extra }); + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(DIRECTORY_CHANGED); + expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME); + }); - it("directory_tree does not list a subdirectory through it", async () => { - swapAfterRealpath(); - const result = await call(client, "directory_tree", { path: dir }); - expect(result.isError).toBe(true); - expect(textOf(result)).toMatch(DIRECTORY_CHANGED); - expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME); - }); + it("directory_tree does not list a subdirectory through it", async () => { + swapAfterRealpath(); + const result = await call(client, "directory_tree", { path: dir }); + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(DIRECTORY_CHANGED); + expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME); + }); - it("search_files does not search a subdirectory through it, and says so", async () => { - swapAfterRealpath(); - const result = await call(client, "search_files", { - path: dir, - pattern: "**", - }); - expect(result.isError).toBeFalsy(); - expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME); - // The swapped directory is reported as unreadable, not as empty. - expect(textOf(result)).toContain(`${flip}`); - expect(textOf(result)).toMatch(/could not be read/i); + it("search_files does not search a subdirectory through it, and says so", async () => { + swapAfterRealpath(); + const result = await call(client, "search_files", { + path: dir, + pattern: "**", }); - }, -); + expect(result.isError).toBeFalsy(); + expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME); + // The swapped directory is reported as unreadable, not as empty. + expect(textOf(result)).toContain(`${flip}`); + expect(textOf(result)).toMatch(/could not be read/i); + }); +}); describe("listings that are not swapped", () => { it("list every tool's way, from the directory validation resolved", async () => { diff --git a/src/filesystem/__tests__/move-into-own-subtree.test.ts b/src/filesystem/__tests__/move-into-own-subtree.test.ts new file mode 100644 index 0000000000..1dd528d2ec --- /dev/null +++ b/src/filesystem/__tests__/move-into-own-subtree.test.ts @@ -0,0 +1,210 @@ +// Moving a directory into itself is refused for what it is (#5555). The +// same-device move first renames its source to a staging name, which carries +// the destination's directory away with it when that directory is inside the +// source, so the move went on to report "Parent directory does not exist" for +// a directory that did exist. The refusal now comes before anything is +// renamed, with EINVAL and a message naming both paths. The protocol-level +// tests drive move_file through a client; the unit tests below them call +// renameIntoDirectory directly, for the spellings validatePath would have +// resolved away and for the moves that must still go through. + +import fs from "fs"; +import path from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Client } from "@modelcontextprotocol/client"; +import { renameIntoDirectory } from "../pinned-directory.js"; +import { + call, + connect, + makeTempDir, + quietStderr, + textOf, + type Connected, +} from "./helpers.js"; + +const symlinks = process.platform !== "win32"; + +let dir: string; +let cwd: string; +let conn: Connected; +let client: Client; + +beforeEach(async () => { + quietStderr(); + cwd = process.cwd(); + dir = await makeTempDir("mcp-fs-move-into-self-"); + fs.mkdirSync(path.join(dir, "sub", "inner"), { recursive: true }); + fs.writeFileSync(path.join(dir, "sub", "x.txt"), "x"); + conn = await connect([dir]); + client = conn.client; +}); + +afterEach(async () => { + vi.restoreAllMocks(); + process.chdir(cwd); + await conn.close(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +/** Every name under `directory`, relative to it, sorted. */ +function tree(directory: string): string[] { + return fs + .readdirSync(directory, { recursive: true, encoding: "utf-8" }) + .map((name) => name.split(path.sep).join("/")) + .sort(); +} + +/** The source is where it was, and no staging name was left behind. */ +function expectUntouched(): void { + expect(tree(dir)).toEqual(["sub", "sub/inner", "sub/x.txt"]); + expect(fs.readFileSync(path.join(dir, "sub", "x.txt"), "utf-8")).toBe("x"); + expect(process.cwd()).toBe(cwd); +} + +function refusal(source: string, destination: string): string { + return `Cannot move a directory into itself: ${destination} is inside ${source}`; +} + +/** What renameIntoDirectory throws for this move. */ +function errorOf(source: string, destination: string): NodeJS.ErrnoException { + try { + renameIntoDirectory(source, destination); + } catch (error) { + return error as NodeJS.ErrnoException; + } + throw new Error("expected renameIntoDirectory to throw"); +} + +describe("move_file of a directory into itself (#5555)", () => { + it("refuses a destination below the source, naming the real reason", async () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "inner", "sub"); + const result = await call(client, "move_file", { source, destination }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(refusal(source, destination)); + expect(textOf(result)).not.toContain("Parent directory does not exist"); + expectUntouched(); + }); + + it("refuses a destination directly inside the source", async () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "new"); + const result = await call(client, "move_file", { source, destination }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(refusal(source, destination)); + expectUntouched(); + }); + + it("refuses a source given with a trailing separator", async () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "inner", "sub"); + const result = await call(client, "move_file", { + source: source + path.sep, + destination, + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(refusal(source, destination)); + expectUntouched(); + }); + + it("still reports a destination directory that really is missing", async () => { + const missing = path.join(dir, "nope"); + const result = await call(client, "move_file", { + source: path.join(dir, "sub"), + destination: path.join(missing, "sub"), + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(`Parent directory does not exist: ${missing}`); + expectUntouched(); + }); + + it("still moves a directory beside itself, under a name that extends its own", async () => { + const result = await call(client, "move_file", { + source: path.join(dir, "sub"), + destination: path.join(dir, "sub2"), + }); + expect(result.isError).toBeFalsy(); + expect(tree(dir)).toEqual(["sub2", "sub2/inner", "sub2/x.txt"]); + }); + + it("still moves a directory out of its own subtree, into its parent", async () => { + const result = await call(client, "move_file", { + source: path.join(dir, "sub", "inner"), + destination: path.join(dir, "inner"), + }); + expect(result.isError).toBeFalsy(); + expect(tree(dir)).toEqual(["inner", "sub", "sub/x.txt"]); + }); + + it("still moves a file into a directory beside it", async () => { + const result = await call(client, "move_file", { + source: path.join(dir, "sub", "x.txt"), + destination: path.join(dir, "sub", "inner", "x.txt"), + }); + expect(result.isError).toBeFalsy(); + expect(tree(dir)).toEqual(["sub", "sub/inner", "sub/inner/x.txt"]); + }); +}); + +describe("renameIntoDirectory, for a directory moved into itself (#5555)", () => { + it("fails with EINVAL before anything is renamed", () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "inner", "sub"); + const rename = vi.spyOn(fs, "renameSync"); + const error = errorOf(source, destination); + expect(error.code).toBe("EINVAL"); + expect(error.message).toBe(refusal(source, destination)); + expect(rename).not.toHaveBeenCalled(); + expectUntouched(); + }); + + it("refuses a destination directory that does not exist below the source", () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "nope", "sub"); + const error = errorOf(source, destination); + expect(error.code).toBe("EINVAL"); + expect(error.message).toBe(refusal(source, destination)); + expectUntouched(); + }); + + // The directory is compared by identity, so a spelling of it that a string + // comparison would take for another directory is still the source. + it("refuses another case of the source on a case-insensitive volume", (context) => { + if (!fs.existsSync(path.join(dir, "SUB"))) { + context.skip(); + } + const source = path.join(dir, "sub"); + const destination = path.join(dir, "SUB", "inner", "sub"); + const error = errorOf(source, destination); + expect(error.code).toBe("EINVAL"); + expect(error.message).toBe(refusal(source, destination)); + expectUntouched(); + }); + + // A symlink to a directory is not that directory: moving the link moves + // only the link, so its target's subtree is a fine place for it. + it.skipIf(!symlinks)( + "moves a symlink to a directory into that directory", + () => { + fs.symlinkSync(path.join(dir, "sub"), path.join(dir, "link")); + renameIntoDirectory( + path.join(dir, "link"), + path.join(dir, "sub", "inner", "link"), + ); + expect( + fs.lstatSync(path.join(dir, "sub", "inner", "link")).isSymbolicLink(), + ).toBe(true); + expect(fs.existsSync(path.join(dir, "link"))).toBe(false); + expect(fs.existsSync(path.join(dir, "sub", "x.txt"))).toBe(true); + }, + ); + + it("leaves a missing source to the rename, which names it", () => { + const source = path.join(dir, "gone"); + const error = errorOf(source, path.join(dir, "sub", "gone")); + expect(error.code).toBe("ENOENT"); + expect(error.message).toContain(source); + expect(error.message).not.toContain("into itself"); + expectUntouched(); + }); +}); diff --git a/src/filesystem/__tests__/search-files-description.test.ts b/src/filesystem/__tests__/search-files-description.test.ts index 5c0401f6b7..589b93740c 100644 --- a/src/filesystem/__tests__/search-files-description.test.ts +++ b/src/filesystem/__tests__/search-files-description.test.ts @@ -4,6 +4,12 @@ // the files, so the description now says the tool matches names, never // contents. These tests pin that wording and each matching rule it states, so // the description cannot drift from the behavior again. +// +// They also pin what an empty result says (#5553): a bare "No matches found" +// gave a model nothing to correct a pattern with, so it repeated +// '*.ext' patterns that cannot reach a subdirectory. The empty result now +// names the pattern and the directory, restates how the pattern is read, and +// suggests the '**/' form when the pattern has no '**'. import fs from "fs/promises"; import path from "path"; @@ -62,7 +68,32 @@ describe("search_files description (#896, #3419)", () => { }); it("does not match a file's contents", async () => { - expect(await search("**/needle")).toEqual(["No matches found"]); + expect(await search("**/needle")).toEqual([ + `No matches found for pattern '**/needle' under ${dir}. ` + + "The pattern is a glob matched case-sensitively against each entry's path " + + "relative to that directory: it matches names, never file contents.", + ]); + }); + + it("suggests the '**/' form when an empty search's pattern has no '**'", async () => { + const result = await call(client, "search_files", { + path: dir, + pattern: "app*.md", + }); + expect(result.isError).toBeFalsy(); + const text = textOf(result); + expect(text).toBe( + `No matches found for pattern 'app*.md' under ${dir}. ` + + "The pattern is a glob matched case-sensitively against each entry's path " + + "relative to that directory: it matches names, never file contents. " + + "It has no '**', so it only matches at one depth ('*.ext' only directly " + + "under the directory); try '**/app*.md' to match at any depth.", + ); + expect(result.structuredContent).toEqual({ content: text }); + // The suggested pattern is one that works. + expect(await search("**/app*.md")).toEqual([ + path.join(dir, "src", "app.md"), + ]); }); it("matches '*.ext' only directly under path", async () => { diff --git a/src/filesystem/__tests__/search-unreadable.test.ts b/src/filesystem/__tests__/search-unreadable.test.ts index 9b0d1fbe45..4febd94528 100644 --- a/src/filesystem/__tests__/search-unreadable.test.ts +++ b/src/filesystem/__tests__/search-unreadable.test.ts @@ -100,7 +100,7 @@ describe("search_files with an unreadable subdirectory (#5189)", () => { }); expect(result.isError).toBeFalsy(); const [matches, note] = textOf(result).split("\n\n"); - expect(matches).toBe("No matches found"); + expect(matches).toMatch(/^No matches found for pattern /); const [heading, ...listed] = note.split("\n"); expect(heading).toBe( "The search is incomplete: 2 directories could not be read, and any matches inside are missing:", diff --git a/src/filesystem/__tests__/server-tools.test.ts b/src/filesystem/__tests__/server-tools.test.ts index fb7152c54b..eadae875a4 100644 --- a/src/filesystem/__tests__/server-tools.test.ts +++ b/src/filesystem/__tests__/server-tools.test.ts @@ -2122,7 +2122,7 @@ describe("search_files", () => { path: dir, pattern: "*.none", }); - expect(textOf(result)).toBe("No matches found"); + expect(textOf(result)).toMatch(/^No matches found for pattern '\*\.none' /); }); it("silently skips a symlink that leaves the allowed directories", async () => { diff --git a/src/filesystem/package.json b/src/filesystem/package.json index 63c6d015ac..21ba5524d5 100644 --- a/src/filesystem/package.json +++ b/src/filesystem/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/server-filesystem", - "version": "2.4.0", + "version": "2.4.1", "description": "MCP server for filesystem access", "license": "SEE LICENSE IN LICENSE", "mcpName": "io.github.modelcontextprotocol/server-filesystem", diff --git a/src/filesystem/pinned-directory.ts b/src/filesystem/pinned-directory.ts index 7374c9b7a9..620eaf944e 100644 --- a/src/filesystem/pinned-directory.ts +++ b/src/filesystem/pinned-directory.ts @@ -38,8 +38,13 @@ // On Windows the working directory is a string and relative paths resolve // against it, so reading it back proves nothing; there the leaf is lstat'd // relative to the anchor and must be the file the descriptor opened, which -// narrows the race without closing it. A listing there has no such check, and -// is no more anchored than a readdir by path. +// narrows the race without closing it. A listing there has no leaf to check, +// so the listed directory is checked on both sides of the read instead +// (listedDirectoryIdentity, #5600): before and after, its path must resolve to +// itself, so no link or junction is on it, and must name one and the same +// directory by identity. A swap still in place at either check is refused; one +// made and undone between the two is not seen, so that too narrows the race +// without closing it. // That gap is a decided limit of the implementation, not pending work: // closing it needs handle-relative opens, so native code (#5260, closed as // not planned). The README states it for users, under "Access Control". @@ -417,6 +422,50 @@ function returnStaged(staged: string, name: string): boolean { } } +/** + * Whether `destinationDirectory` is the directory at `sourcePath` or lies + * inside it (#5555), so the move would put a directory into itself. Decided + * by identity, not by comparing path strings: each directory from + * `destinationDirectory` up to the root is stat'd and compared with the + * source, so another spelling of the same directory (a different case on a + * case-insensitive volume, another normalization) cannot slip past. The + * paths are as validatePath resolved them, so going up one name at a time + * does not have to see through a symlink. A source that is not a directory + * itself, a symlink to one included, has no subtree to be moved into. + * + * This is a refusal, not an anchor: it reads by path, and when it is wrong + * (a directory swapped in between) the anchored steps of the move still hold. + */ +function isInsideSource( + sourcePath: string, + destinationDirectory: string, +): boolean { + let source: fs.BigIntStats; + try { + source = fs.lstatSync(sourcePath, { bigint: true }); + } catch { + // A missing source is the rename's error to report. + return false; + } + if (!source.isDirectory()) { + return false; + } + for (let directory = destinationDirectory; ; ) { + try { + if (isSameEntry(fs.statSync(directory, { bigint: true }), source)) { + return true; + } + } catch { + // Missing or unreadable, so not the source; one above it still can be. + } + const parent = path.dirname(directory); + if (parent === directory) { + return false; + } + directory = parent; + } +} + /** * Rename `sourcePath` to `destinationPath`, keeping both inside their * validated directories. rename() takes two paths and Node has no @@ -436,6 +485,11 @@ function returnStaged(staged: string, name: string): boolean { * cannot go back (something took its name in the meantime, or its directory * no longer resolves to the one validated, which is never entered), the error * says where it was left. + * + * A directory cannot be moved into itself, and that is refused (EINVAL) + * before step 1 (#5555): step 1 moves the source away, and with it the + * destination's directory, so step 2 would report that directory, which + * exists, as missing. */ export function renameIntoDirectory( sourcePath: string, @@ -444,6 +498,14 @@ export function renameIntoDirectory( const sourceDirectory = path.dirname(sourcePath); const name = path.basename(sourcePath); const destinationDirectory = path.dirname(destinationPath); + if (isInsideSource(sourcePath, destinationDirectory)) { + throw Object.assign( + new Error( + `Cannot move a directory into itself: ${destinationPath} is inside ${sourcePath}`, + ), + { code: "EINVAL" }, + ); + } const held = stagingName(); const expected = inDirectory(sourceDirectory, () => { try { @@ -1035,17 +1097,31 @@ function cannotListError(directory: string, error: unknown): Error { * validation is refused rather than listed. Entries come back as * fs.readdir(directory, { withFileTypes: true }) returns them, and errors in * its wording. Synchronous; see the module header for what callers do first. + * + * On Windows entering proves nothing and "." is resolved from the path again + * (see the module header), so the directory is checked before the read and + * again after it (listedDirectoryIdentity), and the entries are returned only + * if both checks found the same directory. */ export function readDirectoryInPlace(directory: string): fs.Dirent[] { return inDirectory( directory, () => { + const before = onWindows() + ? listedDirectoryIdentity(directory) + : undefined; let entries: fs.Dirent[]; try { entries = fs.readdirSync(".", { withFileTypes: true }); } catch (error) { throw namingPath(error, ".", directory); } + if (before) { + const after = listedDirectoryIdentity(directory); + if (after.dev !== before.dev || after.ino !== before.ino) { + throw directoryChangedError(directory); + } + } // Read from ".", so each entry's parentPath is "."; name the directory, // as a readdir of its path would. for (const entry of entries) { @@ -1056,3 +1132,33 @@ export function readDirectoryInPlace(directory: string): fs.Dirent[] { cannotListError, ); } + +/** + * The identity (volume serial and file id) of the directory `directory` names + * right now, for the Windows listing check (#5600); it throws the + * directory-changed refusal unless `directory`, a path validatePath returned, + * still names a directory with no link on the way to it: + * + * - its last component is a directory, where lstat reports a junction or a + * directory symlink as a link; + * - its real path is itself. validatePath returned it from the same native + * realpath, so anything else means a component of it is now a link. + * + * The two calls resolve the path separately, and the listing resolves it a + * third time, so this detects a swap that is in place when it runs and + * nothing more. The identities of two calls are compared by the caller as + * they are (both are lstats of the path, so a `dev` an older libuv reports + * as 0 is 0 in both; see isSameEntry for the path-against-handle case). + */ +function listedDirectoryIdentity( + directory: string, +): Pick { + const found = fs.lstatSync(directory, { bigint: true }); + if ( + !found.isDirectory() || + !isSameDirectory(fs.realpathSync.native(directory), directory) + ) { + throw directoryChangedError(directory); + } + return found; +} diff --git a/src/filesystem/server.json b/src/filesystem/server.json new file mode 100644 index 0000000000..32574b8908 --- /dev/null +++ b/src/filesystem/server.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-filesystem", + "title": "Filesystem", + "description": "Read, write, search and edit files, with access limited to allowed directories or client Roots", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/filesystem" + }, + "packages": [ + { + "registryType": "npm", + "identifier": "@modelcontextprotocol/server-filesystem", + "transport": { + "type": "stdio" + }, + "packageArguments": [ + { + "type": "positional", + "valueHint": "allowed_directory", + "description": "A directory the server may read and write. Repeat for each directory to allow.", + "format": "filepath", + "isRequired": true, + "isRepeated": true + } + ] + } + ] +} diff --git a/src/filesystem/server.ts b/src/filesystem/server.ts index f9a80d30be..4b7a59ef30 100644 --- a/src/filesystem/server.ts +++ b/src/filesystem/server.ts @@ -1063,7 +1063,24 @@ export function createServer( }, }, ); - let text = results.length > 0 ? results.join("\n") : "No matches found"; + // An empty result says what was searched and how the pattern is read, + // and how to widen a pattern that cannot reach subdirectories: a bare + // "No matches found" left a model repeating the same '*.ext' pattern + // (#5553). It stays one paragraph, opening with those three words. + let text: string; + if (results.length > 0) { + text = results.join("\n"); + } else { + text = + `No matches found for pattern '${args.pattern}' under ${args.path}. ` + + "The pattern is a glob matched case-sensitively against each entry's path " + + "relative to that directory: it matches names, never file contents."; + if (!args.pattern.includes("**")) { + text += + " It has no '**', so it only matches at one depth ('*.ext' only directly " + + `under the directory); try '**/${args.pattern}' to match at any depth.`; + } + } if (unreadable.length > 0) { text += `\n\nThe search is incomplete: ${unreadable.length} ` + diff --git a/src/git/README.md b/src/git/README.md index 95d5a00875..6d051f8e99 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -14,6 +14,8 @@ Please note that mcp-server-git is currently in early development. The functiona ### Tools +Every tool's `repo_path` is taken literally: neither a leading `~` nor `$NAME` or `${NAME}` is expanded, and a relative path is relative to the server's working directory. + 1. `git_status` - Shows the working tree status - Input: @@ -63,13 +65,13 @@ Please note that mcp-server-git is currently in early development. The functiona - Returns: Confirmation of reset operation 8. `git_log` - - Shows the commit logs with optional date filtering + - Shows the commit log, newest commit first. With only `repo_path` it returns the latest commits; the two timestamps are optional filters for a date range - Inputs: - `repo_path` (string): Path to Git repository - `max_count` (number, optional): Maximum number of commits to show, at least 1 (default: 10) - - `start_timestamp` (string, optional): Start timestamp for filtering commits. Accepts ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024') - - `end_timestamp` (string, optional): End timestamp for filtering commits. Accepts ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024') - - Returns: Array of commit entries with hash, author, date, and message + - `start_timestamp` (string, optional): Only show commits at or after this time; omit for no lower bound. Accepts ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024') + - `end_timestamp` (string, optional): Only show commits at or before this time; omit for no upper bound. Accepts ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024') + - Returns: `Commit history:` followed by one entry per commit (hash, author, date and message), newest first. When a timestamp filter matches no commits, the text says so and suggests omitting both timestamps, rather than returning an empty history 9. `git_create_branch` - Creates a new branch @@ -91,7 +93,8 @@ Please note that mcp-server-git is currently in early development. The functiona - `source_branch` (string): Branch, tag or commit to merge into the current branch (check out the branch to merge into first with `git_checkout`) - `fast_forward_only` (boolean, optional): Only fast-forward, failing if the branches have diverged (default `true`). `false` lets Git create a merge commit when they have - Returns: `Fast-forwarded`, `Merged ... with merge commit `, or `Already up to date` - - Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, and a merge that would overwrite an ignored local file. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was + - Refuses a detached HEAD, a working tree with uncommitted changes, a merge already in progress, and a merge that would overwrite an ignored local file, whether it fast-forwards or makes a merge commit. A merge that stops on conflicts is aborted (`git merge --abort`) and the error names the conflicting files, so the repository is left as it was + - Directory renames are not followed: a file the source adds in a directory the current branch renamed is merged at the path the source gave it 12. `git_show` - Shows the contents of a commit, or of a file or directory at a revision - Inputs: @@ -113,7 +116,7 @@ Please note that mcp-server-git is currently in early development. The functiona - Inputs: - `repo_path` (string): Path to the Git repository. - Returns: One line per remote and direction, `\t (fetch)` or `(push)` (a partial clone's fetch line ends with its filter, such as ` [blob:none]`), or `No remotes configured` - - A credential embedded in a URL is never returned: the whole userinfo of a URL such as `https://user:token@host/...` or `https://token@host/...` is shown as ``, and so is every query value (`?private_token=`, keeping the parameter names) and a non-empty fragment (`#`). An SSH username (`ssh://git@host/...`) is kept, since it names an account rather than authenticating one; a password after it is redacted. A remote-helper address (`https::https://user:token@host/...`) has its inner URL redacted the same way. A URL where a `?` or `#` comes before the userinfo's `@` (`https://host?t=a@b`) cannot be split safely, so it is shown as `https://`. A token carried as a path segment (`https://host/token/SECRET/r.git`) is not redacted, since it cannot be told apart from a repository name. scp-style addresses (`git@host:path`) and local paths are shown as configured, and a `file://` URL keeps its `?` and `#` parts, which belong to a local file name. A line that cannot be parsed is shown as ``, and if a configured remote URL (or `insteadOf` rewrite) contains a newline, which git itself refuses, the tool returns an error instead of a listing. + - A credential embedded in a URL is never returned: the whole userinfo of a URL such as `https://user:token@host/...` or `https://token@host/...` is shown as ``, and so is every query value (`?private_token=`, keeping the parameter names) and a non-empty fragment (`#`). An SSH username (`ssh://git@host/...`) is kept, since it names an account rather than authenticating one; a password after it is redacted. A remote-helper address (`https::https://user:token@host/...`) has its inner URL redacted the same way. A URL where a `?` or `#` comes before the userinfo's `@` (`https://host?t=a@b`) cannot be split safely, so it is shown as `https://`. A token carried as a path segment (`https://host/token/SECRET/r.git`) is not redacted, since it cannot be told apart from a repository name. A value that holds a URL anywhere but at its start (` https://user:token@host/...`, with leading whitespace) cannot be split safely, so it is shown as ``; a remote name holding a tab is matched against the configured names, so the URL after it is still redacted. scp-style addresses (`git@host:path`) and local paths are shown as configured, and a `file://` URL keeps its `?` and `#` parts, which belong to a local file name. A line that cannot be parsed is shown as ``, and if a configured remote URL (or `insteadOf` rewrite) contains a newline, which git itself refuses, the tool returns an error instead of a listing. ### Protocol versions @@ -173,13 +176,16 @@ python -m mcp_server_git `--repository` (`-r`) accepts any path inside a Git working tree. At startup the server walks up to the enclosing repository root, the way `git rev-parse --show-toplevel` does, so `--repository .` works when a shared config is launched from any subdirectory of the repository. A path inside the repository therefore allows tool calls anywhere in that repository, not only under the subdirectory given. A path that does not exist, or is not inside a Git repository, is logged as a one-line error at startup. -A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. A linked worktree can still be the `--repository`, though its Git directory lives under the main repository's `.git`; only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. With `--repository` set, the server also refuses a repository whose Git directory: +A tool call's `repo_path` must be inside that repository, and so must the directories Git then uses for it: a repository nested inside whose `.git` file, `commondir` or `core.worktree` points outside is refused. The `--repository` root itself may use a Git directory outside it only when that directory names the root back. A linked worktree's Git directory lives under the main repository's `.git` (`.git/worktrees/`), and the main repository's record of the worktree names the root back. Only the worktree itself may use that directory, so a repository nested in the worktree whose `.git` names it, or the main repository's `.git`, is refused. A submodule checkout can be the `--repository` too, or any root whose Git directory's own `config` sets `core.worktree` back to it, as a submodule's (`.git/modules/` in the superproject) does. Any other root whose `.git` file or `commondir` names a directory outside it, including one made with `git init --separate-git-dir`, is refused on every call, and the server logs a warning saying so at startup. The root's Git directory and common directory are fixed when the server starts: if the root's `.git` is later replaced, or gains a `commondir`, so that Git would use a different directory outside the root, the call is refused. With `--repository` set, the server also refuses a repository whose Git directory: - names alternate object stores (`objects/info/alternates` or `objects/info/http-alternates` with any entry), wherever they are. A clone made with `--reference` or `--shared` therefore cannot be used under `--repository`; `git repack -a -d` and then deleting `objects/info/alternates` makes it self-contained. - holds a symbolic link (at `objects`, `refs`, `index`, `HEAD` or anywhere else in it) that resolves outside both the allowed repository and that Git directory. A link that stays inside is followed, and what it leads to is checked the same way. A `hooks` directory linked elsewhere is allowed, since no hook runs. +- holds a Windows directory junction that resolves outside both, anywhere in it. A junction is judged like a symbolic link: one that stays inside is followed and what it leads to is checked, and a `hooks` junction is allowed. It also refuses a repository whose index (`.git/index`) names a path Git would read outside the working tree: an entry that is absolute, or has an empty, `.`, `..` or `.git` component (on Windows also one with a `:`, or with `\` as a separator), which is what `git add` refuses to write. Git reads an index as it finds it, so a hand-written one could otherwise make `git_diff_unstaged`, `git_diff` and `git_status` show files outside the repository. For the same reason, every Git command the server runs, with or without `--repository`, sets `core.untrackedCache` to `false`: the untracked cache is kept in the index and names the directories `git status` lists, so Git scans the working tree instead. +These checks run when a tool call opens the repository, and again after each Git command in the call that writes the working tree (`git_checkout`, `git_merge` and the `git merge --abort` after a conflict, and the autostash `git_commit` reapplies when it concludes a merge), since such a write can change the repository's configuration (a `.git/config` linked to a tracked file that gains a `core.worktree`). If the repository no longer passes, the call stops with an error before it runs another Git command, and the working tree stays as that command wrote it; a merge that conflicted is then still in progress rather than aborted. + ### A repository's own programs A repository's configuration and hooks travel with it (an unpacked archive, a shared folder, a vendored tree), so the server never runs a program they name, with or without `--repository`. Every Git command it runs overrides, through `GIT_CONFIG_COUNT`, the settings that would start one: @@ -187,6 +193,7 @@ A repository's configuration and hooks travel with it (an unpacked archive, a sh - `core.fsmonitor` is `false`, and `core.hooksPath` points at the null device, so no hook runs; `git_commit` also skips the hooks GitPython would run itself (`pre-commit`, `commit-msg`, `post-commit`). - Diffs pass `--no-ext-diff` and `--no-textconv`, so `diff.external`, `diff..command` and `diff..textconv` are ignored. - Each filter driver (`filter..clean`, `smudge`, `process`) and merge driver (`merge..driver`) that the repository's own configuration defines is emptied, including one with an empty name (`[filter ""]`, selected by `filter=`): files are staged and checked out unfiltered, and a file a merge driver would have merged is a conflict, which `git_merge` aborts. Drivers from your global or system configuration, such as Git LFS's, keep working. +- Git LFS's driver, trusted as yours, reads its own settings from the repository's configuration, so each program that configuration names for it is emptied too: an extension's `lfs.extension..clean` and `smudge`, and a transfer agent's `lfs.customtransfer..path` and `args` (and `lfs.standalonetransferagent`). A tool that would run an emptied extension fails with Git LFS's error. Git LFS never downloads an object either (`GIT_LFS_SKIP_SMUDGE=1`), since a download runs the SSH command, credential helper and askpass program set for an endpoint the repository chooses: `git_checkout` and `git_merge` write each Git LFS file as its pointer file, and `git lfs pull` (or `git lfs checkout`, when the objects are already local) replaces the pointers with the content afterwards. - The repository's configuration can depend on its working tree (an `[include]` or `[includeIf]` path into it, or a `.git/config` linked to a tracked file), so a tool that writes the working tree (`git_checkout`, `git_merge`, and the `git merge --abort` after a conflict) reads the drivers again before it runs any other Git command, and a driver that the files it wrote define is emptied as well. - `commit.gpgSign` and `merge.verifySignatures` are `false`, and `git_merge` passes `--no-gpg-sign` and `--no-verify-signatures`. Each `branch..mergeOptions` the repository's own configuration sets is emptied, since Git reads it as command-line options. `submodule.recurse` and `merge.autoStash` are `false`, and `core.pager` is `cat`. - Git never fetches a missing object from a promisor remote by itself (`GIT_NO_LAZY_FETCH=1`), since that fetch runs the transport program the repository's configuration names (`remote..uploadpack`, `core.sshCommand`). In a partial clone, or any repository that declares a promisor remote, a tool that needs an object that is not on disk reports it missing. A Git too old to honor the variable (before 2.45.1, other than the maintenance releases 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4 and 2.44.1 made with it) refuses a repository that declares a promisor remote (`remote..promisor`, `remote..partialCloneFilter` or `extensions.partialClone`, with or without a remote name). diff --git a/src/git/pyproject.toml b/src/git/pyproject.toml index be0ca1ade9..cb7e7b4b76 100644 --- a/src/git/pyproject.toml +++ b/src/git/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mcp-server-git" -version = "2026.11.18" +version = "2026.11.27" description = "A Model Context Protocol server providing tools to read, search, and manipulate Git repositories programmatically via LLMs" readme = "README.md" requires-python = ">=3.10" diff --git a/src/git/server.json b/src/git/server.json new file mode 100644 index 0000000000..8056b60a39 --- /dev/null +++ b/src/git/server.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-git", + "title": "Git", + "description": "Read, search and manipulate Git repositories: status, diff, log, commit, branch and more", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/git" + }, + "packages": [ + { + "registryType": "pypi", + "identifier": "mcp-server-git", + "transport": { + "type": "stdio" + } + } + ] +} diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index a6116db44b..9c3b5606aa 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -22,9 +22,12 @@ import logging import os import re +import sys +import tempfile import threading from collections.abc import Callable, Iterator -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager +from contextvars import ContextVar from enum import Enum from functools import wraps from importlib.metadata import version @@ -43,6 +46,9 @@ from .transport import run +if sys.platform == "win32": # pragma: no cover # the coverage gate runs on Linux + import _winapi + # The version this server reports in serverInfo, read from the installed # distribution's metadata (pyproject.toml) so it cannot drift from the # published version (#360). Without it the SDK reports its own `mcp` version. @@ -179,11 +185,29 @@ def _git_text(repo: git.Repo, command: str, *args: str) -> str: # value shows that git applied the overrides. A driver's name may be empty # (`[filter ""]`, read back as `filter..clean`, selected by `filter=`), so # the name is matched with `.*`, not `.+`. +# +# A trusted driver can still read the repository's configuration itself. +# Git LFS's does: it runs `lfs.extension..clean` and `.smudge` on every +# file it filters, and a transfer agent (`lfs.customtransfer..path` +# and `.args`, picked by `lfs.standalonetransferagent`) when it downloads an +# object, so those keys are emptied the same way. An emptied extension makes +# Git LFS fail the command rather than run anything. A download also runs +# programs no key in this list names (`core.sshCommand`, `credential.helper` +# and `core.askpass`, for an endpoint the repository picks), so `harden_repo` +# turns downloads off (`_LFS_ENV`) instead. _LISTED_KEYS = ( r"^(core\.hookspath|filter\..*\.(clean|smudge|process)|merge\..*\.driver" - r"|branch\..+\.mergeoptions)$" + r"|branch\..+\.mergeoptions|lfs\.extension\..*\.(clean|smudge)" + r"|lfs\.customtransfer\..*\.(path|args)|lfs\.standalonetransferagent)$" ) +# GIT_LFS_SKIP_SMUDGE=1 makes Git LFS's smudge filter write each file's +# pointer instead of its content, so a checkout or merge never downloads an +# object, and never starts the programs a download runs. The repository's +# configuration cannot turn it back on: Git LFS reads it from the environment +# only. +_LFS_ENV = {"GIT_LFS_SKIP_SMUDGE": "1"} + # Scopes whose configuration the user wrote rather than the repository. _TRUSTED_SCOPES = frozenset({"system", "global", "command"}) @@ -332,8 +356,9 @@ def _submodule_drivers(repo: git.Repo) -> set[str]: def harden_repo(repo: git.Repo) -> None: """Keep every git command run for `repo` from running a program it names. - Sets `HARDENED_CONFIG` on the repository's git, then reads which filter - and merge drivers the repository's own configuration (its `.git/config`, + Sets `HARDENED_CONFIG` and `_LFS_ENV` on the repository's git, then reads + which filter and merge drivers (and Git LFS programs, `_LISTED_KEYS`) the + repository's own configuration (its `.git/config`, a worktree's `config.worktree`, and files they include) defines, and overrides each with an empty command. The same read checks that git applied the overrides: git older than 2.31 ignores GIT_CONFIG_COUNT, and @@ -344,7 +369,9 @@ def harden_repo(repo: git.Repo) -> None: (`_PROMISOR_KEYS`). """ entries = list(HARDENED_CONFIG) - repo.git.update_environment(GIT_NO_LAZY_FETCH="1", **_config_env(entries)) + repo.git.update_environment( + GIT_NO_LAZY_FETCH="1", **_LFS_ENV, **_config_env(entries) + ) try: listed = repo.git.config("--show-scope", "-z", "--get-regexp", _LISTED_KEYS) except git.GitCommandError as e: @@ -459,7 +486,9 @@ def _has_staged_changes(repo: git.Repo) -> bool: return bool(repo.index.diff(repo.head.commit)) -def git_commit(repo: git.Repo, message: str) -> str: +def git_commit( + repo: git.Repo, message: str, *, allowed_repository: Path | None = None +) -> str: # repo.index.commit() writes a tree unconditionally, so without this check # a caller that forgot to stage gets a hash back for an empty commit and no # way to tell it apart from a real one. @@ -480,7 +509,7 @@ def git_commit(repo: git.Repo, message: str) -> str: commit = repo.index.commit(message, parent_commits=parents, skip_hooks=True) for name in ("MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "AUTO_MERGE"): (git_dir / name).unlink(missing_ok=True) - autostash_note = _apply_merge_autostash(repo) + autostash_note = _apply_merge_autostash(repo, allowed_repository) else: # skip_hooks: GitPython runs the repository's hooks itself, ignoring # the core.hooksPath override (`harden_repo`). @@ -489,7 +518,9 @@ def git_commit(repo: git.Repo, message: str) -> str: return f"Changes committed successfully with hash {commit.hexsha}{autostash_note}" -def _apply_merge_autostash(repo: git.Repo) -> str: +def _apply_merge_autostash( + repo: git.Repo, allowed_repository: Path | None = None +) -> str: """Reapply a `git merge --autostash` stash, as `git commit` does. Mirrors git's sequencer: apply the stash, store it in the stash list if @@ -503,7 +534,9 @@ def _apply_merge_autostash(repo: git.Repo) -> str: try: # Through _rewrite_tree although nothing after it runs a driver today # (`git stash store` runs none): any later git command must be safe. - _rewrite_tree(repo, "stash", "apply", stash_oid) + _rewrite_tree( + repo, "stash", "apply", stash_oid, allowed_repository=allowed_repository + ) note = "\nApplied autostash." except git.GitCommandError: repo.git.stash("store", "-m", "autostash", "-q", stash_oid) @@ -652,8 +685,16 @@ def git_create_branch( return f"Created branch '{branch_name}' from {base_label}" -def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str: - """Run `git `, which writes the working tree, then re-harden. +def _rewrite_tree( + repo: git.Repo, + command: str, + *args: str, + allowed_repository: Path | None = None, + config: str | None = None, +) -> str: + """Run `git `, which writes the working tree, then re-check. + + `config`, a `name=value`, is passed as `git -c` for this command only. `harden_repo` reads the repository's configuration when the call opens the repository, but that configuration can depend on the working tree: an @@ -671,9 +712,20 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str: If that read fails, the overrides may be incomplete, so the call stops with a `GitError`, which a caller's `except GitCommandError` cleanup does not catch, and no further git command runs. + + The same holds for where git operates (#5599). `open_repo` checked the + directories git uses against `allowed_repository` (`--repository`) before + the write, and the write can move them: a `.git/config` that is a link to + a tracked file gains a `core.worktree` naming a directory outside, and + the next git command that writes the tree (the `git merge --abort` after + a conflict) writes there instead. So `validate_opened_repo` runs again + too, after the drivers are read, as at open. A repository that no longer + passes stops the call the same way: no git command can be trusted to + stay inside, the cleanup included, so the tree stays as written. """ try: - return getattr(repo.git, command)(*args) + runner = repo.git(c=config) if config is not None else repo.git + return getattr(runner, command)(*args) finally: try: harden_repo(repo) @@ -684,9 +736,22 @@ def _rewrite_tree(repo: git.Repo, command: str, *args: str) -> str: f"tree was left as git {command} wrote it (a merge may still be in " f"progress), and no further git command was run: {e}" ) from e + if allowed_repository is not None: + try: + validate_opened_repo(repo, Path(repo.working_dir), allowed_repository) + except (ValueError, OSError, git.GitError) as e: + raise git.GitError( + f"Stopped: after git {command} changed the working tree, the " + "repository no longer passes the --repository check. The " + f"working tree was left as git {command} wrote it (a merge may " + "still be in progress), and no further git command was run: " + f"{e}" + ) from e -def git_checkout(repo: git.Repo, branch_name: str) -> str: +def git_checkout( + repo: git.Repo, branch_name: str, *, allowed_repository: Path | None = None +) -> str: # Defense in depth: reject branch names starting with '-' to prevent flag injection, # even if a malicious ref with that name exists (e.g. via filesystem manipulation) if branch_name.startswith("-"): @@ -699,7 +764,9 @@ def git_checkout(repo: git.Repo, branch_name: str) -> str: # --quiet: without it, git checks each checked-out submodule of the new # branch for local changes, running git inside it under its own # configuration; the reply below does not use git's output. - _rewrite_tree(repo, "checkout", "--quiet", branch_name) + _rewrite_tree( + repo, "checkout", "--quiet", branch_name, allowed_repository=allowed_repository + ) # rev_parse accepts any revision, so branch_name may have been a sha, tag or # remote-tracking ref rather than a branch. Report what actually happened instead of # claiming a branch switch; a detached HEAD is easy to commit onto by mistake. @@ -717,7 +784,12 @@ def _git_stderr(error: git.GitCommandError) -> str: return message or str(error) -def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str: +def _merge_failure( + repo: git.Repo, + error: git.GitCommandError, + what: str, + allowed_repository: Path | None = None, +) -> str: """Why `git merge` failed, after undoing whatever it left behind. A merge that stops on conflicts, or fails to write its merge commit, @@ -737,7 +809,7 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str ).splitlines() # Through _rewrite_tree although it is the last git command here, so a git # command added after it reads drivers the restored tree defines. - _rewrite_tree(repo, "merge", "--abort") + _rewrite_tree(repo, "merge", "--abort", allowed_repository=allowed_repository) if conflicts: return ( f"{what} stopped on conflicts in: {', '.join(conflicts)}. {unchanged} " @@ -746,8 +818,104 @@ def _merge_failure(repo: git.Repo, error: git.GitCommandError, what: str) -> str return f"{what} failed. {unchanged} Git reported:\n{_git_stderr(error)}" +def _on_disk_spelling(root: Path, path: str) -> str: + """`path`, an existing entry under `root`, as the directory listings spell it. + + On a case-insensitive or normalization-insensitive filesystem (macOS, + Windows) the path a source tracks can name an entry whose name is spelled + differently (`.ENV` for `.env`, or decomposed for precomposed Unicode). + Git matches a pathspec to its own spelling, so each component is replaced + with the listed name of the same file (by device and inode). + """ + parent = root + spelled: list[str] = [] + for name in path.split("/"): + names = os.listdir(parent) + if name not in names: + wanted = os.lstat(parent / name) + name = next( + entry + for entry in names + if os.path.samestat(os.lstat(parent / entry), wanted) + ) + spelled.append(name) + parent = parent / name + return "/".join(spelled) + + +def _ignored_files_overwritten(repo: git.Repo, head: str, source: str) -> list[str]: + """The ignored files in the working tree a merge of `source` would replace. + + Git does not honor `--no-overwrite-ignore` when it makes a merge commit (a + fast-forward does), so `git_merge` checks before it runs. The tree is + clean, so every untracked path is one HEAD does not track, and the merge + writes only such a path when it is one of: + + - a path the source tracks and HEAD does not. This includes one HEAD + deleted since the merge base: if the source changed it, the + modify/delete conflict writes the source's version, so it must be + counted, not filtered out against the merge base. (The merge runs with + `merge.directoryRenames=false`, so git does not move a path the source + adds into a directory HEAD renamed, a path in neither tree.) + - the side name of a file/directory conflict: HEAD's file `` moved + to `~HEAD`, or the source's to `~`. + + For each, what is in the way is whatever exists there (a file, a link, or + a directory and everything in it) or the nearest existing ancestor that is + not a directory. The ignored files among those are returned; an untracked + file that is not ignored is left for git to refuse, as it does. + """ + root = Path(repo.working_dir) + changes = repo.git.diff_tree( + "-r", "-z", "--no-renames", "--name-status", "--diff-filter=AD", head, source + ).split("\0") + added: set[str] = set() + deleted: set[str] = set() + for status, path in zip(changes[0::2], changes[1::2]): + (added if status == "A" else deleted).add(path) + deleted_dirs = { + "/".join(parts[:depth]) + for parts in (path.split("/") for path in deleted) + for depth in range(1, len(parts)) + } + written = set(added) + for path in added: + parts = path.split("/") + for depth in range(1, len(parts)): + if (prefix := "/".join(parts[:depth])) in deleted: + written.add(f"{prefix}~HEAD") + if path in deleted_dirs: + written.add(f"{path}~{source}") + in_the_way: set[str] = set() + for path in written: + parts = path.split("/") + for depth in range(1, len(parts) + 1): + prefix = "/".join(parts[:depth]) + target = root / prefix + if not os.path.lexists(target): + break + if depth == len(parts) or target.is_symlink() or not target.is_dir(): + in_the_way.add(_on_disk_spelling(root, prefix)) + break + if not in_the_way: + return [] + listed = repo.git.ls_files( + "-z", + "--others", + "--ignored", + "--exclude-standard", + "--", + *(f":(top,literal){path}" for path in sorted(in_the_way)), + ) + return sorted(filter(None, listed.split("\0"))) + + def git_merge( - repo: git.Repo, source_branch: str, fast_forward_only: bool = True + repo: git.Repo, + source_branch: str, + fast_forward_only: bool = True, + *, + allowed_repository: Path | None = None, ) -> str: """Merge `source_branch` into the current branch, or change nothing. @@ -757,6 +925,9 @@ def git_merge( The conflicts are reported for the caller to resolve by hand. By default only a fast-forward is allowed; `fast_forward_only=False` lets git create a merge commit when the branches have diverged. + + `allowed_repository` is the `--repository` the call was opened under, + checked again after each write to the working tree (`_rewrite_tree`). """ # Defense in depth: reject sources starting with '-' to prevent flag # injection, even if a malicious ref with that name exists. @@ -804,6 +975,9 @@ def git_merge( # for it (see `_LISTED_KEYS`). --no-overwrite-ignore refuses to # replace an ignored local file (a `.env`, say) that the source tracks: # `is_dirty()` cannot see one, and git would overwrite it unrecoverably. + # Git honors it only on a fast-forward, so a merge commit is checked + # first (`_ignored_files_overwritten`), and runs with directory-rename + # detection off, so it writes no path that check cannot predict. # # Git is given the commit validated above, not the name: a name can stand # for more than one commit (`git merge FETCH_HEAD` merges every head @@ -811,6 +985,15 @@ def git_merge( # With a sha, git's default message would name the sha, so the message # names what the caller asked for. mode = "--ff-only" if fast_forward_only else "--ff" + what = f"Merge of '{source_branch}' into '{target}'" + if not fast_forward: + ignored = _ignored_files_overwritten(repo, head.hexsha, source.hexsha) + if ignored: + raise ValueError( + f"{what} refused: it would overwrite ignored local files: " + f"{', '.join(ignored)}. Nothing was changed. Move or remove " + "them first." + ) try: _rewrite_tree( repo, @@ -825,10 +1008,11 @@ def git_merge( "-m", f"Merge '{source_branch}' into '{target}'", source.hexsha, + allowed_repository=allowed_repository, + config="merge.directoryRenames=false", ) except git.GitCommandError as e: - what = f"Merge of '{source_branch}' into '{target}'" - raise ValueError(_merge_failure(repo, e, what)) from e + raise ValueError(_merge_failure(repo, e, what, allowed_repository)) from e merged = repo.head.commit if fast_forward: return f"Fast-forwarded '{target}' to '{source_branch}' ({merged.hexsha[:7]})" @@ -914,6 +1098,113 @@ def validate_repo_path(repo_path: Path, allowed_repository: Path | None) -> None ) +# The git directory and common directory of each `--repository` root, as +# `record_root_git_dirs` found them when its server was created, or None when +# the root may use no git directory outside itself. Fixing the pair then, rather +# than reopening the root on every call, keeps a `.git` or `commondir` written +# into the root afterwards from naming a different repository as its own. +_ROOT_GIT_DIRS: dict[Path, tuple[Path, Path] | None] = {} + + +class _RootGit(git.Git): + """`git.Git` run in its working directory as given, never env-expanded. + + `git.Git` expands `$NAME` and `~` in a str working directory whatever + `expand_vars` says, and runs in the current directory when the expansion + does not exist; it takes a `Path` as it is. + """ + + def __init__(self, working_dir: str | os.PathLike[str] | None = None) -> None: + super().__init__(None if working_dir is None else Path(working_dir)) + + +class _RootRepo(git.Repo): + """`git.Repo` whose git commands and object reads run through `_RootGit`. + + Set as the wrapper type, so the object database and the environment + `git.Repo` sets up use it too. + """ + + GitCommandWrapperType = _RootGit + + +def record_root_git_dirs(allowed_repository: Path) -> tuple[Path, Path] | None: + """Record the git directories the `--repository` root may use outside itself. + + A root's git directory and common directory are its own when both lie + inside it, or when the git directory outside names the root back, which + only its owner can write: + + - a linked worktree: its git directory is `/worktrees/`, + and that directory's `gitdir` file, which `git worktree add` writes in + the main repository, names the root's `.git`; + - a git directory that is its own common directory and whose own + `config` sets `core.worktree` to the root, as `git submodule` writes it + for a submodule checkout (`/.git/modules/`). + + Any other git directory outside the root (a `.git` file naming another + repository, a `commondir` outside, `git init --separate-git-dir`) is not + the root's own, since nothing outside the root confirms it: None is + recorded, and every call that would use it is refused. + """ + allowed = allowed_repository.resolve() + own: tuple[Path, Path] | None = None + try: + with _RootRepo(allowed, expand_vars=False) as repo: + harden_repo(repo) + git_dir, common_dir = ( + Path(p).resolve() + for p in repo.git.rev_parse( + "--path-format=absolute", "--git-dir", "--git-common-dir" + ).splitlines() + ) + seen_by_gitpython = ( + Path(repo.git_dir).resolve(), + Path(repo.common_dir).resolve(), + ) + if seen_by_gitpython == (git_dir, common_dir) and ( + (git_dir.is_relative_to(allowed) and common_dir.is_relative_to(allowed)) + or _is_linked_worktree_of(allowed, git_dir, common_dir) + or _is_submodule_of(repo, allowed, git_dir, common_dir) + ): + own = (git_dir, common_dir) + except (git.GitError, OSError, ValueError): + pass + _ROOT_GIT_DIRS[allowed_repository] = own + return own + + +def _is_linked_worktree_of(allowed: Path, git_dir: Path, common_dir: Path) -> bool: + """Whether `git_dir` is the main repository's record of worktree `allowed`.""" + if git_dir.parent != common_dir / "worktrees": + return False + try: + named = (git_dir / "gitdir").read_text(encoding="utf-8").strip() + except OSError: + return False + # Relative when written with `worktree.useRelativePaths`. + return (git_dir / named).resolve() == allowed / ".git" + + +def _is_submodule_of( + repo: git.Repo, allowed: Path, git_dir: Path, common_dir: Path +) -> bool: + """Whether `git_dir` is a submodule's git directory checked out at `allowed`. + + Only `git_dir`'s own `config` is read (`--file`, so no other scope and no + include contributes); `core.worktree` there is relative to `git_dir`. + """ + if git_dir != common_dir: + return False + try: + named = repo.git.config( + "--file", str(git_dir / "config"), "--get", "core.worktree" + ) + except git.GitCommandError: + return False + return (git_dir / named).resolve() == allowed + + def validate_opened_repo( repo: git.Repo, repo_path: Path, allowed_repository: Path | None ) -> None: @@ -924,8 +1215,9 @@ def validate_opened_repo( a directory anywhere else, so the working tree, git directory and common directory git actually uses are checked too. The working tree must lie inside the allowed repository. The two git directories must lie inside it, - or be the allowed repository's own as a pair, opened from the allowed - repository itself: a linked worktree's git directory lives under the main + or be the allowed repository's own as a pair (`record_root_git_dirs`, + fixed when the server is created), opened from the allowed repository + itself: a linked worktree's git directory lives under the main repository's `.git`, outside the worktree it serves, and only that worktree may use it. A repository nested inside a linked worktree whose `.git` names the main repository's git directory is refused. @@ -968,14 +1260,16 @@ def outside(used: Path) -> ValueError: p for p in git_dirs + common_dirs if not p.resolve().is_relative_to(allowed) ] if escaped: - with git.Repo(allowed) as allowed_repo: - own_git_dir = Path(allowed_repo.git_dir).resolve() - own_common_dir = Path(allowed_repo.common_dir).resolve() + if allowed_repository in _ROOT_GIT_DIRS: + own = _ROOT_GIT_DIRS[allowed_repository] + else: + own = record_root_git_dirs(allowed_repository) is_own = ( - bool(working_trees) + own is not None + and bool(working_trees) and all(Path(w).resolve() == allowed for w in working_trees) - and all(p.resolve() == own_git_dir for p in git_dirs) - and all(p.resolve() == own_common_dir for p in common_dirs) + and all(p.resolve() == own[0] for p in git_dirs) + and all(p.resolve() == own[1] for p in common_dirs) ) if not is_own: raise outside(escaped[0]) @@ -1034,6 +1328,107 @@ def _check_index_entries(repo: git.Repo, repo_path: Path) -> None: _ALTERNATES = ("alternates", "http-alternates") +@contextmanager +def _own_object_store(repo: git.Repo, *, writes: bool = False) -> Iterator[None]: + """Run `repo`'s git on its own objects only, whatever its alternates say. + + `_check_git_dir_contents` refuses an alternates entry when the repository + is opened, but the file can be rewritten before git reads an object, and + git has no setting that turns alternates off. So git is pointed + (`GIT_OBJECT_DIRECTORY`) at a new, private directory holding a link to + each of the repository's loose-object directories and to its `pack` + directory, and nothing else: git reads the alternates list from that + directory's `info/alternates`, which does not exist. On Windows the links + are directory junctions, which need no privilege. + + A loose-object directory the repository lacks yet gets no entry for a + call that only reads, so git finds nothing there, as in the store + itself: such a call writes nothing to the repository, and works on a + store it cannot write to. (`_GIT_LOCK` keeps another call from creating + one meanwhile.) + + Git follows the links for writing too: a new loose object is written to + a temporary file in its own `xx` directory and renamed there, and a pack + in `pack`, so what git writes lands in the repository's store. Git would + create a missing `xx` inside the private directory, where the object + would be lost, so for a call that `writes`, every name has an entry: + each directory the repository lacks is created first, as git would on + its first write to it, and one that cannot be created is held by an + empty file, so that a write into it fails as it would in the store. + + GitPython's persistent `git cat-file` processes are stopped before and + after, so none reads with the environment it does not belong to. + """ + # Resolved: a linked worktree's common directory reads `/../..`, + # and a junction's target is not a path Windows collapses `..` in. + objects = Path(repo.common_dir).resolve() / "objects" + own = Path(tempfile.mkdtemp(prefix="mcp-git-objects-")) + links: list[Path] = [] + placeholders: list[Path] = [] + try: + for name in [f"{i:02x}" for i in range(256)] + ["pack"]: + target = objects / name + entry = own / name + if writes: + try: + target.mkdir(exist_ok=True) + except OSError: + pass + if not target.is_dir(): + if writes: + entry.touch() + placeholders.append(entry) + continue + if sys.platform != "win32": + os.symlink(target, entry, target_is_directory=True) + else: # pragma: no cover # Windows only; the coverage gate runs on Linux + _winapi.CreateJunction(str(target), str(entry)) + links.append(entry) + repo.git.clear_cache() + with repo.git.custom_environment(GIT_OBJECT_DIRECTORY=str(own)): + try: + yield + finally: + repo.git.clear_cache() + finally: + # Each link is removed as a link, so what it names is never touched. + for link in links: + if sys.platform != "win32": + os.unlink(link) + else: # pragma: no cover # Windows only; the coverage gate runs on Linux + os.rmdir(link) + for placeholder in placeholders: + os.unlink(placeholder) + os.rmdir(own) + + +# What a tool call or prompt has to undo when it ends: `open_repo` enters a +# repository's `_own_object_store` here, since most tools never close the +# repository they open. +_CALL: ContextVar[ExitStack | None] = ContextVar("_CALL", default=None) +# Whether the running tool can write objects (`writes_objects`). +_WRITES: ContextVar[bool] = ContextVar("_WRITES", default=False) + + +@contextmanager +def _one_call() -> Iterator[None]: + """Scope one tool call or prompt; what it entered in `_CALL` ends with it.""" + with ExitStack() as stack: + token = _CALL.set(stack) + try: + yield + finally: + _CALL.reset(token) + + +def _read_own_objects_for_call(repo: git.Repo) -> None: + """Run `repo`'s git through `_own_object_store` until the call ends.""" + stack = _CALL.get() + if stack is None: + raise RuntimeError("a repository opened under --repository needs _one_call()") + stack.enter_context(_own_object_store(repo, writes=_WRITES.get())) + + def _check_git_dir_contents( repo_path: Path, directory: Path, @@ -1049,10 +1444,17 @@ def _check_git_dir_contents( `directory` itself: a link at `objects`, `refs`, `index`, `HEAD` or anything else in a git directory is followed by git, for reading and for writing (a linked `index` takes git_add's writes elsewhere). - - A link that is allowed and names a directory is walked too, since git - follows it into that directory and on into any link inside it; each - directory is walked once, so a cycle of links ends. + - A directory that resolves outside them, which is what a Windows + directory junction is: `is_symlink()` is false for one and `is_dir()` + true, and git follows it as it follows a link. Every directory is + judged by where it resolves rather than by detecting a junction + (`is_junction()` exists only from Python 3.12): an ordinary directory + resolves to itself, inside the directory being walked, and passes. + + A link or directory that is allowed is walked where it resolves, since + git follows it there and on into any link inside it; each directory is + walked once, so a cycle of links ends, and one whose target is gone + (a dangling link or junction) is not walked. `hooks` is not walked: no hook runs (`HARDENED_CONFIG`), so a hooks directory linked to a shared one elsewhere is harmless. @@ -1076,21 +1478,16 @@ def _check_git_dir_contents( for entry in entries: if current == directory and entry.name == "hooks": continue - if entry.is_symlink(): - target = Path(entry.path).resolve() - if not ( - target.is_relative_to(allowed) - or target.is_relative_to(directory) - ): - raise outside(target) - if target.is_dir() and target not in visited: - visited.add(target) - pending.append(target) - elif entry.is_dir(): - real = Path(entry.path).resolve() - if real not in visited: - visited.add(real) - pending.append(real) + if not (entry.is_symlink() or entry.is_dir()): + continue + target = Path(entry.path).resolve() + if not ( + target.is_relative_to(allowed) or target.is_relative_to(directory) + ): + raise outside(target) + if target.is_dir() and target not in visited: + visited.add(target) + pending.append(target) def git_branch( @@ -1153,13 +1550,18 @@ def git_branch( # after the `::` is a URL of its own, and is redacted as one. _REMOTE_HELPER = re.compile(r"^(?P[A-Za-z][A-Za-z0-9+.-]*)::") -# One line of `git remote -v`: `\t (fetch|push)`, and on a -# partial clone's fetch line the promisor filter after it (` [blob:none]`). -# `.` matches everything but '\n', so a URL holding another line separator -# (U+2028, say) stays whole. -_REMOTE_LINE = re.compile( - r"^(?P[^\t]*)\t(?P.*) \((?Pfetch|push)\)" - r"(?P \[.*\])?$" +# A scheme followed by `://` anywhere in a value. A value holding one that +# `_URL_SCHEME` does not find at its start (after a space or a tab, say) holds +# a URL that cannot be split from what precedes it. +_EMBEDDED_URL = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://") + +# What follows `\t` on a line of `git remote -v`: ` (fetch|push)`, +# and on a partial clone's fetch line the promisor filter after it +# (` [blob:none]`). `.` matches everything but '\n', so a URL holding another +# line separator (U+2028, say) stays whole. The name is not matched here: it +# may hold a tab itself, so it is taken from the configured names instead. +_REMOTE_ENTRY = re.compile( + r"^(?P.*) \((?Pfetch|push)\)(?P \[.*\])?$" ) # Schemes whose username is an account name rather than a secret, so it is kept @@ -1209,15 +1611,16 @@ def redact_url(url: str) -> str: kept: a token there cannot be told apart from a repository name. A URL whose userinfo would hold a '?' or '#' cannot be split safely and is shown as `scheme://`. A remote-helper address (`::`) has its inner URL redacted. - An scp-like address (`git@host:path`) or a local path is not a URL and is - returned as is. + A value holding `scheme://` anywhere but at its start (` https://...`) + cannot be split safely either, and is withheld whole. An scp-like address + (`git@host:path`) or a local path is not a URL and is returned as is. """ helper = _REMOTE_HELPER.match(url) if helper is not None: return url[: helper.end()] + redact_url(url[helper.end() :]) authority = _URL_SCHEME.match(url) if authority is None: - return url + return REDACTED if _EMBEDDED_URL.search(url) else url scheme = authority["scheme"] match = _URL_USERINFO.match(url) if match is None: @@ -1271,6 +1674,13 @@ def git_remote(repo: git.Repo) -> str: '\\n' alone, the only separator git prints, not on every separator `str.splitlines` knows, which would cut a URL holding U+2028 in two. A URL holding a newline itself is refused (`_remote_url_has_newline`). + + A remote name may hold a tab, so the tab that ends it is not the first one + on the line. Each line's name is the longest configured name (from + `git remote`, one per line: git allows no newline in a name) that the line + starts with, followed by a tab. Whatever a shorter name would have left in + the URL column is then left to `redact_url`, which withholds a value with + a URL that does not start it. """ if _remote_url_has_newline(repo): raise ValueError( @@ -1278,21 +1688,24 @@ def git_remote(repo: git.Repo) -> str: "be listed without risking a credential in it; git refuses such " "URLs as well" ) + names = sorted( + filter(None, _git_text(repo, "remote").split("\n")), key=len, reverse=True + ) output = _git_text(repo, "remote", "-v").rstrip("\n") if not output: return "No remotes configured" lines = [] for line in output.split("\n"): - match = _REMOTE_LINE.match(line) - if match is None: + name = next((n for n in names if line.startswith(n + "\t")), None) + match = None if name is None else _REMOTE_ENTRY.match(line[len(name) + 1 :]) + if name is None or match is None: # Not a line in the shape `git remote -v` prints (a URL holding a - # newline, say): it cannot be parsed, so none of it is returned. + # newline, say, or a name not configured): it cannot be parsed, + # so none of it is returned. lines.append(REDACTED) continue url = redact_url(match["url"]) - lines.append( - f"{match['name']}\t{url} ({match['direction']}){match['filter'] or ''}" - ) + lines.append(f"{name}\t{url} ({match['direction']}){match['filter'] or ''}") return "\n".join(lines) @@ -1345,8 +1758,22 @@ def reports_failures(fn: Callable[_P, str]) -> Callable[_P, str]: @wraps(fn) def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> str: - with _GIT_LOCK, reported_to_model(): + with _GIT_LOCK, _one_call(), reported_to_model(): + return fn(*args, **kwargs) + + return wrapper + + +def writes_objects(fn: Callable[_P, str]) -> Callable[_P, str]: + """Mark a tool that writes to the repository, so its object store can be.""" + + @wraps(fn) + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> str: + token = _WRITES.set(True) + try: return fn(*args, **kwargs) + finally: + _WRITES.reset(token) return wrapper @@ -1462,6 +1889,30 @@ def reported_as_invalid_params() -> Iterator[None]: raise MCPError(code=INVALID_PARAMS, message=str(e)) from e +class _LiteralGit(git.Git): + """A `git.Git` whose working directory is taken literally. + + `git.Git` runs `os.path.expandvars` on a `str` working directory, and + `git.Repo` hands it one, whatever `expand_vars` the repository was opened + with. A `Path` is only resolved, so a `$NAME` in it stays as written. + """ + + def __init__(self, working_dir: str | os.PathLike[str] | None = None) -> None: + super().__init__(None if working_dir is None else Path(working_dir)) + + +class _LiteralRepo(git.Repo): + """A `git.Repo` whose git commands run in the directory it was opened at. + + Opened with `expand_vars=False` and an absolute path, a repository path is + taken literally: neither a `$NAME` nor a leading `~` in it becomes the + value of the server's environment, in the directory opened, in where its + commands run, or in an error. + """ + + GitCommandWrapperType = _LiteralGit + + def create_server(repository: Path | None) -> MCPServer: """The git server, confined to `repository` when one is given.""" @@ -1491,15 +1942,30 @@ async def reject_unknown_tools( subscriptions=False, ) + # The git directories the root may use outside itself are fixed now, not + # read again from the root on each call. + if repository is not None and record_root_git_dirs(repository) is None: + logging.getLogger(__name__).warning( + f"{repository}: its Git directory is outside it and is not a " + "linked worktree's or a submodule's, so tool calls that use it " + "will be refused" + ) + def open_repo(repo_path: str) -> git.Repo: path = Path(repo_path) validate_repo_path(path, repository) - repo = git.Repo(path) + # Opened at exactly the path checked above. GitPython expands a leading + # `~` in a relative path whatever `expand_vars` says, so it is made + # absolute first, which leaves nothing for it to expand. + repo = _LiteralRepo(path.absolute(), expand_vars=False) try: # First, so that no git command run for the repository, the # confinement checks' included, runs a program it names. harden_repo(repo) validate_opened_repo(repo, path, repository) + if repository is not None: + # Last, once the directories it links to have been checked. + _read_own_objects_for_call(repo) except Exception: repo.close() raise @@ -1516,7 +1982,12 @@ def open_repo(repo_path: str) -> git.Repo: def commit_message( repo_path: Annotated[str, Field(description="The path to the Git repository.")], ) -> str: - with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo: + with ( + _GIT_LOCK, + _one_call(), + reported_as_invalid_params(), + open_repo(repo_path) as repo, + ): return commit_message_prompt(repo) @server.prompt( @@ -1539,7 +2010,12 @@ def summarize_changes( ), ] = None, ) -> str: - with _GIT_LOCK, reported_as_invalid_params(), open_repo(repo_path) as repo: + with ( + _GIT_LOCK, + _one_call(), + reported_as_invalid_params(), + open_repo(repo_path) as repo, + ): return summarize_changes_prompt(repo, target) @server.tool( @@ -1596,8 +2072,9 @@ def diff( structured_output=False, ) @reports_failures + @writes_objects def commit(repo_path: str, message: str) -> str: - return git_commit(open_repo(repo_path), message) + return git_commit(open_repo(repo_path), message, allowed_repository=repository) @server.tool( name=GitTools.ADD.value, @@ -1606,6 +2083,7 @@ def commit(repo_path: str, message: str) -> str: structured_output=False, ) @reports_failures + @writes_objects def add(repo_path: str, files: Annotated[list[str], Field(min_length=1)]) -> str: return git_add(open_repo(repo_path), files) @@ -1616,12 +2094,22 @@ def add(repo_path: str, files: Annotated[list[str], Field(min_length=1)]) -> str structured_output=False, ) @reports_failures + @writes_objects def reset(repo_path: str) -> str: return git_reset(open_repo(repo_path)) @server.tool( name=GitTools.LOG.value, - description="Shows the commit logs", + # #5552: small models read the old one-line description as "a time + # window is required" and filtered to an empty one. Say the order and + # that the filters are optional, where the model picks its arguments. + description=( + "Shows the commit log, newest commit first. For the latest " + "commits, pass only repo_path (and optionally max_count). " + "start_timestamp and end_timestamp are optional filters for a " + "date range: omit them unless a specific period is asked for, " + "because a range that holds no commits returns none." + ), annotations=READ_ONLY, structured_output=False, ) @@ -1638,19 +2126,33 @@ def log( start_timestamp: Annotated[ str | None, Field( - description=f"Start timestamp for filtering commits. {TIMESTAMP_FORMATS}" + description=( + "Optional: only show commits at or after this time. " + f"Omit for no lower bound. {TIMESTAMP_FORMATS}" + ) ), ] = None, end_timestamp: Annotated[ str | None, Field( - description=f"End timestamp for filtering commits. {TIMESTAMP_FORMATS}" + description=( + "Optional: only show commits at or before this time. " + f"Omit for no upper bound. {TIMESTAMP_FORMATS}" + ) ), ] = None, ) -> str: entries = git_log( open_repo(repo_path), max_count, start_timestamp, end_timestamp ) + if not entries and (start_timestamp or end_timestamp): + # #5552: an empty history under a filter reads as "the repository + # has no commits". Name the filter as the cause and the way out. + return ( + "Commit history:\n" + "No commits match the given start_timestamp/end_timestamp. " + "Omit both to see the latest commits." + ) return "Commit history:\n" + "\n".join(entries) @server.tool( @@ -1660,6 +2162,7 @@ def log( structured_output=False, ) @reports_failures + @writes_objects def create_branch( repo_path: str, branch_name: str, @@ -1683,8 +2186,11 @@ def create_branch( structured_output=False, ) @reports_failures + @writes_objects def checkout(repo_path: str, branch_name: str) -> str: - return git_checkout(open_repo(repo_path), branch_name) + return git_checkout( + open_repo(repo_path), branch_name, allowed_repository=repository + ) @server.tool( name=GitTools.MERGE.value, @@ -1697,6 +2203,7 @@ def checkout(repo_path: str, branch_name: str) -> str: structured_output=False, ) @reports_failures + @writes_objects def merge( repo_path: str, source_branch: Annotated[ @@ -1715,7 +2222,12 @@ def merge( ), ] = True, ) -> str: - return git_merge(open_repo(repo_path), source_branch, fast_forward_only) + return git_merge( + open_repo(repo_path), + source_branch, + fast_forward_only, + allowed_repository=repository, + ) @server.tool( name=GitTools.SHOW.value, @@ -1785,7 +2297,9 @@ async def serve(repository: Path | None, transport: str = "stdio") -> None: # Walk up to the enclosing working tree, like `git rev-parse # --show-toplevel`, so `--repository .` works from a subdirectory. root = Path( - git.Repo(repository, search_parent_directories=True).working_dir + git.Repo( + repository, search_parent_directories=True, expand_vars=False + ).working_dir ) except git.NoSuchPathError: logger.error(f"{repository} does not exist") diff --git a/src/git/tests/snapshots/list_tools.json b/src/git/tests/snapshots/list_tools.json index 12953ca0f2..79849cd1b0 100644 --- a/src/git/tests/snapshots/list_tools.json +++ b/src/git/tests/snapshots/list_tools.json @@ -197,7 +197,7 @@ }, { "name": "git_log", - "description": "Shows the commit logs", + "description": "Shows the commit log, newest commit first. For the latest commits, pass only repo_path (and optionally max_count). start_timestamp and end_timestamp are optional filters for a date range: omit them unless a specific period is asked for, because a range that holds no commits returns none.", "inputSchema": { "properties": { "repo_path": { @@ -221,7 +221,7 @@ } ], "default": null, - "description": "Start timestamp for filtering commits. Accepts: ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024')", + "description": "Optional: only show commits at or after this time. Omit for no lower bound. Accepts: ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024')", "title": "Start Timestamp" }, "end_timestamp": { @@ -234,7 +234,7 @@ } ], "default": null, - "description": "End timestamp for filtering commits. Accepts: ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024')", + "description": "Optional: only show commits at or before this time. Omit for no upper bound. Accepts: ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024')", "title": "End Timestamp" } }, diff --git a/src/git/tests/test_alternates_race.py b/src/git/tests/test_alternates_race.py new file mode 100644 index 0000000000..e9dac111fc --- /dev/null +++ b/src/git/tests/test_alternates_race.py @@ -0,0 +1,407 @@ +"""Under `--repository`, git reads only the repository's own objects. + +`_check_git_dir_contents` refuses an alternate object store when a repository +is opened, but the alternates file is an ordinary file in the git directory, +so its contents can change between that check and the object reads that +follow it. Under `--repository`, `open_repo` therefore runs git, for the rest +of the tool call or prompt, on an object directory of its own +(`_own_object_store`) whose alternates list is always empty, so what the +repository's alternates file says while git reads objects no longer matters. + +The tests are deterministic rather than a race: the check is wrapped so that +it plants an alternates entry right after it has passed, which is the state +git would see if a write landed in that window. Each route that reads an +object a caller names is driven that way. Writes go through the same object +directory, so the tools that write objects are shown to still land them in +the repository's store. Without `--repository`, alternates keep working, +since a `--shared` or `--reference` clone is a supported repository there. +""" + +import os +import sys +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any +from unittest import mock + +import git +import pytest +from conftest import connect, make_repo, wire +from mcp.shared.exceptions import MCPError + +from mcp_server_git import server + +MARKER = "ONLY_IN_THE_OTHER_REPOSITORY\n" +MESSAGE = "only in the other repository" + + +def objects_of(repo: git.Repo) -> Path: + return Path(repo.common_dir) / "objects" + + +def root_of(repo: git.Repo) -> Path: + assert repo.working_dir is not None + return Path(repo.working_dir) + + +@pytest.fixture +def other(tmp_path: Path) -> git.Repo: + """A repository outside the allowed one, with a commit of its own.""" + repo = make_repo(tmp_path / "other") + (root_of(repo) / "only-here.txt").write_text(MARKER, newline="\n") + repo.index.add(["only-here.txt"]) + repo.index.commit(MESSAGE) + return repo + + +@contextmanager +def alternates_planted_after_check(alternates: Path, entry: str) -> Iterator[None]: + """Write `entry` to `alternates` each time the git-directory check passes.""" + check: Callable[..., None] = server._check_git_dir_contents + + def check_then_plant(*args: Any, **kwargs: Any) -> None: + check(*args, **kwargs) + alternates.write_text(entry, newline="\n") + + with mock.patch.object(server, "_check_git_dir_contents", check_then_plant): + yield + + +async def call(repository: Path | None, tool: str, arguments: dict[str, Any]) -> Any: + async with connect(repository) as session: + return wire(await session.call_tool(tool, arguments)) + + +async def summarize(repository: Path, repo_path: Path, target: str) -> str: + """The git_summarize_changes prompt's text, or the error it was refused with.""" + async with connect(repository) as session: + try: + result = await session.get_prompt( + "git_summarize_changes", + {"repo_path": str(repo_path), "target": target}, + ) + except MCPError as e: + return f"refused: {e}" + return str(wire(result)) + + +# Each route that reads objects a caller names: the tool and its arguments, +# with {blob} and {commit} standing for the other repository's objects. +ROUTES = [ + ("git_show", {"revision": "{blob}"}), + ("git_show", {"revision": "{commit}"}), + ("git_show", {"revision": "{commit}:"}), + ("git_diff", {"target": "{commit}"}), + ("git_log", {}), + ("git_checkout", {"branch_name": "{commit}"}), + ("git_create_branch", {"branch_name": "new", "base_branch": "{commit}"}), +] + + +@pytest.mark.parametrize( + ("tool", "arguments"), ROUTES, ids=[f"{t}-{a}" for t, a in ROUTES] +) +async def test_restricted_tools_ignore_alternates_written_after_the_check( + test_repository: git.Repo, other: git.Repo, tool: str, arguments: dict[str, str] +): + root = root_of(test_repository) + git_dir = Path(test_repository.git_dir) + alternates = objects_of(test_repository) / "info" / "alternates" + alternates.parent.mkdir(parents=True, exist_ok=True) + commit = other.head.commit.hexsha + names = {"blob": other.git.rev_parse("HEAD:only-here.txt"), "commit": commit} + if tool == "git_log": + # A branch naming the other repository's commit, checked out. + (git_dir / "refs" / "heads" / "elsewhere").write_text(f"{commit}\n") + (git_dir / "HEAD").write_text("ref: refs/heads/elsewhere\n") + + with alternates_planted_after_check(alternates, f"{objects_of(other)}\n"): + result = await call( + root, + tool, + {"repo_path": str(root)} + | {k: v.format(**names) for k, v in arguments.items()}, + ) + + # The entry really was in place when the tool read objects. + assert alternates.read_bytes() == f"{objects_of(other)}\n".encode() + assert result["isError"] is True, result + text = result["content"][0]["text"] + assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text + assert MESSAGE not in text + assert "only-here.txt" not in text + assert not (root / "only-here.txt").exists() + assert not (git_dir / "refs" / "heads" / "new").exists() + + +async def test_restricted_prompt_ignores_alternates_written_after_the_check( + test_repository: git.Repo, other: git.Repo +): + root = root_of(test_repository) + alternates = objects_of(test_repository) / "info" / "alternates" + alternates.parent.mkdir(parents=True, exist_ok=True) + + with alternates_planted_after_check(alternates, f"{objects_of(other)}\n"): + text = await summarize(root, root, other.head.commit.hexsha) + + assert alternates.read_bytes() == f"{objects_of(other)}\n".encode() + assert text.startswith("refused: ") + assert "ONLY_IN_THE_OTHER_REPOSITORY" not in text + + +async def test_restricted_tools_still_read_the_repositorys_own_objects( + test_repository: git.Repo, +): + root = root_of(test_repository) + (root / "packed.txt").write_text("PACKED\n") + test_repository.index.add(["packed.txt"]) + test_repository.index.commit("packed") + test_repository.git.gc("--quiet") # moves every object into a pack + (root / "loose.txt").write_text("LOOSE\n") + test_repository.index.add(["loose.txt"]) + test_repository.index.commit("loose") + + for tool, arguments, expected in [ + ("git_show", {"revision": "HEAD:packed.txt"}, "PACKED"), + ("git_show", {"revision": "HEAD:loose.txt"}, "LOOSE"), + ("git_show", {"revision": "HEAD"}, "+LOOSE"), + ("git_show", {"revision": "HEAD~1"}, "+PACKED"), + ("git_diff", {"target": "HEAD~2"}, "+PACKED"), + ("git_log", {}, "packed"), + ]: + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, result + assert expected in result["content"][0]["text"] + assert "+LOOSE" in await summarize(root, root, "HEAD~1") + + +async def test_restricted_writes_land_in_the_repositorys_own_store(tmp_path: Path): + # A repository with no loose-object directories yet, so every object the + # tools write is the first in its directory. + # Named, since git's default branch name is configurable. + repo = git.Repo.init(tmp_path / "fresh", initial_branch="main") + root = root_of(repo) + for config in [("user.name", "t"), ("user.email", "t@example.com")]: + repo.git.config(*config) + (root / "a.txt").write_text("A\n") + (root / "b.txt").write_text("B\n") + + for tool, arguments in [ + ("git_add", {"files": ["a.txt"]}), + ("git_commit", {"message": "first"}), + ("git_create_branch", {"branch_name": "side"}), + ("git_checkout", {"branch_name": "side"}), + ("git_add", {"files": ["b.txt"]}), + ("git_commit", {"message": "on side"}), + ("git_checkout", {"branch_name": "main"}), + ]: + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, (tool, result) + (root / "c.txt").write_text("C\n") + repo.index.add(["c.txt"]) + repo.index.commit("on main") + # git itself writes the merge commit, through the private directory. + result = await call( + root, + "git_merge", + {"repo_path": str(root), "source_branch": "side", "fast_forward_only": False}, + ) + assert result["isError"] is False, result + + head = repo.git.rev_parse("HEAD") + assert "with merge commit" in result["content"][0]["text"] + # Every object is in the repository's own store, read by a git that runs + # outside the server: fsck fails on any object HEAD reaches but lacks. + assert len(repo.git.rev_list("--objects", "HEAD").splitlines()) >= 9 + repo.git.fsck("--no-dangling") + assert repo.commit(head).parents[1].message.rstrip() == "on side" + + +async def test_restricted_read_only_calls_write_nothing_to_the_store( + test_repository: git.Repo, +): + # A link to a loose-object directory the store lacks reads as absent, so + # a call that only reads creates none of them. + root = root_of(test_repository) + objects = objects_of(test_repository) + before = sorted(p.name for p in objects.iterdir()) + for tool, arguments in [ + ("git_status", {}), + ("git_log", {}), + ("git_show", {"revision": "HEAD"}), + ("git_diff", {"target": "HEAD"}), + ("git_branch", {"branch_type": "local"}), + ]: + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, (tool, result) + await summarize(root, root, "HEAD") + assert sorted(p.name for p in objects.iterdir()) == before + + +@contextmanager +def private_store_seen_by( + tool_function: str, seen: dict[str, set[str]] +) -> Iterator[None]: + """Record the private object directory's entries while `tool_function` runs. + + Each entry is recorded as its name, with `/` after a link to a directory + and nothing after a placeholder file, so the result is the same whether + the platform links with symbolic links or with junctions. + """ + original = getattr(server, tool_function) + + def recording(repo: git.Repo, *args: Any, **kwargs: Any) -> str: + own = Path(repo.git.environment()["GIT_OBJECT_DIRECTORY"]) + seen[tool_function] = { + p.name + ("/" if p.is_dir() else "") for p in own.iterdir() + } + return original(repo, *args, **kwargs) + + with mock.patch.object(server, tool_function, recording): + yield + + +async def test_restricted_private_store_links_only_what_the_call_can_use( + tmp_path: Path, +): + # A repository with only a few loose-object directories. A read links + # just those (on Windows a junction cannot name a missing directory); a + # write has an entry for every name, so git never creates one inside the + # private directory, where what it wrote would be lost. + repo = make_repo(tmp_path / "few") + root = root_of(repo) + (root / "a.txt").write_text("A\n") + repo.index.add(["a.txt"]) + repo.index.commit("one") + objects = objects_of(repo) + existing = {p.name for p in objects.iterdir() if len(p.name) == 2} + assert 0 < len(existing) < 256 + every = {f"{i:02x}/" for i in range(256)} | {"pack/"} + + seen: dict[str, set[str]] = {} + with ( + private_store_seen_by("git_status", seen), + private_store_seen_by("git_create_branch", seen), + ): + status = await call(root, "git_status", {"repo_path": str(root)}) + branch = await call( + root, "git_create_branch", {"repo_path": str(root), "branch_name": "b"} + ) + + assert status["isError"] is False and branch["isError"] is False + assert seen["git_status"] == {f"{n}/" for n in existing} | {"pack/"} + assert seen["git_create_branch"] == every + # The write call created the directories it linked, as git would. + assert {p.name for p in objects.iterdir() if len(p.name) == 2} == { + f"{i:02x}" for i in range(256) + } + + +async def test_restricted_private_store_of_a_linked_worktree_names_real_paths( + tmp_path: Path, +): + # GitPython gives a linked worktree's common directory as + # `/../..`. A junction's target is not a path Windows collapses + # `..` in, so each link names the main repository's objects directly. + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + expected = (Path(main.git_dir).resolve() / "objects").resolve() + targets: list[Path] = [] + original = server.git_status + + def recording(repo: git.Repo) -> str: + own = Path(repo.git.environment()["GIT_OBJECT_DIRECTORY"]) + targets.extend(Path(os.readlink(p)) for p in own.iterdir()) + return original(repo) + + try: + with mock.patch.object(server, "git_status", recording): + result = await call(worktree, "git_status", {"repo_path": str(worktree)}) + finally: + main.close() + + assert result["isError"] is False, result + assert targets + for target in targets: + assert ".." not in target.parts, target + assert Path(str(target).removeprefix("\\\\?\\")).parent == expected + + +@pytest.mark.skipif( + sys.platform == "win32" or os.geteuid() == 0, + reason="needs a directory that chmod can make unwritable", +) +async def test_restricted_server_works_on_a_store_it_cannot_write( + test_repository: git.Repo, +): + root = root_of(test_repository) + objects = objects_of(test_repository) + seen: dict[str, set[str]] = {} + objects.chmod(0o555) + try: + for tool, arguments, expected in [ + ("git_status", {}, "Repository status"), + ("git_log", {}, "initial commit"), + ("git_show", {"revision": "HEAD:test.txt"}, "test"), + # A tool that writes but adds no object: the loose-object + # directories it cannot create are left out. + ("git_create_branch", {"branch_name": "side"}, "side"), + ]: + with private_store_seen_by("git_create_branch", seen): + result = await call(root, tool, {"repo_path": str(root)} | arguments) + assert result["isError"] is False, (tool, result) + assert expected in result["content"][0]["text"] + # Each directory the write call could not create is held by a file, + # so a write into it fails instead of landing in the private store. + missing = {f"{i:02x}" for i in range(256)} - {p.name for p in objects.iterdir()} + assert missing + assert missing <= seen["git_create_branch"] + finally: + objects.chmod(0o755) + + +async def test_restricted_calls_leave_no_object_directory_behind( + test_repository: git.Repo, tmp_path: Path +): + root = root_of(test_repository) + scratch = tmp_path / "scratch" + scratch.mkdir() + with mock.patch("tempfile.tempdir", str(scratch)): + ok = await call(root, "git_show", {"repo_path": str(root), "revision": "HEAD"}) + failed = await call( + root, "git_show", {"repo_path": str(root), "revision": "0" * 40} + ) + await summarize(root, root, "HEAD") + assert ok["isError"] is False + assert failed["isError"] is True + assert list(scratch.iterdir()) == [] + + +def test_a_restricted_repository_is_opened_only_inside_a_call( + test_repository: git.Repo, +): + # Outside `_one_call()` there is nothing to end the private store with. + with pytest.raises(RuntimeError, match="needs _one_call"): + server._read_own_objects_for_call(test_repository) + + +async def test_unrestricted_git_show_follows_alternates( + test_repository: git.Repo, other: git.Repo +): + # Without --repository, a clone made with --shared or --reference reads + # its objects from the store it names, as git does. + root = root_of(test_repository) + alternates = objects_of(test_repository) / "info" / "alternates" + alternates.parent.mkdir(parents=True, exist_ok=True) + alternates.write_text(f"{objects_of(other)}\n", newline="\n") + + result = await call( + None, + "git_show", + {"repo_path": str(root), "revision": other.git.rev_parse("HEAD:only-here.txt")}, + ) + + assert result["isError"] is False, result + assert result["content"][0]["text"] == MARKER diff --git a/src/git/tests/test_expand_vars.py b/src/git/tests/test_expand_vars.py new file mode 100644 index 0000000000..b0ec82541c --- /dev/null +++ b/src/git/tests/test_expand_vars.py @@ -0,0 +1,109 @@ +"""A tool's `repo_path` is taken literally: no `$NAME` or `~` in it is expanded. + +GitPython's `Repo()` expands environment variables in the path it is given +unless it is passed `expand_vars=False`, and expands a leading `~` (from +`HOME`) in any relative path. A `$NAME`, `${NAME}` or `~` in `repo_path` must +name a file whose name holds those characters, so the result of a tool call +(its errors included) never holds the value of `HOME` or of a variable the +path names. A `$NAME` in `--repository` is taken literally too. These tests +set a variable, name it in a path, and assert on what a client receives over +the wire. +""" + +from pathlib import Path + +import git +import pytest +from conftest import connect, make_repo, wire + +VALUE = "value-of-the-variable" +NAME = "MCP_GIT_TEST_VARIABLE" + + +@pytest.fixture(autouse=True) +def variable(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(NAME, VALUE) + + +async def status(repository: Path | None, repo_path: str) -> dict[str, object]: + async with connect(repository) as session: + return wire(await session.call_tool("git_status", {"repo_path": repo_path})) + + +def text_of(result: dict[str, object]) -> str: + content = result["content"] + assert isinstance(content, list) + return "".join(block["text"] for block in content) + + +@pytest.mark.parametrize("reference", [f"${NAME}", f"${{{NAME}}}"]) +async def test_relative_repo_path_is_not_expanded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str +): + monkeypatch.chdir(tmp_path) + result = await status(None, reference) + assert result["isError"] is True + assert VALUE not in text_of(result) + assert reference in text_of(result) + + +@pytest.mark.parametrize("reference", [f"${NAME}", f"${{{NAME}}}"]) +async def test_repo_path_under_repository_is_not_expanded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str +): + root = tmp_path / "repo" + make_repo(root).close() + # With the working directory inside the allowed repository, a relative + # path passes the --repository check before the repository is opened. + monkeypatch.chdir(root) + for repo_path in (reference, str(root / reference)): + result = await status(root, repo_path) + assert result["isError"] is True + assert VALUE not in text_of(result) + + +@pytest.mark.parametrize("reference", ["~", "~/repo"]) +async def test_tilde_in_repo_path_is_not_expanded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reference: str +): + home = tmp_path / VALUE + make_repo(home / "repo").close() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.chdir(tmp_path) + result = await status(None, reference) + assert result["isError"] is True + assert VALUE not in text_of(result) + assert str(tmp_path / reference) in text_of(result) + + +async def test_repository_named_with_a_dollar_sign_opens(tmp_path: Path): + # Made under a plain name and renamed, since `make_repo` would expand it. + root = tmp_path / f"${NAME}" + make_repo(tmp_path / "plain").close() + (tmp_path / "plain").rename(root) + for repository in (None, root): + result = await status(repository, str(root)) + assert result["isError"] is False, result + assert "On branch main" in text_of(result) + # Reading a commit goes through the object database's own git. + async with connect(repository) as session: + log = wire(await session.call_tool("git_log", {"repo_path": str(root)})) + assert log["isError"] is False, log + assert "initial commit" in text_of(log) + + +async def test_repository_with_separate_git_dir_named_with_a_dollar_sign( + tmp_path: Path, +): + # A git dir outside the working tree makes the --repository check compare + # it with the allowed root's own. Its `core.worktree` names the root back, + # as a submodule's git dir does, so the root is one the check accepts. + root = tmp_path / f"${NAME}" + root.mkdir() + git_dir = tmp_path / "gitdir" + git.Git(root).init(f"--separate-git-dir={git_dir}") + git.Git(root).config("core.worktree", str(root)) + result = await status(root, str(root)) + assert result["isError"] is False, result + assert "No commits yet" in text_of(result) diff --git a/src/git/tests/test_junction.py b/src/git/tests/test_junction.py new file mode 100644 index 0000000000..6eef839236 --- /dev/null +++ b/src/git/tests/test_junction.py @@ -0,0 +1,235 @@ +"""A Windows junction in a git directory is held to `--repository` (#5520). + +`_check_git_dir_contents` refuses a symbolic link in a git directory that +resolves outside the allowed repository. A Windows directory junction is not a +symbolic link to Python (`DirEntry.is_symlink()` is false for one, and +`is_dir()` true), yet git follows it like one, so the walk used to enter a +junction's target as an ordinary directory without judging where it was. The +walk now judges every directory by where it resolves. + +Two sets of tests, both through the real server and a client: + +- **Real junctions**, made with `mklink /J` (which needs no privilege). They + run only on Windows, which is the `Test git (Windows)` CI leg. +- **Junction-like entries** on every platform: `os.scandir` is wrapped so a + symbolic link reports itself the way a junction does. A POSIX host cannot + make a junction, and the per-file coverage gate runs on Linux, so these are + what fail there when the fix is taken out. +""" + +import os +import subprocess +import sys +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any +from unittest import mock + +import git +import pytest +from conftest import connect, make_repo, rmtree, wire + +windows_only = pytest.mark.skipif( + sys.platform != "win32", reason="junctions exist only on Windows" +) + +Link = Callable[[Path, Path], None] + + +def root_of(repo: git.Repo) -> Path: + assert repo.working_dir is not None + return Path(repo.working_dir) + + +async def status(repository: Path, repo_path: Path) -> dict[str, Any]: + """`git_status` on `repo_path` from a server restricted to `repository`.""" + async with connect(repository) as session: + return wire( + await session.call_tool("git_status", {"repo_path": str(repo_path)}) + ) + + +def uses_outside(result: dict[str, Any], used: Path, allowed: Path) -> bool: + """The result is the error for a repository git opened outside `allowed`.""" + text = result["content"][0]["text"] + return ( + result["isError"] is True + and f"uses '{used}'" in text + and f"which is outside the allowed repository '{allowed}'" in text + ) + + +def junction(link: Path, target: Path) -> None: + """Make `link` a directory junction to `target` (Windows only).""" + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(link), str(target)], + check=True, + capture_output=True, + ) + + +def symlink(link: Path, target: Path) -> None: + link.symlink_to(target, target_is_directory=True) + + +class JunctionLike: + """A symbolic link's `DirEntry`, answering as a junction's does.""" + + def __init__(self, entry: "os.DirEntry[str]") -> None: + self._entry = entry + self.name = entry.name + self.path = entry.path + + def is_symlink(self) -> bool: + return False + + def is_dir(self) -> bool: + return True + + +class JunctionLikeScan: + """`os.scandir`'s iterator, with each directory link made junction-like.""" + + def __init__(self, scan: Any) -> None: + self._scan = scan + + def __enter__(self) -> Iterator[Any]: + return iter(self) + + def __exit__(self, *exc: object) -> None: + self._scan.close() + + def __iter__(self) -> Iterator[Any]: + for entry in self._scan: + if entry.is_symlink() and entry.is_dir(): + yield JunctionLike(entry) + else: + yield entry + + +@contextmanager +def links_scan_as_junctions() -> Iterator[None]: + real_scandir = os.scandir + with mock.patch( + "mcp_server_git.server.os.scandir", + lambda path: JunctionLikeScan(real_scandir(path)), + ): + yield + + +@contextmanager +def nothing_patched() -> Iterator[None]: + yield + + +# Each case: how to make the link, and what to patch while the server runs. +REAL = pytest.param(junction, nothing_patched, marks=windows_only, id="junction") +LIKE = pytest.param(symlink, links_scan_as_junctions, id="junction-like") +either = pytest.mark.parametrize(("link", "patched"), [REAL, LIKE]) + + +@either +@pytest.mark.parametrize("entry", ["objects", "refs"]) +async def test_junction_leading_outside_is_refused( + tmp_path: Path, + repo: git.Repo, + link: Link, + patched: Callable[[], Any], + entry: str, +): + # `.git/objects` (or `refs`) of a nested repository is a junction to + # another repository's, outside the allowed one. + root = root_of(repo) + other = make_repo(tmp_path / "other") + nested = make_repo(root / "nested") + nested_git = Path(nested.git_dir) + nested.close() + target = Path(other.git_dir) / entry + rmtree(nested_git / entry) + link(nested_git / entry, target) + try: + with patched(): + result = await status(root, root / "nested") + assert uses_outside(result, target.resolve(), root), result + finally: + other.close() + + +@either +async def test_junction_staying_inside_is_followed_and_checked( + tmp_path: Path, repo: git.Repo, link: Link, patched: Callable[[], Any] +): + # A junction to a directory in the allowed repository is allowed, and git + # follows it, so what it leads to is checked: here a second junction, in + # that directory, to outside. + root = root_of(repo) + other = make_repo(tmp_path / "other") + store = root / "store" + store.mkdir() + link(Path(repo.git_dir) / "extra", store) + escape = Path(other.git_dir) / "objects" + link(store / "elsewhere", escape) + # A cycle of allowed junctions ends rather than being walked forever. + link(store / "loop", store) + try: + with patched(): + result = await status(root, root) + assert uses_outside(result, escape.resolve(), root), result + finally: + other.close() + + +@either +async def test_junctions_that_stay_inside_are_accepted( + tmp_path: Path, repo: git.Repo, link: Link, patched: Callable[[], Any] +): + # Into the working tree, within the git directory, and around in a cycle: + # none leads anywhere new. Nor does a `hooks` junction to a shared + # directory outside, since no hook runs. + root = root_of(repo) + git_dir = Path(repo.git_dir) + docs = root / "docs" + docs.mkdir() + link(git_dir / "extra", docs) + link(git_dir / "refs-again", git_dir / "refs") + link(git_dir / "loop", git_dir) + shared_hooks = tmp_path / "shared-hooks" + shared_hooks.mkdir() + hooks = git_dir / "hooks" + if hooks.exists(): + rmtree(hooks) + link(hooks, shared_hooks) + with patched(): + result = await status(root, root) + assert result["isError"] is False, result + + +@windows_only +async def test_dangling_junction_inside_is_not_walked(repo: git.Repo): + # A junction is still a directory to `is_dir()` once its target is gone; + # walking it would fail the call with the scan's own error. + root = root_of(repo) + gone = root / "gone" + gone.mkdir() + junction(Path(repo.git_dir) / "extra", gone) + gone.rmdir() + result = await status(root, root) + assert result["isError"] is False, result + + +@windows_only +async def test_dangling_junction_outside_is_refused(tmp_path: Path, repo: git.Repo): + root = root_of(repo) + gone = tmp_path / "gone" + gone.mkdir() + junction(Path(repo.git_dir) / "extra", gone.resolve()) + gone.rmdir() + result = await status(root, root) + # Not `uses_outside`: how a target that is gone is spelled is up to the + # host, so only the refusal is pinned. + assert result["isError"] is True, result + assert ( + f"which is outside the allowed repository '{root}'" + in result["content"][0]["text"] + ), result diff --git a/src/git/tests/test_lfs_config.py b/src/git/tests/test_lfs_config.py new file mode 100644 index 0000000000..0a54332027 --- /dev/null +++ b/src/git/tests/test_lfs_config.py @@ -0,0 +1,267 @@ +"""Git LFS never runs a program the repository's own configuration names. + +The Git LFS filter comes from the user's global or system configuration, so +the server trusts it and leaves it working. Git LFS then reads its own keys +from the repository's configuration, and some of them name programs: an +extension's `clean` and `smudge` commands, and a transfer agent's `path` and +`args`. A download also runs the SSH command, credential helpers and askpass +program configured for an endpoint the repository can pick. `harden_repo` +empties the first group the way it empties filter drivers, and turns +downloads off (GIT_LFS_SKIP_SMUDGE), which covers the rest. + +Git LFS is not installed in CI, so the protocol-level tests that always run +use a stand-in `git-lfs`: a filter that reads those keys with `git config` +and runs what they name, as Git LFS does, so a test sees exactly the +configuration and environment the real one would. The tests that drive the +real Git LFS skip when it is not on PATH. The payloads are POSIX shell +scripts, so the protocol-level tests skip on Windows. +""" + +import shlex +import shutil +import stat +from pathlib import Path +from typing import Any + +import git +import pytest +from conftest import connect, wire +from test_empty_driver_name import make_stale +from test_repository_config import Payload, commit_file, posix_only, root_of +from test_submodule_config import embed + +from mcp_server_git.server import _submodule_drivers, harden_repo + +# The Git LFS keys that name a program, each with a subsection name that +# exercises the match: plain, dotted and empty. +LFS_PROGRAM_KEYS = ( + "lfs.extension.poc.clean", + "lfs.extension.poc.smudge", + "lfs.extension.a.b.clean", + "lfs.extension..smudge", + "lfs.customtransfer.poc.path", + "lfs.customtransfer.poc.args", + "lfs.standalonetransferagent", +) + +real_lfs = pytest.mark.skipif( + shutil.which("git-lfs") is None, reason="Git LFS is not installed" +) + +# What `git lfs install` writes to the user's configuration. +LFS_DRIVER = ( + '[filter "lfs"]\n' + "\tclean = git-lfs clean -- %f\n" + "\tsmudge = git-lfs smudge -- %f\n" + "\tprocess = git-lfs filter-process\n" + "\trequired = true\n" +) + + +@pytest.fixture +def payload(tmp_path: Path) -> Payload: + return Payload(tmp_path / "payload") + + +def use_global_config( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: str +) -> None: + """Make `content` the user's whole configuration, for git and the server.""" + config = tmp_path / "global-config" + config.write_text(content) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(config)) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + + +# -------------------------------------------------------------------------- +# harden_repo itself +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize("key", LFS_PROGRAM_KEYS) +def test_harden_repo_empties_the_repositorys_lfs_programs(repo: git.Repo, key: str): + repo.git.config(key, "program") + harden_repo(repo) + assert repo.git.config("--get", key) == "" + + +def test_harden_repo_keeps_the_users_own_lfs_programs( + tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch +): + use_global_config( + tmp_path, + monkeypatch, + '[lfs "extension.mine"]\n\tclean = my-clean\n' + '[lfs "customtransfer.mine"]\n\tpath = my-agent\n' + "[lfs]\n\tstandalonetransferagent = mine\n", + ) + harden_repo(repo) + assert repo.git.config("--get", "lfs.extension.mine.clean") == "my-clean" + assert repo.git.config("--get", "lfs.customtransfer.mine.path") == "my-agent" + assert repo.git.config("--get", "lfs.standalonetransferagent") == "mine" + + +def test_harden_repo_turns_lfs_downloads_off(repo: git.Repo): + harden_repo(repo) + assert repo.git.environment()["GIT_LFS_SKIP_SMUDGE"] == "1" + + +def test_a_submodules_lfs_programs_are_listed(repo: git.Repo): + # The Git LFS run inside a checked-out submodule reads the submodule's + # configuration, so its keys are emptied like the opened repository's. + inner = embed(repo, "sm") + inner.git.config("lfs.extension.poc.clean", "program") + assert "lfs.extension.poc.clean" in _submodule_drivers(repo) + + +# -------------------------------------------------------------------------- +# Through the server, with a stand-in for Git LFS +# -------------------------------------------------------------------------- + + +def install_stand_in(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A user filter `lfs` that runs what the LFS keys name, as Git LFS does. + + Its clean step runs the `poc` extension's `clean`; its smudge step runs + the extension's `smudge` and, unless GIT_LFS_SKIP_SMUDGE is set, the + transfer agent `lfs.standalonetransferagent` picks. It then passes the + file through unchanged. + """ + script = tmp_path / "git-lfs-stand-in.sh" + script.write_text( + "#!/bin/sh\n" + 'run() { if [ -n "$1" ]; then sh -c "$1" git.Repo: + """`repo` with Git LFS installed for the user and one LFS file committed.""" + use_global_config(tmp_path, monkeypatch, LFS_DRIVER) + commit_file(repo, ".gitattributes", "*.bin filter=lfs diff=lfs merge=lfs -text\n") + commit_file(repo, "a.bin", "a\n") + return repo + + +async def call(name: str, repo: git.Repo, **arguments: str) -> dict[str, Any]: + async with connect(root_of(repo)) as session: + return wire( + await session.call_tool( + name, {"repo_path": str(root_of(repo)), **arguments} + ) + ) + + +@real_lfs +@posix_only +async def test_git_lfs_keeps_working( + tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch +): + lfs_repo(tmp_path, repo, monkeypatch) + make_stale(root_of(repo) / "a.bin") + result = await call("git_status", repo) + assert result["isError"] is False + assert "nothing to commit" in result["content"][0]["text"] + + +@real_lfs +@posix_only +async def test_git_lfs_extension_never_runs( + tmp_path: Path, repo: git.Repo, payload: Payload, monkeypatch: pytest.MonkeyPatch +): + # Git LFS fails the command when an extension's program is empty. + lfs_repo(tmp_path, repo, monkeypatch) + repo.git.config("lfs.extension.poc.clean", payload.command("clean")) + repo.git.config("lfs.extension.poc.priority", "0") + make_stale(root_of(repo) / "a.bin") + + result = await call("git_status", repo) + + assert payload.runs() == [] + assert result["isError"] is True + + +@real_lfs +@posix_only +async def test_git_lfs_transfer_agent_never_runs( + tmp_path: Path, repo: git.Repo, payload: Payload, monkeypatch: pytest.MonkeyPatch +): + # The object is not in the local store, so a checkout would download it. + # It writes the pointer file instead. + lfs_repo(tmp_path, repo, monkeypatch) + repo.git.checkout("-b", "other") + commit_file(repo, "b.bin", "b\n") + repo.git.checkout("main") + shutil.rmtree(Path(repo.git_dir) / "lfs" / "objects") + repo.git.config("lfs.url", "http://127.0.0.1:9/") + repo.git.config("lfs.standalonetransferagent", "poc") + # Git LFS runs the path as one program, with the arguments split from `args`. + repo.git.config("lfs.customtransfer.poc.path", str(payload.script)) + repo.git.config("lfs.customtransfer.poc.args", "agent") + + result = await call("git_checkout", repo, branch_name="other") + + assert payload.runs() == [] + assert result["isError"] is False, result + pointer = (root_of(repo) / "b.bin").read_text() + assert pointer.startswith("version https://git-lfs.github.com/spec/v1\n") diff --git a/src/git/tests/test_merge.py b/src/git/tests/test_merge.py index 4853b4e1bc..0111bc055c 100644 --- a/src/git/tests/test_merge.py +++ b/src/git/tests/test_merge.py @@ -8,6 +8,8 @@ and the repository afterwards. """ +import os +import unicodedata from pathlib import Path from typing import Any @@ -265,6 +267,200 @@ async def test_ignored_file_the_source_tracks_is_not_overwritten(repo: git.Repo) assert (root_of(repo) / ".env").read_text() == "SECRET=local\n" +def ignored_local(repo: git.Repo, ignore: str, tracked: dict[str, str]) -> str: + """Ignore `ignore` on main, track `tracked` on a diverged `feature`. + + Leaves `main` checked out with one commit of its own, so merging + `feature` makes a merge commit. Returns main's head sha. + """ + commit_file(repo, ".gitignore", ignore) + repo.git.checkout("-b", "feature") + for name, content in tracked.items(): + path = root_of(repo) / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, newline="\n") + repo.git.add("-f", name) + repo.index.commit("track ignored paths") + repo.git.checkout("main") + return commit_file(repo, "main.txt", "main\n").hexsha + + +async def test_merge_commit_refuses_to_overwrite_an_ignored_file(repo: git.Repo): + # Git does not honor --no-overwrite-ignore when it makes a merge commit, + # so the tool checks the incoming paths itself before git runs. + head = ignored_local(repo, ".env\n", {".env": "tracked\n"}) + (root_of(repo) / ".env").write_text("SECRET=local\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == tool_error( + "git_merge", + "Merge of 'feature' into 'main' refused: it would overwrite ignored " + "local files: .env. Nothing was changed. Move or remove them first.", + ) + assert repo.head.commit.hexsha == head + assert not (Path(repo.git_dir) / "MERGE_HEAD").exists() + assert (root_of(repo) / ".env").read_text() == "SECRET=local\n" + + +async def test_merge_commit_refuses_ignored_files_in_a_directory_it_replaces( + repo: git.Repo, +): + # The source tracks a file where an ignored directory is, and a file + # under an ignored file: both would destroy the ignored content. + head = ignored_local( + repo, "cache\nlocal.cfg\n", {"cache": "file\n", "local.cfg/x": "x\n"} + ) + (root_of(repo) / "cache").mkdir() + (root_of(repo) / "cache" / "data").write_text("keep\n") + (root_of(repo) / "local.cfg").write_text("keep\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == tool_error( + "git_merge", + "Merge of 'feature' into 'main' refused: it would overwrite ignored " + "local files: cache/data, local.cfg. Nothing was changed. Move or " + "remove them first.", + ) + assert repo.head.commit.hexsha == head + assert (root_of(repo) / "cache" / "data").read_text() == "keep\n" + assert (root_of(repo) / "local.cfg").read_text() == "keep\n" + + +async def test_merge_commit_into_an_ignored_directory_is_allowed(repo: git.Repo): + # A new file inside an ignored directory replaces nothing that is there. + ignored_local(repo, "build/\n", {"build/tracked.txt": "tracked\n"}) + (root_of(repo) / "build").mkdir() + (root_of(repo) / "build" / "local.txt").write_text("keep\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == text_result( + f"Merged 'feature' into 'main' with merge commit {repo.head.commit.hexsha[:7]}" + ) + assert (root_of(repo) / "build" / "local.txt").read_text() == "keep\n" + assert (root_of(repo) / "build" / "tracked.txt").read_text() == "tracked\n" + + +def refused(*paths: str) -> dict[str, Any]: + return tool_error( + "git_merge", + "Merge of 'feature' into 'main' refused: it would overwrite ignored " + f"local files: {', '.join(paths)}. Nothing was changed. Move or remove " + "them first.", + ) + + +@pytest.mark.parametrize("renames", [None, "true"]) +async def test_merge_commit_does_not_follow_a_directory_rename_onto_an_ignored_file( + repo: git.Repo, renames: str | None +): + # HEAD renamed d/ to e/ since the fork, and the source adds d/new. With + # directory-rename detection git would write e/new, a path in neither + # tree; the tool turns it off, so the file lands at d/new. + commit_file(repo, ".gitignore", "new\n") + (root_of(repo) / "d").mkdir() + commit_file(repo, "d/kept.txt", "kept\n") + repo.git.checkout("-b", "feature") + commit_file(repo, "d/new", "feature\n") + repo.git.checkout("main") + repo.git.mv("d", "e") + repo.index.commit("rename d to e") + if renames is not None: + with repo.config_writer() as config: + config.set_value("merge", "directoryRenames", renames) + (root_of(repo) / "e" / "new").write_text("LOCAL\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result == text_result( + f"Merged 'feature' into 'main' with merge commit {repo.head.commit.hexsha[:7]}" + ) + assert (root_of(repo) / "e" / "new").read_text() == "LOCAL\n" + assert (root_of(repo) / "d" / "new").read_text() == "feature\n" + + +async def test_merge_commit_refuses_an_ignored_file_at_a_file_directory_side_name( + repo: git.Repo, +): + # HEAD tracks a file p where the source tracks a directory p/: git moves + # HEAD's file to p~HEAD, which would replace an ignored file of that name. + commit_file(repo, ".gitignore", "*~*\n") + repo.git.checkout("-b", "feature") + (root_of(repo) / "p").mkdir() + commit_file(repo, "p/x", "feature\n") + repo.git.checkout("main") + head = commit_file(repo, "p", "main\n").hexsha + (root_of(repo) / "p~HEAD").write_text("LOCAL\n") + + assert await merge(repo, "feature", fast_forward_only=False) == refused("p~HEAD") + assert repo.head.commit.hexsha == head + assert (root_of(repo) / "p~HEAD").read_text() == "LOCAL\n" + + +async def test_merge_commit_refuses_an_ignored_file_at_the_source_side_name( + repo: git.Repo, +): + # The other way round: the source's file q moves to q~. + commit_file(repo, ".gitignore", "*~*\n") + repo.git.checkout("-b", "feature") + sha = commit_file(repo, "q", "feature\n").hexsha + repo.git.checkout("main") + (root_of(repo) / "q").mkdir() + head = commit_file(repo, "q/y", "main\n").hexsha + (root_of(repo) / f"q~{sha}").write_text("LOCAL\n") + + assert await merge(repo, "feature", fast_forward_only=False) == refused(f"q~{sha}") + assert repo.head.commit.hexsha == head + assert (root_of(repo) / f"q~{sha}").read_text() == "LOCAL\n" + + +def spelling_insensitive(directory: Path, stored: str, other: str) -> bool: + """Whether the filesystem under `directory` finds `stored` as `other`.""" + probe = directory / stored + probe.write_text("") + try: + return (directory / other).exists() and other not in os.listdir(directory) + finally: + probe.unlink() + + +NFC = unicodedata.normalize("NFC", "caf\u00e9.env") +NFD = unicodedata.normalize("NFD", NFC) + + +@pytest.mark.parametrize( + ("local", "tracked"), [(".env", ".ENV"), (NFC, NFD)], ids=["case", "unicode"] +) +async def test_merge_commit_refuses_an_ignored_file_spelled_differently( + repo: git.Repo, local: str, tracked: str +): + # On a case- or normalization-insensitive filesystem the source's spelling + # names the same file; the check matches it by identity, not by name. + if not spelling_insensitive(root_of(repo), local, tracked): + pytest.skip("the filesystem tells these spellings apart") + commit_file(repo, ".gitignore", "*.env\n.env\n") + repo.git.checkout("-b", "feature") + (root_of(repo) / tracked).write_text("feature\n") + repo.git.add("-f", "--", tracked) + repo.index.commit("track") + (root_of(repo) / tracked).unlink() + repo.git.checkout("main") + head = commit_file(repo, "main.txt", "main\n").hexsha + (root_of(repo) / local).write_text("LOCAL\n") + + result = await merge(repo, "feature", fast_forward_only=False) + + assert result["isError"] is True + assert ( + "refused: it would overwrite ignored local files" + in (result["content"][0]["text"]) + ) + assert repo.head.commit.hexsha == head + assert (root_of(repo) / local).read_text() == "LOCAL\n" + + @pytest.mark.parametrize("options", ["--no-commit", "--squash"]) async def test_configured_merge_options_still_complete_the_merge( repo: git.Repo, options: str diff --git a/src/git/tests/test_protocol.py b/src/git/tests/test_protocol.py index ffdaf91276..82d3865ee0 100644 --- a/src/git/tests/test_protocol.py +++ b/src/git/tests/test_protocol.py @@ -635,6 +635,14 @@ def add_commits(repo: git.Repo, n: int) -> list[git.Commit]: return commits +# #5552: what git_log returns when a timestamp filter matches nothing. +NO_COMMITS_IN_RANGE = ( + "Commit history:\n" + "No commits match the given start_timestamp/end_timestamp. " + "Omit both to see the latest commits." +) + + async def test_git_log_default(repo: git.Repo): commits = add_commits(repo, 2) initial = repo.head.commit.parents[0].parents[0] @@ -691,11 +699,11 @@ async def test_git_log_timestamps_filter(repo: git.Repo): future = await call( None, "git_log", {"repo_path": root, "start_timestamp": "2099-01-01"} ) - assert future == text_result("Commit history:\n") + assert future == text_result(NO_COMMITS_IN_RANGE) past = await call( None, "git_log", {"repo_path": root, "end_timestamp": "2000-01-01"} ) - assert past == text_result("Commit history:\n") + assert past == text_result(NO_COMMITS_IN_RANGE) both = await call( None, "git_log", @@ -708,6 +716,44 @@ async def test_git_log_timestamps_filter(repo: git.Repo): assert both == text_result("Commit history:\n" + log_entry(repo.head.commit)) +async def test_git_log_empty_window_names_the_filter(repo: git.Repo): + # #5552: a small model asked for the latest commit passed "now" for both + # timestamps, got a bare "Commit history:" and concluded the repository + # had no commits. The reply now says the filter matched nothing. + add_commits(repo, 2) + root = str(root_of(repo)) + # Committed a moment ago, so the window that ends before them is empty. + result = await call( + None, + "git_log", + { + "repo_path": root, + "max_count": 1, + "start_timestamp": "2000-01-01", + "end_timestamp": "2000-01-02", + }, + ) + assert result == text_result(NO_COMMITS_IN_RANGE) + # The same call with no filter returns the newest commit, with no hint. + latest = await call(None, "git_log", {"repo_path": root, "max_count": 1}) + assert latest == text_result("Commit history:\n" + log_entry(repo.head.commit)) + + +async def test_git_log_description_states_order_and_optional_filters(): + # #5552: the description is where a model decides its arguments, so it + # says the order and that both timestamps can be left out. + async with connect(None) as session: + tools = wire(await session.list_tools())["tools"] + log = next(t for t in tools if t["name"] == "git_log") + assert "newest commit first" in log["description"] + assert "optional" in log["description"] + assert log["inputSchema"]["required"] == ["repo_path"] + for name in ("start_timestamp", "end_timestamp"): + assert log["inputSchema"]["properties"][name]["description"].startswith( + "Optional: " + ) + + async def test_git_log_rejects_timestamp_flag_injection(repo: git.Repo): root = str(root_of(repo)) assert await call( diff --git a/src/git/tests/test_remote.py b/src/git/tests/test_remote.py index f887cfa56c..e2ee26d3a4 100644 --- a/src/git/tests/test_remote.py +++ b/src/git/tests/test_remote.py @@ -173,6 +173,12 @@ async def test_not_a_repository(tmp_path: Path): ("file://u:p@host/srv/r?x", "file://@host/srv/r?x"), # A password holding a line separator other than '\n'. ("https://u:s3cret\u2028tok@example.com/r", "https://@example.com/r"), + # A value holding a URL that does not start it cannot be split safely, + # so it is withheld whole. + (" https://bob:token@example.com/r.git", ""), + ("d\thttps://alice:token@example.com/r.git", ""), + ("x https://example.com/r.git", ""), + ("https:: https://alice:token@example.com/r", "https::"), ], ) def test_redact_url(url: str, expected: str): @@ -183,14 +189,16 @@ def test_unparseable_line_is_withheld(repo: git.Repo): # `git remote -v` always prints `\t ()`. A line in # any other shape (a URL holding a raw newline is split across two) cannot # be parsed, so none of it is returned. - with mock.patch.object( - server, - "_git_text", - return_value=( + outputs = { + ("remote",): "origin\nup\n", + ("remote", "-v"): ( "origin\thttps://u:pa\nss@example.com/r (fetch)\n" "origin\tno-direction\n" "up\thttps://example.com/r (push)\n" ), + } + with mock.patch.object( + server, "_git_text", side_effect=lambda _repo, *args: outputs[args] ): assert git_remote(repo) == ( "\n\n\nup\thttps://example.com/r (push)" @@ -261,3 +269,60 @@ async def test_query_and_fragment_credentials_are_redacted_over_the_wire( "origin\thttps://git.example.com/g/r.git?private_token= (fetch)\n" "origin\thttps://git.example.com/g/r.git# (push)" ) + + +async def test_tab_in_remote_name_keeps_the_url_whole( + tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch +): + # A remote name may hold a tab, which `git remote -v` prints as is before + # the tab that ends the name. The name is matched against the configured + # names, so the URL after it, rewritten by a credential-bearing `insteadOf` + # in the user's global config, is still redacted. + global_config = tmp_path / "global.gitconfig" + global_config.write_text( + '[url "https://alice:HOSTTOKEN@srv.example.com/"]\n' + "\tinsteadOf = https://srv.example.com/\n", + encoding="utf-8", + ) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config)) + repo.git.config("remote.c\td.url", "https://srv.example.com/org/r.git") + result = await call_remote(None, repo) + assert result == text_result( + "c\td\thttps://@srv.example.com/org/r.git (fetch)\n" + "c\td\thttps://@srv.example.com/org/r.git (push)" + ) + assert "HOSTTOKEN" not in result["content"][0]["text"] + + +async def test_url_not_starting_with_its_scheme_is_withheld(repo: git.Repo): + # A configured value with leading whitespace is printed as is by git; the + # URL inside it does not start the value, so it is withheld whole. + repo.git.config("remote.lead.url", " https://bob:REPOTOKEN@example.com/r.git") + result = await call_remote(None, repo) + assert result == text_result("lead\t (fetch)\nlead\t (push)") + assert "REPOTOKEN" not in result["content"][0]["text"] + + +def test_longest_configured_name_is_matched(repo: git.Repo): + # With remotes `c` and `cd` both configured, a line starting + # `cd` is read as the longer name, and whichever remote it came + # from, a URL left holding a tab and another URL is withheld. + outputs = { + ("remote",): "c\nc\td\n", + ("remote", "-v"): ( + "c\td\thttps://u:p@example.com/r (fetch)\n" + "c\td\thttps://u:p@example.com/r (push)\n" + "unknown\thttps://u:p@example.com/r (fetch)\n" + ), + } + with ( + mock.patch.object(server, "_remote_url_has_newline", return_value=False), + mock.patch.object( + server, "_git_text", side_effect=lambda _repo, *args: outputs[args] + ), + ): + assert git_remote(repo) == ( + "c\td\thttps://@example.com/r (fetch)\n" + "c\td\thttps://@example.com/r (push)\n" + "" + ) diff --git a/src/git/tests/test_root_git_dir.py b/src/git/tests/test_root_git_dir.py new file mode 100644 index 0000000000..8ebe9c2a00 --- /dev/null +++ b/src/git/tests/test_root_git_dir.py @@ -0,0 +1,306 @@ +"""The `--repository` root's own git directories, fixed when the server starts. + +A root's git directory may lie outside it only when it is a linked worktree, +whose git directory the main repository records under `.git/worktrees/` with a +`gitdir` file naming the root back. Any other git directory outside the root, +whether the root's `.git` names it when the server starts or a `.git` or +`commondir` written into the root afterwards does, is not the root's own, so +each call that would use it is refused. Each test drives the server through an +in-process MCP client and asserts on what comes back. +""" + +from pathlib import Path +from typing import Any + +import git +import pytest +from conftest import connect, make_repo, rmtree, wire + +from mcp_server_git import server as git_server +from mcp_server_git.server import ( + _RootRepo, + create_server, + record_root_git_dirs, + validate_opened_repo, +) + +OUTSIDE_TEXT = "outside content\n" + + +def outside_repo(path: Path) -> git.Repo: + repo = make_repo(path) + (path / "outside.txt").write_text(OUTSIDE_TEXT) + repo.index.add(["outside.txt"]) + repo.index.commit("outside") + return repo + + +async def show(root: Path, repo_path: Path, revision: str) -> dict[str, Any]: + async with connect(root) as session: + return wire( + await session.call_tool( + "git_show", {"repo_path": str(repo_path), "revision": revision} + ) + ) + + +def refused(result: dict[str, Any], used: Path) -> bool: + text = result["content"][0]["text"] + return ( + result["isError"] is True + and f"uses '{used}'" in text + and "which is outside the allowed repository" in text + and OUTSIDE_TEXT not in text + ) + + +async def test_a_root_whose_git_file_names_another_repository_is_refused( + tmp_path: Path, +) -> None: + other = outside_repo(tmp_path / "other") + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + try: + result = await show(root, root, "HEAD:outside.txt") + assert refused(result, Path(other.git_dir).resolve()), result + # The other repository named directly is refused as before. + direct = await show(root, tmp_path / "other", "HEAD:outside.txt") + assert direct["isError"] is True + assert OUTSIDE_TEXT not in direct["content"][0]["text"] + finally: + other.close() + + +async def test_a_root_whose_git_dir_is_replaced_after_startup_is_refused( + tmp_path: Path, +) -> None: + other = outside_repo(tmp_path / "other") + root_repo = make_repo(tmp_path / "root") + root = tmp_path / "root" + root_repo.close() + try: + async with connect(root) as session: + before = wire( + await session.call_tool( + "git_show", {"repo_path": str(root), "revision": "HEAD:test.txt"} + ) + ) + assert before["isError"] is False + rmtree(root / ".git") + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + after = wire( + await session.call_tool( + "git_show", + {"repo_path": str(root), "revision": "HEAD:outside.txt"}, + ) + ) + assert refused(after, Path(other.git_dir).resolve()), after + finally: + other.close() + + +@pytest.mark.parametrize("when", ["before startup", "after startup"]) +async def test_a_root_whose_commondir_names_another_repository_is_refused( + tmp_path: Path, when: str +) -> None: + other = outside_repo(tmp_path / "other") + root_repo = make_repo(tmp_path / "root") + root = tmp_path / "root" + commondir = Path(root_repo.git_dir) / "commondir" + root_repo.close() + if when == "before startup": + commondir.write_text(f"{other.git_dir}\n") + try: + async with connect(root) as session: + if when == "after startup": + commondir.write_text(f"{other.git_dir}\n") + result = wire( + await session.call_tool( + "git_show", + {"repo_path": str(root), "revision": "HEAD:outside.txt"}, + ) + ) + assert refused(result, Path(other.git_dir).resolve()), result + finally: + other.close() + + +async def test_a_linked_worktree_root_is_served(tmp_path: Path) -> None: + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + try: + result = await show(worktree, worktree, "HEAD:test.txt") + assert result["isError"] is False, result + finally: + main.close() + + +async def test_a_linked_worktree_root_with_relative_paths_is_served( + tmp_path: Path, +) -> None: + # `worktree.useRelativePaths` writes the `gitdir` file relative to the + # worktree's git directory; write it that way by hand, whatever git runs. + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + gitdir = Path(main.git_dir) / "worktrees" / "worktree" / "gitdir" + gitdir.write_text("../../../../worktree/.git\n") + try: + result = await show(worktree, worktree, "HEAD:test.txt") + assert result["isError"] is False, result + finally: + main.close() + + +async def test_a_root_naming_another_worktrees_git_dir_is_refused( + tmp_path: Path, +) -> None: + # The other repository's linked worktree record names its own worktree, + # not this root, so the root cannot claim it. + other = outside_repo(tmp_path / "other") + other.git.worktree("add", str(tmp_path / "other-wt")) + record = Path(other.git_dir) / "worktrees" / "other-wt" + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {record}\n") + try: + result = await show(root, root, "HEAD:outside.txt") + assert refused(result, record.resolve()), result + finally: + other.close() + + +async def test_a_worktree_record_without_its_gitdir_file_is_refused( + tmp_path: Path, +) -> None: + main = make_repo(tmp_path / "main") + worktree = tmp_path / "worktree" + main.git.worktree("add", str(worktree)) + record = Path(main.git_dir) / "worktrees" / "worktree" + (record / "gitdir").unlink() + try: + result = await show(worktree, worktree, "HEAD:test.txt") + assert refused(result, record.resolve()), result + finally: + main.close() + + +def test_the_root_is_recorded_on_first_use_without_a_server(tmp_path: Path) -> None: + # validate_opened_repo called directly, with no server created for the + # root, records the root's git directories then and holds it to them. + other = outside_repo(tmp_path / "other") + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + git_server._ROOT_GIT_DIRS.pop(root, None) + try: + with ( + git.Repo(root, expand_vars=False) as repo, + pytest.raises(ValueError, match="outside the allowed repository"), + ): + validate_opened_repo(repo, root, root) + assert git_server._ROOT_GIT_DIRS[root] is None + finally: + other.close() + + +def test_a_root_that_is_not_a_repository_records_nothing(tmp_path: Path) -> None: + assert record_root_git_dirs(tmp_path) is None + + +def add_submodule(tmp_path: Path) -> tuple[git.Repo, Path]: + """A superproject with a submodule checked out at `/mod`.""" + source = make_repo(tmp_path / "source") + source.close() + superproject = make_repo(tmp_path / "super") + superproject.git.execute( + [ + "git", + "-c", + "protocol.file.allow=always", + "submodule", + "add", + str(tmp_path / "source"), + "mod", + ] + ) + return superproject, tmp_path / "super" / "mod" + + +async def test_a_submodule_root_is_served(tmp_path: Path) -> None: + superproject, module = add_submodule(tmp_path) + try: + result = await show(module, module, "HEAD:test.txt") + assert result["isError"] is False, result + finally: + superproject.close() + + +async def test_a_root_naming_another_submodules_git_dir_is_refused( + tmp_path: Path, +) -> None: + # The submodule's git directory sets `core.worktree` to the submodule's + # own checkout, not this root, so the root cannot claim it. + superproject, _ = add_submodule(tmp_path) + modules = (tmp_path / "super" / ".git" / "modules" / "mod").resolve() + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {modules}\n") + try: + result = await show(root, root, "HEAD:test.txt") + assert result["isError"] is True, result + assert git_server._ROOT_GIT_DIRS[root] is None + finally: + superproject.close() + + +async def test_a_root_whose_git_dir_is_not_its_own_is_logged_at_startup( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + other = outside_repo(tmp_path / "other") + root = tmp_path / "root" + root.mkdir() + (root / ".git").write_text(f"gitdir: {other.git_dir}\n") + try: + with caplog.at_level("WARNING", logger="mcp_server_git.server"): + await show(root, root, "HEAD:test.txt") + assert any( + "is not a linked worktree's or a submodule's" in record.getMessage() + for record in caplog.records + ) + finally: + other.close() + + +@pytest.mark.parametrize("target", ["another repository", "nothing"]) +def test_a_root_named_like_an_environment_variable_is_recorded_as_itself( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, target: str +) -> None: + # A linked worktree root whose directory name is literally `$NAME`: its + # git directories are recorded from the root itself, not from wherever + # `$NAME` expands to. + other = outside_repo(tmp_path / "other") + other.close() + named = tmp_path / "other" if target == "another repository" else tmp_path / "x" + monkeypatch.setenv("GHSA_ROOT_NAME", str(named)) + main = make_repo(tmp_path / "main") + worktree = tmp_path / "$GHSA_ROOT_NAME" + main.git.worktree("add", str(worktree)) + record = (Path(main.git_dir) / "worktrees" / "$GHSA_ROOT_NAME").resolve() + try: + create_server(worktree) + assert git_server._ROOT_GIT_DIRS[worktree] == ( + record, + Path(main.git_dir).resolve(), + ) + # The repository the recording opens runs its commands, and reads + # its objects, in the root itself. + with _RootRepo(worktree.resolve(), expand_vars=False) as opened: + toplevel = Path(opened.git.rev_parse("--show-toplevel")).resolve() + assert toplevel == worktree.resolve() + assert opened.odb.info(opened.head.commit.binsha).type == b"commit" + assert opened.head.commit.hexsha == main.head.commit.hexsha + finally: + main.close() diff --git a/src/git/tests/test_tree_confinement.py b/src/git/tests/test_tree_confinement.py new file mode 100644 index 0000000000..bcaa669266 --- /dev/null +++ b/src/git/tests/test_tree_confinement.py @@ -0,0 +1,257 @@ +"""Under `--repository`, a tool call's own writes cannot move where git works. + +`open_repo` checks the directories git uses (`validate_opened_repo`) once, +when a call opens the repository. But a repository's configuration can depend +on its working tree: a `.git/config` that is a link to a tracked file changes +whenever a merge or a checkout rewrites that file. A branch that adds +`core.worktree = ` to it so moves the working tree in +the middle of a call, and the git commands the call runs next (the +`git merge --abort` after a conflict, which writes files) would work in that +directory (#5599, the follow-up to GHSA-9vjp-x34c-xg6v). Every tree-writing +command goes through `_rewrite_tree`, which runs the check again before any +other git command, and stops the call when the repository no longer passes. + +The tests drive the real server through a client and assert that a directory +outside the allowed repository is left exactly as it was. They link +`.git/config` to a tracked file, so they skip on Windows, where creating a +symbolic link needs a privilege; the tests of `_rewrite_tree` itself run +everywhere. +""" + +import os +import sys +from pathlib import Path +from unittest import mock + +import git +import pytest +from conftest import connect, make_repo, wire +from test_repository_config import root_of + +from mcp_server_git import server +from mcp_server_git.server import _rewrite_tree, git_checkout + +needs_symlinks = pytest.mark.skipif( + sys.platform == "win32", reason="creating a symbolic link needs a privilege" +) + +STOPPED = ( + "Error executing tool {tool}: Stopped: after git {command} changed the " + "working tree, the repository no longer passes the --repository check. The " + "working tree was left as git {command} wrote it (a merge may still be in " + "progress), and no further git command was run: Repository path '{root}' " + "uses '{outside}', which is outside the allowed repository '{root}'" +) + + +def outside_dir(tmp_path: Path) -> Path: + """A directory beside the repository, holding a file named like a tracked one.""" + outside = tmp_path / "outside" + outside.mkdir() + (outside / "m.txt").write_text("not the repository's\n") + return outside + + +def contents(directory: Path) -> dict[str, str]: + return {p.name: p.read_text() for p in directory.iterdir()} + + +def worktree_config(repo: git.Repo, outside: Path) -> str: + """The repository's configuration, with `core.worktree` naming `outside`.""" + original = (Path(repo.git_dir) / "config").read_text() + return f"{original}[core]\n\tworktree = {outside.as_posix()}\n" + + +def track_config(repo: git.Repo) -> None: + """Commit `m.txt` and `repo.cfg`, a copy of the repository's configuration.""" + root = root_of(repo) + (root / "m.txt").write_text("base\n") + (root / "repo.cfg").write_text((Path(repo.git_dir) / "config").read_text()) + repo.index.add(["m.txt", "repo.cfg"]) + repo.index.commit("base") + + +def link_config(repo: git.Repo) -> None: + """Make `.git/config` a link to the tracked `repo.cfg`. + + The link stays inside the repository, so the check at open allows it. + """ + config = Path(repo.git_dir) / "config" + config.unlink() + os.symlink(root_of(repo) / "repo.cfg", config) + + +def feature_moves_the_worktree(repo: git.Repo, outside: Path) -> None: + """Branch `feature` changes m.txt and adds `core.worktree` to repo.cfg.""" + root = root_of(repo) + moved = worktree_config(repo, outside) + repo.git.checkout("-b", "feature") + (root / "m.txt").write_text("theirs\n") + (root / "repo.cfg").write_text(moved) + repo.index.add(["m.txt", "repo.cfg"]) + repo.index.commit("theirs") + repo.git.checkout("main") + + +async def call(repo: git.Repo, tool: str, **arguments: object) -> dict[str, object]: + root = root_of(repo) + async with connect(root) as session: + result = await session.call_tool(tool, {"repo_path": str(root), **arguments}) + return wire(result) + + +def stopped( + repo: git.Repo, outside: Path, tool: str, command: str +) -> dict[str, object]: + text = STOPPED.format( + tool=tool, command=command, root=root_of(repo), outside=outside.resolve() + ) + return {"content": [{"type": "text", "text": text}], "isError": True} + + +@needs_symlinks +@pytest.mark.anyio +async def test_a_conflicting_merge_that_moves_the_worktree_is_not_aborted_outside( + tmp_path: Path, +) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + root = root_of(repo) + track_config(repo) + feature_moves_the_worktree(repo, outside) + (root / "m.txt").write_text("ours\n") + repo.index.add(["m.txt"]) + repo.index.commit("ours") + link_config(repo) + + result = await call( + repo, "git_merge", source_branch="feature", fast_forward_only=False + ) + + # Without the second check, `git merge --abort` ran with the working tree + # at `outside`: it overwrote m.txt there and wrote repo.cfg beside it. + assert contents(outside) == before + assert result == stopped(repo, outside, "git_merge", "merge") + # Neither `git diff` nor `git merge --abort` ran: the merge is as git left it. + assert (Path(repo.git_dir) / "MERGE_HEAD").exists() + repo.close() + + +@needs_symlinks +@pytest.mark.anyio +async def test_a_fast_forward_that_moves_the_worktree_is_reported( + tmp_path: Path, +) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + track_config(repo) + feature_moves_the_worktree(repo, outside) + link_config(repo) + + result = await call(repo, "git_merge", source_branch="feature") + + assert contents(outside) == before + assert result == stopped(repo, outside, "git_merge", "merge") + repo.close() + + +@needs_symlinks +@pytest.mark.anyio +async def test_a_checkout_that_moves_the_worktree_is_reported(tmp_path: Path) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + track_config(repo) + feature_moves_the_worktree(repo, outside) + link_config(repo) + + result = await call(repo, "git_checkout", branch_name="feature") + + assert contents(outside) == before + assert result == stopped(repo, outside, "git_checkout", "checkout") + repo.close() + + +@needs_symlinks +@pytest.mark.anyio +async def test_an_autostash_that_moves_the_worktree_is_reported(tmp_path: Path) -> None: + outside = outside_dir(tmp_path) + before = contents(outside) + repo = make_repo(tmp_path / "repo") + root = root_of(repo) + track_config(repo) + repo.git.checkout("-b", "feature") + (root / "m.txt").write_text("theirs\n") + repo.index.add(["m.txt"]) + repo.index.commit("theirs") + repo.git.checkout("main") + # A merge left for git_commit to conclude, whose autostash holds the + # change to repo.cfg. The configuration is not linked to it yet, so the + # setup's own git commands stay in the repository. + (root / "repo.cfg").write_text(worktree_config(repo, outside)) + repo.git.merge("--autostash", "--no-ff", "--no-commit", "feature") + autostash = Path(repo.git_dir) / "MERGE_AUTOSTASH" + assert autostash.exists() + link_config(repo) + + result = await call(repo, "git_commit", message="merge feature") + + assert contents(outside) == before + assert result == stopped(repo, outside, "git_commit", "stash") + # Nothing ran after `git stash apply`: the autostash was not cleared. + assert autostash.exists() + repo.close() + + +@pytest.mark.anyio +async def test_an_ordinary_repository_merges_and_checks_out_as_before( + tmp_path: Path, +) -> None: + repo = make_repo(tmp_path / "repo") + root = root_of(repo) + repo.git.checkout("-b", "feature") + (root / "new.txt").write_text("new\n") + repo.index.add(["new.txt"]) + commit = repo.index.commit("new") + repo.git.checkout("main") + + merged = await call(repo, "git_merge", source_branch="feature") + switched = await call(repo, "git_checkout", branch_name="feature") + + text = f"Fast-forwarded 'main' to 'feature' ({commit.hexsha[:7]})" + assert merged["content"] == [{"type": "text", "text": text}] + assert switched["content"] == [ + {"type": "text", "text": "Switched to branch 'feature'"} + ] + repo.close() + + +def test_without_an_allowed_repository_nothing_is_checked(repo: git.Repo) -> None: + repo.git.branch("feature") + with mock.patch.object(server, "validate_opened_repo") as validate: + assert git_checkout(repo, "feature") == "Switched to branch 'feature'" + validate.assert_not_called() + + +@pytest.mark.parametrize( + "failure", + [ + # A git command of the check itself failing: reported as a GitError + # that is not a GitCommandError, which git_merge's cleanup would catch. + git.GitCommandError(["git", "rev-parse"], 128), + ValueError("uses '/elsewhere', which is outside the allowed repository"), + OSError("a git directory that cannot be listed"), + ], +) +def test_a_failed_check_stops_the_call(repo: git.Repo, failure: Exception) -> None: + with ( + mock.patch.object(server, "validate_opened_repo", side_effect=failure), + pytest.raises(git.GitError) as raised, + ): + _rewrite_tree(repo, "status", allowed_repository=root_of(repo)) + assert not isinstance(raised.value, git.GitCommandError) + assert raised.value.__cause__ is failure + assert "no longer passes the --repository check" in str(raised.value) + assert "after git status changed the working tree" in str(raised.value) diff --git a/src/git/uv.lock b/src/git/uv.lock index 31f128c409..51c47883b4 100644 --- a/src/git/uv.lock +++ b/src/git/uv.lock @@ -720,7 +720,7 @@ wheels = [ [[package]] name = "mcp-server-git" -version = "2026.11.18" +version = "2026.11.27" source = { editable = "." } dependencies = [ { name = "click" }, diff --git a/src/memory/CHANGELOG.md b/src/memory/CHANGELOG.md index e72798e421..ebca3cdd18 100644 --- a/src/memory/CHANGELOG.md +++ b/src/memory/CHANGELOG.md @@ -1,5 +1,15 @@ # @modelcontextprotocol/server-memory +## 2.2.2 + +### Patch Changes + +- [#5676](https://github.com/modelcontextprotocol/servers/pull/5676) [`ba351a3`](https://github.com/modelcontextprotocol/servers/commit/ba351a32d8960db8317983929a232308610689ba) [@cliffhall](https://github.com/cliffhall) - fix(memory): GHSA-48j5-hj63-c82c + +- [#5623](https://github.com/modelcontextprotocol/servers/pull/5623) [`0f3ff98`](https://github.com/modelcontextprotocol/servers/commit/0f3ff986d092533a3b713ed9b8223e3eac488f92) [@cliffhall](https://github.com/cliffhall) - Close three narrow gaps in how the memory file lock changes hands between server processes: a writer could start while a live lock was momentarily moved aside by a server checking a stale one, a lock could be put back after its holder had finished (delaying later writes by up to 30 seconds), and a server releasing a lock it had held past the stale timeout could remove the lock of the server that took over. The momentary `.lock.break` file now orders every release and stale-lock break, and a server that has just created the lock waits for it to go before writing. Servers on this version and on 2.2.1 or earlier can still share a memory file; the older server's own releases and acquisitions keep those gaps. + +- [#5637](https://github.com/modelcontextprotocol/servers/pull/5637) [`7e0a6c4`](https://github.com/modelcontextprotocol/servers/commit/7e0a6c46853c82158c6cb80f81cfc995cf893c5f) [@cliffhall](https://github.com/cliffhall) - Keep the memory file lock exclusive on Windows when a stale-lock break takes a live lock aside by mistake: putting it back is retried while Windows briefly refuses to replace the lock another writer created in the gap, instead of giving up and letting that writer run beside the live lock's holder ([#5635](https://github.com/modelcontextprotocol/servers/issues/5635)). + ## 2.2.1 ### Patch Changes diff --git a/src/memory/README.md b/src/memory/README.md index b4226ff278..b119225f86 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -294,7 +294,7 @@ When `MEMORY_FILE_PATH` is not set and the server directory still holds a legacy - The directory must already exist: the server creates the memory file, not the directories above 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. Writes from several processes are serialized by a lock, described next. +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. #### Sharing one memory file between clients @@ -302,6 +302,8 @@ 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. +- 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__/atomic-save.test.ts b/src/memory/__tests__/atomic-save.test.ts index 288ff9dd2a..4cd3fd7a1e 100644 --- a/src/memory/__tests__/atomic-save.test.ts +++ b/src/memory/__tests__/atomic-save.test.ts @@ -78,9 +78,18 @@ describe("KnowledgeGraphManager persistence durability", () => { expect(before).toContain("Alice"); // Simulate the process being interrupted while persisting the next write. - vi.spyOn(fs, "writeFile").mockImplementationOnce(async () => { - throw new Error("ENOSPC: simulated interruption"); - }); + const realOpen = fs.open; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + const handle = await realOpen(...args); + if (String(args[0]).endsWith(".tmp")) { + handle.writeFile = async () => { + throw new Error("ENOSPC: simulated interruption"); + }; + } + return handle; + }) as typeof fs.open); await expect( manager.createEntities([ diff --git a/src/memory/__tests__/external-destruction.test.ts b/src/memory/__tests__/external-destruction.test.ts new file mode 100644 index 0000000000..20a3b3a708 --- /dev/null +++ b/src/memory/__tests__/external-destruction.test.ts @@ -0,0 +1,212 @@ +// Characterization tests for the graph file being destroyed from outside the +// server between two operations (#5539): deleted, truncated to zero bytes, +// replaced by a directory, or joined by the temp remnant of a killed run. +// The other suites pin these states only as a server finds them at its first +// call (no file yet, a directory at the path) or as a save fails from inside +// (a mocked write or rename). Here one server stays connected across the +// change, so each case also pins that nothing read before it is served or +// written back afterwards. +// +// Driven through an SDK Client over the in-memory transport rather than +// KnowledgeGraphManager directly, as the issue proposed: what these cases +// promise is what a client is told (an empty graph, or a tool error rather +// than an empty graph), and a manager call skips the error mapping that +// produces it. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import type { Client } from "@modelcontextprotocol/client"; +import { + call, + connect, + makeTempGraph, + readFileText, + textOf, +} from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +const alice = { + name: "Alice", + entityType: "person", + observations: ["Works at Acme"], +}; +const bob = { name: "Bob", entityType: "person", observations: [] }; +const aliceLine = + '{"type":"entity","name":"Alice","entityType":"person","observations":["Works at Acme"]}'; +const bobLine = + '{"type":"entity","name":"Bob","entityType":"person","observations":[]}'; +const emptyGraph = { entities: [], relations: [] }; + +describe("the graph file destroyed from outside between operations (#5539)", () => { + let dir: string; + let filePath: string; + let cleanup: () => Promise; + let conn: Connection; + let client: Client; + let errorSpy: ReturnType; + + // Every case starts from a connected server that has saved Alice. + beforeEach(async () => { + ({ dir, filePath, cleanup } = await makeTempGraph()); + errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + conn = await connect(filePath); + client = conn.client; + await call(client, "create_entities", { entities: [alice] }); + expect(await readFileText(filePath)).toBe(`${aliceLine}\n`); + }); + + afterEach(async () => { + await conn.close(); + await cleanup(); + vi.restoreAllMocks(); + }); + + describe("deleted", () => { + beforeEach(async () => { + await fs.unlink(filePath); + }); + + it("reads as an empty graph, and a read does not recreate the file", async () => { + const result = await call(client, "read_graph"); + + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual(emptyGraph); + expect(await fs.readdir(dir)).toEqual([]); + expect(errorSpy).not.toHaveBeenCalled(); + }); + + it("recreates the file on the next write, holding only what that write added", async () => { + const created = await call(client, "create_entities", { + entities: [bob], + }); + + expect(created.isError).toBeUndefined(); + expect(created.structuredContent).toEqual({ entities: [bob] }); + expect(await readFileText(filePath)).toBe(`${bobLine}\n`); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); + expect((await call(client, "read_graph")).structuredContent).toEqual({ + entities: [bob], + relations: [], + }); + }); + + it("refuses a write that depends on a deleted entity, creating nothing", async () => { + const result = await call(client, "add_observations", { + observations: [{ entityName: "Alice", contents: ["Prefers email"] }], + }); + + expect(result.isError).toBe(true); + expect(textOf(result)).toBe("Entity with name Alice not found"); + expect(await fs.readdir(dir)).toEqual([]); + }); + }); + + describe("truncated to zero bytes", () => { + beforeEach(async () => { + await fs.writeFile(filePath, ""); + }); + + it("reads as an empty graph, logging nothing and leaving the file as it is", async () => { + const result = await call(client, "read_graph"); + + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual(emptyGraph); + expect(await readFileText(filePath)).toBe(""); + expect(errorSpy).not.toHaveBeenCalled(); + }); + + it("keeps working: the next write saves only what it added", async () => { + const created = await call(client, "create_entities", { + entities: [bob], + }); + + expect(created.isError).toBeUndefined(); + expect(created.structuredContent).toEqual({ entities: [bob] }); + expect(await readFileText(filePath)).toBe(`${bobLine}\n`); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); + }); + }); + + // persistence.test.ts pins a directory that is at the path when the server + // first looks. This is the file a running server already saved turning + // into one: the calls must fail rather than report an empty graph, which a + // later save would then write over whatever replaces the directory. + describe("replaced by a directory", () => { + beforeEach(async () => { + await fs.unlink(filePath); + await fs.mkdir(filePath); + }); + + it("fails reads and writes with EISDIR, leaving nothing behind", async () => { + for (const [name, args] of [ + ["read_graph", {}], + ["create_entities", { entities: [bob] }], + ["delete_entities", { entityNames: ["Alice"] }], + ] as const) { + const result = await call(client, name, args); + expect(result.isError).toBe(true); + // Only the code is asserted: the text after it is Node's own, and + // whether it ends with the path differs by platform (#5076, #5162). + expect(textOf(result)).toMatch(/^EISDIR: /); + expect(result.structuredContent).toBeUndefined(); + } + + // No lock file and no temp file beside the directory, nothing in it. + expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); + expect(await fs.readdir(filePath)).toEqual([]); + }); + + it("serves again once the directory is gone", async () => { + expect((await call(client, "read_graph")).isError).toBe(true); + await fs.rmdir(filePath); + + const created = await call(client, "create_entities", { + entities: [bob], + }); + + expect(created.isError).toBeUndefined(); + expect(await readFileText(filePath)).toBe(`${bobLine}\n`); + }); + }); + + // A run killed between saveGraph's temp-file write and its rename leaves + // `.<32 hex>.tmp` beside the graph file. This one holds a complete + // record and a cut-off one, so a load that read it would show either. + describe("beside an orphaned temp file from a killed run", () => { + const remnantName = "memory.jsonl.0123456789abcdef0123456789abcdef.tmp"; + const remnantText = + '{"type":"entity","name":"Ghost","entityType":"person","observations":[]}\n' + + '{"type":"entity","name":"Trunc'; + let remnantPath: string; + + beforeEach(async () => { + remnantPath = path.join(dir, remnantName); + await fs.writeFile(remnantPath, remnantText); + }); + + it("loads only the graph file", async () => { + const result = await call(client, "read_graph"); + + expect(result.structuredContent).toEqual({ + entities: [alice], + relations: [], + }); + expect(errorSpy).not.toHaveBeenCalled(); + }); + + it("saves past it, leaving the remnant untouched", async () => { + const created = await call(client, "create_entities", { + entities: [bob], + }); + + expect(created.isError).toBeUndefined(); + expect(await readFileText(filePath)).toBe(`${aliceLine}\n${bobLine}\n`); + expect(await readFileText(remnantPath)).toBe(remnantText); + expect((await fs.readdir(dir)).sort()).toEqual([ + "memory.jsonl", + remnantName, + ]); + expect(errorSpy).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index e1f049a094..63b5fc719a 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -1,9 +1,12 @@ // Unit tests for withFileLock, the lock file that orders mutations from // separate server processes sharing one graph file (#4797): mutual exclusion, // release, breaking an abandoned lock, and giving up on a held one; and the -// exit-time release of the locks this process still holds (#5485). +// exit-time release of the locks this process still holds (#5485); and the +// guard that orders acquiring, releasing and breaking against each other +// (#5565). import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; -import { promises as fs } from "fs"; +import fsSync, { promises as fs } from "fs"; +import { syncBuiltinESMExports } from "module"; import os from "os"; import path from "path"; import { spawn, spawnSync } from "child_process"; @@ -345,32 +348,38 @@ describe("withFileLock", () => { const realUtimes = fs.utimes; let replaced!: () => void; const replacement = new Promise((resolve) => (replaced = resolve)); + const readFile = vi.spyOn(fs, "readFile"); + const lockReads = () => + readFile.mock.calls.filter(([file]) => file === lockPath).length; // Our first heartbeat refreshes our own lock; right after it, another // process breaks the lock as stale and re-takes it with its own token. + // Reads are counted from just before it, inside the heartbeat, not from when + // the operation resumes: on a slow runner the next beat can read the lock + // before then, and clearing later would wipe that read (#5634). const utimes = vi .spyOn(fs, "utimes") .mockImplementationOnce(async (...args) => { await realUtimes(...args); + readFile.mockClear(); await fs.writeFile(lockPath, "someone else"); await realUtimes(lockPath, old, old); replaced(); }); - const readFile = vi.spyOn(fs, "readFile"); - const lockReads = () => - readFile.mock.calls.filter(([file]) => file === lockPath).length; await withFileLock( lockPath, async () => { await replacement; - readFile.mockClear(); - // Several heartbeats later, only the first one, on our own lock, has - // touched the file: the next one read the new owner's token and stopped - // the interval, so the beats after it do not even read the file. - await new Promise((resolve) => setTimeout(resolve, 250)); + // Only the first heartbeat, on our own lock, refreshes the file: the + // next one reads the new owner's token and stops the interval, so the + // beats after it do not even read the file. The next beat is waited + // for rather than timed, so a slow runner only makes this take longer. + await vi.waitFor(() => expect(lockReads()).toBeGreaterThan(0), { + timeout: 5_000, + interval: 10, + }); expect(utimes).toHaveBeenCalledTimes(1); const reads = lockReads(); - expect(reads).toBeGreaterThan(0); await new Promise((resolve) => setTimeout(resolve, 350)); expect(lockReads()).toBe(reads); }, @@ -487,6 +496,701 @@ describe("withFileLock", () => { expect(graph.entities.map((e) => e.name).sort()).toEqual([...names].sort()); expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); }); + + // The hand-off windows of #5565. Each interleaving is injected at an exact + // file-system call, so none depends on timing. A lock that replaces the one + // a breaker judged, while that breaker holds the guard, can only come from + // a writer that does not take part in the guard (a server older than this + // fix), so those tests plant it, or hide the guard from the writer. + describe("hand-off windows (#5565)", () => { + const guardPath = () => `${lockPath}.break`; + + // Run hook once, while the lock the breaker took is aside: after the + // rename that took it, before it is deleted or put back. + function onceLockAside(hook: () => Promise): void { + const realStat = fs.stat; + let fired = false; + vi.spyOn(fs, "stat").mockImplementation((async ( + ...args: Parameters + ) => { + if (!fired && String(args[0]).endsWith(".stale")) { + fired = true; + await hook(); + } + return realStat(...args); + }) as typeof fs.stat); + } + + // Watch fs.open. `opened(file, flags)` resolves once the next such open + // has settled; `hideOnce(file, flags)` makes the next such open report + // no file. + function watchOpens(): { + opened: (file: string, flags: string) => Promise; + hideOnce: (file: string, flags: string) => void; + } { + const realOpen = fs.open; + const waiters: { key: string; resolve: () => void }[] = []; + const hidden: string[] = []; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + const key = `${String(args[0])} ${String(args[1])}`; + const hide = hidden.indexOf(key); + if (hide !== -1) { + hidden.splice(hide, 1); + throw Object.assign(new Error("ENOENT: hidden"), { code: "ENOENT" }); + } + try { + return await realOpen(...args); + } finally { + for (const waiter of waiters.splice(0)) { + if (waiter.key === key) { + waiter.resolve(); + } else { + waiters.push(waiter); + } + } + } + }) as typeof fs.open); + return { + opened: (file, flags) => + new Promise((resolve) => + waiters.push({ key: `${file} ${flags}`, resolve }), + ), + hideOnce: (file, flags) => { + hidden.push(`${file} ${flags}`); + }, + }; + } + + it("does not let a writer that created the lock while a live one was aside run beside its holder", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + const opens = watchOpens(); + let successor: { ino: bigint } | undefined; + // A successor's live lock replaces the stale one after the breaker + // judged it, so the breaker takes the live lock aside by mistake. + onceBeforeRemoval(async () => { + await fs.unlink(lockPath); + await fs.writeFile(lockPath, "successor"); + successor = await fs.stat(lockPath, { bigint: true }); + }); + // While it is aside the lock path is free, and a third writer creates + // its own lock there. + let thirdRan!: () => void; + const thirdStarted = new Promise((resolve) => (thirdRan = resolve)); + const third = vi.fn(async () => { + thirdRan(); + return "third ran"; + }); + let thirdOutcome: Promise | undefined; + onceLockAside(async () => { + const sawBreak = opens.opened(guardPath(), "r"); + thirdOutcome = withFileLock(lockPath, third, fast).catch( + (error: unknown) => error, + ); + // Go on once the third writer has either run (the defect) or found + // the break in progress and is waiting it out. + await Promise.race([thirdStarted, sawBreak]); + }); + + await expect( + withFileLock(lockPath, async () => "breaker ran", fast), + ).rejects.toThrow("Timed out"); + const outcome = await thirdOutcome; + + // The third writer never ran beside the successor: its lock was + // overwritten by the restored one, it noticed, and it went on waiting. + expect(third).not.toHaveBeenCalled(); + expect(outcome).toBeInstanceOf(Error); + expect((outcome as Error).message).toContain("Timed out"); + expect(await fs.readFile(lockPath, "utf-8")).toBe("successor"); + expect((await fs.stat(lockPath, { bigint: true })).ino).toBe( + successor?.ino, + ); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]); + }); + + // Stage a successor's live lock in place of the stale one before the + // breaker takes it aside, as onceBeforeRemoval does, and fail the first + // `failures` attempts to put it back with `code`. Returns a count of + // those attempts. + function stageSuccessorAndFailRestore( + failures: number, + code: string, + ): () => number { + const realRename = fs.rename; + let staged = false; + let restores = 0; + vi.spyOn(fs, "rename").mockImplementation(async (from, to) => { + if (!staged && from === lockPath) { + staged = true; + await fs.unlink(lockPath); + await fs.writeFile(lockPath, "successor"); + } + if (String(from).endsWith(".stale") && to === lockPath) { + restores += 1; + if (restores <= failures) { + throw Object.assign(new Error(code), { code }); + } + } + return realRename(from, to); + }); + return () => restores; + } + + // On Windows a rename over a file that anything holds open fails, and the + // writer that created the lock in the gap keeps opening it while it waits + // out the break. Giving up then left the live lock aside and let that + // writer run beside its holder (#5635). + it("keeps putting a live lock back while Windows refuses to replace the lock created in the gap", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const opens = watchOpens(); + const restores = stageSuccessorAndFailRestore(2, "EPERM"); + let thirdRan!: () => void; + const thirdStarted = new Promise((resolve) => (thirdRan = resolve)); + const third = vi.fn(async () => { + thirdRan(); + return "third ran"; + }); + let thirdOutcome: Promise | undefined; + onceLockAside(async () => { + const sawBreak = opens.opened(guardPath(), "r"); + thirdOutcome = withFileLock(lockPath, third, fast).catch( + (error: unknown) => error, + ); + await Promise.race([thirdStarted, sawBreak]); + }); + + await expect( + withFileLock(lockPath, async () => "breaker ran", fast), + ).rejects.toThrow("Timed out"); + const outcome = await thirdOutcome; + + // The two injected refusals were retried and a third attempt went to + // the real rename. On a real Windows host that rename can itself be + // refused while the third writer has the lock open, and is retried + // again, so three is the floor, not the count (#5683). + expect(restores()).toBeGreaterThanOrEqual(3); + expect(third).not.toHaveBeenCalled(); + expect((outcome as Error).message).toContain("Timed out"); + expect(await fs.readFile(lockPath, "utf-8")).toBe("successor"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]); + }); + + it("does not retry a failed put-back off Windows, where the failure lasts", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const restores = stageSuccessorAndFailRestore(1, "EPERM"); + + await expect( + withFileLock(lockPath, async () => "ran", fast), + ).rejects.toThrow("EPERM"); + + expect(restores()).toBe(1); + expect(heldLockPaths()).toEqual([]); + expect(await exists(guardPath())).toBe(false); + }); + + // Windows' EPERM also means a busy lock to the acquire loop, so a put-back + // that never lands must fail with an error of its own, or the breaker + // would go back to acquiring with the live lock still aside. + it("fails the acquisition on Windows once a live lock cannot be put back before the guard would be taken for a crash's", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const restores = stageSuccessorAndFailRestore(Infinity, "EPERM"); + const operation = vi.fn(async () => "ran"); + + const error: unknown = await withFileLock(lockPath, operation, { + staleMs: 50, + timeoutMs: 5_000, + retryMs: 5, + }).catch((e: unknown) => e); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain( + "Could not put back the live memory file lock", + ); + expect(((error as Error).cause as NodeJS.ErrnoException).code).toBe( + "EPERM", + ); + expect(operation).not.toHaveBeenCalled(); + expect(restores()).toBeGreaterThan(1); + expect(heldLockPaths()).toEqual([]); + expect(await exists(guardPath())).toBe(false); + }); + + it("does not restore a lock its holder released while it was aside", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + const opens = watchOpens(); + let finish!: () => void; + const mayFinish = new Promise((resolve) => (finish = resolve)); + let successor: Promise | undefined; + // A successor takes a live lock after the breaker judged the stale one. + // It does not wait out the break, as a server older than this fix would + // not: the guard is hidden from it. + onceBeforeRemoval(async () => { + await fs.unlink(lockPath); + opens.hideOnce(guardPath(), "r"); + let holding!: () => void; + const held = new Promise((resolve) => (holding = resolve)); + successor = withFileLock(lockPath, async () => { + holding(); + await mayFinish; + return "successor ran"; + }); + await held; + }); + // The successor finishes while its lock is aside. + onceLockAside(async () => { + const releaseWaits = opens.opened(guardPath(), "wx"); + finish(); + // Go on once its release has either finished without finding its + // lock (the defect) or is waiting for the break to end. + await Promise.race([successor, releaseWaits]); + }); + + // The breaker put the successor's lock back, the successor's release + // then removed it, and the waiter acquired at once: no lock nobody + // holds is left for it to wait out. + expect(await withFileLock(lockPath, async () => "waiter ran", fast)).toBe( + "waiter ran", + ); + expect(await successor).toBe("successor ran"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("does not let a release remove a lock broken and re-taken after its comparison", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const realUnlink = fs.unlink; + let letNextFinish!: () => void; + const nextMayFinish = new Promise( + (resolve) => (letNextFinish = resolve), + ); + let nextRan!: () => void; + const nextStarted = new Promise((resolve) => (nextRan = resolve)); + let lockWhileNextRan: boolean | undefined; + const next = vi.fn(async () => { + nextRan(); + await nextMayFinish; + lockWhileNextRan = await exists(lockPath); + return "next ran"; + }); + let nextOutcome: Promise | undefined; + let fired = false; + + await withFileLock(lockPath, async () => { + // The holder's release has compared its token and is about to remove + // the lock. Its lock has gone unrefreshed past another writer's stale + // timeout, and that writer tries to break and re-take it right now. + vi.spyOn(fs, "unlink").mockImplementation(async (file) => { + if (!fired && file === lockPath) { + fired = true; + const old = new Date(Date.now() - 600_000); + await fs.utimes(lockPath, old, old); + nextOutcome = withFileLock(lockPath, next, { + staleMs: 30_000, + timeoutMs: 100, + retryMs: 5, + }).catch((error: unknown) => error); + // Go on once the other writer has either taken the lock (the + // defect) or given up waiting for the release to end. + await Promise.race([nextStarted, nextOutcome]); + } + return realUnlink(file); + }); + }); + letNextFinish(); + const outcome = await nextOutcome; + + // The other writer could not break the lock mid-release, so the release + // removed its own lock and nothing else. + expect(next).not.toHaveBeenCalled(); + expect(lockWhileNextRan).toBeUndefined(); + expect(outcome).toBeInstanceOf(Error); + expect((outcome as Error).message).toContain("Timed out"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual([]); + }); + + // The same interleaving at exit, where the release is synchronous, so + // only another process can act inside it: a child running the built + // server's withFileLock tries to break the lock and take it, and then + // exits without releasing. Like the SIGTERM test below, it runs the last + // build of dist/. + it("does not let the release at exit remove a lock broken and re-taken after its comparison", async () => { + const distIndex = pathToFileURL( + path.join( + path.dirname(fileURLToPath(import.meta.url)), + "..", + "dist", + "index.js", + ), + ).href; + const script = ` + const { withFileLock } = await import(${JSON.stringify(distIndex)}); + try { + await withFileLock( + ${JSON.stringify(lockPath)}, + async () => process.exit(0), + { staleMs: 30000, timeoutMs: 200, retryMs: 5 }, + ); + } catch (error) { + console.log(error.message); + process.exit(3); + } + `; + const realUnlinkSync = fsSync.unlinkSync; + let other: ReturnType | undefined; + vi.spyOn(fsSync, "unlinkSync").mockImplementation((file) => { + if (!other && file === lockPath) { + // The exiting holder has compared its token and is about to remove + // the lock, which has gone unrefreshed past the other process's + // stale timeout. + const old = new Date(Date.now() - 600_000); + fsSync.utimesSync(lockPath, old, old); + other = spawnSync( + process.execPath, + ["--input-type=module", "-e", script], + { encoding: "utf-8" }, + ); + } + return realUnlinkSync(file); + }); + syncBuiltinESMExports(); + + try { + await withFileLock(lockPath, async () => { + releaseHeldLocks(); + }); + } finally { + vi.restoreAllMocks(); + syncBuiltinESMExports(); + } + + // The other process could not break the lock mid-release: it gave up + // (status 3) rather than taking the lock (status 0) and having it + // removed from under it. + expect(other?.stdout).toContain("Timed out"); + expect(other?.status).toBe(3); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("leaves its lock in place at exit while another process holds the guard", async () => { + await withFileLock(lockPath, async () => { + // Another process is breaking this lock, or crashed doing so. + await fs.writeFile(guardPath(), ""); + + releaseHeldLocks(); + + expect(heldLockPaths()).toEqual([]); + expect((await fs.readdir(dir)).sort()).toEqual([ + "memory.jsonl.lock", + "memory.jsonl.lock.break", + ]); + await fs.unlink(guardPath()); + }); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it.each([ + ["and the guard it took for it", false], + ["when that guard was cleared from under it", true], + ])( + "removes, at exit, a lock whose release the exit interrupted, %s", + async (_, guardCleared) => { + const realReadFile = fs.readFile; + let duringRelease: string[] | undefined; + let afterExit: string[] | undefined; + await withFileLock(lockPath, async () => { + // The release reads the lock next, with the guard already taken. + vi.spyOn(fs, "readFile").mockImplementationOnce((async ( + ...args: Parameters + ) => { + duringRelease = (await fs.readdir(dir)).sort(); + if (guardCleared) { + await fs.unlink(guardPath()); + } + releaseHeldLocks(); + afterExit = await fs.readdir(dir); + return realReadFile(...args); + }) as typeof fs.readFile); + }); + + expect(duringRelease).toEqual([ + "memory.jsonl.lock", + "memory.jsonl.lock.break", + ]); + expect(afterExit).toEqual([]); + expect(heldLockPaths()).toEqual([]); + }, + ); + + it("gives the guard up in one synchronous step, so an exit cannot find it tracked but gone", async () => { + // Were the guard removed by an awaited unlink, an exit between the + // removal and its continuation would treat a guard another process + // had taken since as this process's own, and remove it. + const unlink = vi.spyOn(fs, "unlink"); + let guardSeen = false; + const realReadFile = fs.readFile; + await withFileLock(lockPath, async () => { + vi.spyOn(fs, "readFile").mockImplementationOnce((async ( + ...args: Parameters + ) => { + guardSeen = await exists(guardPath()); + return realReadFile(...args); + }) as typeof fs.readFile); + }); + + expect(guardSeen).toBe(true); + expect(unlink.mock.calls.map(([file]) => String(file))).not.toContain( + guardPath(), + ); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("waits for the guard before releasing", async () => { + const opens = watchOpens(); + let contended: Promise | undefined; + const held = withFileLock( + lockPath, + async () => { + // A breaker is at work when the holder finishes. + await fs.writeFile(guardPath(), ""); + contended = opens.opened(guardPath(), "wx"); + return "ran"; + }, + fast, + ); + // The release found the guard taken and is waiting. Nothing is removed + // until the breaker is done. + while (!contended) { + await new Promise((resolve) => setImmediate(resolve)); + } + await contended; + expect(await exists(lockPath)).toBe(true); + await fs.unlink(guardPath()); + + expect(await held).toBe("ran"); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("still releases its lock when the guard cannot be created", async () => { + const realOpen = fs.open; + const result = await withFileLock(lockPath, async () => { + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === guardPath()) { + throw Object.assign(new Error("EACCES: simulated"), { + code: "EACCES", + }); + } + return realOpen(...args); + }) as typeof fs.open); + return "ran"; + }); + + expect(result).toBe("ran"); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("waits out a break in progress before running under a lock it has just created", async () => { + await fs.writeFile(guardPath(), ""); + const opens = watchOpens(); + const sawBreak = opens.opened(guardPath(), "r"); + const operation = vi.fn(async () => "ran"); + const held = withFileLock(lockPath, operation, fast); + + await sawBreak; + // The lock is created, but the writer has not started. + expect(await exists(lockPath)).toBe(true); + expect(operation).not.toHaveBeenCalled(); + await fs.unlink(guardPath()); + + expect(await held).toBe("ran"); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("keeps a lock it has just created fresh while it waits out a guard", async () => { + // A guard left by a crash a moment ago: the new lock waits for it to + // go stale, and must not look abandoned itself by the time it does. + await fs.writeFile(guardPath(), ""); + const opens = watchOpens(); + const firstCheck = opens.opened(guardPath(), "r"); + const held = withFileLock(lockPath, async () => "ran", fast); + await firstCheck; + const old = new Date(Date.now() - 600_000); + await fs.utimes(lockPath, old, old); + + // Each turn of the wait checks the guard, then refreshes the lock, so + // two more checks put one whole refresh after the ageing above. + await opens.opened(guardPath(), "r"); + await opens.opened(guardPath(), "r"); + const { mtimeMs } = await fs.stat(lockPath); + expect(mtimeMs).toBeGreaterThan(Date.now() - 60_000); + await fs.unlink(guardPath()); + + expect(await held).toBe("ran"); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("leaves a lock that displaced its own in place when its check fails", async () => { + const realOpen = fs.open; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === guardPath() && args[1] === "r") { + // A breaker has put another holder's lock back over the new one, + // and then the check for a break in progress fails. + await fs.writeFile(lockPath, "another holder"); + throw Object.assign(new Error("EACCES: simulated"), { + code: "EACCES", + }); + } + return realOpen(...args); + }) as typeof fs.open); + + await expect( + withFileLock(lockPath, async () => "ran", fast), + ).rejects.toThrow("EACCES: simulated"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readFile(lockPath, "utf-8")).toBe("another holder"); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]); + }); + + it("clears a guard left by a crash rather than waiting on it", async () => { + await fs.writeFile(guardPath(), ""); + const longAgo = new Date(Date.now() - 120_000); + await fs.utimes(guardPath(), longAgo, longAgo); + + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("waits, on Windows, for a guard another process is still deleting", async () => { + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const pendingDelete = Object.assign(new Error("EPERM"), { + code: "EPERM", + }); + const realOpen = fs.open; + let guardChecks = 0; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === guardPath() && args[1] === "r") { + guardChecks += 1; + if (guardChecks === 1) { + throw pendingDelete; + } + } + return realOpen(...args); + }) as typeof fs.open); + + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); + expect(guardChecks).toBe(2); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("fails, removing the lock it created, when the guard cannot be checked", async () => { + const realOpen = fs.open; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === guardPath() && args[1] === "r") { + throw Object.assign(new Error("EACCES: simulated"), { + code: "EACCES", + }); + } + return realOpen(...args); + }) as typeof fs.open); + + await expect( + withFileLock(lockPath, async () => "ran", fast), + ).rejects.toThrow("EACCES: simulated"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("fails, removing the lock it created, when that lock cannot be read back", async () => { + vi.spyOn(fs, "readFile").mockRejectedValueOnce( + Object.assign(new Error("EIO: simulated"), { code: "EIO" }), + ); + + await expect( + withFileLock(lockPath, async () => "ran", fast), + ).rejects.toThrow("EIO: simulated"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("takes the lock again when the one it created was removed before it could run", async () => { + const realReadFile = fs.readFile; + // A breaker older than #5560 deletes the new lock by path, between + // its creation and the creator's check. + vi.spyOn(fs, "readFile").mockImplementationOnce((async ( + ...args: Parameters + ) => { + await fs.unlink(lockPath); + return realReadFile(...args); + }) as typeof fs.readFile); + + expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("keeps tracking a lock this process took at the path of one it lost", async () => { + const realReadFile = fs.readFile; + let finish!: () => void; + const mayFinish = new Promise((resolve) => (finish = resolve)); + let other: Promise | undefined; + let trackedAfterLoss: string[] | undefined; + // The first writer's new lock is displaced before its check, and a + // second writer in this process takes the lock at the same path. + vi.spyOn(fs, "readFile").mockImplementationOnce((async ( + ...args: Parameters + ) => { + await fs.unlink(lockPath); + let holding!: () => void; + const held = new Promise((resolve) => (holding = resolve)); + other = withFileLock(lockPath, async () => { + holding(); + await mayFinish; + return "second ran"; + }); + await held; + // Let the first writer find the loss, then look at what is tracked. + setImmediate(() => { + setTimeout(() => { + trackedAfterLoss = heldLockPaths(); + finish(); + }, 20); + }); + return realReadFile(...args); + }) as typeof fs.readFile); + + expect( + await withFileLock(lockPath, async () => "first ran", { + ...fast, + timeoutMs: 5_000, + }), + ).toBe("first ran"); + expect(await other).toBe("second ran"); + // The first writer's loss did not untrack the second writer's lock. + expect(trackedAfterLoss).toEqual([lockPath]); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual([]); + }); + }); }); describe("releasing held locks on exit (#5485)", () => { diff --git a/src/memory/__tests__/invalid-record-removal.test.ts b/src/memory/__tests__/invalid-record-removal.test.ts new file mode 100644 index 0000000000..4d01dd9912 --- /dev/null +++ b/src/memory/__tests__/invalid-record-removal.test.ts @@ -0,0 +1,262 @@ +// Characterization tests for #5541: what a stored record that fails the schema +// costs once it is in the graph file. #4885 made the server skip such a line +// on read and write it back verbatim on every save, so that a write never +// drops data it could not read (persistence.test.ts pins both). The +// consequence pinned here is that the record is then out of every tool's +// reach: the read tools do not show it, the delete tools report its name as +// not found, the add tools refuse it as missing, and creating an entity under +// its name stores a second record beside it instead of replacing it. Only an +// edit of the file by hand removes or repairs the line. +// +// The tests take no position on whether a remediation tool should exist. They +// state today's contract, and a change that adds one changes these assertions +// visibly. +// +// The claim is about tools, so each case drives the server through an SDK +// Client over an in-memory transport (helpers.ts) and asserts on the tool's +// result and on the file's exact bytes: the "not found" wording a client reads +// is produced in the tool handlers, which a call on KnowledgeGraphManager +// would skip. Every write tool is exercised, since the claim is "no tool". +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { promises as fs } from "fs"; +import { call, connect, makeTempGraph, readFileText } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +const alice = { + name: "Alice", + entityType: "person", + observations: ["Works at Acme"], +}; +const bob = { name: "Bob", entityType: "person", observations: [] }; +const carol = { name: "Carol", entityType: "person", observations: [] }; +const aliceManagesBob = { from: "Alice", to: "Bob", relationType: "manages" }; + +const aliceLine = JSON.stringify({ type: "entity", ...alice }); +const bobLine = JSON.stringify({ type: "entity", ...bob }); +const carolLine = JSON.stringify({ type: "entity", ...carol }); +const aliceManagesBobLine = JSON.stringify({ + type: "relation", + ...aliceManagesBob, +}); + +// An entity record with no entityType, and a relation record with no +// relationType: each parses as JSON and fails its schema. +const invalidEntityLine = + '{"type":"entity","name":"Broken","observations":["missing entityType"]}'; +const invalidRelationLine = '{"type":"relation","from":"Alice","to":"Bob"}'; + +// In the order a save writes them (entities, relations, then the lines it +// could not read), so a save that changes nothing rewrites the same bytes. +const seedLines = [ + aliceLine, + bobLine, + aliceManagesBobLine, + invalidEntityLine, + invalidRelationLine, +]; + +function fileOf(lines: string[]): string { + return lines.join("\n") + "\n"; +} + +describe("a schema-invalid record is out of every tool's reach (#5541)", () => { + let filePath: string; + let cleanup: () => Promise; + let conn: Connection; + + beforeEach(async () => { + ({ filePath, cleanup } = await makeTempGraph()); + await fs.writeFile(filePath, fileOf(seedLines)); + // Every load logs "Skipping invalid entity/relation in memory file". + vi.spyOn(console, "error").mockImplementation(() => {}); + conn = await connect(filePath); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await conn.close(); + await cleanup(); + }); + + it("is not shown by read_graph, search_nodes or open_nodes", async () => { + const { client } = conn; + + expect((await call(client, "read_graph")).structuredContent).toEqual({ + entities: [alice, bob], + relations: [aliceManagesBob], + }); + expect( + (await call(client, "search_nodes", { query: "Broken" })) + .structuredContent, + ).toEqual({ entities: [], relations: [] }); + expect( + (await call(client, "search_nodes", { query: "missing entityType" })) + .structuredContent, + ).toEqual({ entities: [], relations: [] }); + expect( + (await call(client, "open_nodes", { names: ["Broken"] })) + .structuredContent, + ).toEqual({ entities: [], relations: [] }); + // Reading writes nothing. + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + }); + + it("is reported as not found by delete_entities, and outlives it and a later unrelated write", async () => { + const { client } = conn; + + const deleted = await call(client, "delete_entities", { + entityNames: ["Broken"], + }); + + expect(deleted.isError).toBeUndefined(); + expect(deleted.structuredContent).toEqual({ + success: true, + message: "Deleted 0 of 1 entities. Not found: Broken", + }); + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + + await call(client, "create_entities", { entities: [carol] }); + + expect(await readFileText(filePath)).toBe( + fileOf([ + aliceLine, + bobLine, + carolLine, + aliceManagesBobLine, + invalidEntityLine, + invalidRelationLine, + ]), + ); + expect((await call(client, "read_graph")).structuredContent).toEqual({ + entities: [alice, bob, carol], + relations: [aliceManagesBob], + }); + }); + + it("keeps its observations when delete_observations names them", async () => { + const result = await call(conn.client, "delete_observations", { + deletions: [ + { entityName: "Broken", observations: ["missing entityType"] }, + ], + }); + + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + success: true, + message: "Deleted 0 of 1 observations. Entities not found: Broken", + }); + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + }); + + it("is refused as missing by add_observations, so it cannot be repaired in place", async () => { + const result = await call(conn.client, "add_observations", { + observations: [{ entityName: "Broken", contents: ["a new fact"] }], + }); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([ + { type: "text", text: "Entity with name Broken not found" }, + ]); + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + }); + + it("is refused as a relation's end by create_relations", async () => { + const result = await call(conn.client, "create_relations", { + relations: [{ from: "Alice", to: "Broken", relationType: "knows" }], + }); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([ + { type: "text", text: "Entity with name Broken not found" }, + ]); + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + }); + + // create_entities does not see the invalid record, so the name is free: the + // new entity is stored as a second record under the same name, and the + // invalid line stays. Deleting by that name then removes only the new one. + it("is not replaced by create_entities under its name, which adds a second record beside it", async () => { + const { client } = conn; + const replacement = { + name: "Broken", + entityType: "thing", + observations: ["recreated"], + }; + + const created = await call(client, "create_entities", { + entities: [replacement], + }); + + expect(created.structuredContent).toEqual({ entities: [replacement] }); + expect(await readFileText(filePath)).toBe( + fileOf([ + aliceLine, + bobLine, + JSON.stringify({ type: "entity", ...replacement }), + aliceManagesBobLine, + invalidEntityLine, + invalidRelationLine, + ]), + ); + + const deleted = await call(client, "delete_entities", { + entityNames: ["Broken"], + }); + + expect(deleted.structuredContent).toEqual({ + success: true, + message: "Entities deleted successfully", + }); + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + }); + + describe("an invalid relation record", () => { + // The record has no relationType, and delete_relations requires one, so + // no call can name it: the same call without the field is rejected. + it("matches no delete_relations call, whatever relationType is given", async () => { + const { client } = conn; + + const unnamed = await call(client, "delete_relations", { + relations: [{ from: "Alice", to: "Bob" }], + }); + expect(unnamed.isError).toBe(true); + expect(unnamed.content).toEqual([ + { + type: "text", + text: "Input validation error: Invalid arguments for tool delete_relations: relations.0.relationType: Invalid input: expected string, received undefined", + }, + ]); + + const empty = await call(client, "delete_relations", { + relations: [{ from: "Alice", to: "Bob", relationType: "" }], + }); + expect(empty.structuredContent).toEqual({ + success: true, + message: "Deleted 0 of 1 relations. The rest matched nothing.", + }); + expect(await readFileText(filePath)).toBe(fileOf(seedLines)); + }); + + // delete_entities removes every valid relation that touches the entity; + // the invalid one that names it is left behind. + it("is left behind when delete_entities removes both entities it names", async () => { + const { client } = conn; + + const deleted = await call(client, "delete_entities", { + entityNames: ["Alice", "Bob"], + }); + + expect(deleted.structuredContent).toEqual({ + success: true, + message: "Entities deleted successfully", + }); + expect(await readFileText(filePath)).toBe( + fileOf([invalidEntityLine, invalidRelationLine]), + ); + expect((await call(client, "read_graph")).structuredContent).toEqual({ + entities: [], + relations: [], + }); + }); + }); +}); diff --git a/src/memory/__tests__/persistence.test.ts b/src/memory/__tests__/persistence.test.ts index b1d0236a77..ffadf11287 100644 --- a/src/memory/__tests__/persistence.test.ts +++ b/src/memory/__tests__/persistence.test.ts @@ -6,6 +6,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { promises as fs } from "fs"; import path from "path"; +import os from "os"; import { call, connect, @@ -255,9 +256,20 @@ describe("memory persistence over the protocol", () => { it("keeps serving after a failed save", async () => { const { client } = await open(); - vi.spyOn(fs, "writeFile").mockRejectedValueOnce( - new Error("ENOSPC: simulated full disk"), - ); + const realOpen = fs.open; + let refused = false; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + const handle = await realOpen(...args); + if (!refused && String(args[0]).endsWith(".tmp")) { + refused = true; + handle.writeFile = async () => { + throw new Error("ENOSPC: simulated full disk"); + }; + } + return handle; + }) as typeof fs.open); const failed = await call(client, "create_entities", { entities: [alice], }); @@ -296,15 +308,15 @@ describe("memory persistence over the protocol", () => { // the original mode must differ from a new file's for a loss to show. const original = (await newFileMode()) === 0o600 ? 0o640 : 0o600; await fs.chmod(filePath, original); - const writeFile = vi.spyOn(fs, "writeFile"); + const openSpy = vi.spyOn(fs, "open"); await call(client, "create_entities", { entities: [bob] }); // The temp file is created with that mode, never a wider one first. - expect(writeFile).toHaveBeenCalledWith( + expect(openSpy).toHaveBeenCalledWith( expect.stringMatching(/\.tmp$/), - expect.any(String), - { mode: original }, + "wx", + original, ); expect(await modeOf(filePath)).toBe(original); expect((await call(client, "read_graph")).structuredContent).toEqual({ @@ -335,6 +347,125 @@ describe("memory persistence over the protocol", () => { ); }); + // The temp file's name is in a directory others may write, so anything can + // appear at it while a save runs. The save creates it exclusively and then + // works only through its own handle: whatever stands at the name (a symlink + // to another file, say) is never written, chmodded or renamed onto the + // graph path. POSIX only: creating a symlink on Windows needs privileges. + describe.skipIf(process.platform === "win32")("the temp file's name", () => { + let outsideDir: string; + let outside: string; + const outsideText = "not part of the graph\n"; + + beforeEach(async () => { + outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), "memory-outside-")); + outside = path.join(outsideDir, "outside.txt"); + await fs.writeFile(outside, outsideText); + await fs.chmod(outside, 0o600); + }); + + afterEach(async () => { + await fs.rm(outsideDir, { recursive: true, force: true }); + }); + + function isTempPath(target: unknown): target is string { + return ( + typeof target === "string" && + path.dirname(target) === dir && + target.endsWith(".tmp") + ); + } + + // Runs hook on the temp path when the save creates its temp file, + // before the creating call (when: "before") or after it (when: "after"). + function onTempCreate( + when: "before" | "after", + hook: (tempPath: string) => Promise, + ): void { + const realOpen = fs.open; + const realWriteFile = fs.writeFile; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (!isTempPath(args[0])) return realOpen(...args); + if (when === "before") await hook(args[0]); + const handle = await realOpen(...args); + if (when === "after") await hook(args[0]); + return handle; + }) as typeof fs.open); + vi.spyOn(fs, "writeFile").mockImplementation((async ( + ...args: Parameters + ) => { + if (!isTempPath(args[0])) return realWriteFile(...args); + if (when === "before") await hook(args[0]); + await realWriteFile(...args); + if (when === "after") await hook(args[0]); + }) as typeof fs.writeFile); + } + + async function seed(): Promise<{ + client: Connection["client"]; + before: string; + }> { + const { client } = await open(); + await call(client, "create_entities", { entities: [alice] }); + await fs.chmod(filePath, 0o644); + return { client, before: await readFileText(filePath) }; + } + + async function expectOnlyTheGraphUntouched(before: string): Promise { + expect((await fs.stat(outside)).mode & 0o777).toBe(0o600); + expect(await readFileText(outside)).toBe(outsideText); + expect((await fs.lstat(filePath)).isFile()).toBe(true); + expect(await readFileText(filePath)).toBe(before); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); + } + + it("never writes through a link already at the temp name", async () => { + const { client, before } = await seed(); + onTempCreate("before", (tempPath) => fs.symlink(outside, tempPath)); + + const result = await call(client, "create_entities", { + entities: [bob], + }); + + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/EEXIST/); + await expectOnlyTheGraphUntouched(before); + }); + + it("refuses the save when the temp name is replaced after it is created", async () => { + const { client, before } = await seed(); + onTempCreate("after", async (tempPath) => { + await fs.unlink(tempPath); + await fs.symlink(outside, tempPath); + }); + + const result = await call(client, "create_entities", { + entities: [bob], + }); + + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/was replaced/); + await expectOnlyTheGraphUntouched(before); + }); + + it("saves normally when nothing else touches the temp name", async () => { + const { client } = await seed(); + onTempCreate("after", async () => {}); + + await call(client, "create_entities", { entities: [bob] }); + + expect((await fs.stat(outside)).mode & 0o777).toBe(0o600); + expect((await fs.lstat(filePath)).isFile()).toBe(true); + expect((await fs.stat(filePath)).mode & 0o777).toBe(0o644); + expect((await call(client, "read_graph")).structuredContent).toEqual({ + entities: [alice, bob], + relations: [], + }); + }); + }); + // #4797: two servers on one file (two client processes in practice) used to // both load the same graph, and the second save replaced the first, with // both calls reporting success. Each graph load here is held long enough for diff --git a/src/memory/__tests__/scale-round-trip.test.ts b/src/memory/__tests__/scale-round-trip.test.ts new file mode 100644 index 0000000000..3a59fbe1d8 --- /dev/null +++ b/src/memory/__tests__/scale-round-trip.test.ts @@ -0,0 +1,136 @@ +// Pins that a graph of thousands of records reads back exactly as written +// (#5540). This is a correctness test, not a benchmark: it asserts nothing +// about speed. +// +// Why it exists: the rest of this suite works on graphs of a few dozen +// records at most, so on small files. Here the file is about 600 KB, several +// times a 64 KiB stream chunk, written by ten full rewrites of a growing file +// and one more for the relations. A change that only breaks +// past a size no small test reaches would pass the rest of the suite: a +// default cap or page size on read_graph or search_nodes, a move from +// whole-file reads and writes to streamed ones that drops or splits a record +// at a chunk boundary (the observations hold multi-byte characters for that +// reason), or a rewrite that loses, duplicates or reorders records once a +// second batch lands on a large file. +// +// Why it goes through an MCP client rather than KnowledgeGraphManager: the +// place a default limit would be added is the tool layer, and the tool layer +// is also where a result this large meets the SDK's input and output schema +// validation and its JSON-RPC serialization. Driving the manager directly +// would leave all of that unpinned at scale. The reader is a second +// connection, so a second server with its own manager: it holds nothing the +// writer held in memory, which makes reading through it the equivalent of +// reading after a restart. +// +// Every record is compared, not a count and a sample: a count cannot see an +// observation attached to the wrong entity or a relation with a swapped +// endpoint. +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { call, connect, makeTempGraph, readFileText } from "./helpers.js"; +import type { Connection } from "./helpers.js"; +import type { Entity, Relation } from "../index.js"; + +const ENTITY_COUNT = 5000; +const BATCH_SIZE = 500; +const RELATION_COUNT = 999; + +// Zero-padded, so no name or observation is a substring of another and a +// search for one matches exactly one entity. +const pad = (n: number): string => String(n).padStart(4, "0"); + +const ENTITIES: Entity[] = Array.from({ length: ENTITY_COUNT }, (_, n) => ({ + name: `entity-${pad(n)}`, + entityType: `bulk-${n % 7}`, + observations: [`obs-${pad(n)}`, `観測 ${pad(n)} é`], +})); + +// A chain over the first thousand entities: entity-0000 → entity-0001 → … +const RELATIONS: Relation[] = Array.from( + { length: RELATION_COUNT }, + (_, n) => ({ + from: `entity-${pad(n)}`, + to: `entity-${pad(n + 1)}`, + relationType: "next", + }), +); + +// The setup makes eleven writes, each a full rewrite under the file lock. +// Measured on an Apple-silicon Mac, setup and all three tests together take +// 0.3 to 0.4 s, uninstrumented or under coverage (0.96 s once, on a loaded +// machine). The default 5 s hook timeout is too little headroom over that +// for a slow Windows runner (#5570); thirty seconds is a wide margin that +// still fails a write path whose cost has stopped being linear. +const SETUP_TIMEOUT_MS = 30_000; + +describe("round trip at 5,000-entity scale", () => { + let cleanup: () => Promise; + let filePath: string; + let reader: Connection; + + beforeAll(async () => { + const temp = await makeTempGraph(); + cleanup = temp.cleanup; + filePath = temp.filePath; + + const writer = await connect(filePath); + try { + for (let start = 0; start < ENTITY_COUNT; start += BATCH_SIZE) { + const batch = ENTITIES.slice(start, start + BATCH_SIZE); + const created = await call(writer.client, "create_entities", { + entities: batch, + }); + // Each call reports exactly its own batch as created: nothing + // skipped as a duplicate, nothing carried over from another batch. + expect(created.isError).toBeFalsy(); + expect(created.structuredContent).toEqual({ entities: batch }); + } + const created = await call(writer.client, "create_relations", { + relations: RELATIONS, + }); + expect(created.isError).toBeFalsy(); + expect(created.structuredContent).toEqual({ relations: RELATIONS }); + } finally { + await writer.close(); + } + + reader = await connect(filePath); + }, SETUP_TIMEOUT_MS); + + afterAll(async () => { + await reader?.close(); + await cleanup?.(); + }); + + it("read_graph returns every entity and relation, in order, with no options", async () => { + const result = await call(reader.client, "read_graph"); + + expect(result.isError).toBeFalsy(); + expect(result.structuredContent).toEqual({ + entities: ENTITIES, + relations: RELATIONS, + }); + }); + + it("search_nodes finds the one entity holding an observation, with both relations that touch it", async () => { + const result = await call(reader.client, "search_nodes", { + query: "obs-0500", + }); + + expect(result.isError).toBeFalsy(); + expect(result.structuredContent).toEqual({ + entities: [ENTITIES[500]], + relations: [RELATIONS[499], RELATIONS[500]], + }); + }); + + it("stores one record per line: the entities, then the relations", async () => { + const lines = (await readFileText(filePath)) + .split("\n") + .filter((line) => line !== ""); + + expect(lines.map((line) => JSON.parse(line) as unknown)).toEqual([ + ...ENTITIES.map((entity) => ({ type: "entity", ...entity })), + ...RELATIONS.map((relation) => ({ type: "relation", ...relation })), + ]); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index c98d2173ca..6df277c4fb 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -17,7 +17,14 @@ import { import { McpServer } from "@modelcontextprotocol/server"; import type { Transport } from "@modelcontextprotocol/server"; import { z } from "zod"; -import { promises as fs, readFileSync, realpathSync, unlinkSync } from "fs"; +import { + promises as fs, + closeSync, + openSync, + readFileSync, + realpathSync, + unlinkSync, +} from "fs"; import type { FileHandle } from "fs/promises"; import path from "path"; import os from "os"; @@ -318,15 +325,186 @@ async function isLockStale( } } -// Remove an abandoned lock, returning whether it did. Breaking is itself -// guarded by a second O_EXCL file, so only one waiter breaks at a time and -// re-checks the lock under that guard: two waiters can never both judge the -// same abandoned lock stale and one then remove the lock the other has just -// taken in its place. +// The lock protocol, for writers in separate processes sharing lockPath. +// +// The lock is a file created with O_EXCL: exactly one creator wins. Next to +// it stands a second O_EXCL file, the guard (`.break`), held for a few +// file-system calls at a time. The guard orders every change of the lock +// path's occupant other than the create itself (#5565): +// +// - Breaking a stale lock happens under the guard (breakStaleLock). +// - Releasing a lock happens under the guard (releaseLock, and +// releaseHeldLocks at exit): the holder compares the token and removes the +// file with no breaker able to act in between, and never while a breaker +// has that lock renamed aside. +// - A writer that has just created the lock does not run until no guard +// stands, and then checks that the file at lockPath still holds its token +// (withFileLock). A lock created while a breaker had a live lock aside is +// overwritten when the breaker puts that lock back; its creator finds the +// other token and goes back to waiting. +// +// What this rests on, and where it stops: // -// The guard orders breakers only. The lock's own holder can still release it, -// and a breaker that stalls past staleMs loses its guard to another, so the -// file at lockPath can be replaced by a successor's live lock after the +// - No process stalls for longer than staleMs inside a guarded section. A +// guard older than staleMs is taken to be left by a crash and is cleared, +// so writers never deadlock on one; a holder that really did stall that +// long there loses the guard's protection. The same holds for the lock: a +// 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 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 +// lock file, same contents, same guard, same stale rules), and each +// hand-off window above is closed for the newer process's own acquire and +// release, whichever version the breaker runs. The older process's own +// release and acquire keep the windows they had. + +// The guard file that orders changes to the lock at lockPath. +function guardPathOf(lockPath: string): string { + return `${lockPath}.break`; +} + +// The guards this process holds right now, so the exit hook can remove them: +// a guard left behind stalls the next writer until it goes stale. +const heldGuards = new Set(); + +// Wait before another attempt: retryMs, plus up to the same again of jitter. +function pause(retryMs: number): Promise { + return new Promise((resolve) => + setTimeout(resolve, retryMs + Math.random() * retryMs), + ); +} + +// 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( + guardPath: string, + staleMs: number, +): Promise { + let handle: FileHandle; + try { + handle = await fs.open(guardPath, "r"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return false; + } + // On Windows, a guard still being deleted: it stands for a moment yet. + if (isLockBusy(error)) { + return true; + } + throw error; + } + try { + if ((await judgeLock(handle, staleMs)).stale) { + await fs.unlink(guardPath).catch(ignoreError); + } + } finally { + await handle.close(); + } + return true; +} + +// 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. +async function tryTakeGuard( + guardPath: string, + staleMs: number, +): Promise { + let guard: FileHandle; + try { + guard = await fs.open(guardPath, "wx"); + } catch (error) { + if (!isLockBusy(error)) { + throw error; + } + await isGuardHeld(guardPath, staleMs); + return false; + } + // Tracked before anything else is awaited, as a lock is (see withFileLock). + heldGuards.add(guardPath); + await guard.close().catch(ignoreError); + return true; +} + +// Give up a guard this process took. The removal and the end of its tracking +// are one synchronous step: were the removal awaited, an exit arriving before +// its continuation would still find the guard tracked, and the exit hook +// would remove, as this process's own, a guard another process had taken at +// the same path in between. +function dropGuard(guardPath: string): void { + try { + unlinkSync(guardPath); + } catch { + // Already gone: cleared as stale, or removed by the exit hook. + } + heldGuards.delete(guardPath); +} + +// Whether a rename that replaces a file failed only because the file being +// replaced is open right now. On Windows, renaming over a file that anything +// holds open fails with EPERM (or EACCES, or EBUSY) until that handle closes. +// Elsewhere a rename never fails for that reason, and these codes are lasting. +function isReplaceBusy(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException).code; + return ( + process.platform === "win32" && + (code === "EPERM" || code === "EACCES" || code === "EBUSY") + ); +} + +// Put a live lock that breakStaleLock took aside by mistake back at lockPath. +// A writer that created the lock in the gap keeps opening its file while it +// waits for the guard to go (confirmLock), so on Windows the rename over that +// file can fail for a moment. Giving up then would drop the guard with the +// live lock still aside, and that writer would run beside its holder (#5635). +// So the rename is retried, still under the guard, until it lands. No attempt +// starts once half of staleMs has passed since the guard was taken: past +// staleMs the guard is taken to be left by a crash and protects nothing, and +// the other half is the margin for the attempt in flight. A put-back that +// cannot be made fails with an error of its own rather than the rename's +// code, which on Windows would read as a busy lock and send this writer back +// to acquiring with the live lock still aside. +async function restoreLock( + asidePath: string, + lockPath: string, + guardTakenAt: number, + staleMs: number, + retryMs: number, +): Promise { + const deadline = guardTakenAt + staleMs / 2; + for (;;) { + try { + await fs.rename(asidePath, lockPath); + return; + } catch (error) { + if (!isReplaceBusy(error)) { + throw error; + } + await pause(retryMs); + if (Date.now() >= deadline) { + throw new Error( + `Could not put back the live memory file lock ${lockPath}, left at ${asidePath}`, + { cause: error }, + ); + } + } + } +} + +// Remove an abandoned lock, returning whether it did. Breaking happens under +// the guard, so only one waiter breaks at a time and re-checks the lock under +// it: two waiters can never both judge the same abandoned lock stale and one +// then remove the lock the other has just taken in its place. +// +// The guard keeps every writer that takes part in it from changing the lock +// meanwhile, but not a server older than #5565, whose release ignores it, nor +// a breaker that stalled past staleMs and lost its guard to another. So the +// file at lockPath can still be replaced by a successor's live lock after the // re-check has judged it stale. Removing by path would then delete that live // lock and let a third writer in beside its holder (#5560). So the lock is // never deleted where it stands. It is renamed aside to a name nobody else @@ -337,33 +515,25 @@ async function isLockStale( // then, so the judged file's inode number cannot be reused by a successor's // file and the comparison cannot be fooled. // -// What remains is the moment a live lock spends aside before it is put back: -// a writer that creates the lock in exactly that moment is overwritten by the -// restored one and runs beside its holder. Reaching it takes a replacement -// between the judgement and the rename, then a create between the two -// renames; a lock file cannot close that without the kernel's help. +// While a live lock is aside the lock path is free. The guard is still held +// then, which is what covers that moment: a writer that creates the lock in +// it waits for the guard to go, finds the restored lock's token in place of +// its own, and does not run; and the live lock's holder cannot release until +// its lock is back, so no lock is restored after its holder has finished. async function breakStaleLock( lockPath: string, staleMs: number, + retryMs: number, ): Promise { - const breakerPath = `${lockPath}.break`; - let breaker: FileHandle; - try { - breaker = await fs.open(breakerPath, "wx"); - } catch (error) { - if (!isLockBusy(error)) { - throw error; - } - // Another waiter is breaking the lock. Its guard is held for a moment - // only, so one that outlives staleMs was left by a crash: clear it. - const stats = await fs.stat(breakerPath).catch(() => null); - if (stats && Date.now() - stats.mtimeMs > staleMs) { - await fs.unlink(breakerPath).catch(ignoreError); - } + const guardPath = guardPathOf(lockPath); + // Read before the guard is created, so it is never later than the time the + // guard's age is counted from. + const guardTakenAt = Date.now(); + if (!(await tryTakeGuard(guardPath, staleMs))) { + // Another waiter is breaking the lock, or its holder is releasing it. return false; } try { - await breaker.close(); const judged = await fs.open(lockPath, "r"); try { const { stale, dev, ino } = await judgeLock(judged, staleMs); @@ -375,7 +545,7 @@ async function breakStaleLock( const taken = await fs.stat(asidePath, { bigint: true }); if (taken.dev !== dev || taken.ino !== ino) { // Not the lock that was judged: a successor's live one. Put it back. - await fs.rename(asidePath, lockPath); + await restoreLock(asidePath, lockPath, guardTakenAt, staleMs, retryMs); return false; } console.error(`Breaking stale memory file lock ${lockPath}`); @@ -385,7 +555,7 @@ async function breakStaleLock( await judged.close(); } } finally { - await fs.unlink(breakerPath).catch(ignoreError); + dropGuard(guardPath); } } @@ -407,10 +577,24 @@ export function heldLockPaths(): string[] { return [...heldLocks.keys()]; } +// Stop tracking held, unless lockPath is tracked for another lock by now: one +// that a later withFileLock call in this process took at the same path. +function untrackLock(lockPath: string, held: HeldLock): void { + if (heldLocks.get(lockPath) === held) { + heldLocks.delete(lockPath); + } +} + // Synchronously remove every lock this process still holds, as the process // exits: an `exit` listener cannot wait on a promise. As in withFileLock's own // release, a lock is removed only while it still holds this process's token, -// so a lock broken as stale and re-taken by another process stays in place. +// so a lock broken as stale and re-taken by another process stays in place, +// and only under the guard, so it cannot be broken and re-taken between the +// comparison and the removal (#5565). An exit cannot wait for a guard either: +// when another process holds it (it is breaking this lock, or a crash left +// the guard behind), the lock is left where it is, to be broken as the lock +// of a process that has exited. A guard this process itself holds, because +// the exit interrupted its own release or break, is used and then removed. // A lock is tracked from the moment its exclusive create returns, before its // token is written. Until that write finishes, a file holding only the start // of the token (or none of it) is ours too: the exit interrupted the write. @@ -420,16 +604,30 @@ export function heldLockPaths(): string[] { // is being written, is left alone. export function releaseHeldLocks(): void { for (const [lockPath, { token, written }] of heldLocks) { + const guardPath = guardPathOf(lockPath); try { + if (!heldGuards.has(guardPath)) { + closeSync(openSync(guardPath, "wx")); + heldGuards.add(guardPath); + } const contents = readFileSync(lockPath, "utf-8"); if (written ? contents === token : token.startsWith(contents)) { unlinkSync(lockPath); } } catch { - // Already gone, or unreadable: there is nothing of ours to remove. + // The guard is held elsewhere, or the lock is already gone or + // unreadable: there is nothing here that is safely ours to remove. } } heldLocks.clear(); + for (const guardPath of heldGuards) { + try { + unlinkSync(guardPath); + } catch { + // Already gone. + } + } + heldGuards.clear(); } // The exit codes a shell reports for a process its signal ended: 128 + the @@ -469,13 +667,97 @@ export function installLockCleanup(): void { } } +// Remove the lock at lockPath if it still holds token: if it was broken as +// stale while this process held it, the file may now belong to another +// process. The comparison and the removal happen under the guard, so no +// breaker can replace the lock between them, and a lock a breaker has aside +// is back in place before it is looked for (#5565). The wait for the guard is +// short: its holders keep it for a few file-system calls, and one left by a +// crash is cleared once it is staleMs old. If the guard cannot be created at +// all (the directory has gone, say), the lock is still compared and removed, +// unguarded, rather than left for every other writer to wait out. +async function releaseLock( + lockPath: string, + token: string, + staleMs: number, + retryMs: number, +): Promise { + const guardPath = guardPathOf(lockPath); + let guarded = false; + try { + while (!(await tryTakeGuard(guardPath, staleMs))) { + await pause(retryMs); + } + guarded = true; + } catch { + // Released without the guard, below. + } + const current = await fs.readFile(lockPath, "utf-8").catch(() => null); + if (current === token) { + await fs.unlink(lockPath).catch(ignoreError); + } + if (guarded) { + dropGuard(guardPath); + } +} + +// Refresh the lock at lockPath, if it still holds token, so it does not go +// stale while its holder is alive. Returns false once the lock holds another +// token: it changed hands, and keeping it fresh would stop a crashed new +// owner's lock from ever going stale. +async function refreshLock(lockPath: string, token: string): Promise { + if ((await fs.readFile(lockPath, "utf-8")) !== token) { + return false; + } + const now = new Date(); + await fs.utimes(lockPath, now, now); + return true; +} + +// Whether the lock this writer has just created at lockPath is still its own +// once no break is in progress. A breaker that took a live lock aside by +// mistake puts it back over whatever stands at lockPath, and it holds the +// guard until it has. So the creator waits for the guard to go, then reads +// the token: its own means no restored lock displaced it, and none can now, +// since a breaker that starts later judges this fresh lock live and leaves +// it. The wait is not bounded by the caller's timeout, because a lock held +// meanwhile cannot be given up safely by path; it ends within a few +// file-system calls, or once a guard left by a crash is staleMs old. The lock +// is refreshed on every turn of that wait: its heartbeat has not started, and +// a lock that aged alongside a crash-left guard would otherwise look +// abandoned the moment the guard is cleared. +async function confirmLock( + lockPath: string, + token: string, + staleMs: number, + retryMs: number, +): Promise { + while (await isGuardHeld(guardPathOf(lockPath), staleMs)) { + // A failure here (the lock is aside, or gone) is left to the check below. + await refreshLock(lockPath, token).catch(ignoreError); + await pause(retryMs); + } + try { + return (await fs.readFile(lockPath, "utf-8")) === token; + } catch (error) { + // Renamed aside and deleted: not ours any more. Anything else is a + // failure to read our own lock, and fails the acquisition. + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return false; + } + throw error; + } +} + // Run operation while holding an exclusive lock file at lockPath, so that // mutations from separate server processes sharing one graph file take turns // and each one loads the graph the previous one saved (#4797). The lock is a // file created with O_EXCL, which is atomic on local filesystems: exactly one // creator wins. The holder refreshes the lock's mtime every staleMs / 2 while // it runs. A lock left behind by a crashed process is broken once its owner -// is known to be dead, or once it has gone unrefreshed for staleMs. +// is known to be dead, or once it has gone unrefreshed for staleMs. How +// acquiring, releasing and breaking are ordered against each other is +// described above guardPathOf(). export async function withFileLock( lockPath: string, operation: () => Promise, @@ -503,19 +785,35 @@ export async function withFileLock( // line, so from here on the exit hook can remove it (#5485). const held: HeldLock = { token, written: false }; heldLocks.set(lockPath, held); + let confirmed: boolean; try { await handle.writeFile(token); held.written = true; await handle.close(); + confirmed = await confirmLock(lockPath, token, staleMs, retryMs); } catch (error) { - // The lock was created but not written: remove it rather than leave - // every other writer waiting for it to go stale. + // The lock was created but not written, or could not be confirmed: + // remove it rather than leave every other writer waiting for it to + // go stale. Before its token is written the file can only be ours. + // After, a breaker may have put another holder's lock back over it, + // so it is released like any held lock: only if it still holds our + // token. await handle.close().catch(ignoreError); - await fs.unlink(lockPath).catch(ignoreError); - heldLocks.delete(lockPath); + if (held.written) { + await releaseLock(lockPath, token, staleMs, retryMs); + } else { + await fs.unlink(lockPath).catch(ignoreError); + } + untrackLock(lockPath, held); throw error; } - break; + if (confirmed) { + break; + } + // A lock put back by a breaker displaced ours, so it was never held: + // stop tracking it and wait for the lock like any other writer. + untrackLock(lockPath, held); + continue; } // Someone else holds the lock. Break it if it is abandoned; otherwise @@ -523,7 +821,7 @@ export async function withFileLock( try { if ( (await isLockStale(lockPath, staleMs)) && - (await breakStaleLock(lockPath, staleMs)) + (await breakStaleLock(lockPath, staleMs, retryMs)) ) { continue; } @@ -543,9 +841,7 @@ export async function withFileLock( `Timed out after ${timeoutMs} ms waiting for the memory file lock ${lockPath}`, ); } - await new Promise((resolve) => - setTimeout(resolve, retryMs + Math.random() * retryMs), - ); + await pause(retryMs); } // Keep the lock fresh while the operation runs, so a mutation that outlasts @@ -554,18 +850,14 @@ export async function withFileLock( // as stale and re-taken, the file belongs to another process, and keeping // it fresh would stop a crashed new owner's lock from ever going stale. const heartbeat = setInterval(() => { - const now = new Date(); // Not awaited: an interval callback has no caller to await it, and every // failure (the lock already gone) is caught and ignored here. - void fs - .readFile(lockPath, "utf-8") - .then((current) => { - if (current !== token) { + void refreshLock(lockPath, token) + .then((ours) => { + if (!ours) { // The lock changed hands: stop refreshing it, for good. clearInterval(heartbeat); - return; } - return fs.utimes(lockPath, now, now); }) .catch(ignoreError); }, staleMs / 2); @@ -575,12 +867,7 @@ export async function withFileLock( return await operation(); } finally { clearInterval(heartbeat); - // Release only our own lock: if it was broken as stale while we held it, - // the file may now belong to another process. - const current = await fs.readFile(lockPath, "utf-8").catch(() => null); - if (current === token) { - await fs.unlink(lockPath).catch(ignoreError); - } + await releaseLock(lockPath, token, staleMs, retryMs); // Stop tracking the lock only once the release is done, so an exit during // it still removes the lock. A lock this same process broke as stale and // re-took in another withFileLock call carries that call's token, and @@ -859,22 +1146,42 @@ export class KnowledgeGraphManager { `${path.basename(this.memoryFilePath)}.${randomBytes(16).toString("hex")}.tmp`, ); + // The directory may be writable by others, so anything can appear at + // the temp file's name while the save runs. Create it exclusively ("wx", + // O_CREAT | O_EXCL), which fails rather than open whatever is already + // there, a symlink included, and then write and chmod it only through + // the handle, which keeps reaching the file this call created whatever + // happens to the name. Only the rename has to go by name. + let handle: FileHandle | undefined; try { // Create the temp file with the existing mode, so the graph is never // readable through it more widely than through the file it replaces; // the umask can only narrow that. The chmod then restores any bits the // umask removed. - await fs.writeFile( - tempFilePath, - content, - mode === undefined ? undefined : { mode }, - ); + handle = await fs.open(tempFilePath, "wx", mode); + await handle.writeFile(content); if (mode !== undefined) { - await fs.chmod(tempFilePath, mode); + await handle.chmod(mode); + } + // The rename moves whatever the name holds now, onto the graph path, + // so refuse unless that is still the file written above. Compare while + // the handle is open: the open file's inode number cannot be reused by + // another file until it is closed. + const written = await handle.stat({ bigint: true }); + const named = await fs.lstat(tempFilePath, { bigint: true }); + if (named.ino !== written.ino || named.dev !== written.dev) { + throw new Error( + `Refused to save: ${tempFilePath} was replaced while the graph was ` + + "being written to it. Nothing was saved.", + ); } + await handle.close(); + handle = undefined; await fs.rename(tempFilePath, this.memoryFilePath); } catch (error) { - // Never leave a stray temp file behind on failure. + await handle?.close().catch(() => {}); + // Never leave a stray temp file behind on failure. When the name was + // replaced this removes the replacement, never what a link points at. await fs.unlink(tempFilePath).catch(() => {}); throw error; } diff --git a/src/memory/package.json b/src/memory/package.json index 01ae5dea35..498461177c 100644 --- a/src/memory/package.json +++ b/src/memory/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/server-memory", - "version": "2.2.1", + "version": "2.2.2", "description": "MCP server for enabling memory for Claude through a knowledge graph", "license": "SEE LICENSE IN LICENSE", "mcpName": "io.github.modelcontextprotocol/server-memory", diff --git a/src/memory/server.json b/src/memory/server.json new file mode 100644 index 0000000000..400b34e3fa --- /dev/null +++ b/src/memory/server.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-memory", + "title": "Memory", + "description": "Persistent memory for an assistant, stored as a knowledge graph of entities and relations", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/memory" + }, + "packages": [ + { + "registryType": "npm", + "identifier": "@modelcontextprotocol/server-memory", + "transport": { + "type": "stdio" + } + } + ] +} diff --git a/src/sequentialthinking/__tests__/item-size.test.ts b/src/sequentialthinking/__tests__/item-size.test.ts new file mode 100644 index 0000000000..0319cb3332 --- /dev/null +++ b/src/sequentialthinking/__tests__/item-size.test.ts @@ -0,0 +1,69 @@ +// Characterization tests for the size of one item (#5543). The server's +// documented caps are on other dimensions: MAX_THOUGHT_HISTORY bounds how many +// thoughts are retained, and MAX_BOX_TEXT_WIDTH / MAX_BOX_ROWS bound what one +// thought draws on stderr. Nothing bounds how large a single thought or +// branchId may be: the input schema is a bare `z.string()` for both, and the +// history keeps each one whole. +// +// These cases pin that absence, and take no position on whether a per-item cap +// should exist. If one is ever added, they fail, so the change is a visible, +// deliberate one rather than a silent side effect. +// +// Each case runs with thought logging off and on. Logging is on by default for +// a real client, and drawing the box is the one step between validation and +// retention that reads the whole item, so "accepted" has to hold there too. +// The stderr caps themselves are covered in thought-logging.test.ts. + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { connect, parseOk, thought, type Connected } from "./helpers.js"; + +describe.each([ + { logging: "off", disableThoughtLogging: "true" }, + { logging: "on", disableThoughtLogging: undefined }, +])( + "sequentialthinking item size (characterization), thought logging $logging", + ({ disableThoughtLogging }) => { + let conn: Connected; + + beforeEach(async () => { + // With logging on, every accepted thought draws a box on stderr. + vi.spyOn(console, "error").mockImplementation(() => {}); + conn = await connect({ disableThoughtLogging }); + }); + + afterEach(async () => { + await conn.close(); + vi.restoreAllMocks(); + }); + + it("accepts a thought of a million characters, counted once", async () => { + const result = parseOk( + await conn.think(thought({ thought: "a".repeat(1_000_000) })), + ); + expect(result.thoughtHistoryLength).toBe(1); + }); + + it("accepts a thought of five thousand lines, counted once", async () => { + const result = parseOk( + await conn.think(thought({ thought: "line\n".repeat(5000) })), + ); + expect(result.thoughtHistoryLength).toBe(1); + }); + + it("accepts a ten-thousand-character branchId and lists it verbatim", async () => { + const branchId = "b".repeat(10_000); + const first = parseOk( + await conn.think(thought({ branchFromThought: 1, branchId })), + ); + expect(first.branches).toEqual([branchId]); + + // A later, unbranched thought still reports the id untruncated: it is + // read back from what the server retained, not echoed from the request. + const later = parseOk( + await conn.think(thought({ thoughtNumber: 2, totalThoughts: 3 })), + ); + expect(later.branches).toEqual([branchId]); + expect(later.thoughtHistoryLength).toBe(2); + }); + }, +); diff --git a/src/sequentialthinking/server.json b/src/sequentialthinking/server.json new file mode 100644 index 0000000000..961f0f9676 --- /dev/null +++ b/src/sequentialthinking/server.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-sequential-thinking", + "title": "Sequential Thinking", + "description": "Step-by-step problem solving through a sequence of thoughts that can be revised and branched", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/sequentialthinking" + }, + "packages": [ + { + "registryType": "npm", + "identifier": "@modelcontextprotocol/server-sequential-thinking", + "transport": { + "type": "stdio" + } + } + ] +} diff --git a/src/time/README.md b/src/time/README.md index 877551eff9..1f282cfaaf 100644 --- a/src/time/README.md +++ b/src/time/README.md @@ -37,7 +37,7 @@ The server speaks both eras of the Model Context Protocol over stdio, with nothi The server is built on the SDK's high-level `MCPServer`. Each tool declares an `outputSchema` and returns its result twice: as `structuredContent`, and as the same object in indented JSON in a text block, for a client that does not read structured output. -- **A tool failure is an `isError` result** whose text the model can read and act on, prefixed `Error executing tool : `. That covers an unknown or non-exact timezone (`Invalid timezone: ...`), an empty timezone (`Missing required argument: `), a time not in `HH:MM` 24-hour form, a wall-clock time skipped by a clock change, and an argument missing or of the wrong type (the SDK's validation message). +- **A tool failure is an `isError` result** whose text the model can read and act on, prefixed `Error executing tool : `. That covers an unknown or non-exact timezone (`Invalid timezone: '' is not a known IANA timezone name`, a fixed message that names only the input and never the host's tz database path), an empty timezone (`Missing required argument: `), a time not in `HH:MM` 24-hour form, a wall-clock time skipped by a clock change, and an argument missing or of the wrong type (the SDK's validation message). - **An ambiguous time is reported, not guessed.** On the day a clock change repeats a wall-clock time (a DST fall-back, such as 01:30 on 2024-11-03 in `America/New_York`), `convert_time` returns its first occurrence in `source` and `target`, and the second in `later_occurrence`: a `note` saying the time occurs twice, with that occurrence's own `source`, `target` and `time_difference`. For any other time `later_occurrence` is `null`. - **An unknown tool name is a JSON-RPC `-32602` error** (`Unknown tool: `), not an `isError` result, as both protocol versions specify. - The server registers no prompts or resources. Their list methods answer with empty lists. diff --git a/src/time/pyproject.toml b/src/time/pyproject.toml index f25287ba0a..eb646b3f9c 100644 --- a/src/time/pyproject.toml +++ b/src/time/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mcp-server-time" -version = "2026.11.18" +version = "2026.11.27" description = "A Model Context Protocol server providing tools for time queries and timezone conversions for LLMs" readme = "README.md" requires-python = ">=3.10" diff --git a/src/time/server.json b/src/time/server.json new file mode 100644 index 0000000000..878d020b36 --- /dev/null +++ b/src/time/server.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.modelcontextprotocol/server-time", + "title": "Time", + "description": "Current time lookup and conversion between IANA timezones", + "repository": { + "url": "https://github.com/modelcontextprotocol/servers", + "source": "github", + "subfolder": "src/time" + }, + "packages": [ + { + "registryType": "pypi", + "identifier": "mcp-server-time", + "transport": { + "type": "stdio" + } + } + ] +} diff --git a/src/time/src/mcp_server_time/server.py b/src/time/src/mcp_server_time/server.py index a7c1271483..dff7490e8f 100644 --- a/src/time/src/mcp_server_time/server.py +++ b/src/time/src/mcp_server_time/server.py @@ -117,11 +117,21 @@ def load_zoneinfo(timezone_name: str) -> ZoneInfo: def get_zoneinfo(timezone_name: str) -> ZoneInfo: - """`load_zoneinfo`, failing with a `ToolError` the model can read.""" + """`load_zoneinfo`, failing with a `ToolError` the model can read. + + The message is fixed and names only the input. zoneinfo raises a + different type per kind of bad key, and some of its messages carry the + host's path to the tz database: a key that names a tzdata directory + (`America`) is an `OSError` quoting that directory's absolute path + (#5559). So none of zoneinfo's own text reaches the client, as at startup + (`serve`). + """ try: return load_zoneinfo(timezone_name) except Exception as e: - raise ToolError(f"Invalid timezone: {e!s}") from e + raise ToolError( + f"Invalid timezone: {timezone_name!r} is not a known IANA timezone name" + ) from e class TimeServer: diff --git a/src/time/tests/test_eras.py b/src/time/tests/test_eras.py index e45a109624..60ad14d396 100644 --- a/src/time/tests/test_eras.py +++ b/src/time/tests/test_eras.py @@ -140,7 +140,7 @@ async def test_tool_failure_is_an_is_error_result_in_each_era( assert bad_zone.is_error is True assert text_of(bad_zone) == ( "Error executing tool get_current_time: " - "Invalid timezone: 'No time zone found with key Nope/Nowhere'" + "Invalid timezone: 'Nope/Nowhere' is not a known IANA timezone name" ) diff --git a/src/time/tests/test_protocol.py b/src/time/tests/test_protocol.py index 81ca2d9b88..389ff38213 100644 --- a/src/time/tests/test_protocol.py +++ b/src/time/tests/test_protocol.py @@ -676,19 +676,25 @@ async def test_get_current_time_argument_validation( ({"timezone": ""}, "Missing required argument: timezone"), ( {"timezone": "Invalid/Timezone"}, - "Invalid timezone: 'No time zone found with key Invalid/Timezone'", + "Invalid timezone: 'Invalid/Timezone' is not a known IANA timezone name", ), ( {"timezone": "europe/warsaw"}, - "Invalid timezone: 'No time zone found with key europe/warsaw'", + "Invalid timezone: 'europe/warsaw' is not a known IANA timezone name", ), ( {"timezone": "../etc/passwd"}, - "Invalid timezone: ZoneInfo keys must refer to subdirectories of TZPATH, got: ../etc/passwd", + "Invalid timezone: '../etc/passwd' is not a known IANA timezone name", ), ( {"timezone": "/etc/localtime"}, - "Invalid timezone: ZoneInfo keys may not be absolute paths, got: /etc/localtime", + "Invalid timezone: '/etc/localtime' is not a known IANA timezone name", + ), + # A tzdata directory, not a zone: zoneinfo's OSError quotes the host's + # absolute path to it, which must not reach the client (#5559). + ( + {"timezone": "America"}, + "Invalid timezone: 'America' is not a known IANA timezone name", ), ], ) @@ -1146,11 +1152,21 @@ async def test_convert_time_argument_validation( # Raised by the tool as a ToolError. ( {"source_timezone": "Bad/Zone", "time": "12:00", "target_timezone": "UTC"}, - "Invalid timezone: 'No time zone found with key Bad/Zone'", + "Invalid timezone: 'Bad/Zone' is not a known IANA timezone name", ), ( {"source_timezone": "UTC", "time": "12:00", "target_timezone": "Bad/Zone"}, - "Invalid timezone: 'No time zone found with key Bad/Zone'", + "Invalid timezone: 'Bad/Zone' is not a known IANA timezone name", + ), + # A tzdata directory: the fixed message, not zoneinfo's OSError with + # the host's path (#5559). + ( + {"source_timezone": "America", "time": "12:00", "target_timezone": "UTC"}, + "Invalid timezone: 'America' is not a known IANA timezone name", + ), + ( + {"source_timezone": "UTC", "time": "12:00", "target_timezone": "America"}, + "Invalid timezone: 'America' is not a known IANA timezone name", ), # Like get_current_time, an empty timezone is reported as a missing # argument rather than as zoneinfo's own message. @@ -1196,7 +1212,7 @@ async def test_convert_time_checks_timezones_before_the_time_string() -> None: {"source_timezone": "UTC", "time": "nope", "target_timezone": "Bad/Zone"}, ) assert result == tool_error( - "convert_time", "Invalid timezone: 'No time zone found with key Bad/Zone'" + "convert_time", "Invalid timezone: 'Bad/Zone' is not a known IANA timezone name" ) @@ -1334,7 +1350,12 @@ async def test_get_time_ago_argument_validation( ({"timezone": ""}, "Missing required argument: timezone"), ( {"timezone": "europe/warsaw"}, - "Invalid timezone: 'No time zone found with key europe/warsaw'", + "Invalid timezone: 'europe/warsaw' is not a known IANA timezone name", + ), + # A tzdata directory: no host path in the message (#5559). + ( + {"timezone": "America"}, + "Invalid timezone: 'America' is not a known IANA timezone name", ), # Past what timedelta can hold, and past year 1. ( @@ -1348,7 +1369,7 @@ async def test_get_time_ago_argument_validation( # The timezone is checked before the offset. ( {"timezone": "Bad/Zone", "days_ago": 10**10}, - "Invalid timezone: 'No time zone found with key Bad/Zone'", + "Invalid timezone: 'Bad/Zone' is not a known IANA timezone name", ), ], ) diff --git a/src/time/tests/test_server.py b/src/time/tests/test_server.py index 95f9747adf..84c15fa297 100644 --- a/src/time/tests/test_server.py +++ b/src/time/tests/test_server.py @@ -91,7 +91,7 @@ def test_get_current_time_with_invalid_timezone(): time_server = TimeServer() with pytest.raises( ToolError, - match=r"Invalid timezone: 'No time zone found with key Invalid/Timezone'", + match=r"Invalid timezone: 'Invalid/Timezone' is not a known IANA timezone name", ): time_server.get_current_time("Invalid/Timezone") @@ -103,13 +103,13 @@ def test_get_current_time_with_invalid_timezone(): "invalid_tz", "12:00", "Europe/London", - "Invalid timezone: 'No time zone found with key invalid_tz'", + "Invalid timezone: 'invalid_tz' is not a known IANA timezone name", ), ( "Europe/Warsaw", "12:00", "invalid_tz", - "Invalid timezone: 'No time zone found with key invalid_tz'", + "Invalid timezone: 'invalid_tz' is not a known IANA timezone name", ), ( "Europe/Warsaw", @@ -542,7 +542,7 @@ def test_get_zoneinfo_rejects_a_key_the_tz_database_does_not_list(): patch("mcp_server_time.server.known_timezones", return_value=without_warsaw), pytest.raises( ToolError, - match="Invalid timezone: 'No time zone found with key Europe/Warsaw'", + match="Invalid timezone: 'Europe/Warsaw' is not a known IANA timezone name", ), ): get_zoneinfo("Europe/Warsaw") diff --git a/src/time/uv.lock b/src/time/uv.lock index 4c4fc2bfd2..32b86d2146 100644 --- a/src/time/uv.lock +++ b/src/time/uv.lock @@ -709,7 +709,7 @@ wheels = [ [[package]] name = "mcp-server-time" -version = "2026.11.18" +version = "2026.11.27" source = { editable = "." } dependencies = [ { name = "mcp" },