AIStoreHub Package Vault: Official MCP Servers
Package Slug: mcp-reference-servers
Archetype: mcp_server
Upstream Repository: https://github.com/modelcontextprotocol/servers
Workspace Files & Specifications (68 files)
- .claude/settings.json (269 bytes)
{ "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/scripts/session-instructions-check.mjs\"", "timeout": 30 } ] } ] } } - .claude/skills/board-ops/evals/evals.json (1334 bytes)
[ { "prompt": "Move the board card for issue 4810 to In Review.", "expect": "board-ops" }, { "prompt": "How do I set the Priority field on an issue's card on the Servers V2 board?", "expect": "board-ops" }, { "prompt": "The project board rejected my Status option ID. How do I get the current one?", "expect": "board-ops" }, { "prompt": "I'm about to add an option to one of the board's single-select fields. Should I do anything first?", "expect": "board-ops" }, { "prompt": "Several cards lost their Status value after someone edited the field. How do I put it back?", "expect": "board-ops" }, { "prompt": "Write out every command I need to run to file an issue, start to finish, for: the time server returns the wrong UTC offset for Australia/Lord_Howe during daylight saving. I'll run them myself.", "chain": ["issue-create", "board-ops"] }, { "prompt": "My fix for issue 4810 is committed and the gate is green. Write out every command I need to run from here until the PR is open and tracked, start to finish. I'll run them myself.", "chain": ["pr-flow", "board-ops"] }, { "prompt": "Explain the difference between TCP and UDP.", "expect": null }, { "prompt": "What year was the first Moon landing?", "expect": null } ] - .claude/skills/board-ops/SKILL.md (22514 bytes)
--- name: board-ops description: "gh recipes for the Servers V2 project board (#43): add an issue's card, move its Status, set or change its Priority, delete a card, and recover from a deleted single-select option. Use when moving a card between columns; when setting Status or Priority; when an option ID is rejected; before editing a board field's options; or when cards lost their Status or Priority." disable-model-invocation: false --- # Board operations The rules about _what_ a card's Status and Priority should be live in [`AGENTS.md`](../../../AGENTS.md) under **Issue-driven work style**. This skill is the _mechanics_: the exact `gh` calls, the IDs, and the ways the board can be damaged. Related: `/issue-create` (the create flow, which boards a new issue through the add-card recipe below). **This file is the only place the board's IDs are written down.** Every other skill and document names a column or a field and points here. Two copies of an ID are worse than one, because the stale copy is indistinguishable from the live one. ## The board | Board | Owner | Fields this workflow uses | | --- | --- | --- | | [Servers V2 (#43)](https://github.com/orgs/modelcontextprotocol/projects/43) | `modelcontextprotocol` | Status, Priority | There is one board. It is an **org** project, so every `gh project` command takes `--owner modelcontextprotocol`. The board is **private**: treat a dump of its items as private data (see the snapshot section below). **Only issues go on the board, never PRs, never draft cards.** A PR is tracked through the card of the issue it closes. The one exception is a security advisory's `[GHSA-…]` draft card; see [Advisory draft cards](#advisory-draft-cards). ## IDs The project node id and the field ids are stable: | Thing | ID | | --- | --- | | Project node ID | `PVT_kwDOCt2Azc4BcZgq` | | Status field ID | `PVTSSF_lADOCt2Azc4BcZgqzhXCpm0` | | Priority field ID | `PVTSSF_lADOCt2Azc4BcZgqzhjiM9M` | The **option** ids are **not** stable. They are regenerated whenever a single-select field's option list is edited (see the hazard below), so **this skill does not list them. Resolve an option id by its name, at run time, every time**: ```sh # The board's fields, once per session. Refuses to go on from a failed call. FIELDS=$(gh project field-list 43 --owner modelcontextprotocol --format json) || FIELDS= # opt <Field> <Option name> → the option's current id, or nothing. # The arguments reach jq through --args, never as shell positional parameters: # Claude Code rewrites those in a skill invoked with arguments (#5160). opt() { jq -r '$ARGS.positional as [$f, $o] | .fields[] | select(.name == $f) | .options[] | select(.name == $o) | .id' \ --args "$@" <<<"$FIELDS" } STATUS_OPT=$(opt Status "Todo") PRIORITY_OPT=$(opt Priority "Medium") [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ] \ || echo "option not found — check the name against the list below" >&2 ``` The option **names** are what the workflow depends on: | Field | Options, in board order | | --- | --- | | Status | `Incoming`, `Todo`, `In Progress`, `In Review`, `Done` | | Priority | `Urgent`, `High`, `Medium`, `Low` | What each Status means: | Status | Means | | --- | --- | | Incoming | Arrived unboarded, awaiting review — **no milestone** | | Todo | Approved (a milestone was assigned) | | In Progress | Active work | | In Review | A PR is open | | Done | **Shipped** — a merged PR, or a parent whose last sub-issue closed | If a name above no longer resolves, list what the field actually holds rather than guessing: ```sh # Swap "Status" for "Priority" to see the other field's options. gh project field-list 43 --owner modelcontextprotocol --format json \ | jq '.fields[] | select(.name=="Status") | .options' ``` A renamed option is a change to this table, made in the same change that renames it. ## Finding a card without trusting `--limit` ⚠️ **`gh project item-list --limit N` truncates silently.** Past `N` it returns the first `N` items with no error and no warning, so a `select` over the result matches nothing and a card that exists reads as missing. A limit is a guess about the board's size; don't make the recipes depend on it being right. - **An issue's card is looked up from the issue**, which is independent of board size — see [Move an existing card](#move-an-existing-card). - **A whole-board dump** (the snapshot and the recovery dump below) genuinely needs the full listing. Those recipes use a limit with headroom **and** compare the result's `.items | length` against the `.totalCount` that `item-list --format json` also returns, so a truncated listing fails loudly instead of passing as complete. The check also catches a failed `gh` call, whose empty output has neither key. Where a later step reads the dump from a file, an incomplete dump is deleted, so that step fails on the missing file rather than running on partial data. ## Recipes Every recipe below assumes `FIELDS` and `opt` from [IDs](#ids) are defined in the same shell. ### Add a card and set its fields ```sh # Resolve both options FIRST, so a failed field lookup or a renamed option # never leaves a card on the board with no Status or Priority. STATUS_OPT=$(opt Status "Todo") # an issue you filed through the create flow is approved by definition PRIORITY_OPT=$(opt Priority "Medium") ITEM_ID= if [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ]; then # Prints the item id (PVTI_…); capture it. ITEM_ID=$(gh project item-add 43 --owner modelcontextprotocol --url <issue-url> \ --format json --jq '.id') || ITEM_ID= fi if [ -n "$ITEM_ID" ] && [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ]; then # Chained: a failed Status edit stops before Priority, and the failure shows. gh project item-edit --project-id PVT_kwDOCt2Azc4BcZgq --id "$ITEM_ID" \ --field-id PVTSSF_lADOCt2Azc4BcZgqzhXCpm0 --single-select-option-id "$STATUS_OPT" \ && gh project item-edit --project-id PVT_kwDOCt2Azc4BcZgq --id "$ITEM_ID" \ --field-id PVTSSF_lADOCt2Azc4BcZgqzhjiM9M --single-select-option-id "$PRIORITY_OPT" \ || echo "item-edit FAILED — card $ITEM_ID may be half set; read it back" >&2 else echo "missing option id (nothing added) or item-add failed — nothing edited" >&2 fi ``` Each `item-edit` sets **one** field, so setting both takes two calls; there is no combined form. `item-add` on an issue that already has a card returns the existing card's id rather than adding a second one. For an issue swept in at triage, the only difference is Status → **Incoming** and that you do **not** set a milestone. ### Move an existing card Look the item id up **from the issue** rather than re-adding it. An issue's `projectItems` lists the cards it has on every board, so the lookup does not depend on how many items the board holds (see [Finding a card without trusting `--limit`](#finding-a-card-without-trusting---limit)). Select the card by the board's **node id**, not its number: project numbers are per-owner, and an issue can also sit on a user-owned project that happens to be numbered 43. Querying through the repository also means the issue number cannot match another repo's issue. The mutation runs only on a non-empty id: `item-edit --id ""` fails with an opaque node-resolution error rather than saying the card was not found. The `|| ITEM_ID=` matters too: on a GraphQL error (a number that is a PR, not an issue; a rate limit) `gh api` still prints the raw error JSON to stdout, which would otherwise land in `ITEM_ID` as a non-empty "id". `first:100` is the connection's maximum page; it counts the boards one issue is on, not the cards on a board, so it has no board-size exposure. ```sh N=<ISSUE_NUMBER> ITEM_ID=$(gh api graphql -F n="$N" -f query='query($n:Int!){ repository(owner:"modelcontextprotocol",name:"servers"){issue(number:$n){ projectItems(first:100){nodes{id project{id}}}}}}' \ --jq '.data.repository.issue.projectItems.nodes[] | select(.project.id=="PVT_kwDOCt2Azc4BcZgq") | .id') || ITEM_ID= [ -n "$ITEM_ID" ] || echo "#$N has no card on #43 (or the lookup failed)" >&2 ``` Then edit it. For example, Status → In Review, when its PR opens: ```sh STATUS_OPT=$(opt Status "In Review") if [ -n "$ITEM_ID" ] && [ -n "$STATUS_OPT" ]; then gh project item-edit --project-id PVT_kwDOCt2Azc4BcZgq --id "$ITEM_ID" \ --field-id PVTSSF_lADOCt2Azc4BcZgqzhXCpm0 --single-select-option-id "$STATUS_OPT" else echo "no ITEM_ID or option id — nothing edited" >&2 fi ``` Setting Priority is the same call with `opt Priority "<level>"` and the Priority field id `PVTSSF_lADOCt2Azc4BcZgqzhjiM9M`. ### Read a card back To confirm what a card holds, read it from the issue: ```sh N=<ISSUE_NUMBER> gh api graphql -F n="$N" -f query='query($n:Int!){ repository(owner:"modelcontextprotocol",name:"servers"){issue(number:$n){ projectItems(first:100){nodes{project{id number} fieldValues(first:20){nodes{... on ProjectV2ItemFieldSingleSelectValue{ name field{... on ProjectV2SingleSelectField{name}}}}}}}}}}' \ --jq '.data.repository.issue.projectItems.nodes[] | select(.project.id=="PVT_kwDOCt2Azc4BcZgq") | [.fieldValues.nodes[] | select(.field) | {(.field.name): .name}] | add' ``` ### Delete a card **`Done` means the work shipped.** An issue closed as duplicate / won't fix / not planned / obsolete / superseded shipped nothing, so its card is **deleted**, not parked in Done: ```sh # ITEM_ID from the issue-side LOOKUP block in "Move an existing card" above — # the lookup only, not the item-edit that follows it. if [ -n "$ITEM_ID" ]; then gh project item-delete 43 --owner modelcontextprotocol --id "$ITEM_ID" else echo "no ITEM_ID — nothing deleted" >&2 fi ``` Deleting the card removes it from the board only. **The issue itself is untouched**: it keeps its labels and comments, and stays searchable and linkable forever. Nothing is lost; the board simply stops claiming the work was delivered. Done is read as the record of what a milestone actually delivered, so a duplicate sitting there makes that record wrong in a way nobody can detect later. The close **reason** is the machine-readable form of the same distinction. `gh issue close --reason` accepts only `completed` and `not planned`, so **`duplicate` must be set through the API**: ```sh gh api repos/modelcontextprotocol/servers/issues/<N> -X PATCH \ -f state=closed -f state_reason=duplicate ``` (or "Mark as duplicate" in the web UI, which additionally records a duplicate-of link). ### Advisory draft cards A private security advisory is tracked by a **draft card** titled with the bare id, `[GHSA-xxxx-yyyy-zzzz]`, because a real issue would disclose it before a fix exists. No summary goes in the title until the advisory is published. What goes on the card, and when it moves, is the `/security-advisory` flow; these are only the mechanics. An advisory can also have a **follow-up card**, titled `[GHSA-xxxx-yyyy-zzzz follow-up]`, for work its fix leaves open. The recipes below handle it with one change: put `[$GHSA follow-up]` wherever they have `[$GHSA]`, both in the lookup's `--arg p` and in `item-create`'s `--title`. The advisory card's own lookup matches up to the closing bracket, so it never finds the follow-up. ⚠️ **A draft card has no repository and no issue number**, so the issue-side lookup above cannot find one. Look it up by its **bracketed GHSA id** in the full listing, checked for truncation, then feed that item id to `item-edit` or `item-delete` exactly as usual: ```sh GHSA=GHSA-xxxx-yyyy-zzzz # the advisory's real id ITEM_ID= # never let an earlier lookup's id survive a failed one LOOKED= # set only by a lookup over a COMPLETE listing BOARD=$(gh project item-list 43 --owner modelcontextprotocol --format json --limit 2000) if jq -e '(.items | length) == .totalCount' <<<"$BOARD" >/dev/null; then ITEM_ID=$(jq -r --arg p "[$GHSA]" '.items[] | select(.content.type=="DraftIssue") | select(.content.title | startswith($p)) | .id' <<<"$BOARD") && LOOKED=1 [ -n "$ITEM_ID" ] || echo "no draft card titled [$GHSA] on #43" >&2 else echo "item-list incomplete or failed — raise --limit; not concluding anything" >&2 fi ``` **Create** one only when that lookup ran over a complete listing **and** found none (a second card for the same advisory is a duplicate). Run it in the same shell, straight after the lookup: it refuses on a missing `LOOKED` or a found `ITEM_ID`. It is the add-card recipe with `item-create` in place of `item-add`, Status `Incoming`, and the provisional Priority: ```sh STATUS_OPT=$(opt Status "Incoming") PRIORITY_OPT=$(opt Priority "<provisional level>") if [ "$LOOKED" != 1 ] || [ -n "$ITEM_ID" ]; then echo "lookup incomplete, or [$GHSA] already has a card ($ITEM_ID) — not creating" >&2 elif [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ]; then ITEM_ID=$(gh project item-create 43 --owner modelcontextprotocol \ --title "[$GHSA]" --body "<link and triage lines only>" \ --format json --jq '.id') || ITEM_ID= fi # Then the two chained item-edit calls from "Add a card and set its fields". ``` **Convert** it to an issue when its fix is ready to merge, keeping its opaque title; a follow-up card converts only after the advisory is **published**. When each happens, and what the issue gets, is the `/security-advisory` flow. The web UI has "Convert to issue" on the card; the API equivalent is: ```sh REPO_ID=$(gh api repos/modelcontextprotocol/servers --jq .node_id) || REPO_ID= [ -n "$ITEM_ID" ] && [ -n "$REPO_ID" ] && gh api graphql \ -f item="$ITEM_ID" -f repo="$REPO_ID" -f query='mutation($item:ID!,$repo:ID!){ convertProjectV2DraftIssueItemToIssue(input:{itemId:$item,repositoryId:$repo}){ item{id content{... on Issue{number url}}}}}' ``` The card keeps its place and its field values; the new issue takes the card's title and body. ## ⚠️ The option-deletion hazard This section and its two subsections are copied verbatim from the MCP Inspector's `board-ops`. Only the board number, the IDs, one cross-repo issue reference and one link to a skill this repo does not have were changed, plus two fixes to the recovery recipe from this repo's review: step 1 restores only cards that held the deleted option, and step 3 stops on a failed edit. The closing paragraph also no longer quotes the Inspector's option ids. The incidents they describe happened on the Inspector's board; the mechanism is GitHub's and applies to #43 unchanged. The option-id tables they mention are the Inspector's; here, option ids are resolved by name (see [IDs](#ids)), so there is no table to update, but any option id pasted into an issue, PR or script is invalidated all the same. **Never add, rename, or remove an option on a single-select board field (Status or Priority) with the `updateProjectV2Field` GraphQL mutation unless you pass every existing option's `id`.** That mutation does a **full replace** of the option list: resending options by - .claude/skills/client-smoke/evals/evals.json (1014 bytes)
[ { "prompt": "Smoke-test my change to the time server with the Inspector CLI.", "expect": "client-smoke" }, { "prompt": "How do I call a tool on my locally built server from the command line and get JSON back?", "expect": "client-smoke" }, { "prompt": "The Inspector CLI says 'Multiple servers found in config file' when I pass it my server command. How do I fix it?", "expect": "client-smoke" }, { "prompt": "How do I check my server change against a 2026-07-28 client?", "expect": "client-smoke" }, { "prompt": "How do I get Claude Code to call a tool on my local build of the everything server in one headless command?", "expect": "client-smoke" }, { "prompt": "How do I open the Inspector web UI against my local build of the git server?", "expect": "client-smoke" }, { "prompt": "Summarize the plot of Hamlet in two sentences.", "expect": null }, { "prompt": "Convert 5 kilometers to miles.", "expect": null } ] - .claude/skills/client-smoke/SKILL.md (20814 bytes)
--- name: client-smoke description: "Drive a locally built server with a real client: the Inspector CLI (scripted), the Inspector web UI (through Playwright) and an LLM client. Use when smoke-testing a server change; when calling a tool, reading a resource or getting a prompt from the command line; when choosing a protocol era; or when the Inspector CLI will not connect to, or misreads, a server command." disable-model-invocation: false --- # Client smoke A server change is checked against real clients before its PR opens: the MCP Inspector and an LLM client. This skill is how to run each one against a server built from this checkout, and what the output means. What the PR must then record is in `/pr-flow` (client evidence); building and starting the server is `/local-dev`; automated tests are `/testing`. Three clients, in the order to reach for them: | Client | Driven by | Use it for | | -------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | Inspector **CLI** | A command. This is the **scripted path**, and the one an agent runs | One request, one JSON result: the evidence that goes in a PR | | Inspector **web** UI | A Playwright script in headless Chromium, which an agent writes and runs | What the CLI cannot do: elicitation and sampling round-trips, URL elicitation, tasks, notifications arriving, a long-running tool's progress | | An **LLM client** | A prompt | Whether a model picks the tool and uses its result, which the PR checklist asks for | Build first (`npm run build -w src/<server>`). Every command below runs the last build of a TypeScript server, not your edit. ## The Inspector CLI ```sh npx -y @modelcontextprotocol/inspector --cli <server command> [-- ] <inspector options> ``` It starts the server command over stdio (or connects to a URL), sends one request, prints the result and exits. Pin the Inspector version in anything you keep (`@modelcontextprotocol/inspector@<version>`); the commands here were run on 2.9.0. `--cli --help` is the reference for the options. ```sh INSPECT="npx -y @modelcontextprotocol/inspector --cli" # List, then call, on a TypeScript server $INSPECT node src/everything/dist/index.js stdio --method tools/list --format json $INSPECT node src/everything/dist/index.js stdio \ --method tools/call --tool-name echo --tool-arg message=hello --format json # → {"result":{"content":[{"type":"text","text":"Echo: hello"}]}} # Arguments that are not strings: pass them as JSON $INSPECT node src/everything/dist/index.js stdio \ --method tools/call --tool-name get-sum --tool-args-json '{"a":2,"b":3}' --format json # Resources and prompts $INSPECT node src/everything/dist/index.js stdio \ --method resources/read --uri demo://resource/dynamic/text/1 --format json $INSPECT node src/everything/dist/index.js stdio \ --method prompts/get --prompt-name args-prompt --prompt-args city=Paris --format json # A server that takes a positional argument $INSPECT node src/filesystem/dist/index.js /abs/dir \ --method tools/call --tool-name list_allowed_directories --format json # A Python server: note the `--` (see below) $INSPECT uv --directory src/time run mcp-server-time -- \ --method tools/call --tool-name get_current_time --tool-arg timezone=UTC --format json $INSPECT uv --directory src/git run mcp-server-git --repository "$PWD" -- \ --method tools/list --format json ``` `--format json` prints a result as one JSON object, `{"result": …}`, on **stdout**, and a failure as `{"error": …}` on **stderr**. The server's own stderr (its startup banner) passes through on stderr too. So capture stdout alone for the result, never `2>&1` into a JSON parser: a tool error produces both objects, one on each stream (see the table below). ### How the command line is split The server command comes **first** and the Inspector's options **after** it. With no `--`, the server command ends at the first word that starts with `-`. That rule produces the three failures people actually hit: - **A server command with its own flags needs `--` before the Inspector's options.** `uv --directory …` and `mcp-server-git --repository …` both have one. Without the separator the command is cut at `--directory`, and what runs is a bare `uv`, which prints its help and exits. With it, everything before `--` is the server command and everything after is the Inspector's. - **Putting an Inspector option before the server command loses the command.** `--cli -e KEY=VALUE node …` leaves no server command at all, and the CLI falls back to your personal catalog (`~/.mcp-inspector/mcp.json`). With several servers in it that fails with `Multiple servers found in config file. Please specify one with --server`. Either way it is no longer talking to your build, so move the option after the command. - **`Method is required`** means the options ended up on the wrong side of a `--`. ### Environment variables The spawned server gets only the SDK's default safelist from your shell (`PATH`, `HOME`, `USER` and the like), not the variables you set. Setting `MEMORY_FILE_PATH=… npx …` has no effect on the server; pass it with `-e`: ```sh $INSPECT node src/memory/dist/index.js \ -e MEMORY_FILE_PATH=/abs/tmp/graph.jsonl \ --method tools/call --tool-name read_graph --format json ``` ### Exit codes and errors The exit code is the verdict, so check it rather than reading the text: | Outcome | stdout | stderr | Exit | | -------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------- | ---- | | The request succeeded | `{"result": …}` | | 0 | | The tool ran and returned `isError: true` | `{"result":{"content": …, "isError": true}}` | `{"error":{"code":"tool_is_error", …}}` | 5 | | No such tool | | `{"error":{"code":"tool_not_found", …}}` | 5 | | An HTTP server could not be reached (refused, DNS, timeout) | | `{"error":{"code":"unreachable", …}}` | 4 | | Bad arguments, a failed version negotiation, or a stdio server that exited | | `{"error":{"code":"error", …}}` | 1 | These are the codes observed on 2.9.0 for the cases this repo's servers produce; the CLI defines others (schema and skill checks, authentication) that its `--help` describes. A tool error is a **successful protocol exchange**: the result object is still printed on stdout, and it is what to quote when the change is about an error a tool returns. ### `everything` over HTTP Start the transport in one terminal (or in the background), then give the CLI the URL. The transport is inferred from the path: `/mcp` is Streamable HTTP, `/sse` is HTTP+SSE. ```sh ( URL=http://localhost:3917/mcp # Refuse a port something already answers on: it would be tested instead of this build. curl -s -m 2 -o /dev/null "$URL" && { echo "port 3917 is already in use" >&2; exit 1; } PORT=3917 node src/everything/dist/index.js streamableHttp >/dev/null 2>&1 & SERVER_PID=$! trap 'kill "$SERVER_PID" 2>/dev/null' EXIT # stops it however the subshell ends READY= for _ in $(seq 50); do # at most ten seconds kill -0 "$SERVER_PID" 2>/dev/null || { echo "server exited before listening" >&2; exit 1; } curl -s -m 2 -o /dev/null "$URL" && { READY=1; break; } sleep 0.2 done [ -n "$READY" ] || { echo "server did not listen within ten seconds" >&2; exit 1; } $INSPECT "$URL" --method tools/call --tool-name echo --tool-arg message=over-http --format json ) ``` Each part of that is there for a failure it prevents. The first check refuses a port that already answers, because a stale listener there would be the server under test. Without the wait, the CLI can reach the port before the server is listening and exit 4. The wait is bounded and checks that this server is still alive, so one that fails to bind (the build is missing, the port was taken in between) ends the run instead of hanging it. The subshell's `EXIT` trap stops the server by pid even when the CLI call fails; a listener left on the port makes the next run talk to the old build. By hand in two terminals, the equivalent is waiting for the listening line (`… listening on 127.0.0.1:3917`) and stopping the server with Ctrl-C. A change to a tool, resource or prompt of `everything` is checked over stdio and Streamable HTTP. Check HTTP+SSE as well when the change touches transport or session code; it is deprecated but must keep working. ## Protocol eras The Inspector connects in one of three eras, chosen with `--protocol-era` (the CLI) or **Server Settings → Protocol Era** (the web UI): | Era | What the Inspector does | | ---------------------- | ----------------------------------------------------------- | | `legacy` (the default) | A plain `initialize`. Negotiates 2025-11-25 or older | | `modern` | Pins 2026-07-28 through `server/discover`, with no fallback | | `auto` | Probes `server/discover`, and falls back to `initialize` | **Every server serves both eras**: the Python servers since #4853, the TypeScript servers since #4852 (stdio through the SDK's `serveStdio`, and `everything`'s Streamable HTTP endpoint through `createMcpHandler` for 2026-07-28 requests). Run every command twice, with `--protocol-era legacy` and `--protocol-era modern`, and expect both to succeed. A 2026-07-28 result carries `io.modelcontextprotocol/serverInfo` in its `_meta`, which is the quick way to see which era answered. Do not use `auto` for evidence: it does not say which era answered. `everything` lists some tools on one era only (the task tools on 2026-07-28, the two `toggle-*` tools on the 2025 era), so a `tools/list` that differs between the two runs is expected. The CLI declares no client capabilities, so a tool that asks the client for input (elicitation, sampling, roots) cannot run from it: on the 2025 era `everything` does not list it (`tool_not_found`, exit 5), and on 2026-07-28 the SDK refuses the call because the request did not declare the capability (`Cannot request input 'form' (elicitation/create): the request's client capabilities do not declare the required capability`, exit 1). Drive those from the web UI. On 2026-07-28 the CLI does follow a task handle: a call to `simulate-research-query` polls the task and prints its final result. ## The Inspector web UI The web client is driven with **Playwright** in headless Chromium: an agent writes the script, runs it, and records what came back. It is not a step to hand to a maintainer. Everything below was run on **Inspector 2.12.0** and **Playwright 1.64.1**, against `everything` in both eras; pin both in any script you keep, since the selectors are the UI's, not an API. ```sh npx -y @modelcontextprotocol/[email protected] --web --protocol-era modern -- \ node src/everything/dist/index.js stdio npx -y @modelcontextprotocol/[email protected] --web --protocol-era legacy -- \ uv --directory src/time run mcp-server-time npx -y @modelcontextprotocol/[email protected] --web \ --transport http --server-url http://localhost:3001/mcp ``` ⚠️ **The web launcher reads `--` the other way round from the CLI.** Here the Inspector's own options come **before** `--` and the server command **after** it; in `--cli` mode the server command is before `--` and the options after. A line copied from one mode to the other starts the wrong thing. Pass a server's environment with `-e KEY=VALUE` before the `--`. Install Playwright in a scratch directory **outside the worktree**, never as a dependency of this repo (`npm i [email protected]`, then `npx playwright install chromium`), and run the script from there. The launcher inherits the script's working directory, so spawn it with `cwd` set to the worktree root: the server commands above use paths relative to it, and from the scratch directory no server would start. ### The recipe - **Launch.** Spawn the launcher above with `MCP_AUTO_OPEN_ENABLED=false` in its environment, or it opens a tab in your own browser as well. It prints a tokenized URL (`http://127.0.0.1:6274?MCP_INSPECTOR_API_TOKEN=…`) on stdout; read it from there and navigate to it. Start the launcher in its own process group (`detached: true`) and kill the group when the script ends, so the server it spawned goes with it. - **Connect.** The connect control is a Mantine switch whose input is hidden: `getByRole("switch", { name: /Connect or disconnect/ }).check({ force: true })`. - **Pick a screen.** The Servers, Tools, Prompts and Resources tabs are radios that cannot be clicked; click their label, `locator('label[for$="-Tools"]')`. A tool is then a button named for its title and name: `getByRole("button", { name: / echo$/ })`. - **Fill and run.** A field is a textbox named for its property (`getByRole("textbox", { name: /message/ })`). Run with the **Execute Tool** button; it stays disabled until every required field is filled. - **Selects.** A Mantine Select (an `enum` field, in a tool form or in an elicitation) is a **read-only** textbox: `fill` does nothing. Click it, then press `ArrowDown` and `Enter`, which picks the first option. - **Read the result.** The panel's heading is **Results**, or **Tool Call Failed**. A result with `isError: true` keeps the **Results** heading and adds an alert named **Tool Error** holding the message, so check for that alert rather than the heading. Which heading a failure gets varies by era: rejecting a sampling request shows **Tool Call Failed** on 2026-07-28 and **Results** plus **Tool Error** on 2025-11-25. - **Elicitation.** A dialog named **Elicitation Request**, with **Cancel**, **Decline** and **Submit**. Its question is the paragraph that opens with `“`; the dialog's first `<p>` is its title. - **Multi-step elicitation.** After **Submit**, wait - .claude/skills/issue-create/evals/evals.json (873 bytes)
[ { "prompt": "File an issue titled 'fetch server ignores robots.txt after a redirect' and set it up the way this repo wants.", "expect": "issue-create" }, { "prompt": "Which milestone should a new issue go in, and how do I find the current one?", "expect": "issue-create" }, { "prompt": "Before I file this, how do I check nobody has reported it already?", "expect": "issue-create" }, { "prompt": "I found a bug in the git server while working on something else. How do I get it tracked in this repo?", "expect": "issue-create" }, { "prompt": "Raise an issue for adding a Roots demonstration to the everything server.", "expect": "issue-create" }, { "prompt": "What is the chemical symbol for potassium?", "expect": null }, { "prompt": "Reverse this string: stressed", "expect": null } ] - .claude/skills/issue-create/SKILL.md (9379 bytes)
--- name: issue-create description: "Create a tracked issue in this repo end to end — duplicate check, v2 label, type label, server-scope label, milestone, board card, Status and Priority. Use when asked to file, create, open or raise an issue; when picking its labels or its milestone; when checking whether one already exists; or when work discovered mid-task needs an issue of its own." disable-model-invocation: false --- # Creating an issue An issue **you** create is not "created" until every step below is done. A label is a repo tag, the milestone is a release bucket, and the board is a separate org project: `--label v2` does **not** add a board card, and adding a card does **not** set a Status or a Priority. | # | Step | Applies | | --- | --- | --- | | 1 | **`v2` label** | Always | | 2 | **Type label**: exactly one of `bug` / `enhancement` / `documentation` / `chore` / `question` | Always | | 3 | **Scope label**: `server-<name>` | Only when the issue concerns **one** server | | 4 | **Milestone** | Always | | 5 | **A card on the Servers V2 board (#43)** | Always | | 6 | **Status** on that card: `Todo` (or `In Progress` if you start now) | Always | | 7 | **Priority** on that card | Always | The rules behind each row are in [`AGENTS.md`](../../../AGENTS.md) under **Issue-driven work style**; this skill is the procedure. Rows 5–7 need the board's IDs, which only the `board-ops` skill holds, so **load `board-ops` before step 5**; it is step 5's first action. Set the labels and milestone at **create time**, never by backfilling: an unlabeled issue appears in no `v2`-filtered query, and an unmilestoned one drops out of release planning silently. **Never create a duplicate.** **Never create a draft card** (a board card with no issue number): every board item is a real GitHub issue. The one exception, a private security advisory's `[GHSA-…]` card, is the `security-advisory` skill's. ## 0. Check for an existing issue first Search **all** states, not just open. A closed issue is still a duplicate: it may have been completed, rejected, or filed and superseded, and refiling it loses that history. When one matches, the call is whether to reopen it or file genuinely new work; either way you need to have seen it. ```sh gh issue list --repo modelcontextprotocol/servers --state all --limit 200 \ --search "<keywords>" --json number,title,state,stateReason,labels,milestone ``` This repository has thousands of issues, most from outside contributors, so search with two or three phrasings (the symptom, the tool or server name, the error text) before concluding there is none. Also check the board itself, where approved work already has a card: ```sh BOARD=$(gh project item-list 43 --owner modelcontextprotocol --format json --limit 2000) # --limit truncates silently: trust the listing only when it is complete. if jq -e '(.items | length) == .totalCount' <<<"$BOARD" >/dev/null; then jq -r '.items[] | "\(.content.number)\t\(.status)\t\(.title)"' <<<"$BOARD" \ | grep -i "<keyword>" else echo "board listing incomplete or failed — raise --limit; not concluding anything" >&2 fi ``` ## 1. Pick the labels **`v2`.** Every issue created through this flow carries it. It marks work tracked by this workflow; there is no other version label in this repository. **Type.** Exactly one: | Type | Use for | Not for | | --- | --- | --- | | `bug` | Something is broken, wrong, or regressed against its intended behavior, including a server that reports something false about the protocol | A missing capability that was never built | | `enhancement` | A new capability, or extending an existing one: features, protocol-feature demonstrations, tracking issues | A cleanup with no behavior change | | `documentation` | Prose deliverables: READMEs, `docs/`, `AGENTS.md` rules, skills | Code that happens to need a doc update | | `chore` | Maintenance with no user-facing behavior change: dependencies, build and CI tooling, refactors, release plumbing | Anything a user of a server would notice | | `question` | An open question or discussion with no agreed deliverable yet | Work someone has already decided to do | **Don't force the binary.** `bug` and `enhancement` are the two most reached for, and pressing a docs task or a dependency pin into `enhancement` degrades it to "not a bug", at which point filtering by it stops telling you anything. **Scope.** When the issue concerns exactly one server, add its label: | Server directory | Scope label | | --- | --- | | `src/everything/` | `server-everything` | | `src/filesystem/` | `server-filesystem` | | `src/memory/` | `server-memory` | | `src/sequentialthinking/` | `server-sequentialthinking` | | `src/fetch/` | `server-fetch` | | `src/git/` | `server-git` | | `src/time/` | `server-time` | An issue about the repository as a whole (CI, root scripts, `AGENTS.md`, skills, release tooling) carries **no** scope label. An issue that really spans two or three servers takes each of their labels; one that spans them all is repository-wide and takes none. ## 2. Pick the milestone If the user didn't name one, use the **current** milestone: the open `v2.x` milestone with the nearest due date. ```sh gh api repos/modelcontextprotocol/servers/milestones --jq \ 'map(select(.state=="open" and (.title|startswith("v2")))) | sort_by(.due_on == null, .due_on) | .[] | "\(.title)\tdue \(.due_on // "none" | .[0:10])\topen=\(.open_issues)"' ``` The first line is the default. Milestones are **release** buckets, so pick by _when the work ships_, not by size. If a new issue plainly can't make the current milestone, say so and put it in the next one rather than leaving it blank. A sub-issue normally inherits its parent's milestone. ## 3. Pick the Priority Priority is a board field (Urgent / High / Medium / Low), not a label. Pick it by impact and urgency, and say in one line why: | Priority | For | | --- | --- | | Urgent | A security problem, a broken release, or something blocking other work now | | High | A real defect users hit, or work other planned work depends on | | Medium | The default for planned work | | Low | Nice to have; nothing waits on it | This table is the short form of the scored rubric in `issue-triage`, which is how triage prioritizes inflow. When the choice here is not obvious, score it with that rubric instead. ## 4. Create it ```sh gh issue create --repo modelcontextprotocol/servers \ --title "<title>" \ --label v2 --label "<type from step 1>" --label "<server-name from step 1>" \ --milestone "<milestone from step 2>" \ --body "<body>" ``` Drop the `server-…` label for a repository-wide issue, and repeat it for each server when an issue spans a few. `gh issue create` prints the new issue's URL; keep it for the next step. A good body states the problem, how to reproduce it (the server, its configuration, the client, the request), the expected behavior, and which spec era it concerns when that matters. ## 5. Board it, in Todo, with its Priority Filing an issue for work you intend to happen **is** approving it, so it starts in **Todo** with its milestone already set, not in `Incoming`, which is the queue for issues nobody has evaluated yet. Work you are starting immediately goes straight to **In Progress**. **Load the `board-ops` skill now** and run its add-card recipe with the Status and the Priority from step 3. This file cannot board the issue on its own: the project, field and option IDs live in `board-ops` and only there. An option ID is regenerated whenever its field's option list is edited, so a second copy here would go stale silently and break issue creation even after `board-ops` was fixed. ## 6. Verify Read the issue back and confirm every row of the table at the top: ```sh N=<ISSUE_NUMBER> gh api graphql -F n="$N" -f query='query($n:Int!){ repository(owner:"modelcontextprotocol",name:"servers"){issue(number:$n){ number title milestone{title} labels(first:20){nodes{name}} projectItems(first:100){nodes{project{number owner{... on Organization{login}}} fieldValues(first:20){nodes{... on ProjectV2ItemFieldSingleSelectValue{ name field{... on ProjectV2SingleSelectField{name}}}}}}}}}}' \ --jq '.data.repository.issue | {number, title, milestone: .milestone.title, labels: [.labels.nodes[].name], board: [.projectItems.nodes[] | select(.project.number==43 and .project.owner.login=="modelcontextprotocol") | [.fieldValues.nodes[] | select(.field) | {(.field.name): .name}] | add]}' ``` The issue is created when `labels` holds `v2`, exactly one type and the scope label if one applies, `milestone` is set, and `board` holds exactly one entry with both a `Status` and a `Priority`. The filter matches the board's owner as well as its number, because project numbers are only unique per owner. ## Issues that arrive from elsewhere An issue opened through the GitHub UI, by an outside reporter or by a maintainer, arrives with **no milestone and no card**, and with no labels unless it came through an issue form (the forms apply `v2` and `bug` or `enhancement`, never a scope label). That is normal on arrival, not a defect to fix the moment it lands: it is not approved yet, so it enters the board in **Incoming**, unmilestoned, through triage (the `issue-triage` skill), never through this flow. - .claude/skills/issue-triage/evals/evals.json (879 bytes)
[ { "prompt": "Triage the new issues.", "expect": "issue-triage" }, { "prompt": "How do I decide what Priority an incoming issue deserves?", "expect": "issue-triage" }, { "prompt": "Audit the Servers V2 board for anything that has drifted.", "expect": "issue-triage" }, { "prompt": "Someone opened an issue asking us to list their MCP server in the README. How do I respond?", "expect": "issue-triage" }, { "prompt": "Three outside PRs all fix the same filesystem path bug. What do I do with them?", "expect": "issue-triage" }, { "prompt": "After scoring an issue against the rubric, what do I do with the score?", "expect": "issue-triage" }, { "prompt": "Who wrote the novel Moby-Dick?", "expect": null }, { "prompt": "Convert 45 degrees Celsius to Fahrenheit.", "expect": null } ] - .claude/skills/issue-triage/SKILL.md (41255 bytes)
--- name: issue-triage description: "Triage this repo's inflow — sweep unboarded issues onto the Servers V2 board (#43) as Incoming, score Priority with the rubric and post the score, classify outside PRs and spam (server listings, new servers, duplicates, no-ops) and close them with their canned comments, and run the board audit. Use for \"triage new issues\" or \"triage the PRs\"; when scoring an issue's Priority; when answering or closing an outside PR; or when auditing the board for drift." disable-model-invocation: false --- # Triaging issues and outside PRs This repository receives far more outside issues and pull requests than it opens itself, much of it misdirected (server listings, new servers, questions for the SDK) and much of it racing (several PRs for the same bug). This skill is the procedure for all of it: classify first, answer the classes that do not belong here with a canned response, sweep the rest onto the board unapproved, and check the board afterwards. The **rules** it carries out are in [`AGENTS.md`](../../../AGENTS.md), under **Contributing** and **Issue-driven work style**. The board's IDs, and the recipes that add, move and delete cards, are in `board-ops`, and only there: **load `board-ops` before the first board write.** Labels for an issue you file come from `issue-create`. The plan for the outside-PR backlog is [`docs/contribution-model.md`](../../../docs/contribution-model.md), "The plan"; [Outside PRs](#outside-prs) below is how it is carried out. **"Triage new issues" means:** the [class check](#step-0--classify-before-boarding) and [pass 1](#pass-1--sweep-onto-the-board-no-approval-implied) over every unboarded open issue, then the [board audit](#the-board-audit). **"Triage the PRs" means:** snapshot and classify the open outside PRs into a manifest and stop for a maintainer's review ([Outside PRs](#outside-prs)). Pass 2 and every close of an outside PR need a human, and neither is done unprompted. The one-time sweep of the existing backlog is tracked in #4875 (#4876 for issues, #4877 for PRs). It uses this skill's classes and responses, plus the conventions that tracker sets for the sweep, such as a close label and a reference to #4875 in each close comment. ## Outward-facing actions Every label, comment and close lands on someone else's issue or PR, and a reporter is notified of each one. So: - **A batch of closes happens only after a maintainer has reviewed the manifest** that lists each item, its class, and the issue it will point at. A wrong class is cheap to fix in a file and expensive to fix after a notification went out. Closing a single item the maintainer named is fine. - **Pace every write loop** by `AGENTS.md` **Pacing GitHub writes**, and **stop on the first failed call** rather than carrying on blind. GitHub's secondary rate limit trips well before its primary one, and a loop that keeps going after a 403 leaves a half-applied batch nobody can see. - **Never restate a vulnerability in public**, not even to summarize a report that was already filed publicly. See [Security reports](#security-reports). - **Keep dumps outside the repository.** Every snapshot and manifest below goes in a `mktemp -d` directory. The board is private, and a dump left in the working tree is one `git add -A` away from being published. ## Step 0 — classify before boarding Read each unboarded issue before sweeping it in. Most are real reports, but some belong elsewhere, and boarding one of those would park it in a review queue for work this repository does not do. A class whose Action is **Close** is closed with its [canned response](#canned-responses), gets **no card** (`Done` means shipped, and closed-not-planned work never goes on the board), and needs no labels. A security report is never closed by triage. | Class | Recognized by | Action | Response | | --- | --- | --- | --- | | **Server listing or submission** | Asks for a server to be listed here, in the README or `ADDITIONAL.md` | Close, `not planned` | [Registry, issue](#registry-issue) | | **New server request** | Asks this repository to build or host a new server | Close, `not planned` | [Registry, issue](#registry-issue) | | **Archived server** | About a server in [`servers-archived`](https://github.com/modelcontextprotocol/servers-archived) (GitHub, Slack, Postgres, Puppeteer, …) | Close, `not planned` | [Archived](#archived) | | **SDK or specification** | Reproduces against the SDK directly, or asks for a protocol change | Close, `not planned` | [Elsewhere](#elsewhere) | | **Duplicate** | An open or closed issue already reports it (search all states, as in `issue-create` step 0) | Close as `duplicate` (the `board-ops` API call); delete its card if it has one | [Duplicate](#duplicate) | | **Spam or empty** | No content, unrelated or generated content | Close, `not planned` | None | | **Security report** | Describes a vulnerability in one of the seven servers | **Stop. A maintainer decides** | [Security reports](#security-reports) | | **Everything else** | A bug, a usability problem, an enhancement, a question about these servers | [Pass 1](#pass-1--sweep-onto-the-board-no-approval-implied) | None; the score comment | When a class is a judgment call (a feature a maintainer might still take, a report that could be the SDK or the server), sweep it in rather than closing it. Pass 1 approves nothing, and a maintainer reading `Incoming` can still close it; a wrong close cannot be quietly undone. For the same reason, closes follow [Outward-facing actions](#outward-facing-actions): when a run finds more than one, list them with their classes for a maintainer to confirm, and go on with pass 1 for the rest meanwhile. ```sh # The run's temp dir; create it once, before the first close, and reuse it. D=${D:-$(mktemp -d)} # Copy the class's response from Canned responses into "$D/response.md" (the # text inside the quote, with #ORIGINAL or the SDK link filled in) first. # Close as not planned, with that response (body in a file, so quoting is # safe). The comment and the close are two writes (`gh issue close --comment` # sends them back to back), and a run closes several issues, so every write # here is followed by the PR-close loop's `sleep 8`, including the last one # before the next issue. NOT for a duplicate: post the Duplicate response with # `gh issue comment`, close it with the `board-ops` state_reason=duplicate # call, and delete its card if it has one (`board-ops`, Delete a card), with # the same `sleep 8` after each of those three writes. An empty or missing # response stops here instead of closing silently. BODY=$(cat "$D/response.md") && [ -n "$BODY" ] \ && gh issue comment <N> --repo modelcontextprotocol/servers --body "$BODY" \ && sleep 8 \ && gh issue close <N> --repo modelcontextprotocol/servers --reason "not planned" \ && sleep 8 \ || { echo "no response, or the comment or close failed for #<N> — look before retrying" >&2; false; } # Spam or empty, the one class with no response: gh issue close <N> --repo modelcontextprotocol/servers --reason "not planned" && sleep 8 ``` ## Pass 1 — sweep onto the board (no approval implied) **An issue needs triage when it has no card on #43, whoever filed it.** The test is about state, not authorship. An outside reporter cannot board anything, but a maintainer who opens an issue in the web UI instead of through `issue-create` leaves it unboarded too, and write access makes the board reachable, not automatic. The milestone is not part of the test; it decides where the card lands. For each unboarded open issue left after step 0: 1. **Labels.** `v2`, **exactly one** type label (`bug` / `enhancement` / `documentation` / `chore` / `question`; the table is in `issue-create`), and the server's **scope label** (`server-<name>`) when it concerns one server. The issue forms apply `v2` and `bug` or `enhancement` on their own, but not the scope label, which triage reads off the form's server dropdown. Check the preset type too: a "bug report" that is a usage question is `question`. 2. **Board it** with the `board-ops` add-card recipe, Status **`Incoming`**. 3. **Priority** from [the rubric](#the-priority-rubric), and **post the score as a comment** ([Recording the score](#recording-the-score)). That is an assessment for ordering the queue, not an approval. 4. **Leave the milestone unset.** An empty milestone is what marks it as awaiting review. **The one exception is an unboarded issue that already has a milestone.** Someone recorded the approval and only the card is missing, so it goes straight into **`Todo`**, keeping the milestone. Otherwise triage would silently un-approve work a maintainer had already scheduled. ### Finding the unboarded ones ```sh D=$(mktemp -d); R=modelcontextprotocol/servers # --limit has headroom over the repo's open issues, and a listing that fills it # is treated as truncated: gh does not say when it stops early. gh issue list --repo $R --state open --limit 5000 \ --json number,title,milestone,labels > "$D/open.json" jq -e 'length < 5000' "$D/open.json" >/dev/null \ || { echo "issue listing truncated or failed — raise --limit" >&2; rm -f "$D/open.json"; } # item-list truncates SILENTLY past --limit, and a card missing from the dump # reads as an unboarded issue that then gets a second card. gh project item-list 43 --owner modelcontextprotocol --format json --limit 2000 > "$D/b43.json" jq -e '(.items | length) == .totalCount' "$D/b43.json" >/dev/null \ || { echo "board #43 listing INCOMPLETE — raise --limit and re-run" >&2; rm -f "$D/b43.json"; } # An org board can hold other repositories' issues; keep this repo's only. jq -r --slurpfile b "$D/b43.json" --arg R "$R" ' [$b[0].items[] | select(.content.type=="Issue" and .content.repository==$R) | .content.number] as $boarded | .[] | select(.number as $n | $boarded | index($n) | not) | "#\(.number)\t→ \(if .milestone then "Todo (has milestone \(.milestone.title))" else "Incoming" end)\t\(.title[0:70])"' \ "$D/open.json" ``` A failed or truncated listing deletes its file, so the last step fails on the missing file instead of reporting every issue as unboarded. The finder is only half the resume point. An issue whose card was added but whose Priority or score comment then failed has left the finder's list, and the audit catches a missing Priority but not a missing comment. So after an interrupted batch, **finish the last issue you were working on first** (read its card back with `board-ops` and check its comments), then resume from the finder's output, never from memory. ## Pass 2 — approve what should ship A maintainer reads the `Incoming` column and, for each issue worth doing, **assigns a milestone** and moves the card to **`Todo`** (or **`In Progress`** when picking it up now). That is the whole approval gesture. **Pass 2 is reserved for a human.** Deciding what ships in which release is not something to infer from a rubric score, so never promote a card out of `Incoming` as part of a routine sweep. An issue that should not ship stays in `Incoming` or is closed, and a closed one has its card deleted. ## The priority rubric Score it rather than assert it: rate two axes 1–5, add the signal bonuses, and read the band off the table. Two people triaging the same issue should land in the same place, and the reasoning should survive in a form someone can argue with later. **Axis 1: severity and impact (1–5).** How bad is it when it happens? | Score | Means | | --- | --- | | 1 | Cosmetic: a typo in a README or a tool description, a wording nit. | | 2 | Minor friction with an easy workaround. | | 3 | A tool, resource or prompt is broken or missing, and the workaround is annoying or partial. | | 4 | A server's core function is unusable, or a server **reports something false about the protocol** (a result or schema a conforming client rejects or misreads). | | 5 | Data loss; a security vulnerability, such as an operation that **escapes an allowed root**, SSRF, or command or argument injection; or a release broken on arrival for everyone. | **Axis 2: urgency and staleness (1–5).** How time-sensitive or neglected is it? | Score | Means | | --- | --- | | 1 | No time pressure; nothing waits on it. | | 2 | Wanted eventually. | | 3 | Wanted this milestone, or has sat more than 90 days with no activity. | | 4 | Blocking other work, or tied to a dated external dependency (an SDK release, a spec revision's date). | | 5 | Blocking a release, or hurting users of a published version right now. | **Signal bonuses (+1 each, not an axis of their own).** Corroborating evidence the two axes may have undercounted: - Carries the `bug` label, or concerns security. - Has a milestone, meaning it is **already approved**. This is the _re-scoring_ case: an issue scored in pass 1 has no milestone by rule, so it never earns this bonus. If every issue in a batch is earning it, the milestone is being treated as a formality. - High engagement (many comments, reactions, or linked outside PRs racing to fix it). - Assigned to someone. - A sub-issue of a larger tracker. - The reporter set **Fields → Priority** to `Urgent` or `High`: **+1, flat**, whichever of the two. **Bands.** The axes give 2–10 and there are six bonuses, so totals run 2–16. | Total | Priority | Meaning | | --- | --- | --- | | 12+ | **Urgent** | Drop what you're doing. | | 9–11 | **High** | Next up after current work. | | 6–8 | **Medium** | Scheduled normally. | | ≤5 | **Low** | Nice to have; may sit. | Severity alone does not reach Urgent: a 5/5 with no corroborating signal totals 10 and lands **High**. Urgent is for a severe problem that something _else_ also says is burning. Override the band when it is plainly wrong, and say why in the score comment; a rubric nobody may overrule is a rubric people route around. ### Trust boundary: who can set what **Board #43 is private.** Its Status and Priority are visible only to people with project access. It is the maintainers' working queue, not a published commitment. The **score comment** below is public, though: it is how the reasoning survives, so write it for the reporter to read too. **Fields → Priority** on the issue page is the opposite: an org-level issue field, public, and settable by people outside maintainer triage (the two fields are compared in `board-ops`). A value there is a preference, not an assessment, so it earns the flat +1 and nothing more. It can lift an issue at most one band, and nothing a reporter sets reaches Urgent by itself, because Urgent needs 12 and the issue would already need 11 from the maintainer-assessed axes (at most 10) plus at least one other bonus. **Never copy the value across:** a reporter choosing `Urgent` does not make the card Urgent, or the queue would sort by assertiveness instead of impact. ### Recording the score The board stores only the result, and the board is private. So **post the arithmeti - .claude/skills/local-dev/evals/evals.json (1048 bytes)
[ { "prompt": "How do I run the everything server over Streamable HTTP on a port other than the default from this checkout?", "expect": "local-dev" }, { "prompt": "How do I point Claude Desktop at my local build of the filesystem server instead of the published package?", "expect": "local-dev" }, { "prompt": "I just created a git worktree of this repo and the memory server won't start. What do I check?", "expect": "local-dev" }, { "prompt": "I edited a tool in the memory server but the running server still shows the old behavior. What do I check?", "expect": "local-dev" }, { "prompt": "How do I start the git server from source against a specific repository?", "expect": "local-dev" }, { "prompt": "How do I run the time server from this checkout through uvx rather than the PyPI release?", "expect": "local-dev" }, { "prompt": "Write a haiku about autumn rain.", "expect": null }, { "prompt": "What is 17 multiplied by 23?", "expect": null } ] - .claude/skills/local-dev/SKILL.md (8414 bytes)
--- name: local-dev description: "Install, build and run a server from this checkout. Use when starting a server locally over stdio, SSE or Streamable HTTP; when pointing npx, uvx or an MCP client config at the local build; when a running server still shows old code, or dist is missing; when setting up a git worktree; or when adding an overrides pin." disable-model-invocation: false --- # Local development The short form of the commands, and the dependency **rules**, are in [`AGENTS.md`](../../../AGENTS.md) under **Development setup**. This skill is how to get a server running from the checkout, and what goes wrong on the way. Driving a running server with a client is `/client-smoke`; tests are `/testing`. ## Install and build Node 24 (the development version, and the oldest supported) for the TypeScript servers, and `uv` for the Python ones. ```sh npm install # at the repo root: all four TypeScript workspaces npm run build # every workspace; or: npm run build -w src/<server> ``` Each workspace's `prepare` script is its build, so a root `npm install` also builds every TypeScript server. `tsc` writes each server's `dist/`, which is ignored by git and is what every run command below executes. The Python servers need no separate install step. `uv run` creates the server's `.venv` on first use, at the Python version its `.python-version` pins, and installs the server into it in editable mode. ⚠️ **A fresh git worktree has none of this.** `node_modules`, every `dist/` and every `.venv` are untracked, so a new worktree starts with no installed dependencies and no build. Run `npm install` at the worktree's root before anything else; the first `uv run` in a Python server builds its environment. ## Run a server Every server speaks stdio. A stdio server started by hand waits for JSON-RPC on stdin, so on its own this only shows that it boots; to send it requests, use `/client-smoke`. The TypeScript servers print a startup banner on stderr first. The Python servers print nothing at the default log level, so a silent terminal is a running server, not a hung one. | Server | From the repo root | Arguments and environment | | --- | --- | --- | | `everything` | `node src/everything/dist/index.js stdio` | First argument picks the transport: `stdio` (the default), `sse`, `streamableHttp` | | `filesystem` | `node src/filesystem/dist/index.js <dir> [<dir>…]` | The allowed directories. A client that supports Roots can supply them instead | | `memory` | `node src/memory/dist/index.js` | `MEMORY_FILE_PATH` sets the graph file | | `sequentialthinking` | `node src/sequentialthinking/dist/index.js` | None required | | `fetch` | `uv --directory src/fetch run mcp-server-fetch` | `--user-agent`, `--ignore-robots-txt`, `--proxy-url` | | `git` | `uv --directory src/git run mcp-server-git` | `--repository <path>` | | `time` | `uv --directory src/time run mcp-server-time` | `--local-timezone <IANA name>` | Each server's `README.md` is the reference for its options and environment variables. ⚠️ **`memory` writes inside the build by default.** With no `MEMORY_FILE_PATH`, the graph file is `memory.jsonl` beside the built module, which is `src/memory/dist/memory.jsonl` in a checkout. Point `MEMORY_FILE_PATH` at a temporary file for local runs, so a test graph does not outlive the session inside `dist/`. ### `everything` over HTTP ```sh npm run start:streamableHttp -w src/everything # http://localhost:3001/mcp npm run start:sse -w src/everything # http://localhost:3001/sse PORT=3917 node src/everything/dist/index.js streamableHttp ``` Both HTTP transports listen on `PORT`, default `3001`, so they cannot run side by side without setting it. They bind `HOST`, default `127.0.0.1` (loopback only); `HOST=0.0.0.0` widens it to every interface. Streamable HTTP serves POST, GET and DELETE on `/mcp`. HTTP+SSE serves `GET /sse` and `POST /message`; it is deprecated, kept working, and never the transport to recommend. The two log to different streams: HTTP+SSE writes everything to stderr, while Streamable HTTP writes its request and session messages to stdout and its listening line (which names the bound `host:port`) and errors to stderr. The other six servers serve Streamable HTTP too (#576), selected with a flag rather than an argument, on the same `PORT`, `HOST` and `/mcp` path: ```sh node src/memory/dist/index.js --transport streamable-http node src/filesystem/dist/index.js --transport streamable-http /tmp/scratch # directories required over HTTP (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. ## Run the local package the way a user would A user starts these servers with `npx` or `uvx`. Both accept a path in place of the published name, which exercises the package's `bin` or console script rather than a file path: ```sh npx -y ./src/sequentialthinking # the workspace's bin, from its dist/ uvx --from ./src/time mcp-server-time # builds the project, runs its script ``` `npx` runs whatever is in `dist/`, so build first. For an MCP client's config file, use absolute paths, since the client does not start in this directory: ```json { "mcpServers": { "filesystem-local": { "command": "node", "args": ["/abs/path/to/servers/src/filesystem/dist/index.js", "/abs/dir"] }, "time-local": { "command": "uv", "args": ["--directory", "/abs/path/to/servers/src/time", "run", "mcp-server-time"] } } } ``` Give a local entry a name that differs from the published server's, so the client cannot be running the released package while you read its output as your change. ## When the server still shows old code - **TypeScript runs from `dist/`, never from source.** An edit does nothing until the server is rebuilt: `npm run build -w src/<server>`, or leave `npm run watch -w src/<server>` running. - **A stdio client holds the process it spawned.** Rebuilding does not replace a server a client already started; reconnect or restart the client. - **Python needs no rebuild** under `uv run`, because the install is editable, but the running process still has to be restarted. - **Deleting or renaming a TypeScript source file leaves its old `.js` in `dist/`.** `tsc` does not clean. Remove the server's `dist/` and rebuild when a file went away. ## Dependencies The rules are in `AGENTS.md` under **Dependencies**: pin a transitive dependency with `overrides`, keep shared devDependencies on one range, and commit `uv.lock` with a Python dependency change. What follows is the procedure for each. **An `overrides` pin.** The root `package.json` is the only manifest whose `overrides` npm honors in a workspace, so the entry goes there: ```sh # 1. Add "<package>": "<range>" under "overrides" in the root package.json. npm install npm ls <package> # every copy in the tree, and what pulled each one in npm run build # the pin puts a parent on a version it did not declare, npm test # so the build and tests are the real check, not the audit ``` An override is invisible once the audit is clean. Drop it when the parent package widens its own range, rather than carrying it forever. **A shared devDependency.** `typescript`, `vitest`, `@vitest/coverage-v8` and `@types/node` are declared in each workspace that uses them, and `npm run verify:dep-lockstep` (inside `validate:guards`) fails when two declarations of one package disagree. The guard's own list, in `scripts/verify-dep-lockstep.mjs`, is the set it covers. Bump every declaration in one change, then `npm install` once at the root. **A Python dependency.** Edit that server's `pyproject.toml`, then run `uv lock` in the server's directory and commit `uv.lock` with it. `npm run validate:py -- <server>` syncs with `--locked`, so a stale lockfile fails its first step. ## Docker Each server has a `Dockerfile`, and no gate builds them. 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/<server> -f src/<server>/Dockerfile .`. The Python images build from the **server's directory**: `docker build -t mcp/<server> .`. - .claude/skills/pr-flow/evals/evals.json (1075 bytes)
[ { "prompt": "I've finished the fix for issue 4810. Take it through to a pull request.", "expect": "pr-flow" }, { "prompt": "gh pr edit --add-reviewer copilot didn't request anything on my PR. How do I get Copilot to review it in this repo?", "expect": "pr-flow" }, { "prompt": "I forgot to sign off the last three commits on a branch I already pushed. How do I fix them?", "expect": "pr-flow" }, { "prompt": "What evidence should my PR body show for a change to the memory server's search_nodes tool? There's no UI to screenshot.", "expect": "pr-flow" }, { "prompt": "Copilot left eight comments on my PR, two of them in a Suppressed comments block. How do I answer them so nothing gets lost?", "expect": "pr-flow" }, { "prompt": "My PR into v2/main just merged. What do I still need to do to close it out?", "expect": "pr-flow" }, { "prompt": "What does this regex match? /^[a-z]+$/", "expect": null }, { "prompt": "Translate 'good morning' into Spanish.", "expect": null } ] - .claude/skills/pr-flow/SKILL.md (20318 bytes)
--- name: pr-flow description: "Take an issue through to a PR in this repo and close it out after merge. Use when asked to open, create or submit a PR; when naming a branch; when signing off commits or repairing a missing Signed-off-by; when recording client evidence for a PR; when requesting a Copilot review, answering its comments or deciding whether to run another round; or when closing out after a merge." disable-model-invocation: false --- # PR flow The rules this procedure carries out live in [`AGENTS.md`](../../../AGENTS.md) (**Contributing**, **Issue-driven work style**, **Responding to code reviews**, **Waiting on long-running work**). Board mechanics, including every board ID, are in `/board-ops`; creating a missing issue is `/issue-create`. This file names board columns and nothing else. **Pull requests against this repo are opened by the maintainers only.** Write access is not authorization to open one. Anyone else files a detailed issue (`/issue-create`) and a maintainer takes it from there. ## 1. Start from an issue **Every PR closes an issue.** A PR with no linked issue has no board card, so the work is invisible to the board. If there is no issue yet, create one first with `/issue-create`; never open the PR and backfill. **Read the issue in full, every comment included.** Scope changes, maintainer decisions and "not this, that" corrections are usually in the comments, not the body: ```sh gh issue view <N> --repo modelcontextprotocol/servers --comments ``` Then assign it to yourself and move its card to **In Progress** (the move-a-card recipe in `/board-ops`): ```sh gh issue edit <N> --repo modelcontextprotocol/servers --add-assignee @me ``` ## 2. Branch `v2/<type>/<N>-<slug>`, cut from **`origin/v2/main`** into a **new git worktree**, never by switching branches in the primary checkout. The rule, and the check that this session's own instructions are current, is `AGENTS.md` **Issue-driven work style** (all work in a worktree freshly cut from `origin/v2/main`). If that check, or the `SessionStart` hook, said `STALE`, stop here: a fresh branch does not refresh the rules this session loaded. Run it from the primary checkout. The worktree is a **sibling** directory named for the checkout plus the issue number (`servers` → `../servers-4810`), never a directory inside the repo, where every format, lint and typecheck scope would see a second copy of the source: ```sh git fetch origin v2/main git worktree add --no-track "../$(basename "$PWD")-4810" \ -b v2/fix/4810-filesystem-symlink-escape origin/v2/main cd "../$(basename "$PWD")-4810" npm install ``` - `--no-track` keeps the new branch from tracking `origin/v2/main`, so `git status` does not report your work as "ahead of v2/main", and the first push is an explicit `git push -u origin <branch>` to a branch of its own name. - ⚠️ **The `npm install` is part of the step.** A worktree starts with no `node_modules`, no `dist/` and no `.venv` (`/local-dev`). The root install builds every TypeScript server; a Python server builds its `.venv` on its first `uv run`. Background the install if you have edits to make first; the gate needs it finished. - Every later step (edits, the gate, commits, the push) runs **inside the worktree**. - The harness's `EnterWorktree` tool, where available, does the same; name the branch by the rule above. `<type>` follows the issue's type label: `bug` → `fix`, `enhancement` → `feat`, `documentation` → `docs`, `chore` → `chore`. A `question` has no branch type, because answering one ships nothing: if it turns out to need a change, relabel the issue with the type that change is, then branch. The `v2/` prefix matches the base branch and keeps the work legible in `git branch -a` next to `main`. **Never cut from `main`.** It is the release line and does not carry `v2/main`'s history, so the PR diff would show unrelated changes. **Stacking.** When one issue's work depends on another PR that has not merged yet, branch from that PR's branch (its worktree is cut from it: `git worktree add … -b <child> <parent-branch>`) and open the PR with `--base` set to it. Say in the body that it is stacked and on which PR. When the lower PR merges, retarget the stacked one to `v2/main` (`gh pr edit <PR> --base v2/main`) and rebase it if GitHub reports conflicts. ## 3. Sign off every commit (DCO) This repo adopted the [Developer Certificate of Origin](https://developercertificate.org/) (maintainer decision on #4861). Commit with **`git commit -s`**, every time. The rule is checked twice, by the same script (`scripts/verify-dco.mjs`): - **`npm run verify:dco`**, a stage of the pre-push gate (step 4), over `origin/v2/main..HEAD`: the commits you are about to push. Name another range with `-- --base <rev> --head <rev>` (a stacked branch's base, say). - **The `DCO signoff` job** (`.github/workflows/dco.yml`), on every pull request except into `main`, over the PR's `base.sha..head.sha`. What it checks: each commit carries a `Signed-off-by: Name <email>` trailer whose name **and** email match the commit's author or its committer. Merge commits and bot-authored commits are exempt. There is no partial credit: one unsigned commit out of six fails the whole check. The failure names each unsigned commit and prints the repair below. Two things that look like automation and are not: - ⚠️ **`git config format.signOff true` does nothing here.** Despite the name, it only defaults the `-s` flag for `git format-patch`. `git commit` never reads it, and there is no `commit.signoff` equivalent. - ⚠️ **A `prepare-commit-msg` hook works, but think before installing one.** The trailer is a certification, and a hook makes it on your behalf for _every_ commit, including work you merely cherry-picked. Inside that hook, `git var GIT_AUTHOR_IDENT` returns your config identity rather than the preserved author, so it cannot even tell it is signing for someone else. **Repairing commits already made** means rewriting them, onto the merge base the failure prints: ```sh git rebase --signoff <merge-base> git push --force-with-lease ``` `--signoff` signs each commit as you, the committer. Use `--force-with-lease` rather than `--force`, and rewrite only when you are the sole author and nobody has based work on the branch (a stacked PR above yours has). Nothing else clears the check: an empty "remediation" commit signs nothing that came before it, and the check reads every commit in the range. The signoff is a DCO assertion made in **your own name**. It does not claim you wrote the code, so signing off a cherry-pick is legitimate. Fabricating _someone else's_ certification never is. ## 4. Run the gate Format, then run the pre-push gate, and fix what fails before pushing: ```sh npm run format # TypeScript; in a Python server: uv run --frozen ruff format . npm run local:gate; echo "EXIT=$?" ``` `local:gate` runs every check CI runs, for both languages, whatever the change touched. Verify by the exit code, not by grepping the output. What each stage checks and how to fix a red one is `/pre-push-gate`; the stage list is [`docs/quality-gate.md`](../../../docs/quality-gate.md). One thing the gate deliberately leaves out: | Change touches | Also run | | --- | --- | | A skill's description, or a new skill | `npm run skills:eval` for the **whole** suite (spends model calls; not in the gate or CI). See `AGENTS.md` **Maintaining the skills** | ## 5. Client evidence A PR shows the change working, under the body's **How Has This Been Tested?** section (step 6). Here that means evidence from clients, not screenshots. **A change to server behavior** (a tool, resource, prompt, capability, transport or error it returns) records, for **both** the Inspector V2 and an LLM client, in **both** spec eras (a 2026-07-28 client and a 2025-11-25 client, per #4857): - what the client was asked to do (the Inspector action, or the prompt given to the LLM client), and - what it returned (the result, trimmed to what shows the change). A before/after pair is best when the change fixes a bug: the same request against `v2/main` and against the branch. **A change with no client-observable surface** (docs, skills, workflows, gate tooling, CI) carries a **targeted probe** instead: the one thing that proves it. For example, the guard made to fire on a planted defect and then pass, the workflow run that exercised the new job, the query that reads back the state a skill's recipe produced, or the `skills:eval` scores for a skill. Put the evidence in the PR body under **How Has This Been Tested?**. ## 6. Open the PR Base **`v2/main`** (or the lower branch, when stacked). **Never `main`.** Label it `v2`. The body's **first line is `Closes #<N>`**. The body carries these sections, in order. `.github/pull_request_template.md` is only the "issues, not PRs" banner that turns outside PRs away, so this list is where the structure lives: - **Description**: what changed and why. - **Server Details**: the server (or "none (repository-wide)") and what in it changed (tools, resources, prompts, docs, …). - **Motivation and Context**: the problem it solves; usually a pointer to the issue. - **How Has This Been Tested?**: the evidence from step 5. - **Breaking Changes**: whether users must change their client configuration. - **Types of changes**: tick each that applies: bug fix, new feature, breaking change, documentation update. - **Checklist**: answer every item. Tick each that holds, and tick and mark each that does not apply "(not applicable: <why>)"; leave none blank: - [ ] I have read the [MCP Protocol Documentation](https://modelcontextprotocol.io) - [ ] My changes follow MCP security best practices - [ ] I have updated the server's README accordingly - [ ] I have added a changeset (`npm run changeset`) if this changes what a TypeScript server publishes - [ ] I have tested this with an LLM client - [ ] My code follows the repository's style guidelines - [ ] New and existing tests pass locally - [ ] I have added appropriate error handling - [ ] I have documented all environment variables and configuration options - **Additional context** (optional): implementation notes or design decisions. Write the body to a file and pass it with `--body-file`. A body passed inline in double quotes goes through the shell, so every backtick in its Markdown runs as a command substitution and `$VAR` expands. Keep the file outside the worktree, where `git add -A` cannot pick it up. ```sh BODY=$(mktemp) cat > "$BODY" <<'EOF' Closes #<N> <the sections above, with the evidence> EOF gh pr create --repo modelcontextprotocol/servers \ --base v2/main --label v2 --title "<title>" --body-file "$BODY" ``` ⚠️ Closing keywords only link and auto-close for PRs that target the default branch (`main`). Against `v2/main`, `Closes #N` is only a cross-reference. Keep the line anyway, and **link the PR to the issue explicitly** right after opening it: ```sh PR=<PR_NUMBER>; N=<ISSUE_NUMBER> PR_ID=$(gh pr view "$PR" --repo modelcontextprotocol/servers --json id --jq .id) ISSUE_ID=$(gh issue view "$N" --repo modelcontextprotocol/servers --json id --jq .id) gh api graphql -f query=' mutation($issue:ID!,$pr:ID!) { addCloseIssueReferences(input:{issueId:$issue, pullRequestIds:[$pr]}) { issue { number } } }' -f issue="$ISSUE_ID" -f pr="$PR_ID" # Read the link back: the issue number must be listed. gh pr view "$PR" --repo modelcontextprotocol/servers \ --json closingIssuesReferences --jq '[.closingIssuesReferences[].number]' ``` The link does **not** make the issue close on merge into `v2/main`; that is still done by hand in step 9. Then move the card to **In Review** (`/board-ops`). The PR itself never goes on the board. ## 7. Request a Copilot review Only the GraphQL `requestReviews` mutation with the Copilot **bot id** works. REST, `gh pr edit --add-reviewer`, `userIds` and `copilot-swe-agent` all fail or silently drop the request. ```sh PR_ID=$(gh pr view <PR> --repo modelcontextprotocol/servers --json id --jq .id) gh api graphql -f query=' mutation($pr:ID!,$bot:[ID!]!) { requestReviews(input:{pullRequestId:$pr, botIds:$bot, union:true}) { pullRequest { id } } }' -f pr="$PR_ID" -f bot='BOT_kgDOCnlnWA' ``` A round usually lands in about five minutes. Wait for it with **one backgrounded loop that exits when the round lands, or when its deadline passes**, and wait for its notification rather than re-fetching once per turn. A review is remote state the harness cannot observe, which is the exception in `AGENTS.md` **Waiting on long-running work**, and this loop is where that poll belongs. ```sh PR=<PR> EXPECTED=1 # the review COUNT to reach; see below DEADLINE=$(( $(date +%s) + 20*60 )) while :; do # Capture first, so a gh failure stops the loop instead of being swallowed by # a pipeline. --slurp cannot be combined with --jq, hence the separate jq. raw=$(gh api --paginate --slurp \ repos/modelcontextprotocol/servers/pulls/$PR/reviews) || { echo "gh api failed ($?); not retrying blind" >&2; exit 1; } n=$(jq '[.[][] | select(.user.login | startswith("copilot-pull-request-reviewer"))] | length' <<<"$raw") || { echo "jq failed ($?) on an unexpected response shape" >&2; exit 1; } case $n in '' | *[!0-9]*) echo "not a count: '$n'" >&2; exit 1 ;; esac [ "$n" -ge "$EXPECTED" ] && { echo "round landed ($n reviews)"; break; } [ "$(date +%s)" -ge "$DEADLINE" ] && { echo "SILENT: no review by the deadline"; break; } sleep 30 done ``` `EXPECTED` is the review **count** to reach, so it is `1` only on the first round; on round two the first round's review is still there, and an existence check would return at once. Match the login with `startswith`: it carries a `[bot]` suffix. `sleep 30` is the remote-API floor `AGENTS.md` sets. **Every step that can fail exits the loop rather than retrying**: piping the count into `awk` would make an auth error read as `0`, and an empty count from a `jq` failure would make the comparison fail forever, so the job sleeps and retries without end. A background task that can never succeed is worse than none, because it looks like progress. Once the body lands, give the inline comments about another 60 seconds: they arrive after it (step 8). ## 8. Respond to the review Judge each finding against **the issue the PR closes**, as `AGENTS.md` **Responding to code reviews** says: fix defects in what the PR added; decline scope creep (pre-existing behavior, new capabilities, hardening the issue did not ask for) with a reason, and file an issue (`/issue-create`) for any that is worth doing on its own. Implementing a suggestion differently is fine. - **Reply to each review comment in its own thread**, saying what was done (with the commit) or why it was declined. That reply is the primary response, and it is not optional: each comment is a thread - .claude/skills/pre-push-gate/evals/evals.json (1271 bytes)
[ { "prompt": "npm run local:gate just failed at the verify:install-fresh stage. What do I do?", "expect": "pre-push-gate" }, { "prompt": "The gate printed 'gate-lease: pid 4412 holds the gate lease; waiting for its turn'. Is something stuck? Should I skip the lease?", "expect": "pre-push-gate" }, { "prompt": "The boot smoke stage went red for the git server over stdio. How do I work out what is wrong?", "expect": "pre-push-gate" }, { "prompt": "I ran the pre-push gate in the background and the task says exit code 0. How do I confirm it really passed?", "expect": "pre-push-gate" }, { "prompt": "validate:py reports FAIL for fetch at the sync step during the gate. How do I fix it?", "expect": "pre-push-gate" }, { "prompt": "verify:no-test-retries is failing in my gate run but I never added a test retry. What is it matching?", "expect": "pre-push-gate" }, { "prompt": "The coverage stage of my gate run went red, but the last report it printed was all green. How do I find what failed and fix it?", "expect": "pre-push-gate" }, { "prompt": "What is 17 multiplied by 23?", "expect": null }, { "prompt": "Write a limerick about a cat.", "expect": null } ] - .claude/skills/pre-push-gate/SKILL.md (17041 bytes)
--- name: pre-push-gate description: "Run this repo's pre-push gate and fix it when it goes red. Use when npm run local:gate fails or a stage of it does (verify:install-fresh, a root guard, lint, typecheck, ruff, pyright, pytest, verify:skills:cli, the boot smoke); when the gate says it is waiting on the gate lease; or when checking whether a gate run really passed." disable-model-invocation: false --- # The pre-push gate **The rule** (stated in [`AGENTS.md`](../../../AGENTS.md#before-pushing)): run **`npm run local:gate`** before every push, and push only when it exits 0. `npm run validate` is the inner-loop check and is **not** a substitute. What each stage covers, and how the gate relates to CI, is [`docs/quality-gate.md`](../../../docs/quality-gate.md). The stage list is written out there and nowhere else, on purpose. This skill is how to run the gate and what to do when it goes red. ## Run it ```sh cd <repo root> npm run format # TypeScript. It rewrites files; the gate only checks. npm run local:gate; echo "EXIT=$?" ``` In a Python server you changed, format with `uv run --frozen ruff format .` from that server's directory. **Verify by exit code, not by grepping the output.** A Prettier failure is a few `[warn]` lines that match no obvious failure pattern, and `validate:py` prints `PASS` for two servers above the `FAIL` for the third. ⚠️ If you run it as a background task, the harness's "exit code 0" notification describes the _wrapper_ (the trailing `echo`), not the gate. Read the `EXIT=` line. **Background it and wait for the notification.** Do not spend turns tailing the log; see `AGENTS.md` **Waiting on long-running work**. The gate stops at the first failing stage, so the last stage header in the output is the one that failed. Fix it, then **re-run the whole gate**, not just that stage: the stages after it have not run yet. ## Diagnosing a failing stage Each heading is a stage or guard name as it appears in the output. ### `verify:install-fresh` An installed package's version disagrees with `package-lock.json` (`node_modules` is older than the tree you pulled), or a `package.json` declares a dependency the lockfile does not record. **Run `npm install` at the repo root**, commit the lockfile if it changed, and re-run. It is the first stage because a stale install otherwise passes every static check and fails later as a test reporting the _old_ dependency's behavior. Do not "fix" that test. ### `verify:dco` A commit in `origin/v2/main..HEAD` has no `Signed-off-by:` trailer, or one whose name and email match neither its author nor its committer. The output names each commit and the repair: `git rebase --signoff <merge-base>`, then `git push --force-with-lease` if it was already pushed. Commit with `git commit -s` from then on. The rule, and when a rewrite is safe, is `pr-flow` step 3. "cannot resolve origin/v2/main" means the ref is missing from this clone: `git fetch origin v2/main`. On a stacked branch the gate also checks the lower branch's commits; `npm run verify:dco -- --base <lower branch>` checks only yours. ### `format:check` / `format:check:root` Run `npm run format` at the **root**. It covers `scripts/`, the root configs and every workspace; a single workspace's `format` does not. ### `verify:format-coverage` A tracked source file is matched by no `format:check` glob, so nothing checks its formatting. Put it where a glob reaches it, or extend the glob. Do not add it to `.prettierignore` to make the guard pass. ### `verify:skills` / `verify:skills:cli` A `.claude/skills` manifest does not parse, declares no `disable-model-invocation`, a model-invoked skill lacks its eval cases, or the listing is over budget. The message names the skill. The usual cause is an unquoted `#` or `:` in a `description`. `verify:skills:cli` is the authoritative validator. It fetches the pinned Claude Code CLI with `npx` when the installed one is a different version, so it **fails offline**. (`validate:py`'s `sync` step is the other stage that can: `uv sync --locked` downloads when a server's environment is missing or stale. `coverage:py` opens with the same sync, a no-op once `validate:py` has run.) ### `verify:typecheck-coverage` A tracked `.ts` file lands in no `tsc` program. Usually a new test or config file outside the server's `tsconfig.test.json` `include`. Add it there. ### `verify:dep-lockstep` Two workspaces declare different ranges of a shared toolchain package (`typescript`, `vitest`, `@vitest/coverage-v8`, `prettier`, `@types/node`). Bump it in **every** workspace that declares it, then `npm install`. ### `verify:no-test-retries` A test declares a retry: Vitest's `retry:` option or `--retry` flag, a pytest rerun plugin, or a `flaky` marker. Remove it and fix why the test fails. A race is fixed with fake timers or an awaited condition; a port collision with a port the OS hands out. The guard matches spellings, not semantics, so an unrelated `retry:` property in server source trips it too. Rename the property, or restructure so the key is not written as `retry:` at the start of an expression. ### `verify:action-pins` A job that holds a credential, one whose artifact such a job downloads, or one whose outputs such a job reads, uses an action by a tag (`actions/checkout@v6`) or by a SHA with no exact-version comment. The finding names the workflow, the job and the `uses:` value. Pin it as `owner/repo@<40-hex sha> # vX.Y.Z`, resolving both from one lookup: ```sh ACTION=actions/checkout TAG=v6.1.0 echo "uses: $ACTION@$(gh api "repos/$ACTION/commits/$TAG" --jq .sha) # $TAG" ``` If the job should not have become credentialed, that is the real fix: the guard counts `id-token: write` or `packages: write` (the job's own, or the workflow's when the job declares none); any secret other than `GITHUB_TOKEN`; an `upload-artifact` in a job that a credentialed downloader has anywhere in its `needs` chain; a reusable-workflow call in that position; and any job whose outputs a credentialed job reads (`needs.<job>.outputs`), which is why `release.yml`'s `detect-packages` is pinned although it holds no credential itself. A local `./…` action or workflow in such a job is reported as well. A YAML alias in such a job is reported too; spell the ref out. The rule is in `AGENTS.md` **Credentialed workflow jobs**. ### `test:scripts` A guard's own unit test failed. Two of these are about the gate itself and mean a change broke one of its invariants (`scripts/lib/workflow-gate.test.mjs`): - **"GitHub CI must not run a local-only script"**: a workflow invokes a `local:*` script. Call the underlying checks as their own steps instead. - **"every CI job needs a timeout"**: a job was added without `timeout-minutes`. - **"local:gate must run …"**: a stage was dropped from `local:gate:stages`, or `local:gate` is no longer exactly the lease wrapper. Do not edit the guard to make these pass; the split they enforce is the design. ### `lint` **There is no warning tier.** Every `lint` script runs `--max-warnings 0`, so a warning fails exactly as an error does. Fix the finding. If a rule genuinely must be waived on one line, use its inline disable comment **with a one-line justification**; never widen an ignore list or turn the rule off. ### `typecheck` / `build` `typecheck` runs `tsc -p tsconfig.test.json` (source and tests); `build` runs the server's own `tsc`. An error in a test file only shows in `typecheck`. ### `test` (a TypeScript workspace) Re-run just that suite to iterate: `npm test -w src/<server>`. Read the failure before changing a timeout: an assertion that races is a bug in the test. ### `coverage` A TypeScript file is below 90% on lines, statements, functions or branches. Vitest names each file and dimension: ``` ERROR: Coverage for branches (71.42%) does not meet global threshold (90%) for roots-utils.ts ``` ("global threshold" is Vitest's wording; with `perFile: true` it is checked per file.) The root `npm run coverage` carries on into the remaining workspaces after a failure, so **the failing report is not the last thing printed**: find the `npm ERR!` block, which names the workspace (`in workspace: @modelcontextprotocol/server-<name>`), and read the `ERROR:` lines just above it. 1. Re-run that server alone: `npm run coverage -w src/<server>`. 2. Read its per-file table. The `Uncovered Line #s` column is where the missing tests go (a long list is truncated to `...`, and a long file name to `...-name.ts`; open `coverage/index.html` in the workspace, or narrow the run, for the full list). A branch shortfall with no uncovered lines is the untaken side of a condition, `??`, `?.` or default parameter. 3. **Write the tests.** Drive what a client sees through a `Client` over the in-memory transport; call a helper directly only for its logic (`testing` skill). 4. Only for code that genuinely cannot run, annotate it at the source with its reason, `/* v8 ignore next -- <reason> */` (or `start`/`stop` around a block). A branch that is merely awkward to reach is not unreachable. **Never lower a threshold, drop `perFile`, or widen the coverage `exclude`** to get green; the gate is the rule in `AGENTS.md` **Always test new or modified code**. A failing _test_ in this stage is an ordinary test failure: fix it as under `test`, above. ### `validate:py` The summary at the end names the failing server, and the step that failed is the last `[validate:py] <server>: <step>` line above it. Re-run one server with `npm run validate:py -- <server>`. | Step | Fix | | --- | --- | | `sync` | `uv.lock` no longer matches `pyproject.toml`. Run `uv lock` in that server and commit the lockfile | | `ruff check` | Fix the finding; `uv run --frozen ruff check --fix .` handles the mechanical ones | | `ruff format --check` | `uv run --frozen ruff format .` | | `pyright` | A type error. Add the missing hint rather than an ignore | | `pytest` | `uv run --frozen pytest -k <name>` in that server to iterate | | `build` | A packaging error in `pyproject.toml` | `uv: command not found` means `uv` is not installed. Never substitute `pip`. ### `coverage:py` The Python per-file coverage gate: every file each server measures must reach **90% on lines and 90% on branches**. The summary names the server, the step, and for a shortfall each file and dimension below 90: ``` FAIL time — per-file check (2 below 90%) src/time/src/mcp_server_time/server.py: lines 84.2% (75/89) is below 90% src/time/src/mcp_server_time/server.py: branches 78.5% (11/14) is below 90% ``` Re-run one server with `npm run coverage:py -- <server>`. The per-file table above the summary gives both figures for every file, and coverage.py's own report above that (`term-missing`) lists the uncovered lines and partial branches (`120->124` is the jump from line 120 to 124 never taken). | Step | Fix | | --- | --- | | `sync` | As for `validate:py`: run `uv lock` in that server and commit the lockfile | | `pytest --cov` | A test failed, so no verdict was reached; fix it as for `validate:py`'s `pytest`. `unrecognized arguments: --cov` means `pytest-cov` is missing from the server's dev dependencies | | `per-file check`, "below 90%" | Write tests for the lines and branches the report lists. Drive the server in-process through a `ClientSession` where you can (`/testing`) | | `per-file check`, "was not written" or "measured no files" | The run produced no usable `coverage.json`: check the server's `[tool.coverage.run]` (`branch = true`, `source` naming its package) | | `per-file check`, "not measured with branch coverage" or "no covered_branches/num_branches" | `branch = true` is missing from `[tool.coverage.run]`. The check refuses such a report rather than counting every file's zero branches as 100% | **Never lower the gate**, and never drop a file from `source` to clear it. Code that genuinely cannot run (a guard the types already rule out, a branch the SDK's input validation makes unreachable) is marked at the source with `# pragma: no cover # <reason>`; every pragma carries its reason (`AGENTS.md` **Always test new or modified code**). A pragma on a line that is merely awkward to test is not justified; write the test. ### `smoke` `smoke — FAIL <server> over <transport>` followed by the reason and the tail of the server's stderr. Re-run a subset with `node scripts/smoke-servers.mjs <server> [<server> …]`. - **"dist/index.js does not exist — build first"**: you ran the smoke on its own before building. `npm run build -w src/<server>`. Inside the gate this cannot happen, since `validate` builds first. - **".venv does not exist — sync first"**: the same for a Python server. The smoke never creates an environment; `npm run validate:py -- <server>` does. - **The server exited before answering**: the stderr tail shows why. This is what the smoke is for: the unit tests import the source, so a wrong `bin` path, a file missing from `dist/`, or an import that only resolves under the test runner passes them and fails here. - **"tools/list does not include …"**: a tool was renamed or removed. A published tool is never renamed (`AGENTS.md` **MCP protocol**); if the change is intended, update that server's entry in `SERVERS`. - **A new server fails `test:scripts`** with "every server directory in the repo has a smoke entry": add it to `SERVERS` in `scripts/smoke-servers.mjs`. ### `interface-diff` The last 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 server was selected; a change that touches no server prints `no server changed` and passes. What selects a server is in [`docs/quality-gate.md`](../../../docs/quality-gate.md). **A changed interface does not fail it**: the report is what the PR's sticky comment will show, so read it, and if a change is not one you meant, that is the finding. It fails only when the diff cannot run, with `❌ The interface diff could not run` and the reason: - **"origin/v2/main is not available"**: `git fetch origin v2/main`. - **"src/<server>/dist/index.js does not exist"**: you ran it on its own before building: `npm run build -w src/<server>`. - **"src/<server>/.venv does not exist"**: a Python server was not synced: `cd src/<server> && uv sync --frozen --all-extras --dev` (the gate's `validate:py` does it). - **"does not exist at the base"**: the server is new on this branch, so there is no base to diff it against. - **An `npm ci`, `npm run build` or `uv sync` failure**: the _base_ did not install or build. Offline with a cold npm cache is the usual cause; otherwise name a base that builds with `npm run interface-diff -- --base <ref>`. - **"Base server probe failed" / "Target probe failed"**: a serve - .claude/skills/project-structure/evals/evals.json (1005 bytes)
[ { "prompt": "I need to add a command-line flag to the time server. Does that go in the same file as the tool handlers or somewhere else?", "expect": "project-structure" }, { "prompt": "Does a new helper for the filesystem server's path checks belong in its entry file or in a module of its own?", "expect": "project-structure" }, { "prompt": "I'm adding a new transport to the everything server. Which files do I need to create or touch?", "expect": "project-structure" }, { "prompt": "How do I add a second tool to the git server? Is there a tools directory to put it in?", "expect": "project-structure" }, { "prompt": "Two of the servers need the same small helper. Does it go in a shared package or do I put a copy in each?", "expect": "project-structure" }, { "prompt": "Explain the difference between a mutex and a semaphore.", "expect": null }, { "prompt": "What is the capital of Australia?", "expect": null } ] - .claude/skills/project-structure/SKILL.md (8623 bytes)
--- name: project-structure description: "Find where code lives in this repo's seven servers and decide where a new file goes. Use when choosing the file or directory for a new tool, resource, prompt, transport, helper module, command-line flag or root script; when a server's layout is unclear; or when asking whether code belongs in a server's entry file or a module of its own." disable-model-invocation: false --- # Project structure The top-level tree, with each server's package name and registry, is in [`AGENTS.md`](../../../AGENTS.md) under **Project structure**. This skill is the level below it: what is inside each server, and where a new file goes. Test placement and harnesses are `/testing`; building and running a server is `/local-dev`. There is **no shared library between servers**. Each directory under `src/` is a complete package that versions and publishes on its own, so a helper two servers need is written in both (`expandHome` exists in `filesystem` and in `memory`, and the copy in `memory` says so). Do not add a cross-server import. ## The TypeScript servers All four are npm workspaces of the root `package.json` and share one shape: the 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`. | Server | Layout | Where its features are registered | | --- | --- | --- | | `everything` | `index.ts` picks a transport from `argv`; `server/` holds the factory; `tools/`, `resources/`, `prompts/` hold one file per feature plus an `index.ts`; `transports/` holds one file per transport; `version.ts` reads the package version; `docs/` is shipped | Each feature file exports a `register…` function, wired into its area's `index.ts` (`registerTools`, `registerResources`, `registerPrompts`), which `server/index.ts` calls from `createServer()` | | `filesystem` | `index.ts` is the entry point (argv → transport and allowed directories, `main()`); `http.ts` serves the factory over Streamable HTTP; `server.ts` exports `createServer(allowedDirectories)`; `lib.ts` holds the file operations and path validation, with the allow-list passed in rather than held globally; `path-utils.ts`, `path-validation.ts` and `roots-utils.ts` are focused helpers, and `pinned-directory.ts` runs the write operations inside their verified directory; `version.ts` reads the package version | Inline in `createServer()` in `server.ts`, with `server.registerTool(...)` | | `memory` | `index.ts` holds the `KnowledgeGraphManager`, `createServer(memoryFilePath)`, the stdio `main()` and `run()`, which picks the transport; `http.ts` serves the factory over Streamable HTTP; `version.ts` reads the package version | Inline in `createServer()`; the resource and its subscription handlers are exported `register…` functions in the same file | | `sequentialthinking` | `index.ts` holds `createServer()`, the stdio `main()` and `run()`, which picks the transport; `http.ts` serves the factory over Streamable HTTP; `lib.ts` holds `SequentialThinkingServer`, the logic; `version.ts` reads the package version | Inline in `createServer()` | Three things about `everything` that the table cannot hold: - **`server/index.ts` exports `createServer()`**, which returns `{ server, cleanup }`. Every transport file calls it, once per stdio process or once per HTTP session. A tool that depends on what the client can do (roots, sampling, elicitation) is registered through `registerConditionalTools`, which runs after `initialize`, not through `registerTools`. - **`docs/` is part of the server, not only documentation.** The build copies it into `dist/docs`, every file in it is served as a static resource, and `docs/instructions.md` is returned as the server's `instructions`. A file added there becomes a resource a client can list. - **Its own maps are `src/everything/docs/structure.md` and `src/everything/docs/extension.md`.** A change to the server's files updates `structure.md`, and `src/everything/AGENTS.md` holds the rules that apply only inside that directory. **No server starts on import.** Each one builds its server in a `createServer(...)` factory, and its entry file connects a transport only when it is the process entry point (an `isEntryPoint()` or `isMainModule()` check that compares real paths, so the npm bin symlink still starts it). Keep it that way: a module that binds a port, connects stdio or installs a signal handler at import cannot be driven in-process by the tests. `/testing` covers the in-process harness. ## The Python servers `fetch`, `git` and `time` are independent `uv` projects with the same layout: ``` src/<server>/ ├── pyproject.toml dependencies, the console script, pytest and coverage config ├── uv.lock, .python-version ├── src/mcp_server_<name>/ │ ├── __init__.py main(): the command-line flags, then asyncio.run(serve(...)) │ ├── __main__.py python -m mcp_server_<name> │ ├── transport.py --transport: stdio, or Streamable HTTP on $HOST:$PORT │ └── server.py everything else └── tests/ pytest suite, driving serve() in-process ``` `server.py` holds the Pydantic input models, the functions that do the work, and `serve()`. `serve()` constructs the `Server`, declares the tools (and, in `fetch`, the prompts) with the `@server.list_tools()` / `@server.call_tool()` decorators inside its body, and then runs it over stdio. So a new tool is a set of edits in `server.py`: its input model, its entry in `list_tools`, and its branch in `call_tool`. In `git` and `time` there is a fourth: tool names are members of an enum (`GitTools`, `TimeTools`) that `list_tools` and `call_tool` both dispatch on, so the new name is added there first. `fetch` has one tool and no enum. The `Server` object is local to `serve()` and not importable. ## Where to put a new file | It is… | It goes in | | --- | --- | | A tool, resource or prompt for `everything` | Its own kebab-case file in `tools/`, `resources/` or `prompts/`, exporting a `register…` function, wired into that directory's `index.ts` | | A transport for `everything` | `src/everything/transports/`, plus a `case` in `src/everything/index.ts` and a `start:…` script | | A tool for `filesystem`, `memory` or `sequentialthinking` | A `server.registerTool(...)` call inside that server's `createServer()` (`server.ts` in `filesystem`, `index.ts` in the other two); the logic it calls goes in `lib.ts` (or the class it extends) | | A helper module for `everything` | A kebab-case `.ts` file in the feature area it supports, beside its users (`server/logging.ts`, `server/roots.ts`, `resources/session.ts`), imported with the `.js` extension | | A helper module for `filesystem`, `memory` or `sequentialthinking` | A kebab-case `.ts` file at the workspace root, imported with the `.js` extension | | A tool for a Python server | `server.py`: the tool-name enum member (`git`, `time`), the model, the `list_tools` entry, the `call_tool` branch | | A command-line flag for a Python server | `__init__.py`, passed into `serve()` | | A test | `/testing` | | Root tooling (a guard, a release helper) | `scripts/<name>.mjs`, with a sibling `<name>.test.mjs` when it has logic worth testing; shared helpers in `scripts/lib/` | | A design document | `docs/` | | A procedure for agents | `.claude/skills/<name>/SKILL.md`, with a row in the Skills index | A new server directory is not on this list: the repository does not accept new servers (`CONTRIBUTING.md`). ## What a new file is checked against A TypeScript file in a new location is still inside the gate, because two guards enumerate tracked files rather than trusting a glob: `verify:typecheck-coverage` fails when a tracked `.ts` file is in no project that `typecheck` runs, and `verify:format-coverage` fails when a tracked source file matches no `prettier --check` glob. Both run in `npm run validate:guards`. If one fires on a file you added, the fix is to bring the file into the existing config, not to exclude it. When a file or directory is added, removed, renamed or given a different purpose, every entry that describes it changes in the same PR (`AGENTS.md`, **Maintenance rules**): the root `README.md`, the server's own `README.md`, the tree in `AGENTS.md`, and for `everything`, `docs/structure.md`. - .claude/skills/release/SKILL.md (39340 bytes)
--- name: release description: "Cut a milestone release: the release issue, the preparation PRs on v2/main (audit, changesets Version Packages, Python CalVer), the pure v2/main to main merge PR with its release ledger, then the GitHub Release a maintainer publishes." disable-model-invocation: true --- # Cutting a milestone release How versions and publishing work, and what to do when a publish fails, is [`RELEASING.md`](../../../RELEASING.md). This skill is the procedure for one milestone, start to finish. It is started by name only (`/release`), because a release is never something to begin by inference. A release is cut from **`main`**, after the milestone's work has been merged there from `v2/main`. Nothing publishes from `v2/main`: `release.yml` refuses a Release whose commit is not on `main`. **What stays human.** Publishing the GitHub Release and approving the `release` environment deployments are a maintainer's acts. So is merging any PR. Prepare, verify and recommend; do not perform those. ## 0. Check this session's instructions first A release is the longest-running session and the costliest to get wrong, and it follows this skill and `AGENTS.md` exactly as they were when the session started. Before step 1, run the staleness check in `AGENTS.md` **Issue-driven work style** (all work in a worktree freshly cut from `origin/v2/main`), whatever the `SessionStart` hook printed: the hook ran when the session began, and this check runs now. On `STALE`, or a `STALE` line from the `SessionStart` hook, **stop** and ask for a session started in a fresh worktree. The v2.0.0 release ran its first three steps on a `release` skill 447 commits out of date (#5167). Re-run the check after each preparation PR merges, since `v2/main` moves under the session, **from the session-start revision, not `HEAD`**: this flow moves between worktrees (step 4e moves the verification worktree onto a newer candidate), and a newer worktree's `HEAD` says nothing about the rules this session loaded. The hook prints that revision and the re-check command. ## The shape One **release issue**, up to three **preparation PRs** on `v2/main`, one **merge PR** into `main`, then the **Release**. In that order: each step needs the one before it merged. | | Preparation PRs | The merge PR | | --- | --- | --- | | Base | **`v2/main`** | **`main`** | | Carries | The audit's forced fixes; the TypeScript version bumps; the Python version stamps | The milestone's work, arriving whole from `v2/main`. **No commits of its own** | | References the release issue with | `Closes #N` (a cross-reference only, on `v2/main`) | `Part of #N` (**non-closing**: `main` is the default branch, where `Closes` would close the issue before anything is published) | | Verified by | `npm run local:gate`, CI | `npm run local:gate`, **plus** `npm run pack:verify`, **plus** every milestone issue exercised, written up as the **release ledger** | ⚠️ **Do not fold them together.** A version bump made on the merge branch exists only downstream of `v2/main`, and nothing carries it back: the develop branch would keep reporting the previous version, and the next branch cut from it would too. ## 1. The release issue One per milestone, titled **`Release vX.Y.Z`** (the milestone's name), filed through `/issue-create`: type `chore`, no server-scope label, the milestone it releases. It is what every PR below references, so file it first. Set its card to **In Progress** (`/board-ops`). It stays open until the Release is published (step 6), whatever merges in between. ```sh N=<RELEASE_ISSUE_NUMBER> MILESTONE=vX.Y.Z ``` **Check the milestone is complete** before preparing anything. The only open issue left in it should be the release issue itself: ```sh gh issue list --repo modelcontextprotocol/servers --milestone "$MILESTONE" \ --state open --json number,title --jq '.[] | "#\(.number) \(.title)"' ``` Anything else open is either finished first or moved to the next milestone by a maintainer. Do not release around it silently. ## 2. Preparation PRs, on `v2/main` All three are part of the milestone's work, so all three land on the develop branch and reach `main` with everything else. **All are merged before the merge PR is opened.** A milestone that touches only one language, with a clean audit, has one. Each branch this skill cuts by hand (the audit, the hand-run CalVer stamp, the merge branch) goes into **its own sibling worktree**, as `/pr-flow` step 2 does, never by switching branches in the primary checkout. Run each recipe from the primary checkout; the worktree is named for the checkout, the release issue and the branch's role, since one issue owns several branches. ### 2a. The audit Audit first, so the version bumps sit on a tree that was just checked. ```sh git fetch origin v2/main git worktree add --no-track "../$(basename "$PWD")-$N-audit" \ -b "v2/chore/$N-release-audit" origin/v2/main cd "../$(basename "$PWD")-$N-audit" && npm install # npm: one lockfile covers the root and all four TypeScript workspaces. npm audit --audit-level=high # Python: each server has its own lockfile. `uv` has no audit of its own in the # version pinned here, so the locked requirements go through pip-audit. # Exported to a file first: piped straight in, a failed `uv export` hands # pip-audit empty input, which it reports as clean. And pip-audit exits # non-zero both when it finds something and when it could not run, so a # server counts as audited only when its output holds a verdict. The block # runs in a subshell that exits non-zero if any server was not audited. ( unaudited= for s in fetch git time; do echo "== $s" REQ=$(mktemp) OUT=$(mktemp) if (cd "src/$s" && uv export --frozen --no-emit-project --format requirements-txt) > "$REQ" \ && [ -s "$REQ" ]; then uvx pip-audit --require-hashes --disable-pip -r "$REQ" > "$OUT" 2>&1 cat "$OUT" grep -qE 'No known vulnerabilities found|Found [0-9]+ known vulnerabilit' "$OUT" || { echo "AUDIT DID NOT RUN for $s: no verdict in its output" >&2 unaudited="$unaudited $s" } else echo "EXPORT FAILED for $s: nothing was audited" >&2 unaudited="$unaudited $s" fi rm -f "$REQ" "$OUT" done [ -z "$unaudited" ] || { echo "NOT AUDITED:$unaudited" >&2; exit 1; } ); echo "python audit complete: EXIT=$?" ``` **This step is a report.** Read it; do not let a tool rewrite the tree. The `EXIT=` line says whether every Python server was audited, not whether the audit was clean: `pip-audit`'s findings are in the output above it. ⚠️ **Never `npm audit fix`**, with or without `--force`. `AGENTS.md` **Dependencies** rules it out: it resolves an advisory that has no upward escape by silently downgrading, and the gate does not detect a version going backwards. Each finding gets one of three outcomes, decided by a person: - **A fix inside the declared range**: a direct bump, or an `overrides` entry (npm) or a raised lower bound plus `uv lock` (Python). Each fix is **its own commit**, and a fix to a TypeScript server's runtime dependencies carries a changeset. - **A fix that needs a major**: its own issue and its own PR, not a release-day edit. - **No fix available, or not reachable from the server**: say so in the report, with the reason. Post the report as a comment on the release issue. If fixes were forced, open the PR (`/pr-flow`), body starting `Closes #N`, with the report in it. **If none were, there is no audit PR**: an empty PR is not evidence, the comment is. ### 2b. The TypeScript version bumps: "Version Packages" `version-packages.yml` keeps this PR open whenever `.changeset/` holds pending changesets. Find it: ```sh gh pr list --repo modelcontextprotocol/servers --base v2/main \ --head changeset-release/v2/main --json number,title,url ``` No PR means no TypeScript server has a pending changeset. Check that is true rather than assuming it, since a TypeScript change merged without its changeset releases nothing: ```sh # Refresh first, and read the REMOTE tree: the checkout may be a preparation # branch cut before another PR merged. git fetch origin main v2/main --tags git ls-tree -r --name-only origin/v2/main .changeset/ | grep '\.md$' | grep -vx '.changeset/README.md' # the pending changesets # Since the latest published Release, asked of GitHub: this repo's tags do not # sort into release order (see 5a). PREV=$(gh release view --repo modelcontextprotocol/servers --json tagName --jq .tagName) git log --oneline "$PREV"..origin/v2/main -- \ src/everything src/filesystem src/memory src/sequentialthinking ``` If the second command lists changes to what a server publishes and the first lists no changeset for that server, add the missing changeset through an ordinary PR first. Then, on the PR: 1. **Link it to the release issue, and leave a comment.** The action rewrites the PR's body on every push to `v2/main`, so a `Closes` line there would not survive; this is the exception `AGENTS.md` names. The link lives outside the body, so make it now, with the `addCloseIssueReferences` mutation from `/pr-flow` (step 6), and read it back. On `v2/main` it closes nothing at merge. Then comment `Part of #N`, the textual record that every rewrite leaves alone: ```sh PR=<VERSION_PACKAGES_PR> gh pr comment "$PR" --repo modelcontextprotocol/servers --body "Part of #$N" ``` 2. **Wait for its CI to pass.** The workflow token's push starts no workflow, so the Version Packages workflow dispatches the TypeScript, Python, DCO and MCP interface diff workflows on `changeset-release/v2/main` after each update. A PR does not list dispatched checks, so the result shows as four commit statuses: `TypeScript (dispatched)`, `Python (dispatched)`, `DCO (dispatched)` and `Interface diff (dispatched)`. The PR may also list `DCO signoff` and the diff as pending or failed with no jobs: GitHub holds the token's `pull_request` runs (#5173), so read the statuses instead. Closing and reopening the PR does not start the CI workflows (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`). 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 new versions. 4. **Put `Part of #N` as the body's first line, immediately before the merge**, once nothing else will land on `v2/main` first: any push there regenerates the body and drops the line. ```sh # Read the body first, and edit only on a successful, non-empty read: a # failed read must never replace the generated release notes with the # prefix alone. OLD=$(gh pr view "$PR" --repo modelcontextprotocol/servers --json body --jq .body) \ && [ -n "$OLD" ] \ && printf 'Part of #%s\n\n%s\n' "$N" "$OLD" \ | gh pr edit "$PR" --repo modelcontextprotocol/servers --body-file - \ || echo "body read or edit FAILED — PR body left as it was" >&2 ``` 5. A maintainer merges it, **first checking the line is still the body's first**. If a push regenerated the body in between, repeat step 4: ```sh gh pr view "$PR" --repo modelcontextprotocol/servers \ --json body --jq '.body | split("\n")[0]' # must print: Part of #N ``` ### 2c. The Python version stamps: "Prepare Python Release" Do this **last**, close to the release: it stamps the date it runs on. ```sh gh workflow run prepare-python-release.yml --repo modelcontextprotocol/servers \ --ref v2/main -f issue="$N" ``` It opens a PR that starts with `Closes #N`, on a branch named `v2/chore/<N>-python-calver-<date>`, labeled `v2`, and dispatches the TypeScript, Python, DCO and MCP interface diff workflows on that branch, as the Version Packages workflow does. No PR means no Python server has a shipped change since its last stamp. Then, on the PR: 1. **Link it to the release issue.** Its `Closes #N` is only a cross-reference on `v2/main`, and the workflow makes no API call, so link it with the `addCloseIssueReferences` mutation from `/pr-flow` (step 6) and read it back: `closingIssuesReferences` must list `#N`. On `v2/main` it closes nothing at merge. Find the PR by its branch: ```sh gh pr list --repo modelcontextprotocol/servers --base v2/main \ --json number,headRefName,url \ | jq --arg p "v2/chore/$N-python-calver-" '.[] | select(.headRefName | startswith($p))' ``` 2. **Wait for its four `(dispatched)` statuses to pass**, check that each stamped package really changed, and a maintainer merges it. ⚠️ GitHub only dispatches a workflow that exists on the default branch. Until the first milestone merge carries this one to `main`, do it by hand, which is the same script: ```sh git fetch origin v2/main git worktree add --no-track "../$(basename "$PWD")-$N-calver" \ -b "v2/chore/$N-python-calver-$(date -u +%Y.%-m.%-d)" origin/v2/main cd "../$(basename "$PWD")-$N-calver" && npm install node scripts/prepare-python-release.mjs # prints "name: old -> new" per stamped package git commit -s -am "chore: stamp Python CalVer versions for $(date -u +%Y.%-m.%-d)" ``` then open the PR through `/pr-flow`, body starting `Closes #N`. Its step 6 links the PR to the release issue and reads the link back, as step 1 above does for the workflow's PR: do not skip it. ## 3. The merge PR: `v2/main` → `main` Open it only when every preparation PR has merged. The merge branch is `v2/main` under another name: cut from `origin/v2/main`, with nothing added. The merge itself is made by GitHub when the PR merges, so `main` gets exactly one merge commit and the PR has no commit of its own. (Merging locally first would put a merge commit on the branch, and merging the PR would then add a second.) ```sh git fetch origin main v2/main git worktree add --no-track "../$(basename "$PWD")-$N-merge" \ -b "v2/chore/$N-release-$MILESTONE" origin/v2/main cd "../$(basename "$PWD")-$N-merge" ``` **The merge's result is the release candidate. Prove it will be `v2/main`'s tree before opening the PR:** ```sh git rev-parse 'origin/v2/main^{tree}' git merge-tree --write-tree origin/main HEAD # must print the same hash, and nothing else ``` `git merge-tree` computes the tree the merge into `main` would produce, without touching the checkout. A different hash, or conflict output, means `main` holds a change `v2/main` does not. That is a change that exists only downstream of the develop branch. Stop and find out what it is, rather than pushing. Open the PR against **`main`**, labeled `v2`. Its body's first line is **`Part of #N`**, not `Closes #N`: ```sh BODY=$(mktemp) cat > "$BODY" <<EOF Part of #$N Milestone merge for $MILESTO - .claude/skills/security-advisory/evals/evals.json (1472 bytes)
[ { "prompt": "Someone just reported a path traversal in the filesystem server through the private vulnerability form. What do I do with it?", "expect": "security-advisory" }, { "prompt": "A privately reported vulnerability against the fetch server looks like it's really in the Python SDK's HTTP handling. How do I handle that?", "expect": "security-advisory" }, { "prompt": "How do I get a private fork for an accepted advisory so I can write the fix without it being visible?", "expect": "security-advisory" }, { "prompt": "How do I reply to the person who reported a vulnerability to us privately?", "expect": "security-advisory" }, { "prompt": "The fix for a privately reported vulnerability in the git server just went out in a release. What's left to do before it's finished?", "expect": "security-advisory" }, { "prompt": "Walk me through taking an accepted vulnerability report all the way to a shipped, disclosed fix.", "expect": "security-advisory" }, { "prompt": "What is the capital of Portugal?", "expect": null }, { "prompt": "Rename the local variable `tmp` to `buffer` in this snippet: `const tmp = 1; return tmp + 1;`", "expect": null }, { "prompt": "The fix for a private advisory only covers Linux and macOS; Windows needs a bigger change. Where do I track the Windows work before the advisory is published?", "expect": "security-advisory" } ] - .claude/skills/security-advisory/SKILL.md (30580 bytes)
--- name: security-advisory description: "Take a privately reported vulnerability through this repo's security advisory flow: board it as a draft card, check whether the code is this repo's server or the SDK underneath, accept or reject, fix it in the private fork, release, publish, then turn the card into public tracking. Use when a vulnerability is reported privately; when deciding whether an advisory is ours to fix or belongs to an SDK; when looking up or creating its private fork; when answering a reporter; or when a GHSA-titled board card needs handling." disable-model-invocation: false --- # Handling a security advisory Private vulnerability reporting is enabled on this repository and [`SECURITY.md`](../../../SECURITY.md) routes every report to it. A report therefore arrives as a **repository security advisory**, never as an issue, and for most of its life it must **not** become one: a public issue would disclose the vulnerability before a fix exists. Two steps in this flow are **outward-facing, and both stay human-only**: **accepting** an advisory (the reporter sees it) and **publishing** it (it becomes public, and there is no unpublish). Closing one as invalid, and every reply to a reporter, is outward-facing too. **An agent never takes any of these steps**: not once, not in bulk, not because a checklist said to. It investigates, prepares a recommendation, and a maintainer acts on it. Everything else here is mechanics. ⚠️ **Keep advisory details out of every public place**: issues, PRs, commit messages, branch names, and comments. Until an advisory is published, the only things safe to say in public about the backlog are **aggregate counts** (how many are in each state). A branch named after the bug, or a commit message that describes it, discloses it as surely as an issue would. Related: `/board-ops` holds the board IDs and the draft-card recipes, `/issue-create` gives the converted issue its labels and milestone (step 5), and `/pr-flow` opens the public PR that brings the fix to `v2/main` (step 5). ⚠️ **The fix is written and reviewed in the private fork, then merged through an opaque public PR.** The fork's PR (step 4) links no public issue, carries no labels and is tracked by the draft card; it is never merged. When the fix is ready to merge, the card converts to an issue that keeps its opaque title, and a public PR from the same opaque branch closes it (step 5). That PR follows `/pr-flow` except that **nothing in it describes the vulnerability** and it gets **no Copilot review**. `AGENTS.md` records both PRs as an exception to its PR rules. ## The flow | # | Step | Gate | | --- | --- | --- | | 1 | Advisory in state `triage` → **draft card** on board #43 | Mechanical | | 2 | **Verify the claim**: which server, and does the code belong to it or to an SDK? | Judgment | | 3 | Valid and ours → **accept** (`triage` → `draft`); otherwise close with a reason | **Human only** | | 4 | Create the **private fork**, fix and review there | Mechanical | | 5 | Close to the release: **convert the card** to an opaque issue, open the opaque **public PR**, merge it, close the fork's PR; then milestone merge, **release**, **publish** | **Human only** for merging, releasing and publishing (converting, the PR and closing the fork's PR are mechanical) | | 6 | **After publication**, give the issue its public title and the advisory link | Mechanical | There is **one release line**. Every fix lands on `v2/main` and ships through the next milestone merge to `main` and a release, as any other change does ([`RELEASING.md`](../../../RELEASING.md)). No older line is patched, so "which lines are affected" is never a question here. ### 1. Board it as a draft card An advisory gets a **draft card**, the one exception to [`AGENTS.md`](../../../AGENTS.md#issue-driven-work-style)'s "every board item is a real GitHub issue". - **Title:** the bare id, `[GHSA-xxxx-yyyy-zzzz]`, and **no summary until the advisory is published**. A summary can name the server or the attack class, and the card is read by a wider audience than the advisory (see the body's warning below). The `[GHSA-` prefix is not cosmetic: it is the only thing that tells an advisory draft apart from a stray draft card, which is still a defect to delete, so any audit of the board's drafts keys on it, and it is the exact lookup key. - **Body:** `**Advisory:** <html_url>` on the first line, then the severity the reporter claimed, the reported date, and the provisional Priority line below. The link comes first because a maintainer reading the card has no other route back to the private advisory. ⚠️ **Do not copy the vulnerability description onto the card.** Project access and advisory access are **separate permission sets**: anyone who can see board #43 reads the card, whether or not they are a collaborator on the advisory. The board is private, so this is a wider audience than intended rather than a public leak, but a reproduction or a proof of concept belongs only with the people handling it. The card carries the **link and triage metadata only**. - **Status `Incoming`**, with a **provisional Priority** from what the report claims. `Incoming` is right even though somebody looked at it to make the card: nobody has approved a fix yet, and a draft card has no milestone to carry that approval. ⚠️ **Provisional is the only honest score at this point.** Step 2 checks ownership **before** severity, and a report can look severe right up until it turns out to be an SDK's code, or no vulnerability at all. So score what the report claims now, and **re-score at the end of step 2**. Until the `issue-triage` rubric lands (#4868), map the advisory's severity with the table below. (`/issue-create`'s Priority table would put every security report at `Urgent`, which leaves the re-score nothing to change.) An unverified claim sits one level below a verified one: | Advisory severity | Provisional (step 1, as claimed) | Re-scored (step 2, verified and ours) | | --- | --- | --- | | `critical` | High | Urgent | | `high` | High | Urgent | | `medium` | Medium | High | | `low` | Low | Medium | Re-score by the severity you verified, which may differ from the claim. Write the result into the body as `Priority <level> (provisional, <YYYY-MM-DD>)`: a draft card has no comments, so the body is the only place the score can be recorded. When you re-score (step 2), keep that line, add `Priority <level> (verified, <YYYY-MM-DD>)` under it so the change of view is legible, and **set the card's Priority field to the verified level**. Numbers and level names only; the reasoning behind a score is the impact, which belongs in the private advisory. ⚠️ **Set both fields.** A draft card has no labels and no milestone, so its Status and Priority are all the triage state it carries. The create and lookup recipes are in `/board-ops` ([Advisory draft cards](../board-ops/SKILL.md#advisory-draft-cards)). The card is made **by hand** (by a maintainer, or an agent working for one), not by a workflow: a board write needs `organization projects: write`, which a workflow's `GITHUB_TOKEN` cannot hold. To see what is waiting (**output is private; never paste it into an issue or a PR**): ```sh # --paginate: the endpoint returns 30 per page, and an inventory that silently # stops at the first page reads as "nothing pending". gh api --paginate repos/modelcontextprotocol/servers/security-advisories \ --jq '.[] | select(.state=="triage") | "\(.ghsa_id)\t\(.severity)\t\([.vulnerabilities[]?.package.name] | join(","))\t\(.summary)"' # Aggregate counts by state: the only form that may appear in public. gh api --paginate repos/modelcontextprotocol/servers/security-advisories \ --jq '.[].state' | sort | uniq -c ``` ### 2. Verify the claim: which server, and whose code Before assessing severity, establish that the vulnerable code is **ours**, in this order: 1. **Is it one of the seven servers under `src/`?** Many servers once lived in this repository and were moved to [`servers-archived`](https://github.com/modelcontextprotocol/servers-archived), which is unmaintained and read-only. A report against one of those is **out of scope**: there is no code here to fix and nothing to release. Servers listed in the README or the Registry are third-party; their reports go to their own maintainers. 2. **Is the code path the server's, or an SDK's?** The TypeScript servers are built on the TypeScript SDK's v2 packages (`@modelcontextprotocol/server`, `@modelcontextprotocol/node` and the frozen `@modelcontextprotocol/server-legacy`) ([typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk)), the Python servers on `mcp` ([python-sdk](https://github.com/modelcontextprotocol/python-sdk)). Transport handling (Streamable HTTP, SSE, stdio framing, session management, Origin and DNS-rebinding checks) and message validation usually live in the SDK. A report can be entirely accurate about behavior a server merely exhibits because its SDK does it. Reproduce it, find the line that does the wrong thing, and check whether that line is in `src/<server>/` or reached through the dependency. 3. **Does the server claim the boundary that was crossed?** These are **reference implementations** (the README says so), and a server doing what its README documents is not a vulnerability. A way around a boundary the server _does_ claim (allowed directories, Roots, `robots.txt`) is one. The caveat bears on severity and scope; it is never a reason to skip reading a report. ⚠️ **"The SDK's problem" is not a reason to say it in public.** A genuine, unfixed vulnerability handed to a public SDK issue is disclosed, by us, on someone else's behalf, before they have a fix. Route it through **that SDK's private advisory form** (private reporting is enabled on both SDK repos), and reference a public SDK issue only once the SDK has published. Where the reporter would rather carry it over themselves, say so and let them. #### The reach classes Three servers act on the host, and nearly every real advisory lands in one of their classes. Know them before reading a report, because the report often names the symptom rather than the class: | Server | What it can reach | Classes to check | | --- | --- | --- | | `filesystem` | Reads and writes the local disk, limited to the allowed directories and the client's Roots | **Path traversal** (`..`, absolute paths, Windows drive and UNC forms, a prefix match that lets `/data` admit `/data-other`); **symlink escape** (a link inside an allowed directory pointing out of it, a link swapped in between check and use); **Roots bypass** (the allowed set not narrowed or refreshed as the client's Roots say) | | `git` | Runs git against repository paths it is given | **Path traversal** and **symlink escape** out of the configured repository; **Roots bypass**; **argument injection** (a value that starts with `-` read by git as an option) | | `fetch` | Makes outbound HTTP requests to URLs it is given | **SSRF** (loopback, private and link-local addresses, cloud metadata endpoints, a redirect or a DNS answer that lands on one); **robots bypass** (`robots.txt` not honored, or not re-checked after a redirect, when the server claims to honor it) | `everything`, `memory`, `sequentialthinking` and `time` reach much less: `memory` writes one file at a configured path, and `everything`'s HTTP transports are mostly SDK code (see ownership, above). **Now re-score the card's Priority**: add the `verified` line under the provisional one (step 1), and set the card's Priority field to match with the `/board-ops` edit recipe, so the board orders by the verified level. This is the first point where severity has anything solid under it: the code is ours, it reproduces, and you know which class and which server. ### 3. Accept, or close (human only) **Valid and ours → accept.** In the UI this is "Accept and open as draft"; it moves the advisory `triage` → `draft`. The API shows it as `state` and `submission.accepted`. **Then move the card `Incoming` → `Todo`.** On board #43 the approval act is normally assigning a milestone, and a draft card cannot carry one, so for an advisory draft **accepting the advisory is the approval**. `AGENTS.md` records this as the advisory exemption to its `Incoming` ⇔ milestone rule. The milestone arrives when the card converts to an issue in step 5, where the ordinary rule resumes. **Invalid, out of scope, a duplicate, or an SDK's → close** with a comment saying which, and why; for an SDK's, say where it was routed. A reporter who is told nothing reasonably assumes they were ignored. ⚠️ **Closing an advisory leaves its draft card behind: delete it.** Nothing shipped, so `Done` would be a false record, and `Incoming` would claim work is still queued. The delete recipe is in `/board-ops`. ⚠️ **Accepting, closing and replying are human acts, always.** Each is visible to the reporter, and accepting commits the project to treating the report as a real vulnerability. Nothing in this skill authorizes an agent to take them: write the recommendation (accept or close, the class, the owner, the evidence) and let a maintainer click. ⚠️ **There is no comment API for security advisories.** Not in REST (the advisory object has no comments endpoint) and not in GraphQL (no advisory comment mutation exists). Comments are **UI-only**, so every exchange with a reporter is manual, and the thread cannot be read back with `gh`. ### 4. The private fork An accepted advisory is fixed in a **private fork** GitHub creates for it: a private repository named `servers-ghsa-xxxx-yyyy-zzzz` (the id in lowercase) in the org; read the exact name from `.private_fork.full_name`. ⚠️ **Read `private_fork` FIRST. The POST is not a probe; it CREATES one.** Calling it to "check whether a fork exists" makes one, which then needs cleaning up. ```sh # Does one already exist? gh api repos/modelcontextprotocol/servers/security-advisories/<GHSA_ID> \ --jq '.private_fork // "none"' # Only if that printed "none": gh api -X POST \ repos/modelcontextprotocol/servers/security-advisories/<GHSA_ID>/forks # → 202 Accepted; the fork appears shortly afterwards. ``` ⚠️ **Deleting a private fork needs the `delete_repo` OAuth scope, which a default `gh` token does not carry.** A fork created by mistake cannot be quietly undone; it takes a re-scoped token or an admin in the UI. That asymmetry is the reason for the read-first rule. Fix and review inside the fork. The fix follows the rules in `AGENTS.md` like any other change: a regression test that fails before the fix, and the gate under **Before pushing**. Name the branch `v2/fix/<ghsa-id>` (lowercase, **no descriptive slug**, since a branch name outlives the fork once merged), and keep commit messages equally opaque until publication. **The fork's PR t - .claude/skills/testing/evals/evals.json (1018 bytes)
[ { "prompt": "How do I write a test that drives the everything server through a real MCP client without spawning a process?", "expect": "testing" }, { "prompt": "How do I write a protocol-level test for one of the Python servers?", "expect": "testing" }, { "prompt": "Some sequentialthinking tests show as skipped on my machine. How do I diagnose that?", "expect": "testing" }, { "prompt": "My filesystem test still passes after I broke the tool it covers. How do I diagnose that?", "expect": "testing" }, { "prompt": "Which command gives me a coverage report for one of the Python servers?", "expect": "testing" }, { "prompt": "For a new tool in the memory server, should my test call the handler directly or connect a client?", "expect": "testing" }, { "prompt": "Translate 'good morning' into French.", "expect": null }, { "prompt": "What is the boiling point of water at sea level in Fahrenheit?", "expect": null } ] - .claude/skills/testing/SKILL.md (16878 bytes)
--- name: testing description: "Write, place and run tests for a server in this repo. Use when choosing between driving the server through an MCP client and calling its functions directly; when writing a protocol-level test for a TypeScript or Python server; when choosing the command that runs one suite or a coverage report; or when a test is skipped or passes against a stale build." disable-model-invocation: false --- # Testing The **rules** are in [`AGENTS.md`](../../../AGENTS.md) under **Always test new or modified code**: new behavior comes with tests, every TypeScript file clears the per-file coverage gate, test at the protocol level where you can, and keep expected error output off the console. This skill explains the harness each server has, how to write a test with it, which command runs what, and how to clear the per-file coverage gate. Driving a running server by hand, with the Inspector or an LLM client, is `/client-smoke`. It is evidence for a PR, not a substitute for a test. **Every server is tested in-process, and every file is gated.** The four TypeScript servers link a real `Client` to the server over an in-memory transport (#4854); the three Python servers link a `ClientSession` to the real `serve()` over in-memory streams (#4855). Both languages hold each file to a per-file coverage floor, in CI and in `npm run local:gate`. ## Where a test goes | Server | Directory | File name | Runner | | --- | --- | --- | --- | | `everything`, `filesystem`, `memory`, `sequentialthinking` | `src/<server>/__tests__/` | `<subject>.test.ts` | vitest, `globals: true` | | `fetch`, `git`, `time` | `src/<server>/tests/` | `test_<subject>.py` | pytest, with `pytest-asyncio` (`asyncio_mode = "auto"`) | | Root tooling | `scripts/`, beside the script | `<name>.test.mjs` | `node --test` | Each vitest config includes only `**/__tests__/**/*.test.ts`, so a test file anywhere else in a workspace is never run and reports nothing. Shared test helpers go in `__tests__/` without the `.test` suffix, as each server's connection harness does (`__tests__/harness.ts` in `everything`, `__tests__/helpers.ts` in the other three). ## What each server's tests do | Server | How its tests reach the code | | --- | --- | | `everything`, `filesystem`, `memory`, `sequentialthinking` | An SDK `Client` connected to the server's `createServer()` over `InMemoryTransport`, in the vitest process, through the server's own harness, plus unit tests of helper modules such as `lib.ts`. `everything` drives its stdio, SSE and Streamable HTTP transports in-process too; the other three drive their `http.ts` in-process over a free loopback port, and have one thin spawn smoke of the built `dist/index.js` | | `fetch`, `git`, `time` | A `ClientSession` linked in-process to the real `serve()` over in-memory streams (below), plus direct calls on the pure functions in `server.py` | No TypeScript test uses an in-memory transport yet. ## Choosing a harness for a new test Ask what the test must prove. - **Logic** (a path check, a graph operation, a timezone conversion): call the function directly. That is what `lib.ts` and the functions in `server.py` are for. - **What a client sees** (a tool's result shape, its advertised schema, an error result, a capability, a notification): drive the server through a client. A handler called directly skips the SDK's input validation, output schema validation and error mapping, which is where the wire-level bugs in this repo have been. Which client harness is available depends on the language. ### TypeScript: in-process, over an in-memory transport Each TypeScript server exports a `createServer(…)` factory and starts its transport only from a guarded `main()`, so importing it starts nothing and a test can link a real `Client` to a real server with no process and no build. **Each server's `__tests__/` has a harness that does the linking. Connect through it**, never by calling `createServer()` and `InMemoryTransport.createLinkedPair()` by hand: the harness also does the per-session setup and teardown the server needs. | Server | Factory | Harness | `connect(…)` takes | | --- | --- | --- | --- | | `everything` | `createServer()` in `server/index.ts`, returns `{ server, cleanup }` | `__tests__/harness.ts` | `{ capabilities, setup, sessionId }`, all optional | | `filesystem` | `createServer(allowedDirectories)` in `server.ts` | `__tests__/helpers.ts` | the allowed directories, then `{ capabilities, listRoots }` | | `memory` | `createServer(memoryFilePath)` in `index.ts` | `__tests__/helpers.ts` | the graph file's path (`makeTempGraph()` makes one) | | `sequentialthinking` | `createServer()` in `index.ts` | `__tests__/helpers.ts` | `{ disableThoughtLogging }`, defaulting to `"true"` | Each `connect` returns the `client` and a `close()`; call `close()` in `afterEach`. The harnesses also export small result helpers (`call`, `textOf` and the like); read the one you are using before adding another. ```ts import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { Client } from "@modelcontextprotocol/client"; import { connect, contentOf, textOf, type Session } from "./harness.js"; describe("echo, over the protocol", () => { let session: Session; let client: Client; beforeEach(async () => { session = await connect(); client = session.client; }); afterEach(async () => { await session.close(); }); it("returns the message", async () => { const result = await client.callTool({ name: "echo", arguments: { message: "hi" }, }); expect(textOf(contentOf(result)[0])).toBe("Echo: hi"); }); it("reports bad input as a tool error", async () => { const result = await client.callTool({ name: "echo", arguments: {} }); expect(result.isError).toBe(true); }); }); ``` What `everything`'s harness does that a hand-rolled connection would miss: - **A session id per connection.** Logging, subscriptions, roots and the toggle tools keep per-session state in module-level maps keyed by the transport's session id, and `InMemoryTransport` has none, so every hand-rolled session would share the `undefined` key and leak state into the next test. `connect()` sets a fresh `sessionId` on the server transport (`sessionId: null` keeps it undefined, as stdio does), and `close()` runs the server's `cleanup(sessionId)`, which also stops the timers `createServer()` starts (the roots sync). - **Capabilities.** A tool `everything` registers in `registerConditionalTools` appears only when the client declares the matching capability: pass `capabilities` (`ALL_CAPABILITIES` declares every one), with `setup` to install the client's handlers for the requests the server sends back (sampling, elicitation, roots). - **Notifications.** `session.notifications` collects every notification no specific handler consumed; `ofMethod(notifications, method)` filters it. Assert on what the client receives (tool, resource and prompt lists, call results, errors, notifications), never on SDK internals or a handler's context object: the SDK v2 migration (#4856) must be able to update these tests with import and type changes alone. ### TypeScript: the spawn smoke of the built binary What only the published entry point can show (that `dist/index.js` starts as a bin and serves over stdio; in `memory` and `sequentialthinking`, also through a symlink, as npm's `.bin` entry runs it) is checked by one thin test per server that spawns it with `StdioClientTransport`: `filesystem`'s `bin-smoke.test.ts`, and `stdio-smoke.test.ts` in `memory` and `sequentialthinking`. `everything` has none; its transports are driven in-process. Everything else is tested in-process. Two hazards apply to these tests, and only to them: - ⚠️ **They run the last build, not your edit.** `npm test` does not build. Build first, or run `npm run validate -w src/<server>`, which builds before it tests. - ⚠️ **A missing `dist/` is handled two ways.** `filesystem` and `sequentialthinking` guard the smoke with `skipIf(!existsSync(distIndexPath))`, so with no build it is reported as **skipped** and the run stays green having tested nothing over stdio. `memory`'s has no guard and **fails**. A skipped test in this repo usually means "not built". Close the client in `finally` or `afterEach`: that is what stops the child process. Pipe its stderr (`stderr: "pipe"`), and pass environment variables in the transport's `env` option (`MEMORY_FILE_PATH`, say), since the child inherits only the SDK's default safelist (`PATH`, `HOME`, `USER` and the like). ### Python: `ClientSession` over in-memory streams, in-process Each Python server builds its `Server` inside `serve()` and serves it over the `stdio_server()` it imports into `server.py`. A test replaces that one name with a context manager that yields the server side of a pair of in-memory streams, runs the real `serve()` in a task group, and opens a `ClientSession` on the client side. No process, no build, and the SDK's input validation and error mapping run exactly as they do for a real client: ```python from contextlib import asynccontextmanager from typing import Any, AsyncIterator import anyio import pytest from mcp import ClientSession from mcp.shared.memory import create_client_server_memory_streams import mcp_server_time.server as server_module @asynccontextmanager async def connect(**serve_kwargs: Any) -> AsyncIterator[ClientSession]: async with create_client_server_memory_streams() as (client, server): @asynccontextmanager async def fake_stdio_server() -> AsyncIterator[Any]: yield server with pytest.MonkeyPatch.context() as mp: mp.setattr(server_module, "stdio_server", fake_stdio_server) async with anyio.create_task_group() as tg: tg.start_soon(lambda: server_module.serve(**serve_kwargs)) async with ClientSession(*client) as session: await session.initialize() yield session tg.cancel_scope.cancel() async def test_get_current_time() -> None: async with connect() as session: result = await session.call_tool("get_current_time", {"timezone": "UTC"}) assert result.isError is False ``` - **Patch the name `server.py` looks up** (`mcp_server_<name>.server.stdio_server`), not `mcp.server.stdio.stdio_server`: `server.py` imported the function, so the module attribute is what `serve()` calls. - **Cancel the task group after the session closes.** `serve()` runs until its streams end, so without the cancel the test never returns. - **Assert on the wire shape where you can**, for example `result.model_dump(by_alias=True, mode="json")`, rather than on Python attribute names: the SDK v2 port (#4851) renames them, and a wire-level assertion survives it. - **No network in a test.** `fetch` replaces `httpx.AsyncClient` with one on an `httpx.MockTransport`; `git` works against a temporary repository its fixture creates and closes before removing. `pytest-asyncio` with `asyncio_mode = "auto"` is a dev dependency of all three, so an `async def test_…` runs as it stands. A subprocess test over stdio (`StdioServerParameters(command=sys.executable, args=["-m", "mcp_server_<name>"])` with `mcp.client.stdio.stdio_client`) is kept to a thin smoke of the entry point. coverage.py does not measure a child process, so code reached only that way reads as uncovered. ## Tests that pin a known bug The suites are characterization tests: each asserts what the server does today, so a migration that changes behavior fails a test. Most of what they pin is intended. Some of it is a bug, pinned as it is so that the fix has to change the assertion visibly. Every test of that kind carries one marker, directly above the test (or above its `describe`/class when the whole block pins the same bug): ```ts // KNOWN BUG #<N>: pins current (wrong) behavior; the fix changes this assertion. ``` In Python the same text follows `#`. A bug with no issue yet reads `KNOWN BUG (no issue): <what is wrong>; …`, which also marks it for filing. - `git grep "KNOWN BUG"` lists every test that pins a bug. A test without the marker pins intended behavior, or guards a fixed bug against regression. - **Fixing the bug** means changing that test's assertion to the correct behavior and removing the marker, in the fix PR. - **Pinning a newly found bug**: write the test against what the code does, add the marker, and file the issue (`/issue-create`), then cite it. - A pin of current design that a feature request wants changed is not a bug and gets no marker. ## Running them | Scope | Command | | --- | --- | | One TypeScript server | `npm test -w src/<server>` | | One file, or one test | `npm test -w src/<server> -- __tests__/<file>.test.ts -t "<name>"` | | Every TypeScript server | `npm test` at the root | | One TypeScript server's coverage gate | `npm run coverage -w src/<server>` (see below) | | One TypeScript server's whole chain | `npm run validate -w src/<server>` (format check, lint, typecheck, build, test) | | One Python server | `uv run pytest` in `src/<server>` | | One Python test | `uv run pytest <path to the test file>::<name>` in `src/<server>` (for example `tests/test_server.py::test_git_checkout_existing_branch`) | | One Python server's whole chain | `npm run validate:py -- <server>` | | One Python server's coverage gate | `npm run coverage:py -- <server>` at the root | | Every Python server's coverage gate | `npm run coverage:py` at the root | | Root tooling | `npm run test:scripts` | `npm run typecheck -w src/<server>` is the only step that typechecks the test files in `filesystem`, `memory` and `sequentialthinking`: their build `tsconfig.json` excludes tests, and vitest does not typecheck. ## `test` versus `coverage` `test` is `vitest run`, the fast loop, and part of `validate`. `coverage` is `vitest run --coverage`: the same suite, instrumented, with a v8 report over the workspace's `**/*.ts` (tests and `dist/` excluded) written to the terminal and to the ignored `coverage/` directory (`coverage/index.html` has the line-by-line view). ```sh npm run coverage -w src/<server> # one server npm run coverage # all four ``` **`coverage` is a gate.** Each server's `vitest.config.ts` sets `coverage.thresholds` to 90 on lines, statements, functions and branches with `perFile: true`, so the command fails when any one file is below 90 on any one of them, even if the totals are above. CI runs it as its own job (`typescript.yml` → **Coverage \<server\>**) and `npm run local:gate` as its own stage. `test` and `validate` never measure coverage, so a change can pass them and still fail here: run `coverage` on the server you changed before you push. Clearing a red file: - The `Uncovered Line #s` column is the to-do list. A branch shortfall with no uncovered line is the un - ADDITIONAL.md (16001 bytes)
# Additional links This is a curated collection of community-built frameworks and resources that simplify building MCP servers and clients, along with other useful tools, libraries, and references for working with MCP. ## 📚 Frameworks ### For servers * **[Anubis MCP](https://github.com/zoedsoupe/anubis-mcp)** (Elixir) - A high-performance and high-level Model Context Protocol (MCP) implementation in Elixir. Think like "Live View" for MCP. * **[ModelFetch](https://github.com/phuctm97/modelfetch/)** (TypeScript) - Runtime-agnostic SDK to create and deploy MCP servers anywhere TypeScript/JavaScript runs * **[EasyMCP](https://github.com/zcaceres/easy-mcp/)** (TypeScript) * **[FastAPI to MCP auto generator](https://github.com/tadata-org/fastapi_mcp)** – A zero-configuration tool for automatically exposing FastAPI endpoints as MCP tools by **[Tadata](https://tadata.com/)** * **[FastMCP](https://github.com/punkpeye/fastmcp)** (TypeScript) * **[Foobara MCP Connector](https://github.com/foobara/mcp-connector)** - Easily expose Foobara commands written in Ruby as tools via MCP * **[Foxy Contexts](https://github.com/strowk/foxy-contexts)** – A library to build MCP servers in Golang by **[strowk](https://github.com/strowk)** * **[Higress MCP Server Hosting](https://github.com/alibaba/higress/tree/main/plugins/wasm-go/mcp-servers)** - A solution for hosting MCP Servers by extending the API Gateway (based on Envoy) with wasm plugins. * **[MCP Declarative Java SDK](https://github.com/codeboyzhou/mcp-declarative-java-sdk)** Annotation-driven MCP servers development with Java, no Spring Framework Required, minimize dependencies as much as possible. * **[MCP-Framework](https://mcp-framework.com)** Build MCP servers with elegance and speed in TypeScript. Comes with a CLI to create your project with `mcp create app`. Get started with your first server in under 5 minutes by **[Alex Andru](https://github.com/QuantGeekDev)** * **[MCP Plexus](https://github.com/Super-I-Tech/mcp_plexus)**: A secure, **multi-tenant** and Multi-user MCP python server framework built to integrate easily with external services via OAuth 2.1, offering scalable and robust solutions for managing complex AI applications. * **[mcp_sse (Elixir)](https://github.com/kEND/mcp_sse)** An SSE implementation in Elixir for rapidly creating MCP servers. * **[mxcp](https://github.com/raw-labs/mxcp)** (Python) - Open-source framework for building enterprise-grade MCP servers using just YAML, SQL, and Python, with built-in auth, monitoring, ETL and policy enforcement. * **[Next.js MCP Server Template](https://github.com/vercel-labs/mcp-for-next.js)** (Typescript) - A starter Next.js project that uses the MCP Adapter to allow MCP clients to connect and access resources. * **[PayMCP](https://github.com/blustAI/paymcp)** (Python & TypeScript) - Lightweight payments layer for MCP servers: turn tools into paid endpoints with a two-line decorator. [PyPI](https://pypi.org/project/paymcp/) · [npm](https://www.npmjs.com/package/paymcp) · [TS repo](https://github.com/blustAI/paymcp-ts) * **[Perl SDK](https://github.com/mojolicious/mojo-mcp)** - An SDK for building MCP servers and clients with the Perl programming language. * **[Quarkus MCP Server SDK](https://github.com/quarkiverse/quarkus-mcp-server)** (Java) - **[R mcptools](https://github.com/posit-dev/mcptools)** - An R SDK for creating R-based MCP servers and retrieving functionality from third-party MCP servers as R functions. * **[SAP ABAP MCP Server SDK](https://github.com/abap-ai/mcp)** - Build SAP ABAP based MCP servers. ABAP 7.52 based with 7.02 downport; runs on R/3 & S/4HANA on-premises, currently not cloud-ready. * **[Spring AI MCP Server](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html)** - Provides auto-configuration for setting up an MCP server in Spring Boot applications. * **[Template MCP Server](https://github.com/mcpdotdirect/template-mcp-server)** - A CLI tool to create a new Model Context Protocol server project with TypeScript support, dual transport options, and an extensible structure * **[AgentR Universal MCP SDK](https://github.com/universal-mcp/universal-mcp)** - A python SDK to build MCP Servers with inbuilt credential management by **AgentR** * **[Vercel MCP Adapter](https://github.com/vercel/mcp-adapter)** (TypeScript) - A simple package to start serving an MCP server on most major JS meta-frameworks including Next, Nuxt, Svelte, and more. * **[PHP MCP Server](https://github.com/php-mcp/server)** (PHP) - Core PHP implementation for the Model Context Protocol (MCP) server ### For clients * **[codemirror-mcp](https://github.com/marimo-team/codemirror-mcp)** - CodeMirror extension that implements the Model Context Protocol (MCP) for resource mentions and prompt commands * **[llm-analysis-assistant](https://github.com/xuzexin-hz/llm-analysis-assistant)** <img height="12" width="12" src="https://raw.githubusercontent.com/xuzexin-hz/llm-analysis-assistant/refs/heads/main/src/llm_analysis_assistant/pages/html/imgs/favicon.ico" alt="llm-analysis-assistant Logo" /> - A very streamlined mcp client that supports calling and monitoring stdio/sse/streamableHttp, and can also view request responses through the /logs page. It also supports monitoring and simulation of ollama/openai interface. * **[MCP-Agent](https://github.com/lastmile-ai/mcp-agent)** - A simple, composable framework to build agents using Model Context Protocol by **[LastMile AI](https://www.lastmileai.dev)** * **[Spring AI MCP Client](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html)** - Provides auto-configuration for MCP client functionality in Spring Boot applications. * **[MCP CLI Client](https://github.com/vincent-pli/mcp-cli-host)** - A CLI host application that enables Large Language Models (LLMs) to interact with external tools through the Model Context Protocol (MCP). * **[OpenMCP Client](https://github.com/LSTM-Kirigaya/openmcp-client/)** - An all-in-one vscode/trae/cursor plugin for MCP server debugging. [Document](https://kirigaya.cn/openmcp/) & [OpenMCP SDK](https://kirigaya.cn/openmcp/sdk-tutorial/). * **[PHP MCP Client](https://github.com/php-mcp/client)** - Core PHP implementation for the Model Context Protocol (MCP) Client * **[Runbear](https://runbear.io/solutions/integrations/slack/mcp)** - No-code MCP client for team chat platforms, such as Slack, Microsoft Teams, and Discord. ## 📚 Resources - **[A2A-MCP Java Bridge](https://github.com/vishalmysore/a2ajava)** - A2AJava brings powerful A2A-MCP integration directly into your Java applications. It enables developers to annotate standard Java methods and instantly expose them as MCP Server, A2A-discoverable actions — with no boilerplate or service registration overhead. - **[AiMCP](https://www.aimcp.info)** - A collection of MCP clients&servers to find the right mcp tools by **[Hekmon](https://github.com/hekmon8)** - **[Awesome Crypto MCP Servers by badkk](https://github.com/badkk/awesome-crypto-mcp-servers)** - A curated list of MCP servers by **[Luke Fan](https://github.com/badkk)** - **[Awesome MCP Servers by appcypher](https://github.com/appcypher/awesome-mcp-servers)** - A curated list of MCP servers by **[Stephen Akinyemi](https://github.com/appcypher)** - **[Awesome MCP Servers by punkpeye](https://github.com/punkpeye/awesome-mcp-servers)** (**[website](https://glama.ai/mcp/servers)**) - A curated list of MCP servers by **[Frank Fiegel](https://github.com/punkpeye)** - **[Awesome MCP Servers by wong2](https://github.com/wong2/awesome-mcp-servers)** (**[website](https://mcpservers.org)**) - A curated list of MCP servers by **[wong2](https://github.com/wong2)** - **[Awesome Remote MCP Servers by JAW9C](https://github.com/jaw9c/awesome-remote-mcp-servers)** - A curated list of **remote** MCP servers, including their authentication support by **[JAW9C](https://github.com/jaw9c)** - **[Discord Server](https://glama.ai/mcp/discord)** – A community discord server dedicated to MCP by **[Frank Fiegel](https://github.com/punkpeye)** - **[Install This MCP](https://installthismcp.com)** - Reduce Installation Friction with beautiful installation guides - **[Klavis AI](https://www.klavis.ai)** - Open Source MCP Infra. Hosted MCP servers and MCP clients on Slack and Discord. - **[MCP Badges](https://github.com/mcpx-dev/mcp-badges)** – Quickly highlight your MCP project with clear, eye-catching badges, by **[Ironben](https://github.com/nanbingxyz)** - **[MCPProxy](https://github.com/smart-mcp-proxy/mcpproxy-go)** - Open-source local app that enables access to multiple MCP servers and thousands of tools with intelligent discovery via MCP protocol, runs servers in isolated environments, and features automatic quarantine protection against malicious tools. - **[MCPRepository.com](https://mcprepository.com/)** - A repository that indexes and organizes all MCP servers for easy discovery. - **[mcp-cli](https://github.com/wong2/mcp-cli)** - A CLI inspector for the Model Context Protocol by **[wong2](https://github.com/wong2)** - **[mcp-dockmaster](https://mcp-dockmaster.com)** - An Open-Sourced UI to install and manage MCP servers for Windows, Linux and macOS. - **[mcp-get](https://mcp-get.com)** - Command line tool for installing and managing MCP servers by **[Michael Latman](https://github.com/michaellatman)** - **[mcp-guardian](https://github.com/eqtylab/mcp-guardian)** - GUI application + tools for proxying / managing control of MCP servers by **[EQTY Lab](https://eqtylab.io)** - **[MCP Linker](https://github.com/milisp/mcp-linker)** - A cross-platform Tauri GUI tool for one-click setup and management of MCP servers, supporting Claude Desktop, Cursor, Windsurf, VS Code, Cline, and Neovim. - **[mcp-manager](https://github.com/zueai/mcp-manager)** - Simple Web UI to install and manage MCP servers for Claude Desktop by **[Zue](https://github.com/zueai)** - **[MCP Marketplace Web Plugin](https://github.com/AI-Agent-Hub/mcp-marketplace)** MCP Marketplace is a small Web UX plugin to integrate with AI applications, Support various MCP Server API Endpoint (e.g pulsemcp.com/deepnlp.org and more). Allowing user to browse, paginate and select various MCP servers by different categories. [Pypi](https://pypi.org/project/mcp-marketplace) | [Maintainer](https://github.com/AI-Agent-Hub) | [Website](http://www.deepnlp.org/store/ai-agent/mcp-server) - **[mcp.natoma.ai](https://mcp.natoma.ai)** – A Hosted MCP Platform to discover, install, manage and deploy MCP servers by **[Natoma Labs](https://www.natoma.ai)** - **[mcp.run](https://mcp.run)** - A hosted registry and control plane to install & run secure + portable MCP Servers. - **[MCPHub](https://www.mcphub.com)** - Website to list high quality MCP servers and reviews by real users. Also provide online chatbot for popular LLM models with MCP server support. - **[MCP Router](https://mcp-router.net)** – Free Windows and macOS app that simplifies MCP management while providing seamless app authentication and powerful log visualization by **[MCP Router](https://github.com/mcp-router/mcp-router)** - **[MCP Servers Hub](https://github.com/apappascs/mcp-servers-hub)** (**[website](https://mcp-servers-hub-website.pages.dev/)**) - A curated list of MCP servers by **[apappascs](https://github.com/apappascs)** - **[MCPServers.com](https://mcpservers.com)** - A growing directory of high-quality MCP servers with clear setup guides for a variety of MCP clients. Built by the team behind the **[Highlight MCP client](https://highlightai.com/)** - **[MCP Servers Rating and User Reviews](http://www.deepnlp.org/store/ai-agent/mcp-server)** - Website to rate MCP servers, write authentic user reviews, and [search engine for agent & mcp](http://www.deepnlp.org/search/agent) - **[MCP Sky](https://bsky.app/profile/brianell.in/feed/mcp)** - Bluesky feed for MCP related news and discussion by **[@brianell.in](https://bsky.app/profile/brianell.in)** - **[MCP X Community](https://x.com/i/communities/1861891349609603310)** – A X community for MCP by **[Xiaoyi](https://x.com/chxy)** - **[MCPHub](https://github.com/Jeamee/MCPHub-Desktop)** – An Open Source macOS & Windows GUI Desktop app for discovering, installing and managing MCP servers by **[Jeamee](https://github.com/jeamee)** - **[mcpm](https://github.com/pathintegral-institute/mcpm.sh)** ([website](https://mcpm.sh)) - MCP Manager (MCPM) is a Homebrew-like service for managing Model Context Protocol (MCP) servers across clients by **[Pathintegral](https://github.com/pathintegral-institute)** - **[MCPVerse](https://mcpverse.dev)** - A portal for creating & hosting authenticated MCP servers and connecting to them securely. - **[MCP Servers Search](https://github.com/atonomus/mcp-servers-search)** - An MCP server that provides tools for querying and discovering available MCP servers from this list. - **[Search MCP Server](https://github.com/krzysztofkucmierz/search-mcp-server)** - Recommends the most relevant MCP servers based on the client's query by searching this README file. - **[MCPWatch](https://github.com/kapilduraphe/mcp-watch)** - A comprehensive security scanner for Model Context Protocol (MCP) servers that detects vulnerabilities and security issues in your MCP server implementations. - **[mkinf](https://mkinf.io)** - An Open Source registry of hosted MCP Servers to accelerate AI agent workflows. - **[Open-Sourced MCP Servers Directory](https://github.com/chatmcp/mcp-directory)** - A curated list of MCP servers by **[mcpso](https://mcp.so)** - **[OpenTools](https://opentools.com)** - An open registry for finding, installing, and building with MCP servers by **[OpenTools](https://github.com/opentools)** - **[Programmatic MCP Prototype](https://github.com/domdomegg/programmatic-mcp-prototype)** - Experimental agent prototype demonstrating programmatic MCP tool composition, progressive tool discovery, state persistence, and skill building through TypeScript code execution by **[Adam Jones](https://github.com/domdomegg)** - **[PulseMCP](https://www.pulsemcp.com)** ([API](https://www.pulsemcp.com/api)) - Community hub & weekly newsletter for discovering MCP servers, clients, articles, and news by **[Tadas Antanavicius](https://github.com/tadasant)**, **[Mike Coughlin](https://github.com/macoughl)**, and **[Ravina Patel](https://github.com/ravinahp)** - **[r/mcp](https://www.reddit.com/r/mcp)** – A Reddit community dedicated to MCP by **[Frank Fiegel](https://github.com/punkpeye)** - **[MCP.ing](https://mcp.ing/)** - A list of MCP services for discovering MCP servers in the community and providing a convenient search function for MCP services by **[iiiusky](https://github.com/iiiusky)** - **[MCP Hunt](https://mcp-hunt.com)** - Realtime platform for discovering trending MCP servers with momentum tracking, upvoting, and community discussions - like Product Hunt meets Reddit for MCP - **[Smithery](https://smithery.ai/)** - A registry of MCP servers to find
- AGENTS.md (51832 bytes)
# MCP reference servers This repository holds the official Model Context Protocol reference servers: seven standalone packages under `src/`, four in TypeScript (published to npm) and three in Python (published to PyPI). They are reference implementations, meant to show how each part of the protocol is used, not general-purpose products. **This file holds the _rules_: the conventions a reviewer cites against a diff.** It is loaded in full at the start of every session, so it stays resident and must be complete enough to work from on its own. Procedures (multi-step recipes with commands and live IDs) belong in skills under `.claude/skills/`, which load on demand. A rule that must never silently drop out of context goes here; a recipe that can be re-read from disk goes in a skill. Every rule in this file is true of the repository as it stands. A rule whose machinery does not exist yet is added by the change that builds that machinery, not in advance. ## Skills index | Skill | Covers | How it loads | | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | [`board-ops`](.claude/skills/board-ops/SKILL.md) | `gh project` recipes and the IDs for the Servers V2 board (#43); resolving option IDs by name; the option-deletion hazard and its recovery | Model-invoked, or `/board-ops` | | [`issue-create`](.claude/skills/issue-create/SKILL.md) | The create flow: duplicate check, `v2` + type + server-scope labels, milestone, board card, Status + Priority, and the query that verifies them | Model-invoked, or `/issue-create` | | [`pr-flow`](.claude/skills/pr-flow/SKILL.md) | Issue to PR: branch, DCO signoff and repair, the gate, client evidence, `addCloseIssueReferences`, the Copilot loop and its exits, close-out on merge | Model-invoked, or `/pr-flow` | | [`issue-triage`](.claude/skills/issue-triage/SKILL.md) | Inflow: the class check and canned responses (listings, new servers, duplicates, outside PRs), pass 1 onto the board as Incoming, the priority rubric and its score comment, the board audit | Model-invoked, or `/issue-triage` | | [`pre-push-gate`](.claude/skills/pre-push-gate/SKILL.md) | Running `npm run local:gate` and reading its result; what each stage checks and how to fix it when it fails; waiting on the gate lease | Model-invoked, or `/pre-push-gate` | | [`security-advisory`](.claude/skills/security-advisory/SKILL.md) | A privately reported vulnerability end to end: the `[GHSA-…]` draft card, server or SDK ownership, the reach classes, accepting, the private fork, publishing, public tracking | Model-invoked, or `/security-advisory` | | [`project-structure`](.claude/skills/project-structure/SKILL.md) | What is inside each server: the TypeScript and Python layouts, where each server registers its features, and where a new file goes | Model-invoked, or `/project-structure` | | [`local-dev`](.claude/skills/local-dev/SKILL.md) | Install, build and run each server from the checkout over the transports it implements; local `npx`/`uvx` and client-config runs; stale builds and fresh worktrees; the `overrides`, lockstep and `uv.lock` procedures | Model-invoked, or `/local-dev` | | [`testing`](.claude/skills/testing/SKILL.md) | The in-process protocol-level harness, test placement, the commands per suite, `test` versus `coverage`, and clearing the per-file coverage gate | Model-invoked, or `/testing` | | [`release`](.claude/skills/release/SKILL.md) | A milestone release end to end: the release issue, the preparation PRs on `v2/main` (audit, Version Packages, Python CalVer), the pure `v2/main` → `main` merge PR, the release ledger, and what a maintainer publishes | **Name-only**: `/release` | | [`client-smoke`](.claude/skills/client-smoke/SKILL.md) | Driving a built server with the Inspector CLI (the scripted path), the Inspector web UI (through Playwright) and an LLM client; the CLI's argument split and exit codes; protocol eras and what can be exercised today | Model-invoked, or `/client-smoke` | A PR that adds a skill under `.claude/skills/<name>/SKILL.md` adds its row to this table in the same change, and the table never lists a skill that does not exist. How skills are kept reachable is under [Maintaining the skills](#maintaining-the-skills). ## Project structure ``` servers/ ├── src/ One directory per server; each publishes on its own │ ├── everything/ TS @modelcontextprotocol/server-everything npm Exercises every MCP feature; the protocol showcase │ ├── filesystem/ TS @modelcontextprotocol/server-filesystem npm File operations, access limited to allowed directories / Roots │ ├── memory/ TS @modelcontextprotocol/server-memory npm Knowledge-graph persistence │ ├── sequentialthinking/ TS @modelcontextprotocol/server-sequential-thinking npm Step-by-step reasoning │ ├── fetch/ Py mcp-server-fetch PyPI Fetches web content and converts it for LLMs │ ├── git/ Py mcp-server-git PyPI Git repository operations │ └── time/ Py mcp-server-time PyPI Time and timezone conversion ├── .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-*), │ the skills tooling, release tooling (npm-publish-guard, prepare-python-release, │ pack-and-verify, release-manifest, 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), │ 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), │ 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 ├── .github/pull_request_template.md The "issues, not PRs" banner that turns outside PRs away ├── RELEASING.md How packages are versioned and published, and how to recover a failed publish └── CONTRIBUTING.md The contribution policy: issues, not PRs; what is accepted ``` The four TypeScript servers are **npm workspaces** of the root `package.json`. The three Python servers are independent `uv` projects, each with its own `pyproject.toml`, `uv.lock` and `.python-version`. Every server versions and publishes independently. A server may carry its own `AGENTS.md` for guidance that only applies inside it (`src/everything/AGENTS.md` does). Claude Code loads a nested `AGENTS.md` when it reads a file in that directory, not at session start, so **a rule that applies repo-wide goes in this file, never only in a nested one.** ### New and rewritten source files open with a purpose header A source file you create, or substantially rewrite (code, tests, scripts, workflows, configuration in a format that has comments), opens with a comment stating what the file is for and the reasoning behind it: the first comment in the file, **after any shebang**. `#!/usr/bin/env node` must stay on line 1 of an executable entry point, or the published bin stops working. This is not a bulk migration: files you only touch in passing keep their current form. Read that header rather than restating its reasoning in this file, since a duplicated rationale goes stale silently. A Markdown document states its purpose in its opening paragraph instead, as this one does. A format with no comment syntax (JSON, such as `package.json`) is exempt. ## Development setup Node **24** for the TypeScript servers: the development version and the oldest supported (`engines` is `>=24`), and CI validates each TypeScript server on 24 and 26 in parallel legs. Python **>= 3.10** for the Python servers, at the version each server's `.python-version` pins, except `fetch`, whose floor is **>= 3.11.5**: no `soupsieve` release patched against its open advisories supports an older Python (#5546). A server's floor is the `requires-python` in its `pyproject.toml`; raise one only when a dependency forces it, and record the exception here. Python dependencies are managed with **`uv`, never `pip`**. ```sh # TypeScript: one install at the root covers all four workspaces npm install npm run build # every workspace npm test -w src/<server> # one workspace (vitest) npm run coverage -w src/<server> # the same suite, with the per-file coverage gate # Python: per server cd src/<server> uv sync --frozen --all-extras --dev uv run pytest uv run --frozen pyright uv run ruff check . uv build npm run coverage:py -- <server> # at the root: the per-file coverage gate # Both languages: the pre-push gate (see Before pushing) npm run local:gate ``` ### Before pushing **Run `npm run local:gate` before every push, and push only when it exits 0.** It runs every check CI runs, for both languages, in one command: `verify:install-fresh`, `verify:dco` (every commit since `origin/v2/main` is signed off), the root `validate` (the guards, then each TypeScript workspace's format check, lint, typecheck, build and tests), `coverage` (each 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 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. - **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. - **Judge the gate by its exit code**, not by reading its output: a Prettier failure prints `[warn]` lines that look like nothing. - **The gate runs under a machine-wide lease**, so a second gate started in another worktree queues behind the first instead of contending with it. A "waiting" line is normal; do not bypass it to save time. - **No test may retry.** A retry reports a test that sometimes fails as passing. `verify:no-test-retries` fails on Vitest's `retry` and on pytest's rerun plugins; fix what makes the test fail. - **`npm run pack:verify` is not a gate stage.** It installs each package's publish artifact into an empty directory and boots it, which needs the network. `release.yml` runs it before anything publishes, and the `release` skill runs it by hand for the ledger. - **`verify-main-source` is not a gate stage either.** It applies only to a pull request into `main` (see the merge PR exception under [Contributing](#contributing)), and every local push targets a v2 branch. `main-source.yml` runs it. - **`local:*` scripts never run in a workflow, and every CI job declares `timeout-minutes`.** The script tests enforce both (`scripts/lib/workflow-gate.mjs`). A check added to CI is added to `local:gate:stages` in the same change, so the first sentence of this section stays true. ### Credentialed workflow jobs A workflow job **holds a credential** when it can mint an OIDC token or push a package (`id-token: write`, `packages: write`), or is handed any secret other than `GITHUB_TOKEN`. Today that is `release.yml`'s publish jobs and `sdk-watch.yml`'s `analyze` and `post` jobs (`ANTHROPIC_API_KEY`). Jobs that hold none can still need pinning under the rules below: `release.yml`'s build jobs and `sdk-watch.yml`'s `sweep`, whose outputs `analyze` reads. - **Every action in a credentialed job is pinned to a full commit SHA, with the release it was resolved from in a trailing comment**: `uses: actions/checkout@<40-hex sha> # v6.1.0`. A tag can be moved, and a moved tag runs new code next to the credential with no change in this repository. The same holds for **a job whose artifact a credentialed job downloads**, since what it builds is what gets publi
- aistorehub.json (557 bytes)
{ "name": "Official MCP Servers", "slug": "mcp-reference-servers", "version": "1.0.0", "type": "mcp_server", "description": "Anthropic's official reference Model Context Protocol (MCP) servers, including Filesystem, SQLite, Git, Memory, and Web Fetch tools for Claude Desktop and Cursor.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/modelcontextprotocol/servers", "tags": [ "filesystem", "mcp", "sqlite", "tools", "anthropic" ], "imported_at": "2026-11-22T00:08:32.285Z" } - CODE_OF_CONDUCT.md (5223 bytes)
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
- CONTRIBUTING.md (8564 bytes)
# Contributing to MCP Servers Thank you for your interest in improving the MCP reference servers. Contributors are genuinely valued, and this document explains how to get your input into a form the maintainers can act on quickly and consistently. ## TL;DR **We accept issues, not pull requests.** Design and implementation are done by the repository maintainers. If you've already built a fix or feature locally, share **the prompt you used** to produce it, not the source code. This applies to everyone outside the repository maintainers, including organization members who happen to have write access to this repository. ## Why this policy exists The reference servers are developed with an AI-assisted, prompt-driven workflow built around shared conventions and strict gates (see [`AGENTS.md`](./AGENTS.md)): seven independently published packages in two languages, each with its own tests, type checks, lint and release steps, all tracked on one project board. A diff written outside that workflow has to be reverse-engineered to fit those conventions, tests and gates, and it is often faster to re-derive the change than to adapt the patch. Many outside pull requests also race each other for the same bug. A well-formed issue captures your **intent**, and the **prompt** behind a local change lets us reproduce the work inside our own workflow, with the quality bar already built in. This policy is about efficiency, not gatekeeping. Your bug reports, ideas and prompts directly shape what gets built. ## Who opens pull requests Pull requests against this repository are opened by the **repository maintainers** only. That includes organization members with write access: being able to push a branch here is not the same as being asked to. The constraint is the workflow described above, not permissions. If you're not a repository maintainer, open a **detailed issue** instead and a maintainer will pick it up. A pull request from anyone else is closed with a pointer back to this document; if it held a fix worth keeping, a maintainer files an issue for it first, so the work is not lost. **Every pull request references an issue**, including the maintainers' own. Work is tracked on the project board through issues, so a PR without one is invisible to the board. That is why a well-formed issue is the useful contribution here, and why writing one is never wasted effort. ## How to report a bug or request a feature Open a well-formed issue. [**New issue**](https://github.com/modelcontextprotocol/servers/issues/new/choose) offers a **Bug report** and a **Feature request** form, and both start by asking which server the issue is about. The bug form also asks for the server version, how you ran it, the transport, the protocol era your client speaks and the client you used, because those are the facts triage needs first. GitHub serves the issue chooser from the repository's **default branch** (`main`), and development happens on `v2/main`, which reaches `main` at milestone releases. So a change to the forms goes live at the next milestone merge, not when it merges into `v2/main`. The chooser also links to the private security-advisory form and to the MCP Server Registry. **Never report a security vulnerability in a public issue**; use [the private advisory form](https://github.com/modelcontextprotocol/servers/security/advisories/new) instead. ### What we act on The servers here are **reference implementations**, meant to show how each part of the protocol is used, not general-purpose products. Issues are most likely to be picked up when they ask for: - **Bug fixes.** - **Usability improvements**: making the servers easier to use for humans and agents. - **Enhancements that demonstrate MCP protocol features.** We especially want the reference servers to illustrate underused parts of the protocol beyond Tools, such as Resources, Prompts or Roots. For example, adding Roots support to the filesystem server showcases an important but lesser-known feature. We're more selective about: - **Other new features**, especially ones that are not central to a server's purpose or are highly opinionated. If you need a specific feature, we encourage you to build an enhanced version and publish it to the [MCP Server Registry](https://github.com/modelcontextprotocol/registry). A diverse ecosystem of servers is good for everyone. - **Wholly new documentation**, especially if it is not vendor neutral (for example, how to run a particular server with a particular client). Improvements to existing documentation are welcome, though we generally prefer fixing the rough edge to documenting it. We don't accept: - **New server implementations.** Publish them to the [MCP Server Registry](https://github.com/modelcontextprotocol/registry) instead. - **Server listings.** The README's list of third-party servers has been retired in favor of the Registry. To make your server discoverable, follow the Registry's [quickstart guide](https://github.com/modelcontextprotocol/registry/blob/main/docs/modelcontextprotocol-io/quickstart.mdx). You can browse published servers at [registry.modelcontextprotocol.io](https://registry.modelcontextprotocol.io/). ## If you've already fixed it locally Please don't send a diff or open a pull request. Instead, open an issue that includes: - **The prompt(s) you used** to generate the change: the exact text, so we can reproduce it through our own workflow. - **The behavior before and after** your change. - **How you verified it**: the steps you ran, the tests you added, what you observed, and the MCP client you tried it with. We'll reproduce the change through our workflow so it lands with the right conventions, tests and coverage. ## What makes a good issue A great issue gives us everything we need to act without a round-trip: - **The server** it concerns (`everything`, `filesystem`, `memory`, `sequentialthinking`, `fetch`, `git` or `time`), and its version. - **A clear reproduction or use case**: exact steps to reproduce a bug, or a concrete description of the problem a feature would solve. - **Expected and actual behavior**: what you expected, and what you saw instead. - **The client and environment**: the MCP client and its version, the protocol era it speaks, the transport, how you ran the server (`npx`, `uvx`, Docker, from source), your OS, and the relevant configuration with secrets redacted. - **The exact prompt text**, if you generated a local change. If you're unsure how to scope something, open the issue anyway and say so. We'll help shape it. ## Want to work on the servers with us? The issues-only policy is about how **unsolicited patches** are handled; it is not a closed door. If you'd like to contribute at a deeper level, in general or in a specific area, we'd like to hear from you. See [how the MCP community communicates](https://modelcontextprotocol.io/community/communication) for the Contributor Discord, the community calls, and how each channel is used. From there we can scope a piece of work with you and supervise it through our workflow. All participation is governed by the [Code of Conduct](./CODE_OF_CONDUCT.md). ## For maintainers The rules for maintainers and the agents working for them are in [`AGENTS.md`](./AGENTS.md), and the procedures are in the skills it indexes. Before pushing, run `npm run format` at the repository root and then **`npm run local:gate`**, which runs every check CI runs for both languages: the repo-wide guards, each TypeScript server's `validate` (format check, lint where a warning fails like an error, typecheck, build, tests) and per-file coverage gate (`coverage`), each Python server's `validate:py` chain and per-file coverage gate (`coverage:py`), the skills validator, and a boot smoke of every server. [`docs/quality-gate.md`](./docs/quality-gate.md) describes each stage. While iterating, `npm run validate -w src/<server>` checks a single TypeScript server and `npm run validate:py -- <server>` a single Python one; neither replaces the gate. A pull request that changes what a TypeScript server publishes also carries a **changeset** (`npm run changeset`), which is how that server's next version and its CHANGELOG entry are decided; [`.changeset/README.md`](./.changeset/README.md) says when one is needed and which bump to pick. The Python servers are versioned by date instead. [`RELEASING.md`](./RELEASING.md) describes both, and how a release is published. Thank you for helping make the MCP servers better for everyone!
- eslint.config.js (3968 bytes)
import js from "@eslint/js"; import globals from "globals"; import tseslint from "typescript-eslint"; import { defineConfig, globalIgnores } from "eslint/config"; // The one ESLint config for the whole repo (#4864). Every TypeScript workspace // under `src/*` lints against it (each workspace's `lint` is `eslint .`, and // ESLint finds this file by walking up), and the root's `lint:root` lints the // root tooling with it. There is deliberately no per-workspace config: a second // config is a second place for a rule to be weakened. // // Every `lint` script runs with `--max-warnings 0`, so a warning fails the gate // exactly as an error does — severity here is for the editor, not the gate. A // rule meant to be enforced is set to `error` so the squiggle reads right too. // // Findings are fixed, never silenced through this file: no rule is turned off // and no first-party path is ignored to make `lint` pass. An inline disable is // the only waiver, and it carries a one-line justification. // A leading `_` is the explicit "intentionally unused" marker — an // interface-conformance parameter, a destructuring-rest omission. Honor it // rather than deleting the signal. const unusedVars = { "@typescript-eslint/no-unused-vars": [ "error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_", }, ], }; export default defineConfig([ // Build output and installs are never a gate target: a bundle or a `.d.ts` // tsc wrote is not first-party source, and a finding inside one names a // defect nobody here can fix. When a build starts writing somewhere new, add // that location here in the same change. globalIgnores(["**/dist/**", "**/coverage/**", "**/node_modules/**"]), { // The TypeScript servers. Type-aware, because the rule that matters most // here — `no-floating-promises` — needs type information. // // The parser project is each workspace's `tsconfig.test.json`, not its // `tsconfig.json`: the build config excludes the tests (so `tsc` does not // emit them into `dist/`), and a parser project must literally contain // every file it is asked to lint. `tsconfig.test.json` covers the whole // workspace, and it is also the program `typecheck` runs, so the file set // that is linted and the one that is typechecked cannot drift apart. The // glob picks up a new workspace with no edit here. files: ["src/*/**/*.{ts,mts,cts}"], extends: [js.configs.recommended, tseslint.configs.recommended], languageOptions: { ecmaVersion: 2022, sourceType: "module", globals: { ...globals.node }, parserOptions: { project: ["./src/*/tsconfig.test.json"], tsconfigRootDir: import.meta.dirname, }, }, rules: { ...unusedVars, // The class this catches is invisible at review time: a floated call // reads like an awaited one minus four characters, and the rejection it // drops surfaces somewhere else entirely, or not at all. Every promise is // awaited, returned, ended with `.catch(…)`, or discarded with `void` // plus a comment saying why the caller cannot hold it. "@typescript-eslint/no-floating-promises": "error", }, }, { // Root tooling: the guard scripts and this config. Plain JavaScript that // no tsconfig contains, so it gets the non-type-aware rules — asking the // parser for a project would fail these files outright rather than lint // them. files: ["scripts/**/*.{js,mjs,cjs}", "*.{js,mjs,cjs}"], extends: [js.configs.recommended], languageOptions: { ecmaVersion: "latest", sourceType: "module", globals: { ...globals.node }, }, rules: { "no-unused-vars": [ "error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_", }, ], }, }, ]); - INSTRUCTIONS.md (16878 bytes)
--- name: testing description: "Write, place and run tests for a server in this repo. Use when choosing between driving the server through an MCP client and calling its functions directly; when writing a protocol-level test for a TypeScript or Python server; when choosing the command that runs one suite or a coverage report; or when a test is skipped or passes against a stale build." disable-model-invocation: false --- # Testing The **rules** are in [`AGENTS.md`](../../../AGENTS.md) under **Always test new or modified code**: new behavior comes with tests, every TypeScript file clears the per-file coverage gate, test at the protocol level where you can, and keep expected error output off the console. This skill explains the harness each server has, how to write a test with it, which command runs what, and how to clear the per-file coverage gate. Driving a running server by hand, with the Inspector or an LLM client, is `/client-smoke`. It is evidence for a PR, not a substitute for a test. **Every server is tested in-process, and every file is gated.** The four TypeScript servers link a real `Client` to the server over an in-memory transport (#4854); the three Python servers link a `ClientSession` to the real `serve()` over in-memory streams (#4855). Both languages hold each file to a per-file coverage floor, in CI and in `npm run local:gate`. ## Where a test goes | Server | Directory | File name | Runner | | --- | --- | --- | --- | | `everything`, `filesystem`, `memory`, `sequentialthinking` | `src/<server>/__tests__/` | `<subject>.test.ts` | vitest, `globals: true` | | `fetch`, `git`, `time` | `src/<server>/tests/` | `test_<subject>.py` | pytest, with `pytest-asyncio` (`asyncio_mode = "auto"`) | | Root tooling | `scripts/`, beside the script | `<name>.test.mjs` | `node --test` | Each vitest config includes only `**/__tests__/**/*.test.ts`, so a test file anywhere else in a workspace is never run and reports nothing. Shared test helpers go in `__tests__/` without the `.test` suffix, as each server's connection harness does (`__tests__/harness.ts` in `everything`, `__tests__/helpers.ts` in the other three). ## What each server's tests do | Server | How its tests reach the code | | --- | --- | | `everything`, `filesystem`, `memory`, `sequentialthinking` | An SDK `Client` connected to the server's `createServer()` over `InMemoryTransport`, in the vitest process, through the server's own harness, plus unit tests of helper modules such as `lib.ts`. `everything` drives its stdio, SSE and Streamable HTTP transports in-process too; the other three drive their `http.ts` in-process over a free loopback port, and have one thin spawn smoke of the built `dist/index.js` | | `fetch`, `git`, `time` | A `ClientSession` linked in-process to the real `serve()` over in-memory streams (below), plus direct calls on the pure functions in `server.py` | No TypeScript test uses an in-memory transport yet. ## Choosing a harness for a new test Ask what the test must prove. - **Logic** (a path check, a graph operation, a timezone conversion): call the function directly. That is what `lib.ts` and the functions in `server.py` are for. - **What a client sees** (a tool's result shape, its advertised schema, an error result, a capability, a notification): drive the server through a client. A handler called directly skips the SDK's input validation, output schema validation and error mapping, which is where the wire-level bugs in this repo have been. Which client harness is available depends on the language. ### TypeScript: in-process, over an in-memory transport Each TypeScript server exports a `createServer(…)` factory and starts its transport only from a guarded `main()`, so importing it starts nothing and a test can link a real `Client` to a real server with no process and no build. **Each server's `__tests__/` has a harness that does the linking. Connect through it**, never by calling `createServer()` and `InMemoryTransport.createLinkedPair()` by hand: the harness also does the per-session setup and teardown the server needs. | Server | Factory | Harness | `connect(…)` takes | | --- | --- | --- | --- | | `everything` | `createServer()` in `server/index.ts`, returns `{ server, cleanup }` | `__tests__/harness.ts` | `{ capabilities, setup, sessionId }`, all optional | | `filesystem` | `createServer(allowedDirectories)` in `server.ts` | `__tests__/helpers.ts` | the allowed directories, then `{ capabilities, listRoots }` | | `memory` | `createServer(memoryFilePath)` in `index.ts` | `__tests__/helpers.ts` | the graph file's path (`makeTempGraph()` makes one) | | `sequentialthinking` | `createServer()` in `index.ts` | `__tests__/helpers.ts` | `{ disableThoughtLogging }`, defaulting to `"true"` | Each `connect` returns the `client` and a `close()`; call `close()` in `afterEach`. The harnesses also export small result helpers (`call`, `textOf` and the like); read the one you are using before adding another. ```ts import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { Client } from "@modelcontextprotocol/client"; import { connect, contentOf, textOf, type Session } from "./harness.js"; describe("echo, over the protocol", () => { let session: Session; let client: Client; beforeEach(async () => { session = await connect(); client = session.client; }); afterEach(async () => { await session.close(); }); it("returns the message", async () => { const result = await client.callTool({ name: "echo", arguments: { message: "hi" }, }); expect(textOf(contentOf(result)[0])).toBe("Echo: hi"); }); it("reports bad input as a tool error", async () => { const result = await client.callTool({ name: "echo", arguments: {} }); expect(result.isError).toBe(true); }); }); ``` What `everything`'s harness does that a hand-rolled connection would miss: - **A session id per connection.** Logging, subscriptions, roots and the toggle tools keep per-session state in module-level maps keyed by the transport's session id, and `InMemoryTransport` has none, so every hand-rolled session would share the `undefined` key and leak state into the next test. `connect()` sets a fresh `sessionId` on the server transport (`sessionId: null` keeps it undefined, as stdio does), and `close()` runs the server's `cleanup(sessionId)`, which also stops the timers `createServer()` starts (the roots sync). - **Capabilities.** A tool `everything` registers in `registerConditionalTools` appears only when the client declares the matching capability: pass `capabilities` (`ALL_CAPABILITIES` declares every one), with `setup` to install the client's handlers for the requests the server sends back (sampling, elicitation, roots). - **Notifications.** `session.notifications` collects every notification no specific handler consumed; `ofMethod(notifications, method)` filters it. Assert on what the client receives (tool, resource and prompt lists, call results, errors, notifications), never on SDK internals or a handler's context object: the SDK v2 migration (#4856) must be able to update these tests with import and type changes alone. ### TypeScript: the spawn smoke of the built binary What only the published entry point can show (that `dist/index.js` starts as a bin and serves over stdio; in `memory` and `sequentialthinking`, also through a symlink, as npm's `.bin` entry runs it) is checked by one thin test per server that spawns it with `StdioClientTransport`: `filesystem`'s `bin-smoke.test.ts`, and `stdio-smoke.test.ts` in `memory` and `sequentialthinking`. `everything` has none; its transports are driven in-process. Everything else is tested in-process. Two hazards apply to these tests, and only to them: - ⚠️ **They run the last build, not your edit.** `npm test` does not build. Build first, or run `npm run validate -w src/<server>`, which builds before it tests. - ⚠️ **A missing `dist/` is handled two ways.** `filesystem` and `sequentialthinking` guard the smoke with `skipIf(!existsSync(distIndexPath))`, so with no build it is reported as **skipped** and the run stays green having tested nothing over stdio. `memory`'s has no guard and **fails**. A skipped test in this repo usually means "not built". Close the client in `finally` or `afterEach`: that is what stops the child process. Pipe its stderr (`stderr: "pipe"`), and pass environment variables in the transport's `env` option (`MEMORY_FILE_PATH`, say), since the child inherits only the SDK's default safelist (`PATH`, `HOME`, `USER` and the like). ### Python: `ClientSession` over in-memory streams, in-process Each Python server builds its `Server` inside `serve()` and serves it over the `stdio_server()` it imports into `server.py`. A test replaces that one name with a context manager that yields the server side of a pair of in-memory streams, runs the real `serve()` in a task group, and opens a `ClientSession` on the client side. No process, no build, and the SDK's input validation and error mapping run exactly as they do for a real client: ```python from contextlib import asynccontextmanager from typing import Any, AsyncIterator import anyio import pytest from mcp import ClientSession from mcp.shared.memory import create_client_server_memory_streams import mcp_server_time.server as server_module @asynccontextmanager async def connect(**serve_kwargs: Any) -> AsyncIterator[ClientSession]: async with create_client_server_memory_streams() as (client, server): @asynccontextmanager async def fake_stdio_server() -> AsyncIterator[Any]: yield server with pytest.MonkeyPatch.context() as mp: mp.setattr(server_module, "stdio_server", fake_stdio_server) async with anyio.create_task_group() as tg: tg.start_soon(lambda: server_module.serve(**serve_kwargs)) async with ClientSession(*client) as session: await session.initialize() yield session tg.cancel_scope.cancel() async def test_get_current_time() -> None: async with connect() as session: result = await session.call_tool("get_current_time", {"timezone": "UTC"}) assert result.isError is False ``` - **Patch the name `server.py` looks up** (`mcp_server_<name>.server.stdio_server`), not `mcp.server.stdio.stdio_server`: `server.py` imported the function, so the module attribute is what `serve()` calls. - **Cancel the task group after the session closes.** `serve()` runs until its streams end, so without the cancel the test never returns. - **Assert on the wire shape where you can**, for example `result.model_dump(by_alias=True, mode="json")`, rather than on Python attribute names: the SDK v2 port (#4851) renames them, and a wire-level assertion survives it. - **No network in a test.** `fetch` replaces `httpx.AsyncClient` with one on an `httpx.MockTransport`; `git` works against a temporary repository its fixture creates and closes before removing. `pytest-asyncio` with `asyncio_mode = "auto"` is a dev dependency of all three, so an `async def test_…` runs as it stands. A subprocess test over stdio (`StdioServerParameters(command=sys.executable, args=["-m", "mcp_server_<name>"])` with `mcp.client.stdio.stdio_client`) is kept to a thin smoke of the entry point. coverage.py does not measure a child process, so code reached only that way reads as uncovered. ## Tests that pin a known bug The suites are characterization tests: each asserts what the server does today, so a migration that changes behavior fails a test. Most of what they pin is intended. Some of it is a bug, pinned as it is so that the fix has to change the assertion visibly. Every test of that kind carries one marker, directly above the test (or above its `describe`/class when the whole block pins the same bug): ```ts // KNOWN BUG #<N>: pins current (wrong) behavior; the fix changes this assertion. ``` In Python the same text follows `#`. A bug with no issue yet reads `KNOWN BUG (no issue): <what is wrong>; …`, which also marks it for filing. - `git grep "KNOWN BUG"` lists every test that pins a bug. A test without the marker pins intended behavior, or guards a fixed bug against regression. - **Fixing the bug** means changing that test's assertion to the correct behavior and removing the marker, in the fix PR. - **Pinning a newly found bug**: write the test against what the code does, add the marker, and file the issue (`/issue-create`), then cite it. - A pin of current design that a feature request wants changed is not a bug and gets no marker. ## Running them | Scope | Command | | --- | --- | | One TypeScript server | `npm test -w src/<server>` | | One file, or one test | `npm test -w src/<server> -- __tests__/<file>.test.ts -t "<name>"` | | Every TypeScript server | `npm test` at the root | | One TypeScript server's coverage gate | `npm run coverage -w src/<server>` (see below) | | One TypeScript server's whole chain | `npm run validate -w src/<server>` (format check, lint, typecheck, build, test) | | One Python server | `uv run pytest` in `src/<server>` | | One Python test | `uv run pytest <path to the test file>::<name>` in `src/<server>` (for example `tests/test_server.py::test_git_checkout_existing_branch`) | | One Python server's whole chain | `npm run validate:py -- <server>` | | One Python server's coverage gate | `npm run coverage:py -- <server>` at the root | | Every Python server's coverage gate | `npm run coverage:py` at the root | | Root tooling | `npm run test:scripts` | `npm run typecheck -w src/<server>` is the only step that typechecks the test files in `filesystem`, `memory` and `sequentialthinking`: their build `tsconfig.json` excludes tests, and vitest does not typecheck. ## `test` versus `coverage` `test` is `vitest run`, the fast loop, and part of `validate`. `coverage` is `vitest run --coverage`: the same suite, instrumented, with a v8 report over the workspace's `**/*.ts` (tests and `dist/` excluded) written to the terminal and to the ignored `coverage/` directory (`coverage/index.html` has the line-by-line view). ```sh npm run coverage -w src/<server> # one server npm run coverage # all four ``` **`coverage` is a gate.** Each server's `vitest.config.ts` sets `coverage.thresholds` to 90 on lines, statements, functions and branches with `perFile: true`, so the command fails when any one file is below 90 on any one of them, even if the totals are above. CI runs it as its own job (`typescript.yml` → **Coverage \<server\>**) and `npm run local:gate` as its own stage. `test` and `validate` never measure coverage, so a change can pass them and still fail here: run `coverage` on the server you changed before you push. Clearing a red file: - The `Uncovered Line #s` column is the to-do list. A branch shortfall with no uncovered line is the un - LICENSE (12227 bytes)
The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. No rights beyond those granted by the applicable original license are conveyed for such contributions. --- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to the Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS --- MIT License Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- Creative Commons Attribution 4.0 International (CC-BY-4.0) Documentation in this project (excluding specifications) is licensed under CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for the full license text. - package.json (4074 bytes)
{ "name": "@modelcontextprotocol/servers", "private": true, "version": "0.6.2", "description": "Model Context Protocol servers", "license": "SEE LICENSE IN LICENSE", "author": "Model Context Protocol a Series of LF Projects, LLC.", "homepage": "https://modelcontextprotocol.io", "bugs": "https://github.com/modelcontextprotocol/servers/issues", "type": "module", "workspaces": [ "src/*" ], "files": [], "scripts": { "build": "npm run build --workspaces", "watch": "npm run watch --workspaces", "publish-all": "npm publish --workspaces --access public", "link-all": "npm link --workspaces", "changeset": "changeset", "version-packages": "changeset version && npm install --package-lock-only --ignore-scripts", "verify:skills": "node scripts/verify-skills.mjs", "verify:skills:cli": "node scripts/verify-skills-cli.mjs", "skills:eval": "node scripts/skill-eval.mjs", "test:scripts": "node --test \"scripts/**/*.test.mjs\"", "validate": "npm run validate:guards && npm run validate --workspaces", "validate:guards": "npm run format:check:root && npm run lint:root && npm run verify:format-coverage && npm run verify:skills && npm run verify:typecheck-coverage && npm run verify:dep-lockstep && npm run verify:no-test-retries && npm run verify:action-pins && npm run test:scripts", "format": "npm run format:root && npm run format --workspaces", "format:root": "prettier --write \"scripts/**/*.{ts,mts,cts,js,mjs,cjs}\" \"*.{ts,mts,cts,js,mjs,cjs}\" --ignore-path .prettierignore", "format:check": "npm run format:check:root && npm run format:check --workspaces", "format:check:root": "prettier --check \"scripts/**/*.{ts,mts,cts,js,mjs,cjs}\" \"*.{ts,mts,cts,js,mjs,cjs}\" --ignore-path .prettierignore", "lint": "npm run lint:root && npm run lint --workspaces", "lint:root": "eslint scripts \"*.{js,mjs,cjs}\" --max-warnings 0", "test": "npm run test --workspaces", "coverage": "npm run coverage --workspaces", "verify:format-coverage": "node scripts/verify-format-coverage.mjs", "verify:typecheck-coverage": "node scripts/verify-typecheck-coverage.mjs", "verify:dep-lockstep": "node scripts/verify-dep-lockstep.mjs", "validate:py": "node scripts/validate-py.mjs", "coverage:py": "node scripts/coverage-py.mjs", "verify:install-fresh": "node scripts/verify-install-fresh.mjs", "verify:no-test-retries": "node scripts/verify-no-test-retries.mjs", "verify:action-pins": "node scripts/verify-action-pins.mjs", "verify:dco": "node scripts/verify-dco.mjs", "smoke": "node scripts/smoke-servers.mjs", "interface-diff": "node scripts/interface-diff.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" }, "dependencies": { "@modelcontextprotocol/server-everything": "*", "@modelcontextprotocol/server-filesystem": "*", "@modelcontextprotocol/server-memory": "*", "@modelcontextprotocol/server-sequential-thinking": "*" }, "devDependencies": { "@changesets/changelog-github": "1.0.1", "@changesets/cli": "^3.0.3", "@eslint/js": "^10.0.1", "@modelcontextprotocol/client": "^2.3.1", "eslint": "^10.11.0", "globals": "^17.12.0", "mcp-server-diff": "3.0.0", "prettier": "3.8.4", "proper-lockfile": "^4.1.2", "semver": "^7.8.4", "typescript-eslint": "^8.71.0", "yaml": "^2.9.0" }, "overrides": { "qs": ">=6.16.1", "hono": ">=4.13.16", "@hono/node-server": ">=2.1.6", "proxy-addr": "^2.0.8", "ip-address": "^10.7.4", "brace-expansion": "^5.0.12", "fast-uri": "^3.1.9", "nanoid": "^3.3.18", "source-map-js": "^1.2.2", "minimatch": "^11.0.1" } } - README.md (10844 bytes)
# Model Context Protocol servers This repository is a collection of *reference implementations* for the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), as well as references to community-built servers and additional resources. > [!IMPORTANT] > If you are looking for a list of MCP servers, you can browse published servers on [the MCP Registry](https://registry.modelcontextprotocol.io/). The repository served by this README is dedicated to housing just the small number of reference servers maintained by the MCP steering group. > [!WARNING] > The servers in this repository are intended as **reference implementations** to demonstrate MCP features and SDK usage. They are meant to serve as educational examples for developers building their own MCP servers, not as production-ready solutions. Developers should evaluate their own security requirements and implement appropriate safeguards based on their specific threat model and use case. The servers in this repository showcase the versatility and extensibility of MCP, demonstrating how it can be used to give Large Language Models (LLMs) secure, controlled access to tools and data sources. Typically, each MCP server is implemented with an MCP SDK: - [C# MCP SDK](https://github.com/modelcontextprotocol/csharp-sdk) - [Go MCP SDK](https://github.com/modelcontextprotocol/go-sdk) - [Java MCP SDK](https://github.com/modelcontextprotocol/java-sdk) - [Kotlin MCP SDK](https://github.com/modelcontextprotocol/kotlin-sdk) - [PHP MCP SDK](https://github.com/modelcontextprotocol/php-sdk) - [Python MCP SDK](https://github.com/modelcontextprotocol/python-sdk) - [Ruby MCP SDK](https://github.com/modelcontextprotocol/ruby-sdk) - [Rust MCP SDK](https://github.com/modelcontextprotocol/rust-sdk) - [Swift MCP SDK](https://github.com/modelcontextprotocol/swift-sdk) - [TypeScript MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk) ## 🌟 Reference Servers These servers aim to demonstrate MCP features and the official SDKs. - **[Everything](src/everything)** - Reference / test server with prompts, resources, and tools. - **[Fetch](src/fetch)** - Web content fetching and conversion for efficient LLM usage. - **[Filesystem](src/filesystem)** - Secure file operations with configurable access controls. - **[Git](src/git)** - Tools to read, search, and manipulate Git repositories. - **[Memory](src/memory)** - Knowledge graph-based persistent memory system. - **[Sequential Thinking](src/sequentialthinking)** - Dynamic and reflective problem-solving through thought sequences. - **[Time](src/time)** - Time and timezone conversion capabilities. ### Archived The following reference servers are now archived and can be found at [servers-archived](https://github.com/modelcontextprotocol/servers-archived). - **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime. - **[Brave Search](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search)** - Web and local search using Brave's Search API. Has been replaced by the [official server](https://github.com/brave/brave-search-mcp-server) ([`@brave/brave-search-mcp-server`](https://www.npmjs.com/package/@brave/brave-search-mcp-server)). - **[EverArt](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/everart)** - AI image generation using various models. - **[GitHub](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/github)** - Repository management, file operations, and GitHub API integration. - **[GitLab](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gitlab)** - GitLab API, enabling project management. - **[Google Drive](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gdrive)** - File access and search capabilities for Google Drive. - **[Google Maps](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/google-maps)** - Location services, directions, and place details. - **[PostgreSQL](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres)** - Read-only database access with schema inspection. - **[Puppeteer](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/puppeteer)** - Browser automation and web scraping. - **[Redis](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/redis)** - Interact with Redis key-value stores. - **[Sentry](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io. - **[Slack](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/slack)** - Channel management and messaging capabilities. Now maintained by [Zencoder](https://github.com/zencoderai/slack-mcp-server) - **[SQLite](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sqlite)** - Database interaction and business intelligence capabilities. ## 🚀 Getting Started ### Using MCP Servers in this Repository TypeScript-based servers in this repository can be started with `npx`. For example, this will start the [Memory](src/memory) server: ```sh npx -y @modelcontextprotocol/server-memory ``` Python-based servers in this repository can be started with [`uvx`](https://docs.astral.sh/uv/concepts/tools/) or [`pip`](https://pypi.org/project/pip/). `uvx` is recommended for ease of use and setup. For example, this will start the [Git](src/git) server: ```sh # With uvx uvx mcp-server-git # With pip pip install mcp-server-git python -m mcp_server_git ``` Follow [these](https://docs.astral.sh/uv/getting-started/installation/) instructions to install `uv` / `uvx` and [these](https://pip.pypa.io/en/stable/installation/) to install `pip`. ### Using an MCP Client However, running a server on its own isn't very useful, and should instead be configured into an MCP client. For example, here's the Claude Desktop configuration to use the above server: ```json { "mcpServers": { "memory": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"] } } } ``` On Windows, wrap `npx` with `cmd /c`: ```json { "mcpServers": { "memory": { "command": "cmd", "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-memory"] } } } ``` Additional examples of using the Claude Desktop as an MCP client might look like: ```json { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] }, "git": { "command": "uvx", "args": ["mcp-server-git", "--repository", "path/to/git/repo"] }, "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } } ``` On Windows, apply the same wrapper to the `npx`-based `filesystem` entry above by changing its `"command"` to `"cmd"` and prepending `"/c", "npx"` to its existing `args`. Leave the `uvx` entries unchanged. ### Transports: stdio and Streamable HTTP An MCP server talks to its client over a **transport**. The protocol defines two standard ones, and they run very differently: | Transport | How the server runs | How a client reaches it | |---|---|---| | **stdio** | The client launches the server as a subprocess and talks to it over the process's stdin and stdout. The server opens no port. | A `command` and `args` in the client's configuration, as in the examples above | | **Streamable HTTP** | The server runs on its own as an HTTP service, and can serve many clients | A URL, such as `http://localhost:3001/mcp` | **Every server in this repository serves stdio by default, and every one can also serve Streamable HTTP** on `http://127.0.0.1:3001/mcp` (set `PORT` and `HOST` to move it): [Everything](src/everything) with its `streamableHttp` argument (its README also covers its deprecated HTTP+SSE transport), and the others with `--transport streamable-http`, as each server's README shows. Started without one, a server uses stdio, so when you run `uvx mcp-server-git` or `npx -y @modelcontextprotocol/server-memory` in a terminal, it opens no port, prints at most a one-line startup notice, and then appears to hang. That is expected: it is waiting for a client to send it messages on stdin. You do not normally start a stdio server yourself; your MCP client starts it from its configuration and stops it when it is done. To try a server without setting up a client, use the [MCP Inspector](https://github.com/modelcontextprotocol/inspector). Given a stdio server's command, it launches the server for you and lets you browse and call its tools; given a URL, it connects to a running Streamable HTTP server: ```sh # A stdio server: the Inspector launches it npx @modelcontextprotocol/inspector uvx mcp-server-git # A Streamable HTTP server: start it first, then connect to its URL npx @modelcontextprotocol/server-everything streamableHttp # or: uvx mcp-server-time --transport streamable-http npx @modelcontextprotocol/inspector --transport http --server-url http://localhost:3001/mcp ``` For more, see the [transport layer](https://modelcontextprotocol.io/docs/learn/architecture#transport-layer) in the MCP architecture overview, and [Transports](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports) in the specification. ## 🛠️ Creating Your Own Server Interested in creating your own MCP server? Visit the official documentation at [modelcontextprotocol.io](https://modelcontextprotocol.io/introduction) for comprehensive guides, best practices, and technical details on implementing MCP servers. ## 📚 Learn More See [ADDITIONAL.md](ADDITIONAL.md) for a curated list of frameworks and resources that simplify building MCP servers and clients. ## 🤝 Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for information about contributing to this repository. ## 📦 Releasing See [RELEASING.md](RELEASING.md) for how packages are published (OIDC trusted publishing from CI — no registry tokens) and how to retry a failed publish. ## 🔒 Security See [SECURITY.md](SECURITY.md) for reporting security vulnerabilities. ## 📜 License This project is licensed under the Apache License, Version 2.0 for new contributions, with existing code under MIT - see the [LICENSE](LICENSE) file for details. ## 💬 Community - [GitHub Discussions](https://github.com/modelcontextprotocol/modelcontextprotocol/discussions) ## ⭐ Support If you find MCP servers useful, please consider starring the repository and contributing new servers or improvements! --- Managed by Anthropic, but built together with the community. The Model Context Protocol is open source and we encourage everyone to contribute their own servers and improvements! - RELEASING.md (14641 bytes)
# Releasing How the packages in this repository are versioned and published, and what to do when a publish fails. ## How versioning works **No workflow computes or stamps a version at release time.** The version in each package's manifest is the source of truth, and it changes only through a reviewed pull request on `v2/main`. The two languages use different schemes, for a reason that comes from their registries. ### TypeScript servers: semver, managed by changesets `everything`, `filesystem`, `memory` and `sequentialthinking` use **semver**, managed by [changesets](https://github.com/changesets/changesets). - A PR that changes what one of them publishes includes a **changeset**: a small file under [`.changeset/`](.changeset/README.md), created with `npm run changeset`, naming the package, the bump type and the line that becomes its CHANGELOG entry. - Merged changesets accumulate on `v2/main`. On every push there, [`version-packages.yml`](.github/workflows/version-packages.yml) creates or updates one rolling **"Version Packages" PR** that consumes them: it bumps each affected `package.json`, writes the package's `CHANGELOG.md`, deletes the consumed changeset files and refreshes `package-lock.json`. Merging that PR is what changes a version. - Each server reports that same version in its MCP `serverInfo`, read from `package.json` at run time, so the bump needs no matching source edit. Semver policy: | Bump | When | | --- | --- | | **patch** | A bug fix | | **minor** | A new tool, prompt, resource or option | | **major** | A breaking change: a tool removed or renamed, a schema change that breaks clients, a protocol or Node floor bump | The semver line starts at **`1.0.0`** for all four packages. Their earlier releases were date-stamped (`2025.x`, `2026.x`), which sorts above any semver number, but `npm install` and `npx` resolve the `latest` dist-tag rather than the highest number, so publishing `1.x` is what users get. npm will not move `latest` to a lower version implicitly, so `release.yml` always passes the dist-tag explicitly, and chooses it at publish time: `latest` for the move from the date-stamped line to `1.x` and for any version higher than the registry's current `latest`, and `backfill` otherwise. The second case is an older release's failed leg re-run after a newer version has published: the version becomes installable by number, and `latest` does not move backward. Once `1.0.0` is live, a scope maintainer deprecates the date-stamped range (`>=2025.0.0 <2027.0.0`) by hand, once; the `release` skill has the command and the check to run first. ### Python servers: CalVer `fetch`, `git` and `time` use **CalVer** (`2026.8.1`). pip and uv have no dist-tags and always install the numerically highest version, so the existing `2026.x` line on PyPI has to keep climbing. A maintainer dispatches the **Prepare Python Release** workflow ([`prepare-python-release.yml`](.github/workflows/prepare-python-release.yml)) on `v2/main`, giving it the number of the milestone's release issue. It runs [`scripts/prepare-python-release.mjs`](scripts/prepare-python-release.mjs), which stamps today's date onto each Python package with a shipped change since its last version bump, refreshes its `uv.lock`, and opens a PR whose body starts with `Closes #<release issue>`. A package with no such change is left alone. GitHub only lists a `workflow_dispatch` workflow that exists on the default branch (`main`). Until the first milestone merge carries this one there, run the same script locally on a branch cut from `origin/v2/main` and open the PR by hand: ```bash node scripts/prepare-python-release.mjs # prints one "name: old -> new" line per stamped package ``` ### 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 <branch>` (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. ## How publishing works Publishing is triggered by a maintainer **publishing a GitHub Release** whose tag is on `main`. There is no scheduled or merge-triggered release. The release tag is only a label: it carries no version, and nothing compares it with one. What the workflow does check is where the tag points: a Release whose commit is not on `main` fails before any publish job can start, since `main` only receives reviewed milestone merges. [`release.yml`](.github/workflows/release.yml) runs on `release: published`, checked out at the release tag. It handles every package as its own pair of jobs, a build and a publish (`fail-fast: false`, so one package's failure never blocks another): | Job | Holds | Does | | --- | --- | --- | | **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 | 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`. The build jobs finish before the publish jobs ask for approval, so **wait for every build leg to finish before approving the `release` environment**, and read their logs: they say what each package will do. A package whose build leg passed is safe to approve. One failed build leg does not hold the others back: approve the healthy packages, and handle the failed one as described under [When a publish fails](#when-a-publish-fails). The **registry-diff guard** is what makes a release idempotent and self-healing. A package whose version is already on the registry is **skipped, not failed**: - **npm**: [`scripts/npm-publish-guard.mjs`](scripts/npm-publish-guard.mjs) asks the registry whether the version exists, in the build job. For a published version the job builds nothing and uploads a `SKIP` marker, and the publish job exits cleanly on it. A package the registry has never seen counts as "publish it", so a new server's first release works. An answer the guard cannot read fails the job rather than guessing. - **PyPI**: `skip-existing` on the upload action. So a release publishes exactly the packages whose version moved, and a package whose publish failed is picked up by the next release with nothing to clean up. **Authentication is OIDC trusted publishing on both registries. There are no registry tokens.** - **npm**: each `@modelcontextprotocol/*` package is registered on npmjs.com with a [trusted publisher](https://docs.npmjs.com/trusted-publishers) bound to this repository, workflow filename `release.yml`, and environment `release` (the binding is case-sensitive). Packages publish with [provenance attestations](https://docs.npmjs.com/generating-provenance-statements). - **PyPI**: published via [PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/) using `pypa/gh-action-pypi-publish`, with the same `release.yml` + `release` environment binding. Because of those bindings, the publish jobs must stay in `release.yml` and keep the `release` environment. ## 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. 1. **A release issue**, `Release vX.Y.Z`, is filed for the milestone. Every PR below references it, and it stays open until the Release is published. 2. **Preparation PRs land on `v2/main`**, each starting with `Closes #<release issue>`: - the **audit** (`npm audit`, and `pip-audit` over each Python server's locked requirements): the report goes on the release issue, and any fix it forces is its own commit in a PR; - the **Version Packages** PR (TypeScript), which is linked to the release issue with `addCloseIssueReferences` and a `Part of #N` comment, and gets `Part of #N` as its body's first line just before merging, because the changesets action rewrites its body on every push; - the **Prepare Python Release** PR (Python), which keeps its `Closes #N` line and is also linked to the release issue with `addCloseIssueReferences`, since on `v2/main` a closing keyword is only a cross-reference. A milestone that touches both languages and needs an audit fix has all three. They are merged before the next step starts. 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 #<release issue>`, 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. 7. **The release issue is closed by hand**, and its card moves to Done. ## When a publish fails A failed matrix leg means that one package did not publish; everything that succeeded stays published. When a package's **build** job fails, its publish job still asks for approval and then fails at the download step, having published nothing: there is no artifact for it to publish. **A transient failure (a registry hiccup, a runner fault): re-run the failed jobs on the same run.** ```bash gh run rerun <run-id> --failed --repo modelcontextprotocol/servers ``` - A re-run is still a `release.yml` run in the `release` environment, so it satisfies the trusted-publisher binding. - It re-runs only the failed legs, at the original release tag. It publishes exactly the released code, and the registry-diff guard keeps already-published packages safe. If the failed leg was a build job, re-run it together with its publish job. - It needs a fresh `release` environment approval, and the run must be complete first (approve or reject any pending deployments). - The build jobs' artifacts are kept for **7 days**. Within that time, re-running a failed publish leg alone works, because the artifact it downloads is still there. After that (GitHub allows re-runs for about 30 days), re-run the package's build leg together with its publish leg, or the whole run (`gh run rerun <run-id>`): the build recreates the artifact, and the registry-diff guard skips whatever already published. **A defect in the released code or in the workflow: fix it and release again.** A release event runs the workflow as it is at the tag, so a re-run repeats the same broken step. Fix it on `v2/main` through an ordinary PR, merge `v2/main` into `main`, and publish a new Release. The guard publishes whatever never reached the registry and skips the rest: no stranded versions, and no version edits to force it. **Never:** - Publish manually with an npm token or from a laptop. There are no registry tokens, and a manual publish would break the provenance chain. - Edit a version by hand to force a publish. Versions change only through the Version Packages and Prepare Python Release PRs. ## Environment approvals The `release` environment's required-reviewer list is configured in the repository settings (Settings → Environments → `release`). Reviewer rights come only from that list: repository admin does not confer deployment approval.
- SECURITY.md (4286 bytes)
# Security Policy Thank you for helping keep the Model Context Protocol and its ecosystem secure. This page says how to report a vulnerability in one of the servers in this repository, and where to send a report that belongs somewhere else. ## Reporting a vulnerability If you find a security vulnerability in one of the servers in this repository, report it privately through [GitHub's private vulnerability reporting](https://github.com/modelcontextprotocol/servers/security/advisories/new) for this repository (the **Security** tab → **Report a vulnerability**). See GitHub's guide to [privately reporting a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability). Please **do not** report security vulnerabilities through public GitHub issues, discussions, or pull requests. ## Scope **In scope:** the servers maintained in this repository, under [`src/`](src): | Server | Package | | ------------------ | -------------------------------------------------------- | | everything | `@modelcontextprotocol/server-everything` (npm) | | fetch | `mcp-server-fetch` (PyPI) | | filesystem | `@modelcontextprotocol/server-filesystem` (npm) | | git | `mcp-server-git` (PyPI) | | memory | `@modelcontextprotocol/server-memory` (npm) | | sequentialthinking | `@modelcontextprotocol/server-sequential-thinking` (npm) | | time | `mcp-server-time` (PyPI) | **Report these elsewhere:** - **A vulnerability in an MCP SDK**, including transport handling, session management and message validation that a server only inherits: report it privately to the [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/new) or the [Python SDK](https://github.com/modelcontextprotocol/python-sdk/security/advisories/new). If you are not sure whether the problem is in a server or in its SDK, report it here and we will route it. - **A server that is no longer in this repository.** Servers moved to [`servers-archived`](https://github.com/modelcontextprotocol/servers-archived) are unmaintained and receive no security fixes. - **A third-party server**, including those listed in the [MCP Registry](https://github.com/modelcontextprotocol/registry): report it to that server's maintainers. ## Supported versions Each server is versioned and published on its own. Security fixes are made on the current development line and ship in the **next release** of the affected server; older releases are not patched. Upgrade to the latest release of a server to receive its fixes. ## About these servers The servers here are **reference implementations**, written to demonstrate MCP features and SDK usage rather than as production-ready products. They are still real software that people run, and several act on the host: `filesystem` and `git` read and write local files, and `fetch` makes outbound network requests. A way around a boundary a server claims to enforce (its allowed directories, the client's Roots, or `robots.txt`, for example) is a vulnerability, and we want to hear about it. A server doing what its README documents is not. Deploying a reference server safely for your own threat model remains your responsibility. ## What to include To help us triage and respond quickly, please include: - Which server is affected, and its version - How it was configured (arguments, environment variables, allowed directories or Roots) and which client ran it - A description of the vulnerability and its potential impact - Steps to reproduce it, or a proof of concept - Any suggested fix (optional) ## What happens next A maintainer reviews each report, confirms whether the code is this repository's or an SDK's, and either accepts the advisory or closes it with a reason. An accepted advisory is fixed privately, and published once the fixed release is available. With your agreement, you are credited in the published advisory.
- SKILL.md (22514 bytes)
--- name: board-ops description: "gh recipes for the Servers V2 project board (#43): add an issue's card, move its Status, set or change its Priority, delete a card, and recover from a deleted single-select option. Use when moving a card between columns; when setting Status or Priority; when an option ID is rejected; before editing a board field's options; or when cards lost their Status or Priority." disable-model-invocation: false --- # Board operations The rules about _what_ a card's Status and Priority should be live in [`AGENTS.md`](../../../AGENTS.md) under **Issue-driven work style**. This skill is the _mechanics_: the exact `gh` calls, the IDs, and the ways the board can be damaged. Related: `/issue-create` (the create flow, which boards a new issue through the add-card recipe below). **This file is the only place the board's IDs are written down.** Every other skill and document names a column or a field and points here. Two copies of an ID are worse than one, because the stale copy is indistinguishable from the live one. ## The board | Board | Owner | Fields this workflow uses | | --- | --- | --- | | [Servers V2 (#43)](https://github.com/orgs/modelcontextprotocol/projects/43) | `modelcontextprotocol` | Status, Priority | There is one board. It is an **org** project, so every `gh project` command takes `--owner modelcontextprotocol`. The board is **private**: treat a dump of its items as private data (see the snapshot section below). **Only issues go on the board, never PRs, never draft cards.** A PR is tracked through the card of the issue it closes. The one exception is a security advisory's `[GHSA-…]` draft card; see [Advisory draft cards](#advisory-draft-cards). ## IDs The project node id and the field ids are stable: | Thing | ID | | --- | --- | | Project node ID | `PVT_kwDOCt2Azc4BcZgq` | | Status field ID | `PVTSSF_lADOCt2Azc4BcZgqzhXCpm0` | | Priority field ID | `PVTSSF_lADOCt2Azc4BcZgqzhjiM9M` | The **option** ids are **not** stable. They are regenerated whenever a single-select field's option list is edited (see the hazard below), so **this skill does not list them. Resolve an option id by its name, at run time, every time**: ```sh # The board's fields, once per session. Refuses to go on from a failed call. FIELDS=$(gh project field-list 43 --owner modelcontextprotocol --format json) || FIELDS= # opt <Field> <Option name> → the option's current id, or nothing. # The arguments reach jq through --args, never as shell positional parameters: # Claude Code rewrites those in a skill invoked with arguments (#5160). opt() { jq -r '$ARGS.positional as [$f, $o] | .fields[] | select(.name == $f) | .options[] | select(.name == $o) | .id' \ --args "$@" <<<"$FIELDS" } STATUS_OPT=$(opt Status "Todo") PRIORITY_OPT=$(opt Priority "Medium") [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ] \ || echo "option not found — check the name against the list below" >&2 ``` The option **names** are what the workflow depends on: | Field | Options, in board order | | --- | --- | | Status | `Incoming`, `Todo`, `In Progress`, `In Review`, `Done` | | Priority | `Urgent`, `High`, `Medium`, `Low` | What each Status means: | Status | Means | | --- | --- | | Incoming | Arrived unboarded, awaiting review — **no milestone** | | Todo | Approved (a milestone was assigned) | | In Progress | Active work | | In Review | A PR is open | | Done | **Shipped** — a merged PR, or a parent whose last sub-issue closed | If a name above no longer resolves, list what the field actually holds rather than guessing: ```sh # Swap "Status" for "Priority" to see the other field's options. gh project field-list 43 --owner modelcontextprotocol --format json \ | jq '.fields[] | select(.name=="Status") | .options' ``` A renamed option is a change to this table, made in the same change that renames it. ## Finding a card without trusting `--limit` ⚠️ **`gh project item-list --limit N` truncates silently.** Past `N` it returns the first `N` items with no error and no warning, so a `select` over the result matches nothing and a card that exists reads as missing. A limit is a guess about the board's size; don't make the recipes depend on it being right. - **An issue's card is looked up from the issue**, which is independent of board size — see [Move an existing card](#move-an-existing-card). - **A whole-board dump** (the snapshot and the recovery dump below) genuinely needs the full listing. Those recipes use a limit with headroom **and** compare the result's `.items | length` against the `.totalCount` that `item-list --format json` also returns, so a truncated listing fails loudly instead of passing as complete. The check also catches a failed `gh` call, whose empty output has neither key. Where a later step reads the dump from a file, an incomplete dump is deleted, so that step fails on the missing file rather than running on partial data. ## Recipes Every recipe below assumes `FIELDS` and `opt` from [IDs](#ids) are defined in the same shell. ### Add a card and set its fields ```sh # Resolve both options FIRST, so a failed field lookup or a renamed option # never leaves a card on the board with no Status or Priority. STATUS_OPT=$(opt Status "Todo") # an issue you filed through the create flow is approved by definition PRIORITY_OPT=$(opt Priority "Medium") ITEM_ID= if [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ]; then # Prints the item id (PVTI_…); capture it. ITEM_ID=$(gh project item-add 43 --owner modelcontextprotocol --url <issue-url> \ --format json --jq '.id') || ITEM_ID= fi if [ -n "$ITEM_ID" ] && [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ]; then # Chained: a failed Status edit stops before Priority, and the failure shows. gh project item-edit --project-id PVT_kwDOCt2Azc4BcZgq --id "$ITEM_ID" \ --field-id PVTSSF_lADOCt2Azc4BcZgqzhXCpm0 --single-select-option-id "$STATUS_OPT" \ && gh project item-edit --project-id PVT_kwDOCt2Azc4BcZgq --id "$ITEM_ID" \ --field-id PVTSSF_lADOCt2Azc4BcZgqzhjiM9M --single-select-option-id "$PRIORITY_OPT" \ || echo "item-edit FAILED — card $ITEM_ID may be half set; read it back" >&2 else echo "missing option id (nothing added) or item-add failed — nothing edited" >&2 fi ``` Each `item-edit` sets **one** field, so setting both takes two calls; there is no combined form. `item-add` on an issue that already has a card returns the existing card's id rather than adding a second one. For an issue swept in at triage, the only difference is Status → **Incoming** and that you do **not** set a milestone. ### Move an existing card Look the item id up **from the issue** rather than re-adding it. An issue's `projectItems` lists the cards it has on every board, so the lookup does not depend on how many items the board holds (see [Finding a card without trusting `--limit`](#finding-a-card-without-trusting---limit)). Select the card by the board's **node id**, not its number: project numbers are per-owner, and an issue can also sit on a user-owned project that happens to be numbered 43. Querying through the repository also means the issue number cannot match another repo's issue. The mutation runs only on a non-empty id: `item-edit --id ""` fails with an opaque node-resolution error rather than saying the card was not found. The `|| ITEM_ID=` matters too: on a GraphQL error (a number that is a PR, not an issue; a rate limit) `gh api` still prints the raw error JSON to stdout, which would otherwise land in `ITEM_ID` as a non-empty "id". `first:100` is the connection's maximum page; it counts the boards one issue is on, not the cards on a board, so it has no board-size exposure. ```sh N=<ISSUE_NUMBER> ITEM_ID=$(gh api graphql -F n="$N" -f query='query($n:Int!){ repository(owner:"modelcontextprotocol",name:"servers"){issue(number:$n){ projectItems(first:100){nodes{id project{id}}}}}}' \ --jq '.data.repository.issue.projectItems.nodes[] | select(.project.id=="PVT_kwDOCt2Azc4BcZgq") | .id') || ITEM_ID= [ -n "$ITEM_ID" ] || echo "#$N has no card on #43 (or the lookup failed)" >&2 ``` Then edit it. For example, Status → In Review, when its PR opens: ```sh STATUS_OPT=$(opt Status "In Review") if [ -n "$ITEM_ID" ] && [ -n "$STATUS_OPT" ]; then gh project item-edit --project-id PVT_kwDOCt2Azc4BcZgq --id "$ITEM_ID" \ --field-id PVTSSF_lADOCt2Azc4BcZgqzhXCpm0 --single-select-option-id "$STATUS_OPT" else echo "no ITEM_ID or option id — nothing edited" >&2 fi ``` Setting Priority is the same call with `opt Priority "<level>"` and the Priority field id `PVTSSF_lADOCt2Azc4BcZgqzhjiM9M`. ### Read a card back To confirm what a card holds, read it from the issue: ```sh N=<ISSUE_NUMBER> gh api graphql -F n="$N" -f query='query($n:Int!){ repository(owner:"modelcontextprotocol",name:"servers"){issue(number:$n){ projectItems(first:100){nodes{project{id number} fieldValues(first:20){nodes{... on ProjectV2ItemFieldSingleSelectValue{ name field{... on ProjectV2SingleSelectField{name}}}}}}}}}}' \ --jq '.data.repository.issue.projectItems.nodes[] | select(.project.id=="PVT_kwDOCt2Azc4BcZgq") | [.fieldValues.nodes[] | select(.field) | {(.field.name): .name}] | add' ``` ### Delete a card **`Done` means the work shipped.** An issue closed as duplicate / won't fix / not planned / obsolete / superseded shipped nothing, so its card is **deleted**, not parked in Done: ```sh # ITEM_ID from the issue-side LOOKUP block in "Move an existing card" above — # the lookup only, not the item-edit that follows it. if [ -n "$ITEM_ID" ]; then gh project item-delete 43 --owner modelcontextprotocol --id "$ITEM_ID" else echo "no ITEM_ID — nothing deleted" >&2 fi ``` Deleting the card removes it from the board only. **The issue itself is untouched**: it keeps its labels and comments, and stays searchable and linkable forever. Nothing is lost; the board simply stops claiming the work was delivered. Done is read as the record of what a milestone actually delivered, so a duplicate sitting there makes that record wrong in a way nobody can detect later. The close **reason** is the machine-readable form of the same distinction. `gh issue close --reason` accepts only `completed` and `not planned`, so **`duplicate` must be set through the API**: ```sh gh api repos/modelcontextprotocol/servers/issues/<N> -X PATCH \ -f state=closed -f state_reason=duplicate ``` (or "Mark as duplicate" in the web UI, which additionally records a duplicate-of link). ### Advisory draft cards A private security advisory is tracked by a **draft card** titled with the bare id, `[GHSA-xxxx-yyyy-zzzz]`, because a real issue would disclose it before a fix exists. No summary goes in the title until the advisory is published. What goes on the card, and when it moves, is the `/security-advisory` flow; these are only the mechanics. An advisory can also have a **follow-up card**, titled `[GHSA-xxxx-yyyy-zzzz follow-up]`, for work its fix leaves open. The recipes below handle it with one change: put `[$GHSA follow-up]` wherever they have `[$GHSA]`, both in the lookup's `--arg p` and in `item-create`'s `--title`. The advisory card's own lookup matches up to the closing bracket, so it never finds the follow-up. ⚠️ **A draft card has no repository and no issue number**, so the issue-side lookup above cannot find one. Look it up by its **bracketed GHSA id** in the full listing, checked for truncation, then feed that item id to `item-edit` or `item-delete` exactly as usual: ```sh GHSA=GHSA-xxxx-yyyy-zzzz # the advisory's real id ITEM_ID= # never let an earlier lookup's id survive a failed one LOOKED= # set only by a lookup over a COMPLETE listing BOARD=$(gh project item-list 43 --owner modelcontextprotocol --format json --limit 2000) if jq -e '(.items | length) == .totalCount' <<<"$BOARD" >/dev/null; then ITEM_ID=$(jq -r --arg p "[$GHSA]" '.items[] | select(.content.type=="DraftIssue") | select(.content.title | startswith($p)) | .id' <<<"$BOARD") && LOOKED=1 [ -n "$ITEM_ID" ] || echo "no draft card titled [$GHSA] on #43" >&2 else echo "item-list incomplete or failed — raise --limit; not concluding anything" >&2 fi ``` **Create** one only when that lookup ran over a complete listing **and** found none (a second card for the same advisory is a duplicate). Run it in the same shell, straight after the lookup: it refuses on a missing `LOOKED` or a found `ITEM_ID`. It is the add-card recipe with `item-create` in place of `item-add`, Status `Incoming`, and the provisional Priority: ```sh STATUS_OPT=$(opt Status "Incoming") PRIORITY_OPT=$(opt Priority "<provisional level>") if [ "$LOOKED" != 1 ] || [ -n "$ITEM_ID" ]; then echo "lookup incomplete, or [$GHSA] already has a card ($ITEM_ID) — not creating" >&2 elif [ -n "$STATUS_OPT" ] && [ -n "$PRIORITY_OPT" ]; then ITEM_ID=$(gh project item-create 43 --owner modelcontextprotocol \ --title "[$GHSA]" --body "<link and triage lines only>" \ --format json --jq '.id') || ITEM_ID= fi # Then the two chained item-edit calls from "Add a card and set its fields". ``` **Convert** it to an issue when its fix is ready to merge, keeping its opaque title; a follow-up card converts only after the advisory is **published**. When each happens, and what the issue gets, is the `/security-advisory` flow. The web UI has "Convert to issue" on the card; the API equivalent is: ```sh REPO_ID=$(gh api repos/modelcontextprotocol/servers --jq .node_id) || REPO_ID= [ -n "$ITEM_ID" ] && [ -n "$REPO_ID" ] && gh api graphql \ -f item="$ITEM_ID" -f repo="$REPO_ID" -f query='mutation($item:ID!,$repo:ID!){ convertProjectV2DraftIssueItemToIssue(input:{itemId:$item,repositoryId:$repo}){ item{id content{... on Issue{number url}}}}}' ``` The card keeps its place and its field values; the new issue takes the card's title and body. ## ⚠️ The option-deletion hazard This section and its two subsections are copied verbatim from the MCP Inspector's `board-ops`. Only the board number, the IDs, one cross-repo issue reference and one link to a skill this repo does not have were changed, plus two fixes to the recovery recipe from this repo's review: step 1 restores only cards that held the deleted option, and step 3 stops on a failed edit. The closing paragraph also no longer quotes the Inspector's option ids. The incidents they describe happened on the Inspector's board; the mechanism is GitHub's and applies to #43 unchanged. The option-id tables they mention are the Inspector's; here, option ids are resolved by name (see [IDs](#ids)), so there is no table to update, but any option id pasted into an issue, PR or script is invalidated all the same. **Never add, rename, or remove an option on a single-select board field (Status or Priority) with the `updateProjectV2Field` GraphQL mutation unless you pass every existing option's `id`.** That mutation does a **full replace** of the option list: resending options by - src/everything/__tests__/collections.test.ts (4647 bytes)
/** * Characterizes the resource collections (#3130) through the protocol: a * single `resources/read` of a collection answers with several contents, each * under its item's own URI, and each of those URIs reads back on its own. The * same reads run against a 2025-era client (`initialize`) and a 2026-07-28 * client (`server/discover`), since the collections are served to both. Also * covers the category and item-id completers and the -32602 for a category or * item that is not in the catalog. */ import { afterEach, describe, expect, it } from "vitest"; import { connect, connectModern, type Session } from "./harness.js"; import { COLLECTION_CATEGORIES, COLLECTION_ITEMS, SUMMER_SPECIALS_URI, collectionItemUri, } from "../resources/collections.js"; let session: Session | undefined; afterEach(async () => { await session?.close(); session = undefined; }); /** The contents one item is served as. */ const contentsOf = (item: (typeof COLLECTION_ITEMS)[number]) => ({ uri: collectionItemUri(item.id), mimeType: "application/json", text: JSON.stringify(item, null, 2), }); const CATEGORY_URI = "demo://resource/collection/by-category"; describe.each([ ["2025-era", () => connect()], ["2026-07-28", () => connectModern()], ])("resource collections for a %s client", (_era, open) => { it("lists the summer-specials collection and both templates", async () => { session = await open(); const { resources } = await session.client.listResources(); expect(resources).toContainEqual( expect.objectContaining({ name: "summer-specials", uri: SUMMER_SPECIALS_URI, mimeType: "application/json", }), ); const { resourceTemplates } = await session.client.listResourceTemplates(); expect(resourceTemplates.map((t) => [t.name, t.uriTemplate])).toEqual( expect.arrayContaining([ ["collection-by-category", `${CATEGORY_URI}/{category}`], ["collection-item", "demo://resource/collection/item/{itemId}"], ]), ); }); it("returns every item as a separate content, each under its own URI", async () => { session = await open(); const { contents } = await session.client.readResource({ uri: SUMMER_SPECIALS_URI, }); expect(contents).toEqual(COLLECTION_ITEMS.map(contentsOf)); expect(new Set(contents.map((c) => c.uri)).size).toBe( COLLECTION_ITEMS.length, ); }); it.each(COLLECTION_CATEGORIES)( "returns only the %s items for that category", async (category) => { session = await open(); const { contents } = await session.client.readResource({ uri: `${CATEGORY_URI}/${category}`, }); expect(contents).toEqual( COLLECTION_ITEMS.filter((i) => i.category === category).map(contentsOf), ); }, ); it("reads back each member of a collection under the URI it was returned with", async () => { session = await open(); const { contents } = await session.client.readResource({ uri: SUMMER_SPECIALS_URI, }); for (const member of contents) { const read = await session.client.readResource({ uri: member.uri }); expect(read.contents).toEqual([member]); } }); it.each([ `${CATEGORY_URI}/outerwear`, "demo://resource/collection/item/0", "demo://resource/collection/item/6", "demo://resource/collection/item/01", "demo://resource/collection/item/abc", ])("answers %s, which is not in the catalog, with -32602", async (uri) => { session = await open(); await expect(session.client.readResource({ uri })).rejects.toMatchObject({ code: -32602, data: { uri }, }); }); }); describe("completion/complete for the collection templates", () => { /** Complete one variable of a collection template. */ async function complete(uri: string, name: string, value: string) { session = await connect(); const { completion } = await session.client.complete({ ref: { type: "ref/resource", uri }, argument: { name, value }, }); return completion.values; } it.each([ ["", ["accessories", "footwear", "skincare"]], ["f", ["footwear"]], ["x", []], ])("completes category %j", async (value, expected) => { expect( await complete(`${CATEGORY_URI}/{category}`, "category", value), ).toEqual(expected); }); it.each([ ["", ["1", "2", "3", "4", "5"]], ["3", ["3"]], ["9", []], ])("completes itemId %j", async (value, expected) => { expect( await complete( "demo://resource/collection/item/{itemId}", "itemId", value, ), ).toEqual(expected); }); }); - src/everything/__tests__/gzip-address-classification.test.ts (2972 bytes)
/** * Pins how the `gzip-file-as-resource` guard classifies a resolved address, * one address at a time, so that every range is covered without a resolver or * a request. An IPv6 address that carries an IPv4 destination (IPv4-mapped, * IPv4-translated, or the well-known NAT64 prefix 64:ff9b::/96) is judged by * the IPv4 it wraps; deprecated IPv4-compatible (::/96) and site-local * (fec0::/10) addresses are refused, and so is any IPv6 address outside * global unicast (2000::/3). This mirrors the fetch server's * `_is_public_address`. The suite in gzip-private-addresses.test.ts drives the * same cases through the tool. */ import { describe, expect, it } from "vitest"; import { isNonPublic } from "../tools/gzip-file-as-resource.js"; describe("gzip-file-as-resource address classification", () => { it.each([ // The well-known NAT64 prefix, judged by the IPv4 it wraps ["64:ff9b::a9fe:a9fe", "NAT64 of 169.254.169.254 (cloud metadata)"], ["64:ff9b::7f00:1", "NAT64 of 127.0.0.1"], ["64:ff9b::a00:1", "NAT64 of 10.0.0.1"], ["64:ff9b::169.254.169.254", "NAT64 of the metadata address, dotted"], ["64:ff9b:0:0:0:0:c0a8:1", "NAT64 of 192.168.0.1, uncompressed"], ["64:ff9b::", "NAT64 of 0.0.0.0"], ["64:ff9b:1::1", "local-use NAT64"], // IPv4-mapped and IPv4-translated, judged by the IPv4 they wrap ["::ffff:127.0.0.1", "IPv4-mapped loopback, dotted"], ["::ffff:a9fe:a9fe", "IPv4-mapped metadata address"], ["::ffff:0:7f00:1", "IPv4-translated loopback"], // Deprecated IPv4-compatible, refused whatever it holds ["::7f00:1", "IPv4-compatible loopback"], ["::5db8:d70e", "IPv4-compatible public address"], ["::", "unspecified"], ["::1", "loopback"], // Deprecated site-local ["fec0::1", "site-local"], ["feff::1", "site-local, top of the range"], // Outside 2000::/3, though in no listed range ["4000::1", "reserved by the IETF"], ["1::1", "reserved by the IETF, low"], ["3fff::1", "documentation (RFC 9637)"], ["fd00:ec2::254", "unique local"], ["fe80::1", "link-local"], ["ff02::1", "multicast"], ])("refuses %s (%s)", (address) => { expect(isNonPublic(address, 6)).toBe(true); }); it.each([ ["64:ff9b::5db8:d70e", "NAT64 of the public 93.184.215.14"], ["64:ff9b::93.184.215.14", "the same, dotted"], ["64:ff9b::c000:9", "NAT64 of the 192.0.0.9 exception"], ["::ffff:93.184.215.14", "IPv4-mapped public address"], ["::ffff:0:5db8:d70e", "IPv4-translated public address"], ["2606:4700::1", "global unicast"], ["2001:3::1", "the 2001:3::/32 exception"], ])("allows %s (%s)", (address) => { expect(isNonPublic(address, 6)).toBe(false); }); it.each([ ["169.254.169.254", true], ["10.0.0.1", true], ["192.0.0.9", false], ["93.184.215.14", false], ])("judges the IPv4 address %s as non-public: %s", (address, refused) => { expect(isNonPublic(address, 4)).toBe(refused); }); }); - src/everything/__tests__/gzip-file-as-resource.test.ts (10379 bytes)
/** * Characterizes `gzip-file-as-resource` and the session resources it creates * (#4854), with its default limits: fetching a `data:` or local `http:` URL, * returning the gzipped file as a resource link or an embedded resource, * registering it for later reads, and the errors for bad protocols, oversized * or empty responses and failed fetches. It also guards #4808: two sessions * that use the same file name each keep their own resource. The configurable * limits are in `gzip-limits.test.ts`. Its fixture listens on 127.0.0.1, so it * opts in to private addresses (#5130) before the server loads; the default * refusal is in `gzip-private-addresses.test.ts`. */ import "./private-ips-opted-in.js"; import { createServer as createHttpServer, type Server } from "node:http"; import { once } from "node:events"; import { gunzipSync } from "node:zlib"; import { afterEach, beforeAll, afterAll, describe, expect, it } from "vitest"; import { connect, contentOf, contentOfType, ofMethod, textOf, type Session, } from "./harness.js"; import { RESOURCE_ICONS } from "../server/icons.js"; const TEXT = "hello, gzip"; const DATA_URI = `data:text/plain;base64,${Buffer.from(TEXT).toString("base64")}`; const TEN_MB = 10 * 1024 * 1024; let http: Server; let base: string; beforeAll(async () => { http = createHttpServer((req, res) => { switch (req.url) { case "/file.txt": res.end("served over http"); break; case "/empty": res.writeHead(204).end(); break; case "/claims-too-big": res.writeHead(200, { "content-length": String(TEN_MB + 1) }); res.write("x"); break; case "/streams-too-much": { res.writeHead(200, { "content-type": "application/octet-stream" }); const chunk = Buffer.alloc(1024 * 1024, 120); for (let i = 0; i < 11; i++) res.write(chunk); res.end(); break; } default: res.writeHead(404).end(); } }); http.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"); base = `http://127.0.0.1:${address.port}`; }); afterAll(async () => { http.closeAllConnections(); await new Promise((resolve) => http.close(resolve)); }); const sessions: Session[] = []; afterEach(async () => { await Promise.all(sessions.splice(0).map((s) => s.close())); }); async function open(): Promise<Session> { const s = await connect(); sessions.push(s); return s; } async function gzip(s: Session, args: Record<string, unknown>) { return s.client.callTool({ name: "gzip-file-as-resource", arguments: args }); } async function readBlob(s: Session, uri: string): Promise<Buffer> { const { contents } = await s.client.readResource({ uri }); expect(contents).toHaveLength(1); expect(contents[0]).toMatchObject({ uri, mimeType: "application/gzip" }); return Buffer.from("blob" in contents[0] ? contents[0].blob : "", "base64"); } describe("gzip-file-as-resource", () => { it("returns a link to a session resource holding the gzipped data", async () => { const s = await open(); const result = await gzip(s, { name: "hello.txt.gz", data: DATA_URI }); expect(result.content).toEqual([ { type: "resource_link", uri: "demo://resource/session/hello.txt.gz", name: "hello.txt.gz", mimeType: "application/gzip", icons: RESOURCE_ICONS, }, ]); const blob = await readBlob(s, "demo://resource/session/hello.txt.gz"); expect(gunzipSync(blob).toString()).toBe(TEXT); }); it("lists the session resource and announces the list change", async () => { const s = await open(); await gzip(s, { name: "listed.gz", data: DATA_URI }); const { resources } = await s.client.listResources(); expect(resources).toContainEqual({ uri: "demo://resource/session/listed.gz", name: "listed.gz", mimeType: "application/gzip", icons: RESOURCE_ICONS, }); expect( ofMethod(s.notifications, "notifications/resources/list_changed").length, ).toBeGreaterThan(0); }); it("embeds the gzipped data when outputType is 'resource'", async () => { const s = await open(); const result = await gzip(s, { name: "inline.gz", data: DATA_URI, outputType: "resource", }); const { resource } = contentOfType(contentOf(result)[0], "resource"); expect(resource).toMatchObject({ uri: "demo://resource/session/inline.gz", mimeType: "application/gzip", }); const blob = "blob" in resource ? resource.blob : ""; expect(gunzipSync(Buffer.from(blob, "base64")).toString()).toBe(TEXT); }); it("fetches an http URL", async () => { const s = await open(); await gzip(s, { name: "web.gz", data: `${base}/file.txt` }); const blob = await readBlob(s, "demo://resource/session/web.gz"); expect(gunzipSync(blob).toString()).toBe("served over http"); }); it("replaces a session resource created again under the same name", async () => { const s = await open(); await gzip(s, { name: "same.gz", data: DATA_URI }); const second = `data:text/plain;base64,${Buffer.from("second").toString("base64")}`; const result = await gzip(s, { name: "same.gz", data: second }); expect(result.isError).toBeUndefined(); const blob = await readBlob(s, "demo://resource/session/same.gz"); expect(gunzipSync(blob).toString()).toBe("second"); }); it("keeps each session's resource when two sessions use the same name (#4808)", async () => { // Regression guard for #4808: session resources are tracked per server, // so the second session's registration leaves the first session's // resource (and its content) in place. const a = await open(); const b = await open(); const second = `data:text/plain;base64,${Buffer.from("from b").toString("base64")}`; await gzip(a, { name: "shared.gz", data: DATA_URI }); await gzip(b, { name: "shared.gz", data: second }); const uri = "demo://resource/session/shared.gz"; expect(gunzipSync(await readBlob(a, uri)).toString()).toBe(TEXT); expect(gunzipSync(await readBlob(b, uri)).toString()).toBe("from b"); const { resources } = await a.client.listResources(); expect(resources.map((r) => r.uri)).toContain(uri); }); it("rejects a URL that is not http, https or data", async () => { const s = await open(); const result = await gzip(s, { data: "ftp://example.com/file.txt" }); expect(result).toEqual({ isError: true, content: [ { type: "text", text: "Error processing file ftp://example.com/file.txt: Unsupported URL protocol for ftp://example.com/file.txt. Only http, https, and data URLs are supported.", }, ], }); }); it("rejects something that is not a URL at input validation", async () => { const s = await open(); const result = await gzip(s, { data: "not a url" }); expect(result.isError).toBe(true); expect(textOf(contentOf(result)[0])).toContain("Input validation error"); }); it("rejects a response whose Content-Length is over 10 MB", async () => { const s = await open(); const url = `${base}/claims-too-big`; const result = await gzip(s, { data: url }); expect(textOf(contentOf(result)[0])).toBe( `Content-Length for ${url} exceeds max of ${TEN_MB}: ${TEN_MB + 1}`, ); }); it("rejects a response that streams more than 10 MB", async () => { const s = await open(); const url = `${base}/streams-too-much`; const result = await gzip(s, { data: url }); expect(textOf(contentOf(result)[0])).toBe( `Response from ${url} exceeds ${TEN_MB} bytes`, ); }); it("rejects a response with no body", async () => { const s = await open(); const result = await gzip(s, { data: `${base}/empty` }); expect(textOf(contentOf(result)[0])).toBe("No response body"); }); it("reports a fetch that fails", async () => { const s = await open(); const result = await gzip(s, { data: "http://127.0.0.1:1/unreachable" }); expect(result).toEqual({ isError: true, content: [{ type: "text", text: "fetch failed" }], }); }); }); describe("gzip-file-as-resource with an HTTP error response (#5207)", () => { // A server of its own, so these routes stay apart from the shared one above. let errors: Server; let errorBase: string; beforeAll(async () => { errors = createHttpServer((req, res) => { if (req.url === "/server-error") { res.writeHead(500, { "content-type": "text/plain" }); res.end("internal failure"); return; } res.writeHead(404, { "content-type": "text/html" }); res.end("<h1>Not Found</h1>"); }); errors.listen(0, "127.0.0.1"); await once(errors, "listening"); const address = errors.address(); if (address === null || typeof address === "string") throw new Error("no port"); errorBase = `http://127.0.0.1:${address.port}`; }); afterAll(async () => { errors.closeAllConnections(); await new Promise((resolve) => errors.close(resolve)); }); // Both output types: "resource" is the embedded path the issue reproduced, // and "resourceLink" is the one that would register a session resource, so // it is what the listResources assertion guards. it.each([ ["/missing", "404 Not Found", "resource"], ["/server-error", "500 Internal Server Error", "resource"], ["/missing", "404 Not Found", "resourceLink"], ["/server-error", "500 Internal Server Error", "resourceLink"], ])( "fails on %s with HTTP %s (outputType %s) and registers no resource", async (path, status, outputType) => { const s = await open(); const url = `${errorBase}${path}`; const result = await gzip(s, { name: "error.gz", data: url, outputType, }); expect(result).toEqual({ isError: true, content: [ { type: "text", text: `Fetching ${url} failed with HTTP ${status}`, }, ], }); const { resources } = await s.client.listResources(); expect(resources.map((r) => r.uri)).not.toContain( "demo://resource/session/error.gz", ); }, ); }); - src/everything/__tests__/gzip-limits.test.ts (5190 bytes)
/** * Characterizes the environment variables that configure * `gzip-file-as-resource` (#4854): `GZIP_MAX_FETCH_SIZE`, * `GZIP_MAX_FETCH_TIME_MILLIS` and `GZIP_ALLOWED_DOMAINS`, which is applied to * every redirect hop (#5130). The tool reads them once, when its module loads, * so this file sets them before it imports the server (vitest gives each test * file its own module graph). Its fixture is on loopback, so it also sets * `GZIP_ALLOW_PRIVATE_IPS`. */ import { createServer as createHttpServer, type Server } from "node:http"; import { once } from "node:events"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi, } from "vitest"; import type { Session } from "./harness.js"; let harness: typeof import("./harness.js"); let http: Server; let port: number; beforeAll(async () => { vi.stubEnv("GZIP_MAX_FETCH_SIZE", "16"); vi.stubEnv("GZIP_MAX_FETCH_TIME_MILLIS", "150"); vi.stubEnv("GZIP_ALLOWED_DOMAINS", " Example.COM, localhost ,,[::1]"); vi.stubEnv("GZIP_ALLOW_PRIVATE_IPS", "1"); harness = await import("./harness.js"); http = createHttpServer((req, res) => { if (req.url === "/hang") return; // never answers if (req.url === "/redirect") { res.writeHead(302, { location: "/file" }).end("moved"); return; } if (req.url === "/off-list") { res.writeHead(307, { location: `http://127.0.0.1:${port}/file` }).end(); return; } if (req.url === "/to-missing") { res.writeHead(302, { location: "/missing" }).end(); return; } if (req.url === "/missing") { res.writeHead(404).end("not here"); return; } if (req.url === "/loop") { res.writeHead(301, { location: "/loop" }).end(); return; } res.end("small"); }); http.listen(0); // every interface, so both localhost and 127.0.0.1 reach it await once(http, "listening"); const address = http.address(); if (address === null || typeof address === "string") throw new Error("no port"); port = address.port; }); afterAll(async () => { vi.unstubAllEnvs(); http.closeAllConnections(); await new Promise((resolve) => http.close(resolve)); }); let session: Session | undefined; afterEach(async () => { await session?.close(); session = undefined; }); async function gzip(data: string) { session ??= await harness.connect(); const result = await session.client.callTool({ name: "gzip-file-as-resource", arguments: { name: "limited.gz", data }, }); return harness.contentOf(result)[0]; } async function gzipText(data: string): Promise<string> { return harness.textOf(await gzip(data)); } describe("gzip-file-as-resource limits", () => { it("refuses a host that is not in GZIP_ALLOWED_DOMAINS", async () => { const url = `http://127.0.0.1:${port}/file`; expect(await gzipText(url)).toBe( `Error processing file ${url}: Domain 127.0.0.1 is not in the allowed domains list.`, ); }); it("allows a listed host, case and whitespace aside", async () => { expect(await gzip(`http://localhost:${port}/file`)).toMatchObject({ type: "resource_link", uri: "demo://resource/session/limited.gz", }); }); it("matches a listed IPv6 literal with its brackets", async () => { expect(await gzip(`http://[::1]:${port}/file`)).toMatchObject({ type: "resource_link", }); }); it("refuses a host that only ends with a listed domain's name", async () => { const lookalike = "https://notexample.com/x"; expect(await gzipText(lookalike)).toBe( `Error processing file ${lookalike}: Domain notexample.com is not in the allowed domains list.`, ); }); it("does not apply the domain list to data: URLs, but does apply the size limit", async () => { const data = `data:text/plain;base64,${Buffer.from("x".repeat(17)).toString("base64")}`; expect(await gzipText(data)).toBe(`Response from ${data} exceeds 16 bytes`); }); it("aborts a fetch that takes longer than GZIP_MAX_FETCH_TIME_MILLIS", async () => { const url = `http://localhost:${port}/hang`; expect(await gzipText(url)).toBe( `Fetching ${url} took more than 150 ms and was aborted.`, ); }); it("follows a redirect to a listed host", async () => { expect(await gzip(`http://localhost:${port}/redirect`)).toMatchObject({ type: "resource_link", uri: "demo://resource/session/limited.gz", }); }); it("reports the status of a redirect's final response, not the redirect's", async () => { const url = `http://localhost:${port}/to-missing`; expect(await gzipText(url)).toBe( `Fetching ${url} failed with HTTP 404 Not Found`, ); }); it("applies GZIP_ALLOWED_DOMAINS to a redirect hop (#5130)", async () => { expect(await gzipText(`http://localhost:${port}/off-list`)).toBe( `Error processing file http://127.0.0.1:${port}/file: Domain 127.0.0.1 is not in the allowed domains list.`, ); }); it("abandons a fetch after five redirects", async () => { const url = `http://localhost:${port}/loop`; expect(await gzipText(url)).toBe( `Fetching ${url} followed more than 5 redirects and was abandoned.`, ); }); }); - src/everything/__tests__/gzip-private-addresses.test.ts (7574 bytes)
/** * Characterizes how `gzip-file-as-resource` treats non-public destinations * with its default configuration (#5130): a URL whose host is, or resolves * to, a loopback, private, link-local or other non-public address is refused * before anything is requested, and so is a redirect from a public origin to * one. A public origin cannot be reached from a test, so `node:dns/promises` * and `fetch` are stubbed for one name, `public.example`; every other name * and URL goes to the real resolver and the real `fetch`. The opt-in * (`GZIP_ALLOW_PRIVATE_IPS`) is exercised by the other gzip suites, whose * fixtures are on loopback. The fetch deadline is shortened, before the * server loads, to show that it bounds a lookup that never answers. */ import { createServer as createHttpServer, type Server } from "node:http"; import { once } from "node:events"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi, } from "vitest"; import { connect, contentOf, textOf, type Session } from "./harness.js"; vi.hoisted(() => { vi.stubEnv("GZIP_MAX_FETCH_TIME_MILLIS", "500"); }); vi.mock("node:dns/promises", async (importOriginal) => { const actual = await importOriginal<typeof import("node:dns/promises")>(); const stubbed: Record<string, { address: string; family: number }> = { "public.example": { address: "93.184.215.14", family: 4 }, "anycast.example": { address: "192.0.0.9", family: 4 }, // inside 192.0.0.0/24 "anycast6.example": { address: "2001:3::1", family: 6 }, // inside 2001::/23 // DNS64 synthesizes these: NAT64 of 169.254.169.254, and of 93.184.215.14 "nat64-metadata.example": { address: "64:ff9b::a9fe:a9fe", family: 6 }, "nat64-public.example": { address: "64:ff9b::5db8:d70e", family: 6 }, }; return { ...actual, lookup: (hostname: string, options: { all: true }) => { if (hostname === "stalled.example") return new Promise(() => {}); const answer = stubbed[hostname]; return answer ? Promise.resolve([answer]) : actual.lookup(hostname, options); }, }; }); let http: Server; let port: number; let hits = 0; beforeAll(async () => { http = createHttpServer((_req, res) => { hits++; res.end("internal only"); }); http.listen(0); // every interface, so 127.0.0.1, ::1 and localhost reach it await once(http, "listening"); const address = http.address(); if (address === null || typeof address === "string") throw new Error("no port"); port = address.port; const realFetch = globalThis.fetch; vi.stubGlobal("fetch", (input: URL, init?: RequestInit) => { if (!input.hostname.endsWith(".example")) return realFetch(input, init); if (input.pathname === "/to-loopback") { return Promise.resolve( new Response(null, { status: 302, headers: { location: `http://127.0.0.1:${port}/secret` }, }), ); } return Promise.resolve(new Response("public content")); }); }); afterAll(async () => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); http.closeAllConnections(); await new Promise((resolve) => http.close(resolve)); }); let session: Session | undefined; afterEach(async () => { await session?.close(); session = undefined; hits = 0; }); async function gzip(data: string) { session ??= await connect(); const result = await session.client.callTool({ name: "gzip-file-as-resource", arguments: { name: "private.gz", data }, }); return contentOf(result)[0]; } const refusal = (url: string, host: string, address: string) => `Error processing file ${url}: ${host} resolves to ${address}, which is not a public address. Set GZIP_ALLOW_PRIVATE_IPS=1 to allow private, loopback and link-local addresses.`; describe("gzip-file-as-resource private addresses (#5130)", () => { it("refuses a loopback address by default, without requesting it", async () => { const url = `http://127.0.0.1:${port}/secret`; expect(textOf(await gzip(url))).toBe( refusal(url, "127.0.0.1", "127.0.0.1"), ); expect(hits).toBe(0); }); it("refuses an IPv6 loopback address, and an IPv4-mapped one", async () => { const v6 = `http://[::1]:${port}/secret`; expect(textOf(await gzip(v6))).toBe(refusal(v6, "::1", "::1")); const mapped = `http://[::ffff:7f00:1]:${port}/secret`; expect(textOf(await gzip(`http://[::ffff:127.0.0.1]:${port}/secret`))).toBe( refusal(mapped, "::ffff:7f00:1", "::ffff:7f00:1"), ); expect(hits).toBe(0); }); it("refuses a name that resolves to a loopback address", async () => { const url = `http://localhost:${port}/secret`; expect(textOf(await gzip(url))).toMatch( /^Error processing file http:\/\/localhost:\d+\/secret: localhost resolves to (::1|127\.0\.0\.1), which is not a public address\./, ); expect(hits).toBe(0); }); it.each([ ["link-local (cloud metadata)", "169.254.169.254"], ["RFC 1918", "10.1.2.3"], ["CGNAT", "100.100.100.200"], ["unspecified", "0.0.0.0"], ["multicast", "224.0.0.1"], ])("refuses a %s address", async (_kind, address) => { const url = `http://${address}/latest/meta-data/`; expect(textOf(await gzip(url))).toBe(refusal(url, address, address)); }); it.each([ ["unique local", "fd00:ec2::254"], ["link-local", "fe80::1"], ])("refuses an IPv6 %s address", async (_kind, address) => { const url = `http://[${address}]/latest/meta-data/`; expect(textOf(await gzip(url))).toBe(refusal(url, address, address)); }); it.each([ ["NAT64 of a link-local IPv4", "64:ff9b::a9fe:a9fe"], ["NAT64 of a loopback IPv4", "64:ff9b::7f00:1"], ["NAT64 of an RFC 1918 IPv4", "64:ff9b::a00:1"], ["IPv4-compatible loopback", "::7f00:1"], ["site-local", "fec0::1"], ["reserved (outside 2000::/3)", "4000::1"], ])("refuses an IPv6 %s address", async (_kind, address) => { const url = `http://[${address}]/latest/meta-data/`; expect(textOf(await gzip(url))).toBe(refusal(url, address, address)); }); it("refuses a name whose DNS64 answer wraps a link-local IPv4", async () => { const url = "http://nat64-metadata.example/latest/meta-data/"; expect(textOf(await gzip(url))).toBe( refusal(url, "nat64-metadata.example", "64:ff9b::a9fe:a9fe"), ); }); it("fetches from a NAT64 address that wraps a public IPv4", async () => { expect(await gzip("http://nat64-public.example/file")).toMatchObject({ type: "resource_link", }); }); it("fetches from a public address", async () => { expect(await gzip("http://public.example/file")).toMatchObject({ type: "resource_link", uri: "demo://resource/session/private.gz", }); }); it.each([ ["IPv4", "anycast.example"], ["IPv6", "anycast6.example"], ])( "fetches from a globally reachable %s exception inside a refused range", async (_family, host) => { expect(await gzip(`http://${host}/file`)).toMatchObject({ type: "resource_link", }); }, ); it("bounds the address lookup by GZIP_MAX_FETCH_TIME_MILLIS", async () => { const url = "http://stalled.example/file"; expect(textOf(await gzip(url))).toBe( `Fetching ${url} took more than 500 ms and was aborted.`, ); }); it("refuses a redirect from a public origin to a loopback address", async () => { const hop = `http://127.0.0.1:${port}/secret`; expect(textOf(await gzip("http://public.example/to-loopback"))).toBe( refusal(hop, "127.0.0.1", "127.0.0.1"), ); expect(hits).toBe(0); }); }); - src/everything/__tests__/harness.ts (9771 bytes)
/** * The in-process protocol harness for the everything-server suite (#4854). * * Every protocol-level test links a real SDK `Client` to a real server from * `createServer()` over `InMemoryTransport`, and asserts only on what crosses * the wire: results, errors, notifications and the requests the server sends * back to the client. Nothing here reaches into SDK internals or handler * `extra` objects, so the SDK v2 codemod can update these tests with import * and type changes alone. * * `connect()` serves a 2025-era client: the server is connected to the * transport directly and the client opens with `initialize`. Per-connection * state lives on the server instance (#4852), so each session is isolated by * construction; `close()` runs the server's `cleanup()` the way the * transports do when a connection ends. The transport still gets a session id * (pass `sessionId: null` to leave it undefined, as stdio does), for the tests * that look at one. * * `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. * * `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 * does, and the client negotiates the era with `server/discover`, so every * request carries its capabilities in `_meta`. */ import { randomUUID } from "node:crypto"; import { expect } from "vitest"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import type { ClientCapabilities, ContentBlock, JSONRPCMessage, ServerNotification, } from "@modelcontextprotocol/client"; import { serveStdio } from "@modelcontextprotocol/server/stdio"; import { createServer } from "../server/index.js"; /** Options for one in-process session. */ export type ConnectOptions = { /** The capabilities the client declares in `initialize`. */ capabilities?: ClientCapabilities; /** Install request handlers on the client before it connects. */ setup?: (client: Client) => void; /** The server transport's session id; `null` leaves it undefined. */ sessionId?: string | null; }; /** A connected client, what it has been sent, and how to end the session. */ export type Session = { client: Client; sessionId: string | undefined; /** Every notification the server sent that no specific handler consumed. */ notifications: ServerNotification[]; /** Close the client and run the server's cleanup for this session. */ close: () => Promise<void>; }; /** Connect a fresh client to a fresh server over an in-memory transport. */ export async function connect(options: ConnectOptions = {}): Promise<Session> { const { server, cleanup } = createServer(); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const sessionId = options.sessionId === null ? undefined : (options.sessionId ?? randomUUID()); serverTransport.sessionId = sessionId; const client = new Client( { name: "everything-test-client", version: "0.0.0" }, { capabilities: options.capabilities ?? {} }, ); const notifications: ServerNotification[] = []; client.fallbackNotificationHandler = async (notification) => { notifications.push(notification as ServerNotification); }; options.setup?.(client); await Promise.all([ server.connect(serverTransport), client.connect(clientTransport), ]); return { client, sessionId, notifications, close: async () => { await client.close(); cleanup(); }, }; } /** Options for one in-process 2026-07-28 session. */ export type ModernConnectOptions = { /** The capabilities the client declares with each request. */ capabilities?: ClientCapabilities; /** Install request handlers on the client before it connects. */ setup?: (client: Client) => void; }; /** * Connect a fresh 2026-07-28 client to a server built for the modern era, * served the way the stdio transport serves it. */ export async function connectModern( options: ModernConnectOptions = {}, ): Promise<Session> { const cleanups: Array<() => void> = []; const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const handle = serveStdio( ({ era }) => { const { server, cleanup } = createServer({ era }); cleanups.push(cleanup); return server; }, { transport: serverTransport }, ); const client = new Client( { name: "everything-test-client", version: "0.0.0" }, { capabilities: options.capabilities ?? {}, versionNegotiation: { mode: { pin: "2026-07-28" } }, }, ); const notifications: ServerNotification[] = []; client.fallbackNotificationHandler = async (notification) => { notifications.push(notification as ServerNotification); }; options.setup?.(client); await client.connect(clientTransport); return { client, sessionId: undefined, notifications, close: async () => { await client.close(); await handle.close(); for (const cleanup of cleanups) cleanup(); }, }; } /** The notifications in `notifications` with the given method. */ export function ofMethod<M extends ServerNotification["method"]>( notifications: ServerNotification[], method: M, ): Extract<ServerNotification, { method: M }>[] { return notifications.filter( (n): n is Extract<ServerNotification, { method: M }> => n.method === method, ); } /** * Narrow a content block to the member of the `ContentBlock` union whose * `type` is `type`, throwing if the block is missing or of another kind. */ export function contentOfType<T extends ContentBlock["type"]>( block: ContentBlock | undefined, type: T, ): Extract<ContentBlock, { type: T }> { if (block?.type !== type) { throw new Error(`expected ${type} content, got ${block?.type}`); } return block as Extract<ContentBlock, { type: T }>; } /** The text of a content block that must be a text block. */ export function textOf(block: unknown): string { return contentOfType(block as ContentBlock | undefined, "text").text; } /** The content blocks of a `tools/call` result. */ export function contentOf(result: object): ContentBlock[] { return ("content" in result ? result.content : []) as ContentBlock[]; } /** Every client capability the server gates a tool on. */ export const ALL_CAPABILITIES: ClientCapabilities = { roots: { listChanged: true }, sampling: {}, elicitation: { form: {}, url: {} }, }; /** Every client capability, plus the tasks extension (2026-07-28). */ export const MODERN_CAPABILITIES: ClientCapabilities = { ...ALL_CAPABILITIES, extensions: { "io.modelcontextprotocol/tasks": {} }, }; type Json = Record<string, unknown>; /** A raw 2026-07-28 JSON-RPC peer of a server served by `serveStdio`. */ export type RawSession = { /** Send a request; resolve with its whole response (result or error). */ request: (method: string, params?: Json) => Promise<Json>; /** The result of a request that must succeed. */ result: (method: string, params?: Json) => Promise<Json>; /** The result of a `tools/call`. */ call: (name: string, args?: Json) => Promise<Json>; /** The result of a `tasks/get`. */ get: (taskId: string) => Promise<Json>; close: () => Promise<void>; }; /** * Connect a raw JSON-RPC peer to a server served by `serveStdio`, declaring * `capabilities` in the envelope of every request it sends. */ export async function connectRaw(capabilities: Json): Promise<RawSession> { const [peer, serverTransport] = InMemoryTransport.createLinkedPair(); const cleanups: Array<() => void> = []; const handle = serveStdio( ({ era }) => { const { server, cleanup } = createServer({ era }); cleanups.push(cleanup); return server; }, { transport: serverTransport }, ); const waiting = new Map<number, (message: JSONRPCMessage) => void>(); peer.onmessage = (message) => { if ("id" in message && typeof message.id === "number") { waiting.get(message.id)?.(message); } }; await peer.start(); let nextId = 1; const request = (method: string, params: Json = {}) => { const id = nextId++; return new Promise<Json>((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), }, }, }); }); }; const result = async (method: string, params: Json = {}) => { const response = await request(method, params); expect(response.error).toBeUndefined(); return response.result as Json; }; return { request, result, call: (name, args = {}) => result("tools/call", { name, arguments: args }), get: (taskId) => result("tasks/get", { taskId }), close: async () => { await handle.close(); for (const cleanup of cleanups) cleanup(); }, }; } /** * A list's entries without their `icons`, for a snapshot of the rest. The * icons are long `data:` URIs, one pair per primitive kind, and icons.test.ts * asserts on them for every list in both eras. */ export function withoutIcons<T extends { icons?: unknown }>( entries: T[], ): Omit<T, "icons">[] { return entries.map((entry) => { const rest: Omit<T, "icons"> & { icons?: unknown } = { ...entry }; delete rest.icons; return rest; }); } - src/everything/__tests__/icons.test.ts (6160 bytes)
/** * Icons with light and dark themes (SEP-973, #3131), as each era's client * sees them. * * The server attaches one light/dark icon pair per primitive kind * (server/icons.ts). These tests read what crosses the wire, in both * protocol eras: `serverInfo` from `initialize` (2025-era) or * `server/discover` (2026-07-28), and every entry of `tools/list`, * `prompts/list`, `resources/list` and `resources/templates/list`, and the * resource link a tool returns for a resource it creates (#5434). Each * must carry a "light" and a "dark" icon, and each icon must be a scalable * SVG `data:` URI that decodes to an SVG document. */ import { afterEach, describe, expect, it } from "vitest"; import type { Icon } from "@modelcontextprotocol/client"; import { ALL_CAPABILITIES, connect, connectModern, connectRaw, contentOf, contentOfType, MODERN_CAPABILITIES, type RawSession, type Session, } from "./harness.js"; import { PROMPT_ICONS, RESOURCE_ICONS, RESOURCE_TEMPLATE_ICONS, SERVER_ICONS, TOOL_ICONS, } from "../server/icons.js"; let session: Session | undefined; let raw: RawSession | undefined; afterEach(async () => { await session?.close(); await raw?.close(); session = undefined; raw = undefined; }); const SVG_DATA_URI = "data:image/svg+xml;base64,"; /** A small file for gzip-file-as-resource; a data: URI needs no network. */ const DATA_URI = `data:text/plain;base64,${Buffer.from("icons").toString("base64")}`; /** Assert that `icons` is a themed pair of decodable SVG icons. */ function expectThemedPair(icons: Icon[] | undefined): void { expect(icons).toBeDefined(); const themes = (icons ?? []).map((icon) => icon.theme).sort(); expect(themes).toEqual(["dark", "light"]); for (const icon of icons ?? []) { expect(icon.mimeType).toBe("image/svg+xml"); expect(icon.sizes).toEqual(["any"]); expect(icon.src.startsWith(SVG_DATA_URI)).toBe(true); const svg = Buffer.from( icon.src.slice(SVG_DATA_URI.length), "base64", ).toString("utf8"); expect(svg).toMatch(/^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/); expect(svg).toMatch(/<\/svg>$/); } // The two variants are drawn differently, not one image labelled twice. expect(icons?.[0]?.src).not.toBe(icons?.[1]?.src); } describe("the icon sets", () => { it("gives every primitive kind its own light/dark pair", () => { const sets = [ SERVER_ICONS, TOOL_ICONS, PROMPT_ICONS, RESOURCE_ICONS, RESOURCE_TEMPLATE_ICONS, ]; for (const set of sets) expectThemedPair(set); const lightSources = new Set( sets.map((set) => set.find((icon) => icon.theme === "light")?.src), ); expect(lightSources.size).toBe(sets.length); }); }); describe.each([ { era: "2025-era", open: () => connect({ capabilities: ALL_CAPABILITIES }), }, { era: "2026-07-28", open: () => connectModern({ capabilities: MODERN_CAPABILITIES }), }, ])("icons on the $era surface", ({ open }) => { it("puts the server's pair on serverInfo", async () => { session = await open(); const info = session.client.getServerVersion(); expect(info?.icons).toEqual(SERVER_ICONS); expectThemedPair(info?.icons); }); it("puts the tool pair on every tool", async () => { session = await open(); const { tools } = await session.client.listTools(); expect(tools.length).toBeGreaterThan(0); for (const tool of tools) expect(tool.icons).toEqual(TOOL_ICONS); }); it("puts the prompt pair on every prompt", async () => { session = await open(); const { prompts } = await session.client.listPrompts(); expect(prompts.length).toBeGreaterThan(0); for (const prompt of prompts) expect(prompt.icons).toEqual(PROMPT_ICONS); }); it("puts the resource pair on every listed resource", async () => { session = await open(); const { resources } = await session.client.listResources(); expect(resources.length).toBeGreaterThan(0); for (const resource of resources) { expect(resource.icons).toEqual(RESOURCE_ICONS); } }); it("puts the template pair on every resource template", async () => { session = await open(); const { resourceTemplates } = await session.client.listResourceTemplates(); expect(resourceTemplates.length).toBeGreaterThan(0); for (const template of resourceTemplates) { expect(template.icons).toEqual(RESOURCE_TEMPLATE_ICONS); } }); // #5434: a resource a tool creates is a resource too: its link carries the // resource pair, whichever era's mechanism keeps it readable (a session // resource for a 2025-era client, a minted URI on 2026-07-28). it("puts the resource pair on the link gzip-file-as-resource returns", async () => { session = await open(); const result = await session.client.callTool({ name: "gzip-file-as-resource", arguments: { name: "icons.gz", data: DATA_URI }, }); const link = contentOfType(contentOf(result)[0], "resource_link"); expect(link.icons).toEqual(RESOURCE_ICONS); }); }); // #5434: on the 2025 era the tool also registers the file as a session // resource, which then appears in resources/list with the pair. it("puts the resource pair on the session resource gzip-file-as-resource lists", async () => { session = await connect({ capabilities: ALL_CAPABILITIES }); await session.client.callTool({ name: "gzip-file-as-resource", arguments: { name: "listed-icons.gz", data: DATA_URI }, }); const { resources } = await session.client.listResources(); const generated = resources.find((r) => r.name === "listed-icons.gz"); expect(generated?.icons).toEqual(RESOURCE_ICONS); for (const resource of resources) { expect(resource.icons).toEqual(RESOURCE_ICONS); } }); describe("icons on the raw 2026-07-28 wire", () => { it("carries the server's pair in server/discover's serverInfo", async () => { raw = await connectRaw({}); const discover = await raw.result("server/discover"); expect(discover).toMatchObject({ _meta: { "io.modelcontextprotocol/serverInfo": { icons: SERVER_ICONS }, }, }); }); }); - src/everything/__tests__/in-memory-event-store.test.ts (3029 bytes)
// Unit tests for the Streamable HTTP event store (#4087), called directly // rather than over HTTP: which events a replay sends, and what an unknown event // id yields, are exact here, where streamable-http.test.ts can only observe // them through the SDK (which asks getStreamIdForEventId first and refuses an // unknown id before replaying). import { describe, it, expect } from "vitest"; import type { JSONRPCMessage } from "@modelcontextprotocol/server"; import { InMemoryEventStore } from "../transports/in-memory-event-store.js"; const message = (method: string): JSONRPCMessage => ({ jsonrpc: "2.0", method, }); describe("InMemoryEventStore", () => { it("replays only events from the same stream after the requested event", async () => { const eventStore = new InMemoryEventStore(); const firstStreamEvent = await eventStore.storeEvent( "stream-a", message("notifications/stream-a/first"), ); const otherStreamEvent = await eventStore.storeEvent( "stream-b", message("notifications/stream-b/first"), ); const secondStreamEvent = await eventStore.storeEvent( "stream-a", message("notifications/stream-a/second"), ); await eventStore.storeEvent( "stream-b", message("notifications/stream-b/second"), ); const replayedEvents: Array<{ eventId: string; message: JSONRPCMessage }> = []; const replayedStreamId = await eventStore.replayEventsAfter( firstStreamEvent, { send: async (eventId, replayedMessage) => { replayedEvents.push({ eventId, message: replayedMessage }); }, }, ); expect(replayedStreamId).toBe("stream-a"); expect(replayedEvents).toEqual([ { eventId: secondStreamEvent, message: message("notifications/stream-a/second"), }, ]); expect(replayedEvents.map(({ eventId }) => eventId)).not.toContain( otherStreamEvent, ); }); it("rejects an unknown event id without replaying anything", async () => { const eventStore = new InMemoryEventStore(); await eventStore.storeEvent("stream-a", message("notifications/stream-a")); const replayedEvents: Array<{ eventId: string; message: JSONRPCMessage }> = []; await expect( eventStore.replayEventsAfter("unknown-event-id", { send: async (eventId, replayedMessage) => { replayedEvents.push({ eventId, message: replayedMessage }); }, }), ).rejects.toThrow("Unknown event ID: unknown-event-id"); expect(replayedEvents).toEqual([]); }); it("looks up the stream id for a stored event id", async () => { const eventStore = new InMemoryEventStore(); const eventId = await eventStore.storeEvent( "stream-a", message("notifications/stream-a"), ); await expect(eventStore.getStreamIdForEventId(eventId)).resolves.toBe( "stream-a", ); await expect( eventStore.getStreamIdForEventId("unknown-event-id"), ).resolves.toBeUndefined(); }); }); - src/everything/__tests__/index.test.ts (4415 bytes)
/** * Characterizes the `mcp-server-everything` launcher (#4854): which transport * each argument starts, the usage text for an unknown one, the exit code when * a transport fails to start, and the entry-point guard that keeps importing * the module from starting anything. The transport modules are replaced with * stubs, since each is tested on its own; the boot smoke * (`scripts/smoke-servers.mjs`) runs the real binary. */ import { mkdtempSync, symlinkSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const { startStdioServer, startSseServer, startStreamableHttpServer } = vi.hoisted(() => ({ startStdioServer: vi.fn(), startSseServer: vi.fn(), startStreamableHttpServer: vi.fn(), })); vi.mock("../transports/stdio.js", () => ({ startStdioServer })); vi.mock("../transports/sse.js", () => ({ startSseServer })); vi.mock("../transports/streamableHttp.js", () => ({ startStreamableHttpServer, })); const { run, isEntryPoint } = await import("../index.js"); let exit: ReturnType<typeof vi.spyOn>; let error: ReturnType<typeof vi.spyOn>; let log: ReturnType<typeof vi.spyOn>; beforeEach(() => { vi.clearAllMocks(); exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never); error = vi.spyOn(console, "error").mockImplementation(() => {}); log = vi.spyOn(console, "log").mockImplementation(() => {}); }); afterEach(() => { vi.restoreAllMocks(); }); describe("run", () => { it.each([ ["stdio", startStdioServer], ["sse", startSseServer], ["streamableHttp", startStreamableHttpServer], ])("starts the %s transport", async (name, start) => { await run(name); expect(start).toHaveBeenCalledTimes(1); expect(exit).not.toHaveBeenCalled(); }); it("prints the usage and exits 1 for an unknown transport", async () => { await run("websocket"); expect(error.mock.calls.map((c: unknown[]) => c[0])).toEqual([ "-".repeat(53), " Everything Server Launcher", " Usage: node ./index.js [stdio|sse|streamableHttp]", " Default transport: stdio", "-".repeat(53), "Unknown transport: websocket", ]); expect(log.mock.calls.map((c: unknown[]) => c[0])).toEqual([ "Available transports:", "- stdio", "- sse", "- streamableHttp", ]); expect(exit).toHaveBeenCalledWith(1); }); it("reports a transport that fails to start and exits 1", async () => { const failure = new Error("port trouble"); startSseServer.mockImplementationOnce(() => { throw failure; }); await run("sse"); expect(error).toHaveBeenCalledWith("Error running script:", failure); expect(exit).toHaveBeenCalledWith(1); }); it("does not start anything when imported", async () => { // A fresh import, under vitest rather than as the binary: the entry-point // guard must keep it from starting any transport. vi.resetModules(); await import("../index.js"); expect(startStdioServer).not.toHaveBeenCalled(); expect(startSseServer).not.toHaveBeenCalled(); expect(startStreamableHttpServer).not.toHaveBeenCalled(); expect(exit).not.toHaveBeenCalled(); }); }); describe("isEntryPoint", () => { const self = new URL("../index.ts", import.meta.url); let dir: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "everything-entry-")); }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); }); it("is true for the module's own path", () => { expect(isEntryPoint(fileURLToPath(self), self.href)).toBe(true); }); it("follows a symlink, as npm's bin shim is", () => { const link = join(dir, "mcp-server-everything"); symlinkSync(fileURLToPath(self), link); expect(isEntryPoint(link, self.href)).toBe(true); }); it("is false for another script, a missing path, or none", () => { expect(isEntryPoint(join(dir, "missing.js"), self.href)).toBe(false); expect( isEntryPoint(fileURLToPath(self), pathToFileURL(join(dir, "x.js")).href), ).toBe(false); expect( isEntryPoint( fileURLToPath(new URL("../version.ts", import.meta.url)), self.href, ), ).toBe(false); expect(isEntryPoint(undefined, self.href)).toBe(false); }); }); - src/everything/__tests__/input-descriptions.test.ts (2786 bytes)
// Every property of every tool input schema the server advertises in // tools/list carries a description (#3669). A model reads these to decide what // to pass, and with no description it guesses from the property name alone. // This is the reference implementation other server authors copy, so the rule // is pinned for every tool, existing or added later, and for nested // properties (array items, object fields) as well as top-level ones. import { afterEach, describe, expect, it } from "vitest"; import { ALL_CAPABILITIES, connect, connectModern, MODERN_CAPABILITIES, type Session, } from "./harness.js"; /** A JSON Schema node, as much of it as the walk reads. */ type SchemaNode = { description?: unknown; properties?: Record<string, SchemaNode>; items?: SchemaNode | SchemaNode[]; anyOf?: SchemaNode[]; oneOf?: SchemaNode[]; allOf?: SchemaNode[]; }; /** * The path of every property under `node`, at any depth, that has no * non-empty description: the properties of nested objects and of array * items count, since a model fills those in too. */ function undescribed(node: SchemaNode, path: string): string[] { const missing: string[] = []; for (const [key, child] of Object.entries(node.properties ?? {})) { const at = `${path}.${key}`; if ( typeof child.description !== "string" || child.description.trim() === "" ) { missing.push(at); } missing.push(...undescribed(child, at)); } const items = node.items; for (const item of Array.isArray(items) ? items : items ? [items] : []) { missing.push(...undescribed(item, `${path}[]`)); } for (const branch of [ ...(node.anyOf ?? []), ...(node.oneOf ?? []), ...(node.allOf ?? []), ]) { missing.push(...undescribed(branch, path)); } return missing; } let session: Session | undefined; afterEach(async () => { await session?.close(); session = undefined; }); // Each era lists some tools the other does not (the task tools only on // 2026-07-28, the toggle-* tools only on the 2025 era), so both are checked. // Every capability is declared, so the tools gated on one are listed too. describe.each([ { era: "2025-era", open: () => connect({ capabilities: ALL_CAPABILITIES }), }, { era: "2026-07-28", open: () => connectModern({ capabilities: MODERN_CAPABILITIES }), }, ])("tool input descriptions on the $era surface (#3669)", ({ open }) => { it("describes every input property of every tool", async () => { session = await open(); const { tools } = await session.client.listTools(); expect(tools.length).toBeGreaterThan(0); const missing = tools.flatMap((tool) => undescribed(tool.inputSchema as SchemaNode, tool.name), ); expect(missing).toEqual([]); }); }); - src/everything/__tests__/listen.test.ts (6310 bytes)
// `listenOrExit` is what stops an HTTP transport from reporting a port it does // not hold (#4923: SSE printed "Server is running" on a port another process // had, and stayed up listening on nothing). These tests bind real sockets, // because the defect lived in how Express hands a real listen error to the // success callback; a mocked `listen` would not have reproduced it. // `process.exit` is replaced so the failure path can be observed without ending // the test run, and `console.error` is silenced because that path prints. // The bind address is checked the same way, on a real socket: loopback unless // `HOST` says otherwise (#5371). import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { createServer, type Server } from "node:http"; import { once } from "node:events"; import express from "express"; import { bindHost, DEFAULT_HOST, hostAndPort, listenOrExit, } from "../transports/listen.js"; const LISTENING = "listening line"; describe("listenOrExit", () => { let servers: Server[]; let errorSpy: ReturnType<typeof vi.spyOn>; let exited: Promise<number | undefined>; beforeEach(() => { servers = []; errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); exited = new Promise((resolve) => { vi.spyOn(process, "exit").mockImplementation((code) => { resolve(typeof code === "number" ? code : undefined); return undefined as never; }); }); }); afterEach(async () => { vi.restoreAllMocks(); await Promise.all( servers .filter((server) => server.listening) .map( (server) => new Promise<void>((resolve) => server.close(() => resolve())), ), ); }); /** A server holding a port on loopback, and the port it holds. */ async function holdPort(): Promise<number> { const holder = createServer(); servers.push(holder); // The address the transports bind by default: a holder on another // interface (the wildcard) would not conflict with it on every platform. holder.listen(0, DEFAULT_HOST); await once(holder, "listening"); const address = holder.address(); if (address === null || typeof address === "string") { throw new Error("expected a TCP address"); } return address.port; } /** The address `server` is bound to. */ function boundAddress(server: Server): string { const address = server.address(); if (address === null || typeof address === "string") { throw new Error("expected a TCP address"); } return address.address; } it("prints the listening line once the port is bound, and does not exit", async () => { const server = listenOrExit(express(), 0, DEFAULT_HOST, LISTENING); servers.push(server); await once(server, "listening"); expect(server.listening).toBe(true); expect(boundAddress(server)).toBe("127.0.0.1"); expect(errorSpy).toHaveBeenCalledWith(LISTENING); expect(process.exit).not.toHaveBeenCalled(); }); it("reports a port already in use and exits 1 without claiming to listen", async () => { const port = await holdPort(); const server = listenOrExit(express(), port, DEFAULT_HOST, LISTENING); servers.push(server); expect(await exited).toBe(1); expect(server.listening).toBe(false); expect(errorSpy).toHaveBeenCalledWith( `Failed to start: Port ${port} is already in use on 127.0.0.1. Set PORT to a free port or stop the conflicting process.`, ); expect(errorSpy).not.toHaveBeenCalledWith(LISTENING); }); it("binds the host it is given, such as every interface", async () => { const server = listenOrExit(express(), 0, "0.0.0.0", LISTENING); servers.push(server); await once(server, "listening"); expect(boundAddress(server)).toBe("0.0.0.0"); expect(process.exit).not.toHaveBeenCalled(); }); it("reports a host it cannot bind, and exits 1 without claiming to listen", async () => { // A reserved documentation address (RFC 5737), on no interface here. const server = listenOrExit(express(), 0, "192.0.2.1", LISTENING); servers.push(server); expect(await exited).toBe(1); expect(server.listening).toBe(false); expect(errorSpy).toHaveBeenCalledWith( "HTTP server encountered an error while starting:", expect.objectContaining({ code: "EADDRNOTAVAIL" }), ); expect(errorSpy).not.toHaveBeenCalledWith(LISTENING); }); it("reports an error that is not an object, and exits 1", async () => { const server = listenOrExit(express(), 0, DEFAULT_HOST, LISTENING); servers.push(server); await once(server, "listening"); server.emit("error", "a bare string"); expect(await exited).toBe(1); expect(errorSpy).toHaveBeenCalledWith( "HTTP server encountered an error while starting:", "a bare string", ); }); it("reports any other server error and exits 1", async () => { const server = listenOrExit(express(), 0, DEFAULT_HOST, LISTENING); servers.push(server); await once(server, "listening"); const failure = Object.assign(new Error("permission denied"), { code: "EACCES", }); server.emit("error", failure); expect(await exited).toBe(1); expect(errorSpy).toHaveBeenCalledWith( "HTTP server encountered an error while starting:", failure, ); }); }); describe("bindHost", () => { it("is loopback when HOST is unset", () => { expect(bindHost({})).toBe("127.0.0.1"); expect(DEFAULT_HOST).toBe("127.0.0.1"); }); it("is loopback when HOST is empty", () => { expect(bindHost({ HOST: "" })).toBe("127.0.0.1"); }); it("is HOST when it is set", () => { expect(bindHost({ HOST: "0.0.0.0" })).toBe("0.0.0.0"); }); it("reads the process environment by default", () => { vi.stubEnv("HOST", "::1"); try { expect(bindHost()).toBe("::1"); } finally { vi.unstubAllEnvs(); } }); }); describe("hostAndPort", () => { it("joins a host name or IPv4 address and a port", () => { expect(hostAndPort("127.0.0.1", 3001)).toBe("127.0.0.1:3001"); expect(hostAndPort("localhost", "4567")).toBe("localhost:4567"); }); it("brackets an IPv6 literal", () => { expect(hostAndPort("::1", 3001)).toBe("[::1]:3001"); }); }); - src/everything/__tests__/logging.test.ts (5464 bytes)
/** * Characterizes the simulated logging that `toggle-simulated-logging` drives * (#4854): a random-leveled `notifications/message` at once and then every * five seconds, filtered by the level the client set with `logging/setLevel`, * per session, until toggled off or the session is cleaned up. The timer * belongs to the server instance serving the session, so the messages no * longer name a session id (#4852). The tool is 2025-era only; its 2026-07-28 * replacement, `trigger-log-messages`, is covered by modern.test.ts. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { connect, contentOf, ofMethod, textOf, type Session, } from "./harness.js"; let session: Session; beforeEach(async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); session = await connect(); }); afterEach(async () => { vi.useRealTimers(); vi.restoreAllMocks(); await session.close(); }); function messages(s: Session = session) { return ofMethod(s.notifications, "notifications/message").map( (n) => n.params, ); } async function toggle(s: Session = session): Promise<string> { const result = await s.client.callTool({ name: "toggle-simulated-logging", arguments: {}, }); return textOf(contentOf(result)[0]); } describe("toggle-simulated-logging", () => { it("starts with one message at once, then one every five seconds", async () => { vi.spyOn(Math, "random").mockReturnValue(0.99); expect(await toggle()).toBe( "Started simulated, random-leveled logging at a 5 second pace. Client's selected logging level will be respected. If an interval elapses and the message to be sent is below the selected level, it will not be sent. Thus at higher chosen logging levels, messages should arrive further apart.", ); await vi.waitFor(() => expect(messages()).toHaveLength(1)); expect(messages()[0]).toEqual({ level: "emergency", data: "Emergency-level message", }); await vi.advanceTimersByTimeAsync(10000); expect(messages()).toHaveLength(3); }); it("picks the level at random across all eight levels", async () => { const levels = []; for (let i = 0; i < 8; i++) { vi.spyOn(Math, "random").mockReturnValue(i / 8); if (i === 0) await toggle(); else await vi.advanceTimersByTimeAsync(5000); await vi.waitFor(() => expect(messages()).toHaveLength(i + 1)); levels.push(messages()[i]); } expect(levels.map((m) => ({ level: m.level, data: m.data }))) .toMatchInlineSnapshot(` [ { "data": "Debug-level message", "level": "debug", }, { "data": "Info-level message", "level": "info", }, { "data": "Notice-level message", "level": "notice", }, { "data": "Warning-level message", "level": "warning", }, { "data": "Error-level message", "level": "error", }, { "data": "Critical-level message", "level": "critical", }, { "data": "Alert level-message", "level": "alert", }, { "data": "Emergency-level message", "level": "emergency", }, ] `); }); it("stops when toggled again", async () => { await toggle(); await vi.waitFor(() => expect(messages()).toHaveLength(1)); expect(await toggle()).toBe("Stopped simulated logging"); await vi.advanceTimersByTimeAsync(20000); expect(messages()).toHaveLength(1); }); it("drops messages below the level the client set", async () => { await session.client.setLoggingLevel("error"); vi.spyOn(Math, "random").mockReturnValue(0); // debug await toggle(); await vi.advanceTimersByTimeAsync(5000); expect(messages()).toEqual([]); vi.spyOn(Math, "random").mockReturnValue(0.7); // critical await vi.advanceTimersByTimeAsync(5000); expect(messages().map((m) => m.level)).toEqual(["critical"]); }); it("is per session", async () => { const other = await connect(); try { await toggle(); await vi.advanceTimersByTimeAsync(5000); expect(messages()).toHaveLength(2); expect(messages(other)).toEqual([]); } finally { await other.close(); } }); it("is stopped by the session's cleanup", async () => { const leaving = await connect(); await toggle(leaving); await vi.waitFor(() => expect(messages(leaving)).toHaveLength(1)); // A closed client receives nothing either way, so check the server side: // an interval that outlived cleanup would log each failed send. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); await leaving.close(); await vi.advanceTimersByTimeAsync(20000); expect(messages(leaving)).toHaveLength(1); expect(errorSpy).not.toHaveBeenCalledWith( "Simulated logging message failed:", expect.anything(), ); }); it("logs, rather than throws, a message that cannot be sent", async () => { const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); await toggle(); await session.client.close(); await vi.advanceTimersByTimeAsync(5000); await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledWith( "Simulated logging message failed:", expect.any(Error), ), ); }); }); - src/everything/__tests__/long-running-cancel.test.ts (5116 bytes)
/** * Cancellation of `trigger-long-running-operation` (#1124, #4846). * * The tool waits on a timer per step. Before #4846 it ignored the request's * cancellation: a cancelled call kept stepping and sending progress, and its * pending timer held a stdio server's process open after the client went * away. Each case cancels a call from a real SDK client, in both protocol * eras. * * - Over the stdio transport manager on in-memory pipes, the server's raw * output is read, since the SDK client silently drops progress for a * request it has cancelled: no progress may cross the wire after the * cancel, and the session keeps serving. * - The step timer is what kept the process alive, and nothing on the wire * shows whether it is still pending, so `node:timers/promises` is wrapped * (calling through) to show the tool's wait is abandoned on the cancel. * That wait clears its own timer when its signal aborts. */ import { PassThrough } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; import { Client } from "@modelcontextprotocol/client"; import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; import { connect, connectModern, contentOf, textOf } from "./harness.js"; import type { Session } from "./harness.js"; import { main, type StdioSession } from "../transports/stdio.js"; const timers = vi.hoisted(() => ({ sleeps: [] as Array<{ ms: number | undefined; settled: Promise<unknown> }>, })); vi.mock("node:timers/promises", async (importOriginal) => { const actual = await importOriginal<typeof import("node:timers/promises")>(); return { ...actual, setTimeout: <T>( ms?: number, value?: T, options?: Parameters<typeof actual.setTimeout>[2], ) => { const promise = actual.setTimeout(ms, value, options); timers.sleeps.push({ ms, settled: promise.then( () => "elapsed", (error: unknown) => error, ), }); return promise; }, }; }); let session: Session | undefined; const started: StdioSession[] = []; afterEach(async () => { timers.sleeps.length = 0; await session?.close(); session = undefined; for (const { shutdown } of started.splice(0)) { process.off("SIGINT", shutdown); } }); const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)); describe.each([ ["2025-era", {}], ["2026-07-28", { versionNegotiation: { mode: { pin: "2026-07-28" } } }], ] as const)("over stdio, a cancelled call (%s)", (_era, opts) => { it("sends no progress after the cancel, and the session keeps serving", async () => { const toServer = new PassThrough(); const fromServer = new PassThrough(); started.push(await main(toServer, fromServer)); // Every line the server writes, read alongside the client's transport. let wire = ""; fromServer.on("data", (chunk: Buffer) => { wire += chunk.toString(); }); const client = new Client({ name: "stdio-test", version: "0.0.0" }, opts); await client.connect(new StdioServerTransport(fromServer, toServer)); // Four 50 ms steps: uncancelled, the last progress lands at about 200 ms. const controller = new AbortController(); const call = client.callTool( { name: "trigger-long-running-operation", arguments: { duration: 0.2, steps: 4 }, }, { signal: controller.signal, onprogress: () => controller.abort("cancelled by test"), }, ); await expect(call).rejects.toBeDefined(); await delay(300); expect(wire.match(/"notifications\/progress"/g)).toHaveLength(1); const echo = await client.callTool({ name: "echo", arguments: { message: "after cancel" }, }); expect(echo.content).toEqual([ { type: "text", text: "Echo: after cancel" }, ]); await client.close(); }); }); describe.each([ ["2025-era", () => connect()], ["2026-07-28", () => connectModern()], ])("a cancelled call (%s)", (_era, open) => { it("abandons its pending step wait, so no timer holds the process open", async () => { session = await open(); const controller = new AbortController(); const call = session.client.callTool( { name: "trigger-long-running-operation", arguments: { duration: 20, steps: 2 }, }, { signal: controller.signal }, ); await vi.waitFor(() => expect(timers.sleeps).toHaveLength(1)); controller.abort("cancelled by test"); await expect(call).rejects.toBeDefined(); // The 10 s wait settles at once, rejected by the abort, not elapsed. expect(timers.sleeps[0]?.ms).toBe(10_000); const outcome = await timers.sleeps[0]?.settled; expect(outcome).toMatchObject({ name: "AbortError" }); // The loop stopped: no further step was scheduled. await delay(20); expect(timers.sleeps).toHaveLength(1); const result = await session.client.callTool({ name: "echo", arguments: { message: "still here" }, }); expect(textOf(contentOf(result)[0])).toBe("Echo: still here"); }); }); - src/everything/__tests__/modern.test.ts (25327 bytes)
/** * The everything server as a 2026-07-28 client sees it (#4852), and the tools * added with it as both eras see them. * * - The 2026-07-28 surface: `server/discover` (no `initialize`), the * `extensions` capability, the tool list (capability-gated tools listed up * front, task tools added, the 2025-only toggles absent), and the wire * fields the SDK client consumes: `resultType`, and the `ttlMs` / * `cacheScope` cache hints. * - Multi-round-trip requests written once with `inputRequired(...)`: the * form, sampling, roots and URL tools on 2026-07-28 (2025-era coverage, * through the SDK's legacy shim, is in sampling-elicitation.test.ts and * 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). * - Per-request log levels (`trigger-log-messages`) against the 2025-era * session level. * - Change notifications (`trigger-list-changed`, `trigger-resource-update`) * on a `subscriptions/listen` stream, and unsolicited or after * `resources/subscribe` on 2025-era sessions. * - Minted resources: `gzip-file-as-resource` links on 2026-07-28. * * Over stdio, `get-header-params` sees no header; streamable-http.test.ts * covers its `Mcp-Param-Region` header. */ import { afterEach, describe, expect, it, vi } from "vitest"; import { gunzipSync } from "node:zlib"; import type { Client, ElicitRequest, ElicitResult, } from "@modelcontextprotocol/client"; import { McpServer } from "@modelcontextprotocol/server"; import { CACHE_HINTS } from "../server/index.js"; import { instancePublisher } from "../server/context.js"; import { STATIC_DOCUMENT_CACHE_HINT } from "../resources/files.js"; import { clearMintedResources, MAX_MINTED_BYTES, MAX_MINTED_RESOURCES, MINTED_RESOURCE_TTL_MS, mintBlobResource, } from "../resources/minted.js"; import { LOGGING_LEVELS } from "../tools/trigger-log-messages.js"; import { ALL_CAPABILITIES, connect, connectModern, connectRaw, contentOf, MODERN_CAPABILITIES, ofMethod, textOf, type RawSession, type Session, } from "./harness.js"; let session: Session | undefined; let raw: RawSession | undefined; afterEach(async () => { await session?.close(); await raw?.close(); session = undefined; raw = undefined; clearMintedResources(); vi.useRealTimers(); vi.restoreAllMocks(); }); /** The text blocks of a `tools/call` result. */ function texts(result: object): string[] { return contentOf(result).map(textOf); } describe("the 2026-07-28 surface", () => { it("answers server/discover with the capabilities, the tasks extension and a cache hint", async () => { raw = await connectRaw({}); const discover = await raw.result("server/discover"); expect(discover).toMatchObject({ supportedVersions: expect.arrayContaining(["2026-07-28"]), capabilities: { tools: { listChanged: true }, prompts: { listChanged: true }, resources: { subscribe: true, listChanged: true }, logging: {}, extensions: { "io.modelcontextprotocol/tasks": {} }, }, resultType: "complete", ...CACHE_HINTS["server/discover"], _meta: { "io.modelcontextprotocol/serverInfo": { name: "mcp-servers/everything", }, }, }); }); it("advertises no extensions to a 2025-era client", async () => { session = await connect(); expect(session.client.getServerCapabilities()?.extensions).toBeUndefined(); }); it("marks the task-creating tools as not read-only", async () => { session = await connectModern(); const { tools } = await session.client.listTools(); for (const name of [ "simulate-research-query", "trigger-sampling-request-async", "trigger-elicitation-request-async", ]) { expect( tools.find((t) => t.name === name)?.annotations?.readOnlyHint, ).toBe(false); } }); it("lists the capability-gated and task tools up front, and not the 2025-only toggles", async () => { session = await connectModern(); expect(session.client.getProtocolEra()).toBe("modern"); const names = (await session.client.listTools()).tools.map((t) => t.name); expect(names).toEqual( expect.arrayContaining([ "get-roots-list", "trigger-elicitation-request", "trigger-multi-step-elicitation", "trigger-url-elicitation", "trigger-sampling-request", "simulate-research-query", "trigger-sampling-request-async", "trigger-elicitation-request-async", ]), ); expect(names).not.toContain("toggle-simulated-logging"); expect(names).not.toContain("toggle-subscriber-updates"); }); it.each([ ["tools/list", "tools/list"], ["prompts/list", "prompts/list"], ["resources/list", "resources/list"], ["resources/templates/list", "resources/templates/list"], ] as const)("stamps %s with its cache hint", async (method, hint) => { raw = await connectRaw({}); expect(await raw.result(method)).toMatchObject({ resultType: "complete", ...CACHE_HINTS[hint], }); }); it("stamps a static document read with its own, longer cache hint", async () => { raw = await connectRaw({}); const read = await raw.result("resources/read", { uri: "demo://resource/static/document/instructions.md", }); expect(read).toMatchObject(STATIC_DOCUMENT_CACHE_HINT); }); it("stamps a dynamic resource read as uncacheable", async () => { raw = await connectRaw({}); const read = await raw.result("resources/read", { uri: "demo://resource/dynamic/text/1", }); expect(read).toMatchObject({ ttlMs: 0, cacheScope: "private" }); }); it("answers a read of a resource that does not exist with -32602", async () => { raw = await connectRaw({}); const uri = "demo://resource/dynamic/text/0"; const response = await raw.request("resources/read", { uri }); expect(response.error).toMatchObject({ code: -32602, data: { uri } }); }); it("stamps a tool result with resultType", async () => { raw = await connectRaw({}); expect(await raw.call("echo", { message: "hi" })).toEqual( expect.objectContaining({ resultType: "complete", content: [{ type: "text", text: "Echo: hi" }], }), ); }); it("reports no header for get-header-params over stdio", async () => { session = await connectModern(); const result = await session.client.callTool({ name: "get-header-params", arguments: { region: "eu-west", repeat: 2 }, }); expect(result.structuredContent).toEqual({ region: "eu-west", regionHeader: null, repeated: ["eu-west", "eu-west"], }); }); it("repeats the region once by default", async () => { session = await connectModern(); const result = await session.client.callTool({ name: "get-header-params", arguments: { region: "ap-south" }, }); expect(result.structuredContent).toMatchObject({ repeated: ["ap-south"] }); }); it("validates get-header-params arguments against its JSON Schema", async () => { session = await connectModern(); const result = await session.client.callTool({ name: "get-header-params", arguments: { region: "eu-west", repeat: 9 }, }); expect(result.isError).toBe(true); expect(texts(result)[0]).toContain("must be <= 3"); }); }); describe("multi-round-trip requests on 2026-07-28", () => { /** A 2026-07-28 client answering form elicitations with `answer`. */ async function withElicitation( answer: (request: ElicitRequest) => ElicitResult, ) { const asked: ElicitRequest["params"][] = []; session = await connectModern({ capabilities: ALL_CAPABILITIES, setup: (client) => client.setRequestHandler("elicitation/create", async (request) => { asked.push(request.params); return answer(request); }), }); return { client: session.client, asked }; } it("fills in the form in-band", async () => { const { client, asked } = await withElicitation(() => ({ action: "accept", content: { name: "Ada" }, })); const result = await client.callTool({ name: "trigger-elicitation-request", arguments: {}, }); expect(asked).toHaveLength(1); expect(texts(result).slice(0, 2)).toEqual([ "✅ User provided the requested information!", "User inputs:\n- Name: Ada", ]); }); it("samples in-band", async () => { session = await connectModern({ capabilities: ALL_CAPABILITIES, setup: (client) => client.setRequestHandler("sampling/createMessage", async () => ({ role: "assistant", model: "m", content: { type: "text", text: "sampled" }, })), }); const result = await session.client.callTool({ name: "trigger-sampling-request", arguments: { prompt: "p" }, }); expect(texts(result)[0]).toContain('"text": "sampled"'); }); it("lists the roots in-band", async () => { session = await connectModern({ capabilities: ALL_CAPABILITIES, setup: (client) => client.setRequestHandler("roots/list", async () => ({ roots: [{ uri: "file:///w", name: "W" }], })), }); const result = await session.client.callTool({ name: "get-roots-list", arguments: {}, }); expect(texts(result)[0]).toMatch(/^Current MCP Roots \(1 total\)/); }); it.each([ [ "accept", "✅ User completed the URL elicitation flow.\nURL: https://example.com/auth", ], ["decline", "❌ User declined to open the URL."], ["cancel", "⚠️ User cancelled the URL elicitation."], ] as const)( "reports a URL elicitation the user chose to %s", async (action, text) => { const { client, asked } = await withElicitation(() => ({ action })); const result = await client.callTool({ name: "trigger-url-elicitation", arguments: { url: "https://example.com/auth", errorPath: true }, }); // No -32042 error path on 2026-07-28: the URL comes in-band, with no id. expect(asked).toEqual([ expect.objectContaining({ mode: "url", url: "https://example.com/auth", }), ]); expect(asked[0]).not.toHaveProperty("elicitationId"); expect(texts(result)[0]).toBe(text); }, ); it("refuses an embedded request the client's request did not declare (-32021)", async () => { raw = await connectRaw({}); const response = await raw.request("tools/call", { name: "trigger-sampling-request", arguments: { prompt: "p" }, }); expect(response.error).toMatchObject({ code: -32021 }); }); it("refuses a tampered requestState with -32602 before the tool runs", async () => { raw = await connectRaw({ elicitation: {} }); const response = await raw.request("tools/call", { name: "trigger-multi-step-elicitation", arguments: {}, requestState: "tampered", inputResponses: {}, }); expect(response.error).toMatchObject({ code: -32602 }); }); it("returns input_required with a signed requestState on the wire", async () => { raw = await connectRaw({ elicitation: {} }); const first = await raw.call("trigger-multi-step-elicitation"); expect(first).toMatchObject({ resultType: "input_required", inputRequests: { name: { method: "elicitation/create" } }, requestState: expect.any(String), }); }); }); describe("trigger-multi-step-elicitation", () => { /** Run the tool for a client that answers each question from `answers`. */ async function run( connectTo: typeof connect | typeof connectModern, answers: ElicitResult[], ) { const asked: string[] = []; session = await connectTo({ capabilities: { elicitation: { form: {} } }, setup: (client: Client) => client.setRequestHandler("elicitation/create", async (request) => { asked.push(request.params.message); return answers.shift() ?? { action: "cancel" }; }), }); const result = await session.client.callTool({ name: "trigger-multi-step-elicitation", arguments: {}, }); return { result, asked }; } it.each([ ["2026-07-28", connectModern], ["2025-11-25", connect], ] as const)( "carries the name to the color question on %s", async (_era, connectTo) => { const { result, asked } = await run(connectTo, [ { action: "accept", content: { name: "Ada" } }, { action: "accept", content: { color: "green" } }, ]); expect(asked).toEqual([ "What is your name?", "Thanks, Ada. Which color do you like best?", ]); expect(texts(result)).toEqual(["Ada's favorite color is green."]); expect(result.structuredContent).toEqual({ name: "Ada", color: "green", }); }, ); it("asks again after a blank name or a color that is not a choice", async () => { const { result, asked } = await run(connectModern, [ { action: "accept", content: { name: " " } }, { action: "accept", content: { name: "Ada" } }, { action: "accept", content: { color: "mauve" } }, { action: "accept", content: { color: "red" } }, ]); expect(asked).toEqual([ "What is your name?", "A name is required. What is your name?", "Thanks, Ada. Which color do you like best?", "Thanks, Ada. Which color do you like best?", ]); expect(texts(result)).toEqual(["Ada's favorite color is red."]); }); it.each([ [ [{ action: "decline" as const }], "Stopped: the user chose decline at the name question.", ], [ [ { action: "accept" as const, content: { name: "Ada" } }, { action: "cancel" as const }, ], "Stopped: the user chose cancel at the color question.", ], ])("stops when the user declines or cancels: %j", async (answers, text) => { const { result } = await run(connectModern, [...answers]); expect(result.isError).toBe(true); expect(texts(result)).toEqual([text]); }); }); describe("trigger-log-messages", () => { /** The levels of the log messages a `trigger-log-messages` call delivered. */ async function levelsFrom(s: Session, logLevel?: string): Promise<string[]> { const levels: string[] = []; s.client.setNotificationHandler("notifications/message", (n) => { levels.push(n.params.level); }); const result = await s.client.callTool({ name: "trigger-log-messages", arguments: {}, ...(logLevel && { _meta: { "io.modelcontextprotocol/logLevel": logLevel }, }), }); expect(texts(result)[0]).toMatch( /^Sent one log message at each of 8 levels/, ); return le - src/everything/__tests__/private-ips-opted-in.ts (576 bytes)
/** * Opts a test file in to fetching from loopback and other private addresses * (#5130), for suites whose fixtures listen on 127.0.0.1. Import it first, * before anything that loads the server: `gzip-file-as-resource` reads * `GZIP_ALLOW_PRIVATE_IPS` once, when its module is evaluated, and imports are * evaluated in order (vitest gives each test file its own module graph). The * variable is unset again when the file's tests are done. */ import { afterAll, vi } from "vitest"; vi.stubEnv("GZIP_ALLOW_PRIVATE_IPS", "1"); afterAll(() => { vi.unstubAllEnvs(); }); - src/everything/__tests__/prompts.test.ts (8734 bytes)
/** * Characterizes the everything server's prompts and argument completions * through the protocol (#4854): `prompts/get` for each prompt, and * `completion/complete` for prompt arguments and for the resource templates' * `{resourceId}` variable. */ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { connect, connectModern, textOf, type Session } from "./harness.js"; import { RESOURCE_TYPE_BLOB, RESOURCE_TYPE_TEXT, } from "../resources/templates.js"; let session: Session; beforeEach(async () => { session = await connect(); }); afterEach(async () => { await session.close(); }); describe("simple-prompt", () => { it("returns its fixed message", async () => { const result = await session.client.getPrompt({ name: "simple-prompt" }); expect(result).toEqual({ messages: [ { role: "user", content: { type: "text", text: "This is a simple prompt without arguments.", }, }, ], }); }); }); describe("args-prompt", () => { it("uses the city alone when no state is given", async () => { const result = await session.client.getPrompt({ name: "args-prompt", arguments: { city: "San Francisco" }, }); expect(textOf(result.messages[0].content)).toBe( "What's weather in San Francisco?", ); }); it("appends the state when given", async () => { const result = await session.client.getPrompt({ name: "args-prompt", arguments: { city: "Austin", state: "Texas" }, }); expect(textOf(result.messages[0].content)).toBe( "What's weather in Austin, Texas?", ); }); it("rejects a missing required argument", async () => { await expect( session.client.getPrompt({ name: "args-prompt", arguments: {} }), ).rejects.toThrow(/Invalid arguments for prompt args-prompt/); }); }); describe("completable-prompt", () => { it("builds the promotion message from both arguments", async () => { const result = await session.client.getPrompt({ name: "completable-prompt", arguments: { department: "Engineering", name: "Alice" }, }); expect(textOf(result.messages[0].content)).toBe( "Please promote Alice to the head of the Engineering team.", ); }); }); describe("resource-prompt", () => { it("embeds a text resource", async () => { const result = await session.client.getPrompt({ name: "resource-prompt", arguments: { resourceType: "Text", resourceId: "1" }, }); expect(textOf(result.messages[0].content)).toBe( "This prompt includes the Text resource with id: 1. Please analyze the following resource:", ); expect(result.messages[1]).toMatchObject({ role: "user", content: { type: "resource", resource: { uri: "demo://resource/dynamic/text/1", mimeType: "text/plain", text: expect.stringMatching(/^Resource 1: This is a plaintext/), }, }, }); }); it("embeds a blob resource", async () => { const result = await session.client.getPrompt({ name: "resource-prompt", arguments: { resourceType: "Blob", resourceId: "2" }, }); expect(result.messages[1]).toMatchObject({ content: { type: "resource", resource: { uri: "demo://resource/dynamic/blob/2", mimeType: "application/octet-stream", blob: expect.any(String), }, }, }); }); it("rejects an unknown resource type", async () => { await expect( session.client.getPrompt({ name: "resource-prompt", arguments: { resourceType: "Video", resourceId: "1" }, }), ).rejects.toThrow("Invalid resourceType: Video. Must be Text or Blob."); }); it.each(["0", "-3", "1.5", "abc"])( "rejects resource id %s", async (resourceId) => { await expect( session.client.getPrompt({ name: "resource-prompt", arguments: { resourceType: "Text", resourceId }, }), ).rejects.toThrow( `Invalid resourceId: ${resourceId}. Must be a finite positive integer.`, ); }, ); }); describe("an unknown prompt", () => { it("is a protocol error", async () => { await expect( session.client.getPrompt({ name: "no-such-prompt" }), ).rejects.toThrow("Prompt no-such-prompt not found"); }); }); /** Complete one argument of a prompt. */ async function completePrompt( name: string, argument: string, value: string, context?: Record<string, string>, ) { const { completion } = await session.client.complete({ ref: { type: "ref/prompt", name }, argument: { name: argument, value }, ...(context ? { context: { arguments: context } } : {}), }); return completion.values; } describe("completion/complete for prompts", () => { it.each([ ["", ["Engineering", "Sales", "Marketing", "Support"]], ["S", ["Sales", "Support"]], ["X", []], ])("completes department %j", async (value, expected) => { expect( await completePrompt("completable-prompt", "department", value), ).toEqual(expected); }); it.each([ ["Engineering", "", ["Alice", "Bob", "Charlie"]], ["Sales", "", ["David", "Eve", "Frank"]], ["Marketing", "I", ["Iris"]], ["Support", "K", ["Kim"]], ])( "completes a %s team member from %j", async (department, value, expected) => { expect( await completePrompt("completable-prompt", "name", value, { department, }), ).toEqual(expected); }, ); it("offers no team members without a known department", async () => { expect(await completePrompt("completable-prompt", "name", "")).toEqual([]); expect( await completePrompt("completable-prompt", "name", "", { department: "Legal", }), ).toEqual([]); }); it.each([ ["", ["Text", "Blob"]], ["T", ["Text"]], ["x", []], ])("completes resource-prompt's resourceType %j", async (value, expected) => { expect( await completePrompt("resource-prompt", "resourceType", value), ).toEqual(expected); }); it.each([ ["5", ["5"]], ["0", []], ["abc", []], ])("completes resource-prompt's resourceId %j", async (value, expected) => { expect( await completePrompt("resource-prompt", "resourceId", value), ).toEqual(expected); }); it("offers nothing for an argument without a completer", async () => { expect(await completePrompt("args-prompt", "city", "S")).toEqual([]); }); }); describe("completion/complete for resource templates", () => { it.each([ ["demo://resource/dynamic/text/{resourceId}", "3", ["3"]], ["demo://resource/dynamic/blob/{resourceId}", "12", ["12"]], ["demo://resource/dynamic/text/{resourceId}", "-1", []], ["demo://resource/dynamic/blob/{resourceId}", "x", []], ])("completes %s from %j", async (uri, value, expected) => { const { completion } = await session.client.complete({ ref: { type: "ref/resource", uri }, argument: { name: "resourceId", value }, }); expect(completion.values).toEqual(expected); }); }); /** * Prompt arguments carry no JSON Schema over the wire, only a name, a * description and `required`, so the description is the one place a client * can learn what an argument accepts (#3985). Checked in both eras, since each * is served by its own code path. */ describe.each([ ["2025-era", connect], ["2026-07-28", connectModern], ])("prompts/list argument descriptions (%s)", (_era, open) => { let listed: Session; beforeEach(async () => { listed = await open(); }); afterEach(async () => { await listed.close(); }); it("describes every argument of every prompt", async () => { const { prompts } = await listed.client.listPrompts(); const undescribed = prompts.flatMap((prompt) => (prompt.arguments ?? []) .filter((argument) => !argument.description?.trim()) .map((argument) => `${prompt.name}.${argument.name}`), ); expect(undescribed).toEqual([]); }); it("names resource-prompt's allowed values in its argument descriptions", async () => { const { prompts } = await listed.client.listPrompts(); const prompt = prompts.find((p) => p.name === "resource-prompt"); const descriptionOf = (name: string) => prompt?.arguments?.find((argument) => argument.name === name) ?.description; expect(descriptionOf("resourceType")).toBe( `Type of resource to fetch. Must be "${RESOURCE_TYPE_TEXT}" or "${RESOURCE_TYPE_BLOB}".`, ); expect(descriptionOf("resourceId")).toBe( "ID of the resource to fetch. Must be a positive integer (1 or greater).", ); }); }); - src/everything/__tests__/registrations.test.ts (17164 bytes)
// Checks what each feature area's register function hands the McpServer, // with a mocked server. Its imports are static (#4854): the per-test dynamic // imports they replace ran inside the 5 s test timeout, and a cold start // (transforming the whole tool tree) could take longer than that. import { describe, it, expect, vi } from "vitest"; import { McpServer } from "@modelcontextprotocol/server"; import { registerConditionalTools, registerLegacyTools, registerModernTools, registerTools, } from "../tools/index.js"; import { registerPrompts } from "../prompts/index.js"; import { readInstructions, registerResources } from "../resources/index.js"; import type { ServerContext } from "../server/context.js"; /** A server context for the given era, with a publisher that does nothing. */ function contextFor(era: "legacy" | "modern"): ServerContext { return { era, subscribed: new Set(), publish: { toolsChanged: vi.fn(), promptsChanged: vi.fn(), resourcesChanged: vi.fn(), resourceUpdated: vi.fn(), }, onCleanup: vi.fn(), }; } // Create mock server function createMockServer() { return { registerTool: vi.fn(), registerPrompt: vi.fn(), registerResource: vi.fn(), server: { getClientCapabilities: vi.fn(() => ({})), setRequestHandler: vi.fn(), }, sendLoggingMessage: vi.fn(), sendResourceUpdated: vi.fn(), } as unknown as McpServer; } describe("Registration Index Files", () => { describe("tools/index.ts", () => { it("should register all standard tools", () => { const mockServer = createMockServer(); registerTools(mockServer, contextFor("legacy")); // Should register 14 standard tools (on both eras, non-conditional) expect(mockServer.registerTool).toHaveBeenCalledTimes(14); // Verify specific tools are registered const registeredTools = vi .mocked(mockServer.registerTool) .mock.calls.map((call) => call[0]); expect(registeredTools).toContain("echo"); expect(registeredTools).toContain("get-sum"); expect(registeredTools).toContain("get-env"); expect(registeredTools).toContain("get-tiny-image"); expect(registeredTools).toContain("get-structured-content"); expect(registeredTools).toContain("get-annotated-message"); expect(registeredTools).toContain("trigger-long-running-operation"); expect(registeredTools).toContain("get-resource-links"); expect(registeredTools).toContain("get-resource-reference"); expect(registeredTools).toContain("gzip-file-as-resource"); expect(registeredTools).toContain("get-header-params"); expect(registeredTools).toContain("trigger-list-changed"); expect(registeredTools).toContain("trigger-log-messages"); expect(registeredTools).toContain("trigger-resource-update"); }); it("should register the deprecated 2025-era-only tools", () => { const mockServer = createMockServer(); registerLegacyTools(mockServer, contextFor("legacy")); const registeredTools = vi .mocked(mockServer.registerTool) .mock.calls.map((call) => call[0]); expect(registeredTools).toEqual([ "toggle-simulated-logging", "toggle-subscriber-updates", ]); }); it("should register the capability-gated and task tools up front for 2026-07-28", () => { const mockServer = createMockServer(); registerModernTools(mockServer, contextFor("modern")); const registeredTools = vi .mocked(mockServer.registerTool) .mock.calls.map((call) => call[0]); expect(registeredTools).toEqual([ "get-roots-list", "trigger-elicitation-request", "trigger-multi-step-elicitation", "trigger-url-elicitation", "trigger-sampling-request", "simulate-research-query", "trigger-sampling-request-async", "trigger-elicitation-request-async", ]); }); it("should register conditional tools based on capabilities", () => { // Server with all capabilities const mockServerWithCapabilities = { registerTool: vi.fn(), server: { getClientCapabilities: vi.fn(() => ({ roots: {}, elicitation: { form: {}, url: {} }, sampling: {}, })), }, } as unknown as McpServer; registerConditionalTools( mockServerWithCapabilities, contextFor("legacy"), ); // Should register 5 conditional tools via registerTool when all // capabilities are present. The task tools are 2026-07-28 only (#4852). expect(mockServerWithCapabilities.registerTool).toHaveBeenCalledTimes(5); const registeredTools = vi .mocked(mockServerWithCapabilities.registerTool) .mock.calls.map((call) => call[0]); expect(registeredTools).toContain("get-roots-list"); expect(registeredTools).toContain("trigger-elicitation-request"); expect(registeredTools).toContain("trigger-multi-step-elicitation"); expect(registeredTools).toContain("trigger-url-elicitation"); expect(registeredTools).toContain("trigger-sampling-request"); }); it("should not register conditional tools before capabilities are known", () => { // getClientCapabilities() is undefined until initialize; each gated // tool treats that as "no capabilities". const mockServerBeforeInit = { registerTool: vi.fn(), server: { getClientCapabilities: vi.fn(() => undefined), }, } as unknown as McpServer; // partial mock: McpServer's private members rule out a structural literal registerConditionalTools(mockServerBeforeInit, contextFor("legacy")); expect(mockServerBeforeInit.registerTool).not.toHaveBeenCalled(); }); it("should not register conditional tools when capabilities missing", () => { const mockServerNoCapabilities = { registerTool: vi.fn(), server: { getClientCapabilities: vi.fn(() => ({})), }, } as unknown as McpServer; registerConditionalTools(mockServerNoCapabilities, contextFor("legacy")); // Should not register any capability-gated tools when capabilities are missing expect(mockServerNoCapabilities.registerTool).not.toHaveBeenCalled(); }); it("should register no form-mode elicitation tool for a URL-only client", () => { // The form elicitation tools send form-mode requests, which a client // that declared only `elicitation.url` cannot answer (#4985). const mockServerUrlOnly = { registerTool: vi.fn(), server: { getClientCapabilities: vi.fn(() => ({ elicitation: { url: {} }, })), }, } as unknown as McpServer; // partial mock: McpServer's private members rule out a structural literal registerConditionalTools(mockServerUrlOnly, contextFor("legacy")); const registeredTools = vi .mocked(mockServerUrlOnly.registerTool) .mock.calls.map((call) => call[0]); expect(registeredTools).toEqual(["trigger-url-elicitation"]); }); }); describe("prompts/index.ts", () => { it("should register all prompts", () => { const mockServer = createMockServer(); registerPrompts(mockServer); // Should register 4 prompts expect(mockServer.registerPrompt).toHaveBeenCalledTimes(4); const registeredPrompts = vi .mocked(mockServer.registerPrompt) .mock.calls.map((call) => call[0]); expect(registeredPrompts).toContain("simple-prompt"); expect(registeredPrompts).toContain("args-prompt"); expect(registeredPrompts).toContain("completable-prompt"); expect(registeredPrompts).toContain("resource-prompt"); }); }); describe("instructions vs. capability-gated tools", () => { // The instructions are read once in the server factory and handed to the // McpServer constructor, before `oninitialized` runs and client capabilities // are known. They are therefore the same string for every client, while the // tools registered by registerConditionalTools are not. These tests pin the // two together. // Every capability the conditional tools gate on, so the "all capabilities" // registration below is the full set. const allCapabilities = { roots: {}, sampling: {}, elicitation: { form: {}, url: {} }, }; const registeredWith = (capabilities: object): string[] => { const mockServer = { registerTool: vi.fn(), server: { getClientCapabilities: vi.fn(() => capabilities), }, } as unknown as McpServer; // partial mock: McpServer's private members rule out a structural literal registerConditionalTools(mockServer, contextFor("legacy")); return vi .mocked(mockServer.registerTool) .mock.calls.map((call) => call[0]); }; // A tool is capability-gated if declaring the capabilities makes it appear. // Deriving it as a difference rather than hard-coding a list means a tool // that stops being gated drops out of these assertions on its own. const gatedTools = (): string[] => { const withAll = registeredWith(allCapabilities); const withNone = registeredWith({}); return withAll.filter((name) => !withNone.includes(name)).sort(); }; // The entries of the "Capability-Gated Tools" list, by tool name. const documentedTools = (instructions: string): string[] => { const section = instructions .split(/^## /m) .find((part) => part.startsWith("Capability-Gated Tools")); expect( section, 'instructions.md has no "Capability-Gated Tools" section', ).toBeDefined(); return [...(section ?? "").matchAll(/^- `([a-z0-9-]+)`:/gm)] .map((match) => match[1]) .sort(); }; it("documents exactly the tools that client capabilities gate", () => { // A tool registered only when a capability is declared is absent from // tools/list for every other client, so an agent told to use it has // nothing to call. The instructions must name the same set the gates do. expect(documentedTools(readInstructions())).toEqual(gatedTools()); }); it("never tells an agent to use a capability-gated tool unconditionally", () => { const instructions = readInstructions(); const gated = gatedTools(); // Lines in the gated section are already qualified by the section itself. const sections = instructions.split(/^## /m); const otherLines = sections .filter((part) => !part.startsWith("Capability-Gated Tools")) .flatMap((part) => part.split("\n")); const unconditional = otherLines.filter( (line) => gated.some((name) => line.includes(`\`${name}\``)) && !/\bif\b/i.test(line), ); expect( unconditional, "mention a gated tool without saying it may be absent", ).toEqual([]); }); }); describe("resources/index.ts", () => { it("should register resource templates", () => { const mockServer = createMockServer(); registerResources(mockServer, contextFor("legacy")); // Should register at least the 2 resource templates (text and blob) plus file resources expect(mockServer.registerResource).toHaveBeenCalled(); const registeredResources = vi .mocked(mockServer.registerResource) .mock.calls.map((call) => call[0]); expect(registeredResources).toContain("Dynamic Text Resource"); expect(registeredResources).toContain("Dynamic Blob Resource"); expect(registeredResources).not.toContain("Minted Resource"); }); it("should also serve minted resources on 2026-07-28", () => { const mockServer = createMockServer(); registerResources(mockServer, contextFor("modern")); const registeredResources = vi .mocked(mockServer.registerResource) .mock.calls.map((call) => call[0]); expect(registeredResources).toContain("Minted Resource"); }); it("should read instructions from file", () => { const instructions = readInstructions(); // Should return a string (either content or error message) expect(typeof instructions).toBe("string"); expect(instructions.length).toBeGreaterThan(0); }); }); }); // Every tool carries all four annotation hints as booleans, on every path that // registers tools (#5156). surface.test.ts snapshots the advertised values; // this checks presence at registration, so a refactor that drops a hint fails // here, next to the path that dropped it. The tool set is read from what each // path registers rather than listed, so a tool added later is covered without // editing this test. describe("tool annotation hints at registration", () => { const HINTS = [ "readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint", ] as const; // Every capability registerConditionalTools gates on, so it registers its // whole set. const allCapabilities = { roots: {}, sampling: {}, elicitation: { form: {}, url: {} }, }; type RegisterFn = (server: McpServer, context: ServerContext) => void; /** Each tool a path registers, with the annotations it was registered with. */ const registeredBy = ( register: RegisterFn, era: "legacy" | "modern", ): { name: string; annotations: unknown }[] => { const mockServer = createMockServer(); vi.mocked(mockServer.server.getClientCapabilities).mockReturnValue( allCapabilities, ); register(mockServer, contextFor(era)); return vi.mocked(mockServer.registerTool).mock.calls.map((call) => { const config: { annotations?: unknown } = call[1]; return { name: call[0], annotations: config.annotations }; }); }; /** "tool: hint" for each hint a tool lacks or holds as a non-boolean. */ const missingHints = ( tools: { name: string; annotations: unknown }[], ): string[] => tools.flatMap(({ name, annotations }) => HINTS.filter( (hint) => typeof annotations !== "object" || annotations === null || typeof (annotations as Record<string, unknown>)[hint] !== "boolean", ).map((hint) => `${name}: ${hint}`), ); const paths: { path: string; register: RegisterFn; era: "legacy" | "modern"; includes: string[]; }[] = [ { path: "registerTools (2025 era)", register: registerTools, era: "legacy", includes: ["echo", "get-sum", "trigger-long-running-operation"], }, { path: "registerTools (2026-07-28)", register: registerTools, era: "modern", includes: ["echo", "get-sum", "trigger-long-running-operation"], }, { path: "registerLegacyTools (2025 era)", register: registerLegacyTools, era: "legacy", includes: ["toggl - src/everything/__tests__/resources.test.ts (9368 bytes)
/** * Characterizes the everything server's resources through the protocol * (#4854): reading the static documents and the dynamic templates, the errors * for bad template ids, and resource subscriptions with the simulated * `notifications/resources/updated` stream that `toggle-subscriber-updates` * drives. Session resources (from `gzip-file-as-resource`) are in * `gzip-file-as-resource.test.ts`. */ import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { connect, ofMethod, textOf, contentOf, type Session, } from "./harness.js"; const DOCS_DIR = join(import.meta.dirname, "..", "docs"); let session: Session; beforeEach(async () => { session = await connect(); }); afterEach(async () => { vi.useRealTimers(); await session.close(); }); describe("static document resources", () => { it("serves each file in docs/ as markdown", async () => { for (const file of readdirSync(DOCS_DIR)) { const uri = `demo://resource/static/document/${encodeURIComponent(file)}`; const { contents } = await session.client.readResource({ uri }); expect(contents).toEqual([ { uri, mimeType: "text/markdown", text: readFileSync(join(DOCS_DIR, file), "utf-8"), }, ]); } }); }); describe("dynamic resource templates", () => { it("fabricates a text resource from its id", async () => { const uri = "demo://resource/dynamic/text/42"; const { contents } = await session.client.readResource({ uri }); expect(contents).toEqual([ { uri, mimeType: "text/plain", text: expect.stringMatching( /^Resource 42: This is a plaintext resource created at /, ), }, ]); }); it("fabricates a blob resource from its id, labelled application/octet-stream", async () => { // The content's type matches the one the blob template advertises. const uri = "demo://resource/dynamic/blob/9"; const { contents } = await session.client.readResource({ uri }); expect(contents).toEqual([ { uri, mimeType: "application/octet-stream", blob: expect.any(String) }, ]); const blob = "blob" in contents[0] ? contents[0].blob : ""; expect(Buffer.from(blob, "base64").toString()).toMatch( /^Resource 9: This is a base64 blob created at /, ); }); it.each(["0", "-2", "1.5", "abc"])("rejects resource id %s", async (id) => { // No such resource: -32602 with the URI in the error's data (#4852). const uri = `demo://resource/dynamic/text/${id}`; await expect(session.client.readResource({ uri })).rejects.toMatchObject({ code: -32602, data: { uri }, }); }); it("rejects a URI that matches no resource or template", async () => { await expect( session.client.readResource({ uri: "demo://resource/nowhere" }), ).rejects.toThrow("Resource not found: demo://resource/nowhere"); }); }); describe("resource subscriptions", () => { const URI = "demo://resource/dynamic/text/1"; function logData(): unknown[] { return ofMethod(session.notifications, "notifications/message").map( (n) => n.params.data, ); } function updates(): string[] { return ofMethod( session.notifications, "notifications/resources/updated", ).map((n) => n.params.uri); } it("acknowledges subscribe and unsubscribe with a log message", async () => { await session.client.subscribeResource({ uri: URI }); await session.client.unsubscribeResource({ uri: URI }); // Unsubscribing from a URI with no subscriber set is accepted too. await session.client.unsubscribeResource({ uri: "demo://never" }); expect(logData()).toEqual([ `Received Subscribe Resource request for URI: ${URI}`, `Received Unsubscribe Resource request: ${URI}`, "Received Unsubscribe Resource request: demo://never", ]); }); it("keeps another session's subscription when this one unsubscribes from the same URI", async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); const other = await connect(); try { await other.client.subscribeResource({ uri: URI }); // This session never subscribed; its unsubscribe changes nothing. await session.client.unsubscribeResource({ uri: URI }); await other.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await vi.waitFor(() => expect( ofMethod(other.notifications, "notifications/resources/updated"), ).toHaveLength(1), ); } finally { await other.close(); } }); it("sends updates for subscribed URIs every 5 seconds while toggled on", async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); await session.client.subscribeResource({ uri: URI }); await session.client.subscribeResource({ uri: URI }); // idempotent const on = await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); expect(textOf(contentOf(on)[0])).toBe( "Started simulated resource updated notifications at a 5 second pace. Client will receive updates for any resources it is subscribed to.", ); await vi.waitFor(() => expect(updates()).toEqual([URI])); await vi.advanceTimersByTimeAsync(5000); expect(updates()).toEqual([URI, URI]); // Unsubscribing stops updates for that URI while the interval runs on. await session.client.unsubscribeResource({ uri: URI }); await vi.advanceTimersByTimeAsync(5000); expect(updates()).toEqual([URI, URI]); const off = await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); expect(textOf(contentOf(off)[0])).toBe( "Stopped simulated resource updates", ); }); it("stops sending updates once the toggle is turned off", async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); await session.client.subscribeResource({ uri: URI }); await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await vi.waitFor(() => expect(updates()).toHaveLength(1)); await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await vi.advanceTimersByTimeAsync(15000); expect(updates()).toHaveLength(1); }); it("sends updates only to the sessions subscribed to a URI", async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); const other = await connect(); try { await other.client.subscribeResource({ uri: "demo://other" }); await session.client.subscribeResource({ uri: URI }); await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await other.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await vi.advanceTimersByTimeAsync(5000); expect(new Set(updates())).toEqual(new Set([URI])); expect( new Set( ofMethod(other.notifications, "notifications/resources/updated").map( (n) => n.params.uri, ), ), ).toEqual(new Set(["demo://other"])); } finally { await other.close(); } }); it("drops a closed session's subscriptions without touching another session's (#4712)", async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); const leaving = await connect(); await leaving.client.subscribeResource({ uri: URI }); await session.client.subscribeResource({ uri: URI }); await leaving.close(); // A new client under the departed session's id, which never subscribed: // if cleanup had left the old subscription behind, its updates would // reach this client. const returning = await connect({ sessionId: leaving.sessionId }); try { await returning.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); await vi.advanceTimersByTimeAsync(5000); expect(updates()).toEqual([URI, URI]); expect( ofMethod(returning.notifications, "notifications/resources/updated"), ).toEqual([]); } finally { await returning.close(); } }); it("logs, rather than throws, an update that cannot be sent", async () => { vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); try { await session.client.subscribeResource({ uri: URI }); await session.client.callTool({ name: "toggle-subscriber-updates", arguments: {}, }); // Close the client without the server-side cleanup, so the interval // outlives the transport, as when a connection drops. await session.client.close(); await vi.advanceTimersByTimeAsync(5000); await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledWith( "Simulated resource update failed:", expect.any(Error), ), ); } finally { errorSpy.mockRestore(); } }); }); - src/everything/__tests__/roots.test.ts (5702 bytes)
/** * Characterizes the everything server's use of client roots (#4854): the * `roots/list` request it sends after `initialize` for a client that declares * the roots capability, its re-request on `notifications/roots/list_changed`, * the log message it sends with each result, and the `get-roots-list` tool, * all driven by a test client that answers the server's `roots/list`. */ import { afterEach, describe, expect, it, vi } from "vitest"; import type { Root } from "@modelcontextprotocol/server"; import { connect, contentOf, ofMethod, textOf, type Session, } from "./harness.js"; let session: Session | undefined; afterEach(async () => { vi.restoreAllMocks(); await session?.close(); session = undefined; }); /** Connect a roots-capable client whose `roots/list` answer is `answer()`. */ async function connectWithRoots(answer: () => Root[]) { let requests = 0; const s = await connect({ capabilities: { roots: { listChanged: true } }, setup: (client) => client.setRequestHandler("roots/list", async () => { requests++; return { roots: answer() }; }), }); return { s, requests: () => requests }; } function logData(s: Session): unknown[] { return ofMethod(s.notifications, "notifications/message").map( (n) => n.params, ); } async function getRootsList(s: Session): Promise<string> { const result = await s.client.callTool({ name: "get-roots-list", arguments: {}, }); return textOf(contentOf(result)[0]); } const ROOTS: Root[] = [ { uri: "file:///workspace/one", name: "One" }, { uri: "file:///workspace/two" }, ]; describe("roots sync after initialize", () => { it("requests the client's roots once, shortly after initialize, and logs the count", async () => { const { s, requests } = await connectWithRoots(() => ROOTS); session = s; expect(requests()).toBe(0); await vi.waitFor(() => expect(requests()).toBe(1)); await vi.waitFor(() => expect(logData(s)).toEqual([ { level: "info", logger: "everything-server", data: "Roots updated: 2 root(s) received from client", }, ]), ); }); it("re-requests the roots when the client says they changed", async () => { let roots = ROOTS; const { s, requests } = await connectWithRoots(() => roots); session = s; await vi.waitFor(() => expect(requests()).toBe(1)); roots = [{ uri: "file:///elsewhere", name: "Elsewhere" }]; await s.client.sendRootsListChanged(); await vi.waitFor(() => expect(requests()).toBe(2)); await vi.waitFor(() => expect(logData(s).at(-1)).toMatchObject({ data: "Roots updated: 1 root(s) received from client", }), ); expect(await getRootsList(s)).toContain( "1. Elsewhere\n URI: file:///elsewhere", ); }); it("sends no roots/list to a client without the roots capability", async () => { session = await connect(); // Past the 350 ms delay, nothing has been logged: no sync happened. await new Promise((resolve) => setTimeout(resolve, 450)); expect(logData(session)).toEqual([]); }); it("logs to stderr, and sends nothing, when the client fails to list its roots", async () => { const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); const { s } = await connectWithRoots(() => { throw new Error("no roots for you"); }); session = s; await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledWith( "Failed to request roots from client: no roots for you", ), ); expect(logData(s)).toEqual([]); }); }); describe("get-roots-list", () => { it("lists the roots, naming an unnamed one", async () => { const { s } = await connectWithRoots(() => ROOTS); session = s; expect(await getRootsList(s)).toBe( "Current MCP Roots (2 total):\n\n" + "1. One\n URI: file:///workspace/one\n\n" + "2. Unnamed Root\n URI: file:///workspace/two\n\n" + "Note: This server demonstrates the roots protocol capability but doesn't actually access files. " + "The roots are provided by the MCP client and can be used by servers that need file system access.", ); }); it("asks the client on every call, with a multi-round-trip request (#4852)", async () => { // The tool no longer reads a per-session cache: each call returns // input_required carrying roots/list, which the legacy shim sends as a // real request. The sync after initialize asks on its own. const { s, requests } = await connectWithRoots(() => ROOTS); session = s; await vi.waitFor(() => expect(requests()).toBe(1)); await getRootsList(s); await getRootsList(s); expect(requests()).toBe(3); }); it("explains an empty roots list", async () => { const { s } = await connectWithRoots(() => []); session = s; expect(await getRootsList(s)).toBe( "The client supports roots but no roots are currently configured.\n\n" + "This could mean:\n" + "1. The client hasn't provided any roots yet\n" + "2. The client provided an empty roots list\n" + "3. The roots configuration is still being loaded", ); }); it("reports a client that failed to list its roots as a tool error", async () => { vi.spyOn(console, "error").mockImplementation(() => {}); const { s } = await connectWithRoots(() => { throw new Error("unavailable"); }); session = s; const result = await s.client.callTool({ name: "get-roots-list", arguments: {}, }); expect(result.isError).toBe(true); expect(textOf(contentOf(result)[0])).toContain("unavailable"); }); }); - src/everything/__tests__/sampling-elicitation.test.ts (19086 bytes)
/** * Characterizes the tools that send a request back to the client (#4854): * `trigger-sampling-request` (`sampling/createMessage`), * `trigger-elicitation-request` (form-mode `elicitation/create`) and * `trigger-url-elicitation` (URL mode, by request or by the -32042 error * path). A test client answers each request; the tests pin both what the * server asked and what the tool then returned. */ import { afterEach, describe, expect, it } from "vitest"; import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server"; import type { ClientCapabilities, CreateMessageRequest, ElicitRequest, ElicitResult, } from "@modelcontextprotocol/server"; import { connect, contentOf, textOf, type ConnectOptions, type Session, } from "./harness.js"; let session: Session | undefined; afterEach(async () => { await session?.close(); session = undefined; }); describe("trigger-sampling-request", () => { it("asks the client to sample and returns the client's answer", async () => { const asked: CreateMessageRequest["params"][] = []; session = await connect({ capabilities: { sampling: {} }, setup: (client) => client.setRequestHandler("sampling/createMessage", async (req) => { asked.push(req.params); return { role: "assistant", content: { type: "text", text: "sampled reply" }, model: "test-model", stopReason: "endTurn", }; }), }); const result = await session.client.callTool({ name: "trigger-sampling-request", arguments: { prompt: "Say hi" }, }); // The tool asks in-band (input_required); the SDK's legacy shim sends the // request, adding a progress token of its own (#4852). expect(asked).toEqual([ { _meta: { progressToken: expect.anything() }, messages: [ { role: "user", content: { type: "text", text: "Resource trigger-sampling-request context: Say hi", }, }, ], systemPrompt: "You are a helpful test server.", maxTokens: 100, temperature: 0.7, }, ]); expect(textOf(contentOf(result)[0])).toBe( `LLM sampling result: \n${JSON.stringify( { model: "test-model", stopReason: "endTurn", role: "assistant", content: { type: "text", text: "sampled reply" }, }, null, 2, )}`, ); }); it("passes maxTokens through", async () => { let maxTokens: number | undefined; session = await connect({ capabilities: { sampling: {} }, setup: (client) => client.setRequestHandler("sampling/createMessage", async (req) => { maxTokens = req.params.maxTokens; return { role: "assistant", content: { type: "text", text: "ok" }, model: "m", }; }), }); await session.client.callTool({ name: "trigger-sampling-request", arguments: { prompt: "p", maxTokens: 7 }, }); expect(maxTokens).toBe(7); }); it("reports a client that fails to sample as a tool error", async () => { session = await connect({ capabilities: { sampling: {} }, setup: (client) => client.setRequestHandler("sampling/createMessage", async () => { throw new ProtocolError( ProtocolErrorCode.InvalidRequest, "user rejected", ); }), }); const result = await session.client.callTool({ name: "trigger-sampling-request", arguments: { prompt: "p" }, }); expect(result).toEqual({ isError: true, // The SDK's legacy shim reports a failed input request as a tool error // naming the call it was fulfilling (#4852). content: [ { type: "text", text: "Fulfilling input required by 'tools/call' failed: user rejected", }, ], }); }); }); /** Connect a client whose elicitation answers come from `answer`. */ async function connectElicitation( answer: (req: ElicitRequest) => ElicitResult, capabilities: ClientCapabilities = { elicitation: { form: {}, url: {} } }, options: Omit<ConnectOptions, "capabilities" | "setup"> = {}, ) { const asked: ElicitRequest["params"][] = []; const s = await connect({ ...options, capabilities, setup: (client) => client.setRequestHandler("elicitation/create", async (req) => { asked.push(req.params); return answer(req); }), }); return { s, asked }; } describe("trigger-elicitation-request", () => { async function trigger(answer: ElicitResult) { const { s, asked } = await connectElicitation(() => answer); session = s; const result = await s.client.callTool({ name: "trigger-elicitation-request", arguments: {}, }); return { texts: contentOf(result).map(textOf), asked }; } it("asks for the demo form", async () => { const { asked } = await trigger({ action: "cancel" }); expect(asked).toHaveLength(1); expect(asked[0]).toMatchInlineSnapshot(` { "_meta": { "progressToken": 0, }, "message": "Please provide inputs for the following fields:", "mode": "form", "requestedSchema": { "properties": { "birthdate": { "description": "Your date of birth", "format": "date", "title": "String with date format", "type": "string", }, "check": { "description": "Agree to the terms and conditions", "title": "Boolean", "type": "boolean", }, "email": { "description": "Your email address (will be verified, and never shared with anyone else)", "format": "email", "title": "String with email format", "type": "string", }, "firstLine": { "default": "It was a dark and stormy night.", "description": "Favorite first line of a story", "title": "String with default", "type": "string", }, "homepage": { "description": "Portfolio / personal website", "format": "uri", "title": "String with uri format", "type": "string", }, "integer": { "default": 42, "description": "Your favorite integer (do not give us your phone number, pin, or other sensitive info)", "maximum": 100, "minimum": 1, "title": "Integer", "type": "integer", }, "legacyTitledEnum": { "default": "pet-1", "description": "Choose your favorite type of pet", "enum": [ "pet-1", "pet-2", "pet-3", "pet-4", "pet-5", ], "enumNames": [ "Cats", "Dogs", "Birds", "Fish", "Reptiles", ], "title": "Legacy Titled Single Select Enum", "type": "string", }, "name": { "description": "Your full, legal name", "title": "String", "type": "string", }, "number": { "default": 3.14, "description": "Favorite number (there are no wrong answers)", "maximum": 1000, "minimum": 0, "title": "Number in range 1-1000", "type": "number", }, "titledMultipleSelectEnum": { "default": [ "fish-1", ], "description": "Choose your favorite types of fish", "items": { "anyOf": [ { "const": "fish-1", "title": "Tuna", }, { "const": "fish-2", "title": "Salmon", }, { "const": "fish-3", "title": "Trout", }, ], }, "maxItems": 3, "minItems": 1, "title": "Titled Multiple Select Enum", "type": "array", }, "titledSingleSelectEnum": { "default": "hero-1", "description": "Choose your favorite hero", "oneOf": [ { "const": "hero-1", "title": "Superman", }, { "const": "hero-2", "title": "Green Lantern", }, { "const": "hero-3", "title": "Wonder Woman", }, ], "title": "Titled Single Select Enum", "type": "string", }, "untitledMultipleSelectEnum": { "default": [ "Guitar", ], "description": "Choose your favorite instruments", "items": { "enum": [ "Guitar", "Piano", "Violin", "Drums", "Bass", ], "type": "string", }, "maxItems": 3, "minItems": 1, "title": "Untitled Multiple Select Enum", "type": "array", }, "untitledSingleSelectEnum": { "default": "Monica", "description": "Choose your favorite friend", "enum": [ "Monica", "Rachel", "Joey", "Chandler", "Ross", "Phoebe", ], "title": "Untitled Single Select Enum", "type": "string", }, }, "required": [ "name", ], "type": "object", }, } `); }); it("summarizes every field of an accepted form, in the form's order (#5209)", async () => { const content = { name: "Ada", check: false, firstLine: "Call me Ishmael.", email: "[email protected]", homepage: "https://example.com", birthdate: "1815-12-10", integer: 0, number: 3.5, untitledSingleSelectEnum: "Joey", untitledMultipleSelectEnum: ["Piano", "Drums"], titledSingleSelectEnum: "hero-3", titledMultipleSelectEnum: ["fish-2"], legacyTitledEnum: "pet-2", }; const { texts, asked } = await trigger({ action: "accept", content }); expect(texts).toEqual([ "✅ User provided the requested information!", "User inputs:\n" + "- Name: Ada\n" + "- Agreed to terms: false\n" + "- Favorite first line: Call me Ishmael.\n" + "- Email: [email protected]\n" + "- Homepage: https://example.com\n" + "- Birthdate: 1815-12-10\n" + "- Favorite integer: 0\n" + "- Favorite number: 3.5\n" + "- Favorite friend: Joey\n" + "- Favorite instruments: Piano, Drums\n" + "- Favorite hero: hero-3\n" + "- Favorite fish: fish-2\n" + "- Favorite pet: pet-2", `\nRaw result: ${JSON.stringify({ action: "accept", content }, null, 2)}`, ]); // One line per field the form asked for: the summary and the requested // schema list the same fields. const params = asked[0]; expect(params && "requestedSchema" in params).toBe(true); if (params && "requestedSchema" in params) { expect(Object.keys(content)).toEqual( Object.keys(params.requestedSchema.properties), ); } }); it("leaves out fields the form does not define (#5209)", async () => { const content = { name: "Ada", color: "teal", petType: "pet-2" }; const { texts } = await trigger({ action: "accept", content }); expect(texts.slice(0, 2)).toEqual([ "✅ User provided the requested information!", "User inputs:\n- Name: Ada", ]); // The raw result still shows what the client sent. expect(texts[2]).toContain('"color": "teal"'); }); it("summarizes an accepted form with no fields filled", async () => { const { texts } = await trigger({ action: "accept", content: {} }); expect(texts.slice(0, 2)).toEqual([ "✅ User provided the requested information!", "User inputs:\n", ]); }); it("reports only the raw result for an accept with no content", async () => { const { texts } = await trigger({ action: "accept" }); expect(texts).toEqual([ `\nRaw result: ${JSON.stringify({ action: "accept" }, null, 2)}`, ]); }); it("reports a decline", async () => { const { texts } = await trigger({ action: "decline" }); expect(texts[0]).toBe( "❌ User declined to provide the requested information.", ); }); it("reports a cancel", async () => { const { texts } = await trigger({ action: "cancel" }); expect(texts[0]).toBe("⚠️ User cancelled the elicitation dialog."); }); it("is not listed for a URL-only client, which cannot answer a form request (#4985)", async () => { const { s, asked } = await connectElicitation( () => ({ action: "cancel" }), { elicitation: { url: {} } }, ); session = s; const { tools } = await s.client.listTools(); expect(tools.map((t) => t.name)).not.toContain( "trigger-elicitation-request", ); expect(tools.map((t) => t.name)).toContain("trigger-url-elicitation"); expect(asked).toEqual([]); }); }); describe("trigger-url-elicitation", () => { const URL_ARG = "https://example.com/authorize"; async function callUrlTool(s: Session, args: Record<string, unknown>) { return s.client.callTool({ name: "trigger-url-elicitation", arguments: { url: URL_ARG, ...args }, }); } it("sends a URL-mode elicitation with the given id and reports acceptance", async () => { const { s, asked } = await connectElicitation(() => ({ action: "accept" })); session = s; const result = await callUrlTool(s, { elicitationId: "elic-1" }); expect(asked).toEqual([ { mode: "url", url: URL_ARG, message: "Please open the link to complete this action.", elicitationId: "elic-1", }, ]); expect(contentOf(result).map(textOf)).toEqual([ `✅ User completed the URL elicitation flow.\nElicitation ID: elic-1\nURL: ${URL_ARG}`, `\nRaw result: ${JSON.stringify({ action: "accept" }, null, 2)}`, ]); }); it("generates a UUID elicitation id when none is gi - src/everything/__tests__/server-version.test.ts (2483 bytes)
// The version `everything` reports in `serverInfo` is its package.json version // (#4472). Changesets bumps package.json only, so a literal in the source would // drift at the first "Version Packages" PR; this drives the server through a // client and reads what `initialize` actually returns. import { describe, it, expect, vi } from "vitest"; import { createRequire } from "node:module"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import { createServer } from "../server/index.js"; import { resolvePackageVersion, SERVER_VERSION } from "../version.js"; const packageJson = createRequire(import.meta.url)("../package.json") as { version: string; }; describe("server version", () => { it("uses package.json version instead of a hardcoded string", () => { expect(SERVER_VERSION).toBe(packageJson.version); expect(resolvePackageVersion()).toBe(packageJson.version); }); it("initialize reports package.json version in serverInfo", async () => { const { server, cleanup } = createServer(); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "version-test", version: "0.0.0" }); try { await server.connect(serverTransport); await client.connect(clientTransport); const serverInfo = client.getServerVersion(); expect(serverInfo?.name).toBe("mcp-servers/everything"); expect(serverInfo?.version).toBe(packageJson.version); } finally { cleanup(); await client.close(); await server.close(); } }); }); describe("resolvePackageVersion without a usable package.json", () => { it("skips a package.json with no version and one that cannot be read, then throws", async () => { vi.resetModules(); vi.doMock("node:module", async (importOriginal) => { const real = await importOriginal<typeof import("node:module")>(); let calls = 0; return { ...real, createRequire: () => () => { if (calls++ === 0) return {}; // the first candidate has no version throw new Error("not found"); // the second is missing }, }; }); try { // SERVER_VERSION is resolved at import, so the import itself fails. await expect(import("../version.js")).rejects.toThrow( "Could not locate package.json for server version", ); } finally { vi.doUnmock("node:module"); vi.resetModules(); } }); }); - src/everything/__tests__/server.test.ts (3242 bytes)
/** * The few paths of the server factory and its helpers that no protocol * session reaches (#4854): `cleanup()` for a server no client ever * initialized, and a `text` session resource (the only tool that creates * session resources, gzip-file-as-resource, makes blobs), and `syncRoots()` * for a server with no initialized client. */ import { describe, expect, it, vi } from "vitest"; import { InMemoryTransport, McpServer } from "@modelcontextprotocol/server"; import { Client } from "@modelcontextprotocol/client"; import { createServer } from "../server/index.js"; import { registerSessionResource } from "../resources/session.js"; import { syncRoots } from "../server/roots.js"; describe("createServer", () => { it("cleans up a server that no client has initialized", () => { const { cleanup } = createServer(); expect(() => cleanup()).not.toThrow(); }); }); describe("registerSessionResource", () => { it("registers a text resource and returns a link to it", async () => { const server = new McpServer({ name: "s", version: "0" }); const link = registerSessionResource( server, { uri: "demo://resource/session/note.txt", name: "note.txt", mimeType: "text/plain", }, "text", "a note", ); expect(link).toEqual({ type: "resource_link", uri: "demo://resource/session/note.txt", name: "note.txt", mimeType: "text/plain", }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "c", version: "0" }); await Promise.all([ server.connect(serverTransport), client.connect(clientTransport), ]); const { contents } = await client.readResource({ uri: link.uri }); expect(contents).toEqual([ { uri: "demo://resource/session/note.txt", mimeType: "text/plain", text: "a note", }, ]); await client.close(); }); }); describe("syncRoots", () => { it("does nothing for a server whose client has not initialized", async () => { const server = new McpServer({ name: "s", version: "0" }); expect(await syncRoots(server)).toBeUndefined(); }); }); describe("syncRoots, called again", () => { it("asks again but installs its roots/list_changed handler once", async () => { const server = new McpServer({ name: "s", version: "0" }); let requests = 0; const client = new Client( { name: "c", version: "0" }, { capabilities: { roots: { listChanged: true } } }, ); client.setRequestHandler("roots/list", async () => { requests++; return { roots: [] }; }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); await Promise.all([ server.connect(serverTransport), client.connect(clientTransport), ]); await syncRoots(server); await syncRoots(server); expect(requests).toBe(2); // One handler, so one more request per change, not two. await client.sendRootsListChanged(); await vi.waitFor(() => expect(requests).toBe(3)); await new Promise((resolve) => setTimeout(resolve, 50)); expect(requests).toBe(3); await client.close(); }); }); - src/everything/__tests__/sse.test.ts (11588 bytes)
/** * Characterizes the HTTP+SSE transport manager (#4854). `createApp()` is * served on a free loopback port and driven by the SDK's SSE client, and by * raw HTTP for the requests a well-behaved client never sends. The launcher's * `startSseServer()` is checked with `listenOrExit` stubbed, so no fixed port * is ever bound. * * 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. */ import type { Server } from "node:http"; import { once } from "node:events"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Client, SSEClientTransport } from "@modelcontextprotocol/client"; import { createApp } from "../transports/sse.js"; let http: Server; let base: string; let error: ReturnType<typeof vi.spyOn>; beforeEach(async () => { error = vi.spyOn(console, "error").mockImplementation(() => {}); http = createApp().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"); base = `http://127.0.0.1:${address.port}`; }); afterEach(async () => { http.closeAllConnections(); await new Promise((resolve) => http.close(resolve)); vi.restoreAllMocks(); }); /** Connect an SSE client and return it with the session id the server logged. */ async function connectSse() { const client = new Client({ name: "sse-test", version: "0.0.0" }); await client.connect(new SSEClientTransport(new URL(`${base}/sse`))); const connected = error.mock.calls.filter( (c: unknown[]) => c[0] === "Client Connected: ", ); const sessionId = String(connected.at(-1)?.[1]); return { client, sessionId }; } describe("SSE transport", () => { it("serves the protocol: GET /sse opens the stream, POST /message carries requests", async () => { const { client, sessionId } = await connectSse(); expect(sessionId).toMatch(/^[0-9a-f-]{36}$/); const result = await client.callTool({ name: "echo", arguments: { message: "over sse" }, }); expect(result.content).toEqual([{ type: "text", text: "Echo: over sse" }]); expect(error).toHaveBeenCalledWith("Client Message from", sessionId); await client.close(); }); it("gives each stream its own server and session", async () => { const a = await connectSse(); const b = await connectSse(); expect(a.sessionId).not.toBe(b.sessionId); // Each stream's server keeps its own toggle state: turning logging on // for one leaves the other's off. const toggle = async (client: typeof a.client) => JSON.stringify( ( await client.callTool({ name: "toggle-simulated-logging", arguments: {}, }) ).content, ); expect(await toggle(a.client)).toContain("Started"); expect(await toggle(b.client)).toContain("Started"); expect(await toggle(a.client)).toContain("Stopped"); expect(await toggle(b.client)).toContain("Stopped"); await Promise.all([a.client.close(), b.client.close()]); }); it("forgets the session and cleans up when the stream closes", async () => { const { client, sessionId } = await connectSse(); await client.close(); await vi.waitFor(() => expect(error).toHaveBeenCalledWith("Client Disconnected: ", sessionId), ); // A message for the closed session finds no transport and is answered 404. const response = await fetch(`${base}/message?sessionId=${sessionId}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }), signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(404); expect(error).toHaveBeenCalledWith( `No transport found for sessionId ${sessionId}`, ); }); it("answers a POST for an unknown session with a 404", async () => { const response = await fetch(`${base}/message?sessionId=nope`, { method: "POST", body: "{}", signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(404); expect(await response.json()).toEqual({ jsonrpc: "2.0", error: { code: -32000, message: "Session not found" }, id: null, }); expect(error).toHaveBeenCalledWith("No transport found for sessionId nope"); }); it("answers a POST with no session id with a 400", async () => { const response = await fetch(`${base}/message`, { method: "POST", body: "{}", signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(400); expect(await response.json()).toEqual({ jsonrpc: "2.0", error: { code: -32000, message: "Bad Request: sessionId query parameter is required", }, id: null, }); }); it("answers a second GET /sse for an existing session with a 409, and keeps the first stream", async () => { const { client, sessionId } = await connectSse(); const response = await fetch(`${base}/sse?sessionId=${sessionId}`, { signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(409); expect(await response.json()).toEqual({ jsonrpc: "2.0", error: { code: -32000, message: "Conflict: this session already has an SSE stream", }, id: null, }); expect(error).toHaveBeenCalledWith( "Client Reconnecting? This shouldn't happen; when client has a sessionId, GET /sse should not be called again.", sessionId, ); // The original session is untouched and still serves requests. const result = await client.callTool({ name: "echo", arguments: { message: "still here" }, }); expect(result.content).toEqual([ { type: "text", text: "Echo: still here" }, ]); await client.close(); }); it("answers a GET /sse for an unknown session id with a 404", async () => { const response = await fetch(`${base}/sse?sessionId=unknown`, { signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(404); expect(await response.json()).toEqual({ jsonrpc: "2.0", error: { code: -32000, message: "Session not found" }, id: null, }); expect(error).toHaveBeenCalledWith( "No transport found for sessionId unknown", ); }); it("answers a CORS preflight from a localhost origin, echoing that origin", async () => { const response = await fetch(`${base}/message`, { method: "OPTIONS", headers: { origin: "http://localhost:6274", "access-control-request-method": "POST", }, }); expect(response.status).toBe(204); expect(response.headers.get("access-control-allow-origin")).toBe( "http://localhost:6274", ); expect(response.headers.get("access-control-allow-methods")).toBe( "GET,POST", ); }); it("serves a client whose requests carry a localhost Origin", async () => { const client = new Client({ name: "sse-test", version: "0.0.0" }); // Every request the transport makes, the stream's GET included, carries // the Origin a browser page served from localhost would send. const withOrigin = (url: string | URL, init?: RequestInit) => { const headers = new Headers(init?.headers); headers.set("origin", "http://127.0.0.1:6274"); return fetch(url, { ...init, headers }); }; await client.connect( new SSEClientTransport(new URL(`${base}/sse`), { fetch: withOrigin }), ); const result = await client.callTool({ name: "echo", arguments: { message: "from localhost" }, }); expect(result.content).toEqual([ { type: "text", text: "Echo: from localhost" }, ]); await client.close(); }); describe("a request from a foreign origin", () => { const FOREIGN = "http://elsewhere.example"; it("is refused at preflight, with no CORS grant", async () => { const response = await fetch(`${base}/message`, { method: "OPTIONS", headers: { origin: FOREIGN, "access-control-request-method": "POST", }, }); expect(response.status).toBe(403); expect(response.headers.get("access-control-allow-origin")).toBeNull(); }); it("cannot open an SSE stream", async () => { const response = await fetch(`${base}/sse`, { headers: { origin: FOREIGN }, signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(403); expect(response.headers.get("access-control-allow-origin")).toBeNull(); expect(error).not.toHaveBeenCalledWith( "Client Connected: ", expect.anything(), ); }); it("cannot call a tool on an open session", async () => { const { client, sessionId } = await connectSse(); const messages = () => error.mock.calls.filter( (c: unknown[]) => c[0] === "Client Message from", ).length; const before = messages(); const response = await fetch(`${base}/message?sessionId=${sessionId}`, { method: "POST", headers: { "content-type": "application/json", origin: FOREIGN }, body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "get-env", arguments: {} }, }), signal: AbortSignal.timeout(2000), }); expect(response.status).toBe(403); expect(await response.json()).toMatchObject({ jsonrpc: "2.0", error: { code: -32000 }, id: null, }); // The refused message never reached the session's transport. expect(messages()).toBe(before); await client.close(); }); }); }); describe("startSseServer", () => { afterEach(() => { vi.doUnmock("../transports/listen.js"); vi.resetModules(); vi.unstubAllEnvs(); }); async function start() { vi.resetModules(); const listenOrExit = vi.fn(() => "the http server"); // Only the bind is stubbed; the host is resolved by the real module. vi.doMock("../transports/listen.js", async (importOriginal) => ({ ...(await importOriginal<typeof import("../transports/listen.js")>()), listenOrExit, })); const { startSseServer } = await import("../transports/sse.js"); return { listenOrExit, server: startSseServer() }; } it("binds PORT when it is set", async () => { vi.stubEnv("PORT", "4567"); vi.stubEnv("HOST", ""); const { listenOrExit, server } = await start(); expect(error).toHaveBeenCalledWith("Starting SSE server..."); expect(listenOrExit).toHaveBeenCalledWith( expect.any(Function), "4567", "127.0.0.1", "Server is running on 127.0.0.1:4567", ); expect(server).toBe("the http server"); }); it("binds 3001 on loopback by default", async () => { vi.stubEnv("PORT", ""); vi.stubEnv("HOST", ""); const { listenOrExit } = await start(); expect(listenOrExit).toHaveBeenCalledWith( expect.any(Function), 3001, "127.0.0.1", "Server is running on 127.0.0.1:3001", ); }); it("binds HOST when it is set, and names it in the listening line", async () => { vi.stubEnv("PORT", ""); vi.stubEnv("HOST", "0.0.0.0"); const { listenOrExit } = await start(); expect(listenOrExit).toHaveBeenCalledWith( expect.any(Function), 3001, "0.0.0.0", "Server is running on 0.0.0.0:3001", ); }); }); - src/everything/__tests__/static-files.test.ts (4640 bytes)
/** * Characterizes how the static document resources and the server * instructions handle the docs directory's contents (#4854): the MIME type * chosen by extension, skipped directories and vanished entries, a file that * cannot be read, and a missing docs directory. The shipped docs/ holds only * Markdown, so these cases stand in synthetic entries through a mocked `fs`; * everything else is the real server, driven over the protocol. */ import { afterEach, describe, expect, it, vi } from "vitest"; type FsModule = typeof import("fs"); /** Load the harness against an `fs` whose docs/ is altered by `overrides`. */ async function harnessWithFs(overrides: (real: FsModule) => Partial<FsModule>) { vi.resetModules(); vi.doMock("fs", async (importOriginal) => { const real = await importOriginal<FsModule>(); return { ...real, ...overrides(real) }; }); return import("./harness.js"); } afterEach(() => { vi.doUnmock("fs"); vi.resetModules(); }); const isDocs = (p: unknown) => String(p).replace(/\\/g, "/").includes("/docs"); describe("static document resources", () => { const EXTRA: Record<string, string> = { "notes.txt": "plain notes", "data.json": '{"a":1}', "LONG.MARKDOWN": "# upper case", "raw.bin": "bytes", }; it("types files by extension, skips directories and vanished entries, and reports unreadable files in the text", async () => { const harness = await harnessWithFs((real) => ({ readdirSync: ((p: string) => isDocs(p) ? [ ...(real.readdirSync(p) as string[]), ...Object.keys(EXTRA), "subdir", "vanished.md", "unreadable.md", ] : real.readdirSync(p)) as FsModule["readdirSync"], statSync: ((p: string) => { const name = String(p).split(/[\\/]/).pop()!; if (name === "vanished.md") throw new Error("ENOENT"); if (name === "subdir") return { isFile: () => false }; if (name in EXTRA || name === "unreadable.md") return { isFile: () => true }; return real.statSync(p); }) as FsModule["statSync"], readFileSync: ((p: string, enc: BufferEncoding) => { const name = String(p).split(/[\\/]/).pop()!; if (name === "unreadable.md") throw new Error("EACCES"); if (name in EXTRA) return EXTRA[name]; return real.readFileSync(p, enc); }) as FsModule["readFileSync"], })); const session = await harness.connect(); try { const { resources } = await session.client.listResources(); const byName = Object.fromEntries(resources.map((r) => [r.name, r])); expect(byName["notes.txt"].mimeType).toBe("text/plain"); expect(byName["data.json"].mimeType).toBe("application/json"); expect(byName["LONG.MARKDOWN"].mimeType).toBe("text/markdown"); expect(byName["raw.bin"].mimeType).toBe("text/plain"); expect(byName["subdir"]).toBeUndefined(); expect(byName["vanished.md"]).toBeUndefined(); const { contents } = await session.client.readResource({ uri: byName["data.json"].uri, }); expect(contents).toEqual([ { uri: byName["data.json"].uri, mimeType: "application/json", text: '{"a":1}', }, ]); const unreadable = await session.client.readResource({ uri: byName["unreadable.md"].uri, }); expect(unreadable.contents[0]).toMatchObject({ mimeType: "text/markdown", text: expect.stringMatching( /^Error reading file: .*unreadable\.md\. Error: EACCES$/, ), }); } finally { await session.close(); } }); it("registers none, and says the instructions did not load, without a docs directory", async () => { const harness = await harnessWithFs((real) => ({ readdirSync: ((p: string) => { if (isDocs(p)) throw new Error("ENOENT: no docs"); return real.readdirSync(p); }) as FsModule["readdirSync"], readFileSync: ((p: string, enc: BufferEncoding) => { if (isDocs(p)) throw new Error("ENOENT: no docs"); return real.readFileSync(p, enc); }) as FsModule["readFileSync"], })); const session = await harness.connect(); try { const { resources } = await session.client.listResources(); expect( resources.filter((r) => r.uri.includes("/static/document/")), ).toEqual([]); expect(session.client.getInstructions()).toBe( "Server instructions not loaded: Error: ENOENT: no docs", ); } finally { await session.close(); } }); }); - src/everything/__tests__/stdio.test.ts (4720 bytes)
/** * Characterizes the stdio transport manager (#4854) in-process: `main()` is * given a pair of in-memory streams in place of the process's stdin and * stdout, and a real client talks newline-delimited JSON-RPC over them, as a * client does over a spawned server's pipes. The SIGINT handler it installs * is called directly, with `process.exit` stubbed. */ import { PassThrough } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; import { Client } from "@modelcontextprotocol/client"; import { main, startStdioServer, type StdioSession, } from "../transports/stdio.js"; const started: StdioSession[] = []; afterEach(() => { for (const { shutdown } of started.splice(0)) { process.off("SIGINT", shutdown); } vi.restoreAllMocks(); }); /** * Start the server on in-memory pipes and connect a client to the other * ends. The client side reuses the SDK's stdio framing, reading the server's * stdout and writing its stdin. */ async function startOnPipes() { const toServer = new PassThrough(); const fromServer = new PassThrough(); const stdio = await main(toServer, fromServer); started.push(stdio); const client = new Client({ name: "stdio-test", version: "0.0.0" }); await client.connect(new StdioServerTransport(fromServer, toServer)); return { client, stdio }; } describe("stdio transport", () => { it("serves the protocol over the given streams", async () => { const { client } = await startOnPipes(); expect(client.getServerVersion()?.name).toBe("mcp-servers/everything"); const result = await client.callTool({ name: "echo", arguments: { message: "over stdio" }, }); expect(result.content).toEqual([ { type: "text", text: "Echo: over stdio" }, ]); await client.close(); }); it("serves a 2026-07-28 client on the same pipes (#4852)", async () => { const toServer = new PassThrough(); const fromServer = new PassThrough(); const stdio = await main(toServer, fromServer); started.push(stdio); const client = new Client( { name: "stdio-test", version: "0.0.0" }, { versionNegotiation: { mode: { pin: "2026-07-28" } } }, ); await client.connect(new StdioServerTransport(fromServer, toServer)); expect(client.getProtocolEra()).toBe("modern"); expect(client.getServerCapabilities()?.extensions).toEqual({ "io.modelcontextprotocol/tasks": {}, }); const result = await client.callTool({ name: "echo", arguments: { message: "modern" }, }); expect(result.content).toEqual([{ type: "text", text: "Echo: modern" }]); await client.close(); }); it("closes the server, cleans up and exits 0 on SIGINT", async () => { const exit = vi .spyOn(process, "exit") .mockImplementation(() => undefined as never); const { client, stdio } = await startOnPipes(); expect(process.listeners("SIGINT")).toContain(stdio.shutdown); const closed = new Promise<void>((resolve) => { client.onclose = resolve; }); await stdio.shutdown(); expect(exit).toHaveBeenCalledWith(0); // The server closing its transport does not end the client's side of the // pipes; the client sees its own close. await client.close(); await closed; }); it("announces itself on stderr and starts main", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); const before = process.listeners("SIGINT").length; await startStdioServer(new PassThrough(), new PassThrough()); expect(error).toHaveBeenCalledWith("Starting default (STDIO) server..."); const added = process.listeners("SIGINT").slice(before); expect(added).toHaveLength(1); for (const listener of added) process.off("SIGINT", listener); }); it("reports a transport that cannot start on stderr and in the exit status", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); const broken = new PassThrough(); broken.on = () => { throw new Error("stdin unavailable"); }; const before = process.listeners("SIGINT").length; await startStdioServer(broken, new PassThrough()); await vi.waitFor(() => expect(error).toHaveBeenCalledWith( "Transport error:", expect.objectContaining({ message: "stdin unavailable" }), ), ); // The failure is in the exit status too; reset it so the run is not failed. expect(process.exitCode).toBe(1); process.exitCode = undefined; for (const listener of process.listeners("SIGINT").slice(before)) { process.off("SIGINT", listener); } }); }); - src/everything/__tests__/streamable-http.test.ts (28537 bytes)
/** * Characterizes the Streamable HTTP transport manager (#4854). `createApp()` * is served on a free loopback port and driven by the SDK's Streamable HTTP * client, and by raw HTTP where the test pins the wire itself: the 400 for a * missing session and the 404 for an unknown one (#4982), the priming event on * each SSE stream (#3267), and the event store's replay of the resumed stream * only (#4087). The shutdown handler is called directly (#4983), and * `startStreamableHttpServer()` is * checked with `listenOrExit` stubbed, so no fixed port is ever bound. * * The same endpoint serves 2026-07-28 clients (#4852): a session-less POST * carrying the per-request envelope goes to the SDK's `createMcpHandler`, and * the "2026-07-28 clients" block below drives it with a client that * negotiates that era, including the `Mcp-Param-Region` header the client * mirrors from `get-header-params`'s `x-mcp-header` argument and the change * notifications published on the handler's subscription bus. * * 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. */ import type { Server } from "node:http"; import { once } from "node:events"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; import { Client, StreamableHTTPClientTransport, } from "@modelcontextprotocol/client"; import { createApp, type StreamableHttpApp, } from "../transports/streamableHttp.js"; let app: StreamableHttpApp; let http: Server; let mcp: string; let log: ReturnType<typeof vi.spyOn>; beforeEach(async () => { log = vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); app = createApp(); 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(async () => { http.closeAllConnections(); await new Promise((resolve) => http.close(resolve)); vi.restoreAllMocks(); }); async function connectHttp() { const transport = new StreamableHTTPClientTransport(new URL(mcp)); const client = new Client({ name: "http-test", version: "0.0.0" }); await client.connect(transport); return { client, transport, sessionId: transport.sessionId! }; } const JSON_HEADERS = { "content-type": "application/json", accept: "application/json, text/event-stream", }; const BAD_SESSION = { jsonrpc: "2.0", error: { code: -32000, message: "Bad Request: No valid session ID provided" }, }; const SESSION_NOT_FOUND = { jsonrpc: "2.0", error: { code: -32001, message: "Session not found" }, id: null, }; type SseEvent = { id?: string; data: string }; /** Parse a complete SSE body into its events. */ function parseSse(body: string): SseEvent[] { return body .split("\n\n") .filter((block) => block.trim() !== "") .map((block) => { const event: SseEvent = { data: "" }; for (const line of block.split("\n")) { if (line.startsWith("id: ")) event.id = line.slice(4); if (line.startsWith("data: ")) event.data += line.slice(6); } return event; }); } /** POST one JSON-RPC message, raw. */ async function post(message: object, sessionId?: string) { return fetch(mcp, { method: "POST", headers: { ...JSON_HEADERS, ...(sessionId ? { "mcp-session-id": sessionId, "mcp-protocol-version": "2025-11-25" } : {}), }, body: JSON.stringify(message), }); } /** Initialize a session over raw HTTP; returns its id and the init events. */ async function rawInitialize() { const response = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "raw", version: "0" }, }, }); const sessionId = response.headers.get("mcp-session-id")!; const events = parseSse(await response.text()); const initialized = await post( { jsonrpc: "2.0", method: "notifications/initialized" }, sessionId, ); expect(initialized.status).toBe(202); return { sessionId, events }; } /** * Read an open SSE response for `ms`, then abort it. A replay is written * before the response's headers are, so it has all arrived by then. */ async function readFor( response: Response, ms: number, controller: AbortController, ): Promise<string> { const reader = response.body!.getReader(); const decoder = new TextDecoder(); let text = ""; const timer = setTimeout(() => controller.abort(), ms); try { for (;;) { const { value, done } = await reader.read(); if (done) break; text += decoder.decode(value); } } catch { // aborted: the read window is over } finally { clearTimeout(timer); } return text; } describe("Streamable HTTP transport", () => { it("serves the protocol to the SDK client over one session", async () => { const { client, sessionId } = await connectHttp(); expect(sessionId).toMatch(/^[0-9a-f-]{36}$/); const result = await client.callTool({ name: "echo", arguments: { message: "over http" }, }); expect(result.content).toEqual([{ type: "text", text: "Echo: over http" }]); expect(log).toHaveBeenCalledWith( `Session initialized with ID: ${sessionId}`, ); await client.close(); }); it("starts each SSE response with an empty priming event (#3267)", async () => { // SDK behavior required by SEP-1699 for a 2025-11-25 client when an event // store is configured: an event with an id and no data comes first. const { events } = await rawInitialize(); expect(events).toHaveLength(2); expect(events[0]).toEqual({ id: expect.any(String), data: "" }); expect(JSON.parse(events[1].data)).toMatchObject({ jsonrpc: "2.0", id: 1, result: { serverInfo: { name: "mcp-servers/everything" } }, }); }); it("replays only the resumed stream's events after a Last-Event-ID (#4087)", async () => { // The initialize stream is resumed from its priming event: its own // response is replayed, and the tool result stored afterwards on another // stream is not. const { sessionId, events } = await rawInitialize(); const echo = await post( { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "echo", arguments: { message: "from another stream" } }, }, sessionId, ); expect(await echo.text()).toContain("Echo: from another stream"); const controller = new AbortController(); const resumed = await fetch(mcp, { headers: { accept: "text/event-stream", "mcp-session-id": sessionId, "mcp-protocol-version": "2025-11-25", "last-event-id": events[0].id!, }, signal: controller.signal, }); expect(resumed.status).toBe(200); const replayed = parseSse(await readFor(resumed, 250, controller)); expect(replayed).toEqual([{ id: events[1].id, data: events[1].data }]); expect(log).toHaveBeenCalledWith( `Client reconnecting with Last-Event-ID: ${events[0].id}`, ); }); it("refuses a GET resuming from an unknown Last-Event-ID with a 400 (#4087)", async () => { // The event store reports no stream for the id, so the SDK refuses the // resume rather than mapping it to a stream that does not exist. const { sessionId } = await rawInitialize(); const response = await fetch(mcp, { headers: { accept: "text/event-stream", "mcp-session-id": sessionId, "mcp-protocol-version": "2025-11-25", "last-event-id": "no-such-event", }, }); expect(response.status).toBe(400); expect(await response.json()).toMatchObject({ jsonrpc: "2.0", error: { code: -32000, message: "Invalid event ID format" }, }); }); it("opens a standalone SSE stream without a Last-Event-ID", async () => { const { sessionId } = await rawInitialize(); const controller = new AbortController(); const response = await fetch(mcp, { headers: { accept: "text/event-stream", "mcp-session-id": sessionId, "mcp-protocol-version": "2025-11-25", }, signal: controller.signal, }); expect(response.status).toBe(200); expect(log).toHaveBeenCalledWith( `Establishing new SSE stream for session ${sessionId}`, ); controller.abort(); }); it.each(["GET", "DELETE"])( "answers %s with no session id with a 400", async (method) => { const response = await fetch(mcp, { method }); expect(response.status).toBe(400); expect(await response.json()).toEqual(BAD_SESSION); }, ); it.each(["GET", "DELETE"])( "answers %s for an unknown session with a 404 (#4982)", async (method) => { const response = await fetch(mcp, { method, headers: { "mcp-session-id": "unknown" }, }); expect(response.status).toBe(404); expect(await response.json()).toEqual(SESSION_NOT_FOUND); }, ); it("answers a POST for an unknown session with a 404 that carries the request id (#4982)", async () => { const response = await post( { jsonrpc: "2.0", id: 7, method: "ping" }, "unknown", ); expect(response.status).toBe(404); expect(await response.json()).toEqual({ ...SESSION_NOT_FOUND, id: 7 }); }); it.each([ ["a notification", JSON.stringify({ jsonrpc: "2.0", method: "ping" })], ["a batch", JSON.stringify([{ jsonrpc: "2.0", id: 8, method: "ping" }])], ["a response", JSON.stringify({ jsonrpc: "2.0", id: 8, result: {} })], ["an object that is not JSON-RPC", JSON.stringify({ id: 8 })], ["malformed JSON", "{not json"], [ "a body too large to read for its id", JSON.stringify({ jsonrpc: "2.0", id: 8, pad: "x".repeat(70 * 1024) }), ], ])( "answers a POST of %s for an unknown session with a 404 and a null id", async (_label, body) => { const response = await fetch(mcp, { method: "POST", headers: { ...JSON_HEADERS, "mcp-session-id": "unknown" }, body, }); expect(response.status).toBe(404); expect(await response.json()).toEqual(SESSION_NOT_FOUND); }, ); it("creates a server for a session-less POST that is not initialize, which the SDK then rejects", async () => { const response = await post({ jsonrpc: "2.0", id: 1, method: "ping" }); expect(response.status).toBe(400); expect(await response.json()).toMatchObject({ jsonrpc: "2.0", error: { code: -32000, message: "Bad Request: Server not initialized" }, }); }); it("ends a session on DELETE, cleaning it up and refusing it afterwards with a 404 (#4982)", async () => { const { client, transport, sessionId } = await connectHttp(); await transport.terminateSession(); expect(log).toHaveBeenCalledWith( `Received session termination request for session ${sessionId}`, ); await vi.waitFor(() => expect(log).toHaveBeenCalledWith( `Transport closed for session ${sessionId}, removing from transports map`, ), ); const after = await post( { jsonrpc: "2.0", id: 9, method: "ping" }, sessionId, ); expect(after.status).toBe(404); expect(await after.json()).toEqual({ ...SESSION_NOT_FOUND, id: 9 }); await client.close(); }); it("maps a POST that throws before answering to a JSON-RPC internal error", async () => { vi.spyOn( NodeStreamableHTTPServerTransport.prototype, "handleRequest", ).mockRejectedValueOnce(new Error("boom")); const response = await post({ jsonrpc: "2.0", id: 1, method: "ping" }); expect(response.status).toBe(500); // A session-less POST's body is parsed before it is routed (#4852), so // the error carries the request's id. expect(await response.json()).toEqual({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: 1, }); expect(log).toHaveBeenCalledWith( "Error handling MCP request:", expect.any(Error), ); }); it("leaves a POST alone when it throws after answering", async () => { const { sessionId } = await rawInitialize(); vi.spyOn( NodeStreamableHTTPServerTransport.prototype, "handleRequest", ).mockImplementationOnce(async (_req, res) => { res.writeHead(200).end("partial"); throw new Error("late"); }); const response = await post( { jsonrpc: "2.0", id: 3, method: "ping" }, sessionId, ); expect(response.status).toBe(200); expect(await response.text()).toBe("partial"); }); it("maps a DELETE that throws to a JSON-RPC internal error, unless it already answered", async () => { const { sessionId } = await rawInitialize(); const handle = vi.spyOn( NodeStreamableHTTPServerTransport.prototype, "handleRequest", ); handle.mockRejectedValueOnce(new Error("boom")); const failed = await fetch(mcp, { method: "DELETE", headers: { "mcp-session-id": sessionId }, }); expect(failed.status).toBe(500); expect(await failed.json()).toEqual({ jsonrpc: "2.0", error: { code: -32603, message: "Error handling session termination" }, }); handle.mockImplementationOnce(async (_req, res) => { res.writeHead(200).end("partial"); throw new Error("late"); }); const partial = await fetch(mcp, { method: "DELETE", headers: { "mcp-session-id": sessionId }, }); expect(await partial.text()).toBe("partial"); expect(log).toHaveBeenCalledWith( "Error handling session termination:", expect.any(Error), ); }); it("answers a CORS preflight from a localhost origin, echoing that origin, and exposes the MCP headers", async () => { const response = await fetch(mcp, { method: "OPTIONS", headers: { origin: "http://localhost:6274", "access-control-request-method": "DELETE", }, }); expect(response.status).toBe(204); expect(response.headers.get("access-control-allow-origin")).toBe( "http://localhost:6274", ); expect(response.headers.get("access-control-allow-methods")).toBe( "GET,POST,DELETE", ); }); it.each(["legacy", "modern"] as const)( "serves a %s-era client whose requests carry a localhost Origin", async (era) => { // Every request the transport makes carries the Origin a browser page // served from localhost would send. const withOrigin = (url: string | URL, init?: RequestInit) => { const headers = new Headers(init?.headers); headers.set("origin", "http://[::1]:627 - src/everything/__tests__/surface.test.ts (31151 bytes)
/** * Characterizes what the everything server advertises over the wire (#4854): * `initialize` (server info, capabilities, instructions), and the tool, * prompt, resource and resource-template lists, including which tools appear * only for clients that declare a capability. These lists are the regression * net for the SDK v2 migration: an assertion here that has to change is a * behavior change. Every session here is 2025-era (`initialize`); what a * 2026-07-28 client is offered is in modern.test.ts. */ import { afterEach, describe, expect, it } from "vitest"; import { ALL_CAPABILITIES, connect, ofMethod, type Session, withoutIcons, } from "./harness.js"; let session: Session | undefined; afterEach(async () => { await session?.close(); session = undefined; }); const BASE_TOOLS = [ "echo", "get-annotated-message", "get-env", "get-header-params", "get-resource-links", "get-resource-reference", "get-structured-content", "get-sum", "get-tiny-image", "gzip-file-as-resource", "toggle-simulated-logging", "toggle-subscriber-updates", "trigger-list-changed", "trigger-log-messages", "trigger-long-running-operation", "trigger-resource-update", ]; describe("initialize", () => { it("reports the server info, capabilities and instructions", async () => { session = await connect(); const { client } = session; expect(client.getServerVersion()).toMatchObject({ name: "mcp-servers/everything", title: "Everything Reference Server", }); expect(client.getServerCapabilities()).toEqual({ tools: { listChanged: true }, prompts: { listChanged: true }, resources: { subscribe: true, listChanged: true }, logging: {}, completions: {}, }); expect(client.getInstructions()).toMatch( /^# Everything Server – Server Instructions/, ); }); it("qualifies every capability-gated tool it names, for a client that cannot see them (#4792)", async () => { // The instructions are fixed before client capabilities are known, so a // client that declares no sampling, elicitation or roots capability still // receives them. Each gated tool it names may appear only in the // "Capability-Gated Tools" section or on a line that makes it conditional. session = await connect(); const instructions = session.client.getInstructions() ?? ""; const { tools } = await session.client.listTools(); const names = tools.map((t) => t.name); const gated = [ "get-roots-list", "trigger-elicitation-request", "trigger-multi-step-elicitation", "trigger-sampling-request", "trigger-url-elicitation", ]; const sections = instructions.split(/^## /m); const gatedSection = sections.find((part) => part.startsWith("Capability-Gated Tools")) ?? ""; const unconditional = sections .filter((part) => part !== gatedSection) .flatMap((part) => part.split("\n")) .filter( (line) => gated.some((tool) => line.includes(`\`${tool}\``)) && !/\bif\b/i.test(line), ); for (const tool of gated) { expect(names).not.toContain(tool); expect(gatedSection).toContain(`\`${tool}\``); } expect(unconditional).toEqual([]); }); }); describe("tools/list", () => { it("lists the base tools for a client that declares no capabilities", async () => { session = await connect(); const { tools } = await session.client.listTools(); expect(tools.map((t) => t.name).sort()).toEqual(BASE_TOOLS); }); it("adds every capability-gated tool for a client that declares them all", async () => { session = await connect({ capabilities: ALL_CAPABILITIES }); const { tools } = await session.client.listTools(); expect(tools.map((t) => t.name).sort()).toEqual( [ ...BASE_TOOLS, "get-roots-list", "trigger-elicitation-request", "trigger-multi-step-elicitation", "trigger-sampling-request", "trigger-url-elicitation", ].sort(), ); }); it.each([ [{ roots: {} }, ["get-roots-list"]], [{ sampling: {} }, ["trigger-sampling-request"]], [ { elicitation: {} }, ["trigger-elicitation-request", "trigger-multi-step-elicitation"], ], [ { elicitation: { form: {} } }, ["trigger-elicitation-request", "trigger-multi-step-elicitation"], ], // A URL-only client cannot answer the form request (#4985). [{ elicitation: { url: {} } }, ["trigger-url-elicitation"]], [ { elicitation: { form: {}, url: {} } }, [ "trigger-elicitation-request", "trigger-multi-step-elicitation", "trigger-url-elicitation", ], ], ])( "gates tools on the client's declared capabilities: %j", async (capabilities, extra) => { session = await connect({ capabilities }); const { tools } = await session.client.listTools(); expect(tools.map((t) => t.name).sort()).toEqual( [...BASE_TOOLS, ...extra].sort(), ); }, ); it("sends tools/list_changed after initialize, when the conditional tools are registered", async () => { // A client with no capabilities gets no conditional tools, so nothing is // registered after initialize and no list_changed is sent. session = await connect({ capabilities: ALL_CAPABILITIES }); await session.client.listTools(); expect( ofMethod(session.notifications, "notifications/tools/list_changed") .length, ).toBeGreaterThan(0); }); it("advertises each tool's title and annotations", async () => { session = await connect({ capabilities: ALL_CAPABILITIES }); const { tools } = await session.client.listTools(); const summary = Object.fromEntries( tools .sort((a, b) => a.name.localeCompare(b.name)) .map((t) => [ t.name, { title: t.title, annotations: t.annotations, execution: t.execution, hasOutputSchema: t.outputSchema !== undefined, }, ]), ); expect(summary).toMatchInlineSnapshot(` { "echo": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Echo Tool", }, "get-annotated-message": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Get Annotated Message Tool", }, "get-env": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Print Environment Tool", }, "get-header-params": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": true, "title": "Get Header Params Tool", }, "get-resource-links": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Get Resource Links Tool", }, "get-resource-reference": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Get Resource Reference Tool", }, "get-roots-list": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Get Roots List Tool", }, "get-structured-content": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": true, "title": "Get Structured Content Tool", }, "get-sum": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Get Sum Tool", }, "get-tiny-image": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Get Tiny Image Tool", }, "gzip-file-as-resource": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": true, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "GZip File as Resource Tool", }, "toggle-simulated-logging": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": false, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "Toggle Simulated Logging", }, "toggle-subscriber-updates": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": false, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "Toggle Subscriber Updates", }, "trigger-elicitation-request": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": false, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger Elicitation Request Tool", }, "trigger-list-changed": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger List Changed Tool", }, "trigger-log-messages": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger Log Messages Tool", }, "trigger-long-running-operation": { "annotations": { "destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger Long Running Operation Tool", }, "trigger-multi-step-elicitation": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": false, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger Multi-Step Elicitation Tool", }, "trigger-resource-update": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": false, "readOnlyHint": true, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger Resource Update Tool", }, "trigger-sampling-request": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": true, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger Sampling Request Tool", }, "trigger-url-elicitation": { "annotations": { "destructiveHint": false, "idempotentHint": false, "openWorldHint": true, "readOnlyHint": false, }, "execution": undefined, "hasOutputSchema": false, "title": "Trigger URL Elicitation Tool", }, } `); }); it("advertises each tool's input schema", async () => { session = await connect({ capabilities: ALL_CAPABILITIES }); const { tools } = await session.client.listTools(); const schemas = Object.fromEntries( tools .sort((a, b) => a.name.localeCompare(b.name)) .map((t) => [t.name, t.inputSchema]), ); expect(schemas).toMatchInlineSnapshot(` { "echo": { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "message": { "description": "Message to echo", "type": "string", }, }, "required": [ "message", ], "type": "object", }, "get-annotated-message": { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "includeImage": { "default": false, "description": "Whether to include an example image", "type": "boolean", }, "messageType": { "description": "Type of message to demonstrate different annotation patterns", "enum": [ "error", "success", "debug", ], "type": "string", }, }, "required": [ "messageType", ], "type": "object", }, "get-env": { "$schema": "https://json-schema.org/draft/2020-12/schema", "prop - src/everything/AGENTS.md (3046 bytes)
# MCP "Everything" Server - Development Guidelines ## Build, Test & Run Commands - Build: `npm run build` - Compiles TypeScript to JavaScript - Watch mode: `npm run watch` - Watches for changes and rebuilds automatically - Run STDIO server: `npm run start:stdio` - Starts the MCP server using stdio transport - Run SSE server: `npm run start:sse` - Starts the MCP server with SSE transport - Run StreamableHttp server: `npm run start:streamableHttp` - Starts the MCP server with StreamableHttp transport - Prepare release: `npm run prepare` - Builds the project for publishing ## Code style The repo-wide TypeScript, naming and MCP rules are in the root [`AGENTS.md`](../../AGENTS.md), which is loaded in every session. This file holds only what is specific to this server, and is loaded when a file in this directory is read. Beyond the root rules: - Match the existing code style, import order and module layout of the folder you are working in. - Use kebab-case for file names and for registered tools, prompts and resources (e.g. `get-annotated-message`, not `annotated-message`). ## Extending the Server The Everything Server is designed to be extended at well-defined points. See [Extension Points](docs/extension.md) and [Project Structure](docs/structure.md). The server factory is `src/everything/server/index.ts` and registers all features during startup as well as handling post-connection setup. ### High-level - The server serves both protocol eras (2026-07-28 and 2025-era); the factory is `createServer({ era })`, and what each era gets is wired in `server/index.ts` and `tools/index.ts`. - Tools live under `src/everything/tools/` and are registered via `registerTools(server, context)` (both eras), `registerModernTools` (2026-07-28) or `registerLegacyTools` / `registerConditionalTools` (2025 era). - Resources live under `src/everything/resources/` and are registered via `registerResources(server, context)`. - Prompts live under `src/everything/prompts/` and are registered via `registerPrompts(server)`. - Subscriptions and simulated update routines are under `src/everything/resources/subscriptions.ts`. - Logging helpers are under `src/everything/server/logging.ts`. - Transport managers are under `src/everything/transports/`. ### When adding a new feature - Follow the existing file/module pattern in its folder (naming, exports, and registration function). - Export a `registerX(server)` function that registers new items with the MCP SDK in the same style as existing ones (taking the per-instance `context` too when it needs the era, the change publisher or per-connection state). - Keep no state in module-level maps keyed by session id; see [Extension Points](docs/extension.md). - Wire your new module into the central index (e.g., update `tools/index.ts`, `resources/index.ts`, or `prompts/index.ts`). - Ensure schemas (for tools) are accurate JSON Schema and include helpful descriptions and examples. - Keep the docs in `src/everything/docs/` up to date if you add or modify noteworthy features. - src/everything/CHANGELOG.md (18215 bytes)
# @modelcontextprotocol/server-everything ## 2.3.1 ### Patch Changes - [#5583](https://github.com/modelcontextprotocol/servers/pull/5583) [`66f641e`](https://github.com/modelcontextprotocol/servers/commit/66f641e9ae2fc7726a9420b15fbf68e0613a254b) [@cliffhall](https://github.com/cliffhall) - Fix GHSA-38j4-j742-j7r3. ## 2.3.0 ### Minor Changes - [#5452](https://github.com/modelcontextprotocol/servers/pull/5452) [`41a758c`](https://github.com/modelcontextprotocol/servers/commit/41a758c288398b7aa2b38f6ddaad43dd60e6498d) [@cliffhall](https://github.com/cliffhall) - The Streamable HTTP and HTTP+SSE transports now bind the loopback interface (`127.0.0.1`) by default instead of every interface, so a server started over HTTP is no longer reachable from other hosts on the network. Set the new `HOST` environment variable to widen the bind deliberately (`HOST=0.0.0.0`); the container image sets it. The listening line now names the bound address and port. Thanks to TheodorNEngoy for the prototype in [#3303](https://github.com/modelcontextprotocol/servers/issues/3303). ### Patch Changes - [#5475](https://github.com/modelcontextprotocol/servers/pull/5475) [`2a73097`](https://github.com/modelcontextprotocol/servers/commit/2a7309707ce00d340bc8c29288084a1408f14efb) [@cliffhall](https://github.com/cliffhall) - Describe every tool input property in tools/list ([#3669](https://github.com/modelcontextprotocol/servers/issues/3669)). Every filesystem path argument now says how it is resolved and that it must stay inside the allowed directories, and `excludePatterns` says how its globs match (which differs between `directory_tree` and `search_files`). The memory server's top-level array arguments, and the everything server's `resourceType`, gain descriptions, and `get-resource-reference`'s `resourceId` no longer claims to fetch only text resources. - [#5476](https://github.com/modelcontextprotocol/servers/pull/5476) [`6f16868`](https://github.com/modelcontextprotocol/servers/commit/6f1686851264517f5cec0dde54effa1f68473d44) [@cliffhall](https://github.com/cliffhall) - Raise the `express` dependency floor to `^5.3.0` (monthly dependency refresh). - [#5478](https://github.com/modelcontextprotocol/servers/pull/5478) [`67b541c`](https://github.com/modelcontextprotocol/servers/commit/67b541cc7c862f67f419c4ab339b9c73e86e9e46) [@cliffhall](https://github.com/cliffhall) - Remove the unused `jszip` dependency. Nothing in the server imports it, so installs no longer pull in jszip and its transitive dependencies. - [#5449](https://github.com/modelcontextprotocol/servers/pull/5449) [`1fbdd4e`](https://github.com/modelcontextprotocol/servers/commit/1fbdd4eaf948f883e374af0b18cba3b8b7678e8e) [@cliffhall](https://github.com/cliffhall) - `tasks/update` now measures the answers against its 64 KiB limit in UTF-8 bytes rather than string length, so non-ASCII answers can no longer exceed the byte budget. ## 2.2.1 ### Patch Changes - [#5436](https://github.com/modelcontextprotocol/servers/pull/5436) [`ee12fb1`](https://github.com/modelcontextprotocol/servers/commit/ee12fb1446585fe27407d4fe1a0205c3feffefa8) [@cliffhall](https://github.com/cliffhall) - Give the resource `gzip-file-as-resource` creates the light and dark resource icons, like every other resource. A 2025-era client now sees them on the session resource's `resources/list` entry and on the returned link; a 2026-07-28 client sees them on the minted resource link. ## 2.2.0 ### Minor Changes - [#5389](https://github.com/modelcontextprotocol/servers/pull/5389) [`35bed66`](https://github.com/modelcontextprotocol/servers/commit/35bed663e06c5985aafc04c8483baff8cad341e6) [@cliffhall](https://github.com/cliffhall) - Add light- and dark-themed icons (SEP-973) to the server info and to every tool, prompt, resource and resource template, in both protocol eras. - [#5365](https://github.com/modelcontextprotocol/servers/pull/5365) [`3f867a0`](https://github.com/modelcontextprotocol/servers/commit/3f867a0f70ad5427abe45b7cabc620449c70bb30) [@cliffhall](https://github.com/cliffhall) - Add a resource collection example: reading `demo://resource/collection/summer-specials`, or the `demo://resource/collection/by-category/{category}` template, returns several contents in one `resources/read`, each under its item's own `demo://resource/collection/item/{itemId}` URI, which reads back on its own. Both templates complete their variable. ### Patch Changes - [#5396](https://github.com/modelcontextprotocol/servers/pull/5396) [`25b4a5d`](https://github.com/modelcontextprotocol/servers/commit/25b4a5dc32911b2054f8a9351aa4058ebd552cd0) [@cliffhall](https://github.com/cliffhall) - `trigger-long-running-operation` now honors cancellation in both protocol eras: a cancelled call clears its pending timer and sends no further progress, so it no longer delays stdio shutdown ([#1124](https://github.com/modelcontextprotocol/servers/issues/1124), [#4846](https://github.com/modelcontextprotocol/servers/issues/4846)). - [#5350](https://github.com/modelcontextprotocol/servers/pull/5350) [`4b54ad6`](https://github.com/modelcontextprotocol/servers/commit/4b54ad6e330f295d9c7b8701bd52a9fa36095c7e) [@cliffhall](https://github.com/cliffhall) - `resource-prompt` now names the values its arguments accept in `prompts/list`: `resourceType` must be "Text" or "Blob", and `resourceId` must be a positive integer. Prompt arguments carry no schema, so clients had no way to learn these before calling the prompt. ## 2.1.0 ### Minor Changes - [#5293](https://github.com/modelcontextprotocol/servers/pull/5293) [`f0c74aa`](https://github.com/modelcontextprotocol/servers/commit/f0c74aac70ab45d22b7d9e9373cd09460ec3e82e) [@cliffhall](https://github.com/cliffhall) - `get-env` now masks the values of credential-like environment variables (names with a `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `PASSWD`, `CREDENTIAL`, `AUTH` or `COOKIE` segment) as `"<redacted>"`. Set `GET_ENV_INCLUDE_SECRETS=1` to return every value unmasked. - [#5295](https://github.com/modelcontextprotocol/servers/pull/5295) [`344a4bd`](https://github.com/modelcontextprotocol/servers/commit/344a4bdf3914bebb514a8f27196aa96db2e3b828) [@cliffhall](https://github.com/cliffhall) - `gzip-file-as-resource` now refuses to fetch from loopback, private, link-local (cloud metadata) and other non-public addresses, on the caller's URL and on every redirect hop, and applies `GZIP_ALLOWED_DOMAINS` to every hop too. Set `GZIP_ALLOW_PRIVATE_IPS=1` to fetch from a local or private origin as before. ### Patch Changes - [#5289](https://github.com/modelcontextprotocol/servers/pull/5289) [`d4a8eb0`](https://github.com/modelcontextprotocol/servers/commit/d4a8eb0dd8b889a047938a6be0783923dd174ff1) [@cliffhall](https://github.com/cliffhall) - `trigger-elicitation-request` now summarizes an accepted form by the fields the form actually asks for: it lists the favorite first line and the five enum fields, and no longer reports `color` or `petType`, which the form never defined. - [#5290](https://github.com/modelcontextprotocol/servers/pull/5290) [`81a1e63`](https://github.com/modelcontextprotocol/servers/commit/81a1e63b261fbe169e7f729aeca0a392b473ded8) [@cliffhall](https://github.com/cliffhall) - `gzip-file-as-resource` now fails with an error naming the URL and HTTP status when the fetch returns a non-2xx response, instead of gzipping the error page as the file. - [#5297](https://github.com/modelcontextprotocol/servers/pull/5297) [`9130496`](https://github.com/modelcontextprotocol/servers/commit/9130496ad3a64483d4bd9414111327b1dea39fb0) [@cliffhall](https://github.com/cliffhall) - `get-resource-links`: rename the misleading `isOdd` flag to `isText`, and say in its JSDoc and in `docs/features.md` that even IDs are Text resources and odd IDs are Blob resources. The JSDoc headers of `get-resource-links` and `trigger-long-running-operation` now name the tool their file registers. No behavior change. - [#5298](https://github.com/modelcontextprotocol/servers/pull/5298) [`e220d44`](https://github.com/modelcontextprotocol/servers/commit/e220d444a304630db4eb5acb240a6afc72d220ab) [@cliffhall](https://github.com/cliffhall) - `get-tiny-image` (and `get-annotated-message`'s image) now returns a fully valid PNG: the embedded logo's corrupt `iCCP` color-profile chunk, whose CRC-32 did not match and which strict decoders rejected, is removed. The pixels are unchanged. ## 2.0.1 ### Patch Changes - [#5241](https://github.com/modelcontextprotocol/servers/pull/5241) [`64d488d`](https://github.com/modelcontextprotocol/servers/commit/64d488da642ecef61f3651a7cd565980a010ea5f) [@cliffhall](https://github.com/cliffhall) - Harden request handling in the HTTP transports. ## 2.0.0 ### Major Changes - [#5118](https://github.com/modelcontextprotocol/servers/pull/5118) [`5b400a6`](https://github.com/modelcontextprotocol/servers/commit/5b400a6ec05bd883522665ebeae110bf1a2744ff) [@cliffhall](https://github.com/cliffhall) - Move to the TypeScript SDK v2 packages (`@modelcontextprotocol/server`, `@modelcontextprotocol/node`, and `@modelcontextprotocol/server-legacy` for the deprecated HTTP+SSE transport) from `@modelcontextprotocol/sdk` 1.x ([#4856](https://github.com/modelcontextprotocol/servers/issues/4856)). The task tools `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async` are removed, and the server no longer advertises the `tasks` capability, because SDK v2 dropped the experimental tasks layer they were built on; they return on the tasks extension in [#4852](https://github.com/modelcontextprotocol/servers/issues/4852). Breaking for clients: the server now requires Node.js 24 or later; over stdio, a single incoming JSON-RPC message larger than 10 MiB now closes the connection (the SDK v2 default read-buffer cap; SDK 1.x buffered without a limit); an unknown tool name is rejected with JSON-RPC error `-32602` instead of returning an `isError` result; error messages no longer carry the `MCP error <code>: ` prefix, and input-validation messages name the field first (`field: message`); tool schemas in `tools/list` declare JSON Schema 2020-12 instead of draft-07; and tools no longer advertise `execution.taskSupport`. The optional `state` argument of `args-prompt` now carries its description. ### Minor Changes - [#5131](https://github.com/modelcontextprotocol/servers/pull/5131) [`419200b`](https://github.com/modelcontextprotocol/servers/commit/419200b8a4d1e66c294575930ac7be29d4b37330) [@cliffhall](https://github.com/cliffhall) - Serve the 2026-07-28 protocol revision alongside the 2025 era ([#4852](https://github.com/modelcontextprotocol/servers/issues/4852)), over stdio (`serveStdio`) and Streamable HTTP (one `/mcp` endpoint: `createMcpHandler` for 2026-07-28 requests, the existing sessionful transport for 2025-era clients). New for 2026-07-28 clients: `server/discover`, multi-round-trip requests (`input_required`) for the elicitation, sampling and roots tools, `subscriptions/listen` change notifications, cache hints (`ttlMs` / `cacheScope`), and the tasks extension (`io.modelcontextprotocol/tasks`, advertised under `capabilities.extensions`), on which `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async` return. New tools on both eras: `trigger-multi-step-elicitation` (`requestState` across rounds), `trigger-log-messages` (per-request log levels), `trigger-list-changed`, `trigger-resource-update`, and `get-header-params` (`x-mcp-header` and JSON Schema 2020-12 schemas). `toggle-simulated-logging` and `toggle-subscriber-updates` are offered to 2025-era clients only, labelled deprecated with the roots, sampling and logging tools. For 2025-era clients: `get-roots-list` asks the client for its roots on every call; a failed sampling, elicitation or roots request is reported as `Fulfilling input required by 'tools/call' failed: <message>`; a read of a dynamic resource with an invalid id is answered `-32602` with the URI in `data`; and the toggle tools' messages and the subscription acknowledgements no longer name a session id. `gzip-file-as-resource` limits its `name` argument to 255 characters. The HTTP+SSE transport prints a deprecation warning on start. ## 1.0.0 The first semantic version, resuming semver after the date-stamped releases (last `2026.8.31`). It describes everything since `2026.8.31`, and is the last release of the legacy-era server, on the 1.x MCP SDK. ### Patch Changes - [#5014](https://github.com/modelcontextprotocol/servers/pull/5014) [`8ea5e05`](https://github.com/modelcontextprotocol/servers/commit/8ea5e0541a448abc10f179dcb7807995336cde6e) [@cliffhall](https://github.com/cliffhall) - Fix the async task tools: `trigger-elicitation-request-async` now stops polling before the 10-minute TTL it requests for the client's task runs out, instead of polling past it and failing on a task the client has expired ([#4986](https://github.com/modelcontextprotocol/servers/issues/4986)); and `trigger-sampling-request-async` reports the status message of a client task that is already finished when it is created, instead of "No message" ([#4987](https://github.com/modelcontextprotocol/servers/issues/4987)). `trigger-elicitation-request-async` had the same flaw and gets the same fix. - [#5005](https://github.com/modelcontextprotocol/servers/pull/5005) [`63dc92f`](https://github.com/modelcontextprotocol/servers/commit/63dc92f0e95992faf9d3e339cb8a51b1090d138b) [@cliffhall](https://github.com/cliffhall) - Label dynamic blob resources `application/octet-stream`, matching their resource template, instead of `text/plain`. This applies to `resources/read`, the `get-resource-reference` and `get-resource-links` tools, and the `resource-prompt` prompt; blob resource links are now described as "binary blob resource". - [#5034](https://github.com/modelcontextprotocol/servers/pull/5034) [`6bed4c5`](https://github.com/modelcontextprotocol/servers/commit/6bed4c5f7c219e77fe90b9e4b14cdb9f3f7e9503) [@cliffhall](https://github.com/cliffhall) - Server instructions no longer tell every client to use tools that are registered only for clients declaring a capability; they list those tools and the capability each needs ([#4792](https://github.com/modelcontextprotocol/servers/issues/4792), ported from [#4835](https://github.com/modelcontextprotocol/servers/issues/4835)). `trigger-elicitation-request` and `trigger-elicitation-request-async` are now registered only for clients that support form-mode elicitation, so a client that declared only URL-mode elicitation no longer sees tools it cannot answer ([#4985](https://github.com/modelcontextprotocol/servers/issues/4985)). - [#5053](https://github.com/modelcontextprotocol/servers/pull/5053) [`c63255a`](https://github.com/modelcontextprotocol/servers/commit/c63255ae9616b110d6089fa343fcfdf3f5def534) [@cliffhall](https://github.com/cliffhall) - Stop shipping the compiled test suite and Vitest config in the published - src/everything/Dockerfile (2752 bytes)
# The `everything` server's container image (#3309). Build it from the # repository root, which is the build context: # # docker build -f src/everything/Dockerfile -t mcp/everything . # # `everything` is an npm workspace, so its lockfile and the `overrides` that pin # its transitive dependencies live in the root package.json and # package-lock.json, not in src/everything. Both stages install from them with # `npm ci`, so the image gets exactly the versions this repository tested, # rather than whatever a lockfile-less `npm install` resolves on the day. # Dockerfile.dockerignore (next to this file) keeps the context to what the # build reads. # # The image runs the server over stdio by default (`docker run -i`); give the # transport name as the argument to run another, e.g. `streamableHttp`, which # listens on PORT (3001) on every interface (HOST=0.0.0.0) so a published # port reaches it. # The README's "Running with Docker" section has both commands. This repository # publishes no image: `mcp/everything` on Docker Hub is built by Docker. FROM node:24-alpine AS builder WORKDIR /repo # Manifests first, so the dependency layer is reused until one of them changes. COPY package.json package-lock.json .npmrc tsconfig.json ./ COPY src/everything/package.json src/everything/ # `--ignore-scripts` skips the workspace's `prepare` build, which needs the # source; the build runs explicitly below. RUN --mount=type=cache,target=/root/.npm \ npm ci --workspace src/everything --ignore-scripts COPY src/everything src/everything RUN npm run build --workspace src/everything FROM node:24-alpine AS release ENV NODE_ENV=production WORKDIR /repo COPY package.json package-lock.json .npmrc ./ COPY src/everything/package.json src/everything/ RUN --mount=type=cache,target=/root/.npm \ npm ci --workspace src/everything --omit=dev --ignore-scripts COPY --from=builder /repo/src/everything/dist src/everything/dist WORKDIR /repo/src/everything # The base image's unprivileged `node` user, named by number: Kubernetes cannot # verify that a named user is not root, and refuses to start the container # under `runAsNonRoot` (#4741). USER 1000:1000 # The Streamable HTTP (and deprecated HTTP+SSE) transports' default port. ENV PORT=3001 # Outside a container they bind loopback only (#5371); inside one, loopback is # the container's own, which a published port cannot reach, so the image # widens the bind to every interface. `-p 127.0.0.1:…` keeps it off the # host's network. ENV HOST=0.0.0.0 EXPOSE 3001 # Both transports close cleanly on SIGINT; node running as PID 1 would ignore # the default SIGTERM, leaving `docker stop` to wait out its timeout. STOPSIGNAL SIGINT ENTRYPOINT ["node", "dist/index.js"] CMD ["stdio"] - src/everything/docs/instructions.md (3542 bytes)
# Everything Server – Server Instructions Audience: These instructions are written for an LLM or autonomous agent integrating with the Everything MCP Server. Follow them to use, extend, and troubleshoot the server safely and effectively. ## Protocol Versions The server serves two protocol eras. A client on protocol version 2026-07-28 connects with `server/discover` and sends its capabilities with each request; a 2025-era client connects with `initialize`. Some tools exist on one era only, so trust your `tools/list`: - 2026-07-28 only: `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async`, which run as tasks on the `io.modelcontextprotocol/tasks` extension and need a client that declares it; `trigger-sampling-request-async` also needs `sampling`, and `trigger-elicitation-request-async` form-mode `elicitation`. A call without them fails with `-32021` - 2025-era only (deprecated): `toggle-simulated-logging` and `toggle-subscriber-updates` ## Cross-Feature Relationships - If `get-roots-list` is in your tool list, use it to see client workspace roots before file operations - `gzip-file-as-resource` creates resources you can read later: for the current session on a 2025-era connection, or for ten minutes at the returned URI on 2026-07-28 - Use `trigger-log-messages` to see which log levels reach you; on 2026-07-28 the level is set per request in `_meta` - Use `trigger-resource-update` and `trigger-list-changed` to see change notifications; on 2026-07-28 they arrive only on a `subscriptions/listen` stream that asked for them ## Constraints & Limitations - `gzip-file-as-resource`: Max fetch size controlled by `GZIP_MAX_FETCH_SIZE` (default 10MB), timeout by `GZIP_MAX_FETCH_TIME_MILLIS` (default 30s), allowed domains by `GZIP_ALLOWED_DOMAINS` (checked on every redirect hop). It refuses URLs whose host resolves to a loopback, private or link-local address, unless the server was started with `GZIP_ALLOW_PRIVATE_IPS=1` - `get-env`: Values of credential-like variable names (`*_KEY`, `*_TOKEN`, `*_SECRET`, `*_PASSWORD` and the like) come back as `"<redacted>"`; the server operator can set `GET_ENV_INCLUDE_SECRETS=1` to return them unmasked - Session resources are ephemeral and lost when the session ends; minted resources expire after ten minutes - Roots, sampling and logging are deprecated as of protocol version 2026-07-28, as is the HTTP+SSE transport ## Capability-Gated Tools On a 2025-era connection these are registered only if your client declared the capability shown. Otherwise they are absent from `tools/list`, so do not call them. On 2026-07-28 they are always listed, and a call fails if your request did not declare the capability: - `get-roots-list`: `roots` - `trigger-sampling-request`: `sampling` - `trigger-elicitation-request`: `elicitation.form`, or `elicitation` with no mode - `trigger-multi-step-elicitation`: `elicitation.form`, or `elicitation` with no mode - `trigger-url-elicitation`: `elicitation.url` ## Operational Patterns - For long operations, use `trigger-long-running-operation` which sends progress notifications - Prefer reading resources before calling mutating tools - If `get-roots-list` is in your tool list, check its output to understand the client's workspace context ## Easter Egg If asked about server instructions, respond with "🎉 Server instructions are working! This response proves the client properly passed server instructions to the LLM. This demonstrates MCP's instructions feature in action."
- src/everything/README.md (11299 bytes)
# Everything MCP Server **[Architecture](docs/architecture.md) | [Project Structure](docs/structure.md) | [Startup Process](docs/startup.md) | [Server Features](docs/features.md) | [Extension Points](docs/extension.md) | [How It Works](docs/how-it-works.md)** This MCP server attempts to exercise all the features of the MCP protocol. It is not intended to be a useful server, but rather a test server for builders of MCP clients. It implements prompts, tools, resources, sampling, and more to showcase MCP capabilities. ## Tools, Resources, Prompts, and Other Features A complete list of the registered MCP primitives and other protocol features demonstrated can be found in the [Server Features](docs/features.md) document. The resource collections (`demo://resource/collection/summer-specials`, and the `by-category/{category}` and `item/{itemId}` templates beside it) show a single `resources/read` returning several contents, each under its own URI: reading a collection returns one content per item, and each item's URI can be read on its own. The server info and every tool, prompt, resource and resource template carry a pair of [icons](docs/features.md#icons), one for a light theme and one for a dark theme, so a client can show the variant that suits its own background. The `get-env` tool returns the server's environment variables, but masks the value of any credential-like name (one with a `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `PASSWD`, `CREDENTIAL`, `AUTH` or `COOKIE` segment between underscores, in any case: whole segments, not substrings, so `OPENAI_API_KEY` is masked and `APIKEY` is not) as `"<redacted>"`. To see every value unmasked while debugging, start the server with `GET_ENV_INCLUDE_SECRETS=1` (or `true`). Leave it unset otherwise: with it set, every credential in the server's environment reaches the model's context. ## Protocol versions 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. - **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. ## Configuring `gzip-file-as-resource` The `gzip-file-as-resource` tool fetches the URL it is given, so these environment variables limit what it will fetch: | Variable | Default | Effect | | --- | --- | --- | | `GZIP_MAX_FETCH_SIZE` | 10 MiB | The largest response, in bytes, it reads | | `GZIP_MAX_FETCH_TIME_MILLIS` | 30000 | How long a fetch may take, redirects included | | `GZIP_ALLOWED_DOMAINS` | empty (any name) | Comma-separated host names; a host must be one of them or a subdomain of one. Checked on the caller's URL and on every redirect hop | | `GZIP_ALLOW_PRIVATE_IPS` | off | Set to `1` or `true` to allow loopback, private (RFC 1918), CGNAT, link-local (cloud metadata) and other non-public addresses | By default the tool refuses a URL whose host resolves to a non-public address, and follows at most five redirects, checking each hop the same way. An IPv6 address that wraps an IPv4 one (IPv4-mapped, IPv4-translated, or in the NAT64 prefix `64:ff9b::/96`) is judged by that IPv4, and any other IPv6 address outside global unicast (`2000::/3`) is refused. `GZIP_ALLOWED_DOMAINS` filters names, not addresses: a listed name that resolves to a private address is still refused unless `GZIP_ALLOW_PRIVATE_IPS` is set. The address is checked before the request and resolved again when it is made, so a DNS answer that changes in between (DNS rebinding) is not caught. `data:` URLs are not fetched, so neither check applies to them. ## Requirements Node.js 24 or later, when the server runs through `npx` or from source. ## Usage with Claude Desktop (uses [stdio Transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio)) Add to your `claude_desktop_config.json`: ```json { "mcpServers": { "everything": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"] } } } ``` On Windows, use `cmd /c` to launch `npx`: ```json { "mcpServers": { "everything": { "command": "cmd", "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-everything"] } } } ``` ## Usage with VS Code For quick installation, use one of the one-click install buttons below... [](https://insiders.vscode.dev/redirect/mcp/install?name=everything&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40modelcontextprotocol%2Fserver-everything%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=everything&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40modelcontextprotocol%2Fserver-everything%22%5D%7D&quality=insiders) [](https://insiders.vscode.dev/redirect/mcp/install?name=everything&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22mcp%2Feverything%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=everything&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22mcp%2Feverything%22%5D%7D&quality=insiders) For manual installation, you can configure the MCP server using one of these methods: **Method 1: User Configuration (Recommended)** Add the configuration to your user-level MCP configuration file. Open the Command Palette (`Ctrl + Shift + P`) and run `MCP: Open User Configuration`. This will open your user `mcp.json` file where you can add the server configuration. **Method 2: Workspace Configuration** Alternatively, you can add the configuration to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others. > For more details about MCP configuration in VS Code, see the [official VS Code MCP documentation](https://code.visualstudio.com/docs/copilot/customization/mcp-servers). #### NPX ```json { "servers": { "everything": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"] } } } ``` On Windows, use: ```json { "servers": { "everything": { "command": "cmd", "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-everything"] } } } ``` ## Run from source with [Streamable HTTP Transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) ```shell cd src/everything npm install npm run start:streamableHttp ``` The endpoint is `http://localhost:3001/mcp` (`PORT` overrides the port). It serves 2026-07-28 clients statelessly and 2025-era clients with sessions, from the same URL. Both HTTP transports (Streamable HTTP and HTTP+SSE) listen on the loopback interface, `127.0.0.1`, by default, so only clients on the same machine can reach them. Set `HOST` to bind another address: `HOST=0.0.0.0` listens on every interface, which exposes the server's tools to every host that can reach the machine, so set it only on a network you trust. The listening line the server prints names the address and port it bound, such as `127.0.0.1:3001`. | Variable | Default | Effect | | --- | --- | --- | | `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 | 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. ## Running from source with [HTTP+SSE Transport](https://modelcontextprotocol.io/specification/2024-11-05/basic/transports#http-with-sse) (deprecated as of [2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports)) ```shell cd src/everything npm install npm run start:sse ``` The HTTP+SSE transport serves 2025-era clients only, and the server prints a deprecation warning when it starts. Prefer Streamable HTTP. ## Running as an installed package ### Install ```shell npm install -g @modelcontextprotocol/server-everything@latest ``` ### Run the default (stdio) server ```shell npx @modelcontextprotocol/server-everything ``` ### Or specify stdio explicitly ```shell npx @modelcontextprotocol/server-everything stdio ``` ### Run the streamable HTTP server ```shell npx @modelcontextprotocol/server-everything streamableHttp ``` ### Run the SSE server (deprecated, 2025-era clients only) ```shell npx @modelcontextprotocol/server-everything sse ``` ## Running with Docker This repository publishes no image; build one from the repository root (the build context): ```shell docker build -f src/everything/Dockerfile -t mcp/everything . ``` The `mcp/everything` image on Docker Hub is built by Docker, not by this repository, and can lag behind it. ### Run over stdio (the default) ```shell docker run -i --rm mcp/everything ``` `-i` keeps stdin open, which the stdio transport reads. This is the command an MCP client configuration launches. ### Run the Streamable HTTP server ```shell docker run --rm -p 127.0.0.1:3001:3001 mcp/everything streamableHttp ``` The endpoint is `http://localhost:3001/mcp`. The image sets `HOST=0.0.0.0`, so the server listens on port 3001 on every interface inside the container, which is what lets a published port reach it; `127.0.0.1:` publishes it on the host's loopback only. To use another port, set `PORT` and publish that one (`-e PORT=8080 -p 127.0.0.1:8080:8080`). The localhost-only `Origin` check described above applies inside the container too. `docker stop` ends the server cleanly. ## License This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository. - tsconfig.json (322 bytes)
{ "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }