A stdio MCP server and its protocol tests

Drive lab-docs, a read-only stdio MCP server written with the standard library, the way Claude Code does at connect time: probe, initialize, list and call tools, read resources, get a prompt. Each step is a check, and the run fails if the server ever writes anything to stdout that isn't a JSON-RPC message.

  • Python 3.9+
  • standard library only
  • offline: mcp_server/server.py as a subprocess
  • 4 decision records in mcp_server/docs/
python3 agents-3/mcp_server/test_client.py

The server speaks the 2025-11-25 handshake: two tools (search_docs, get_doc), four docs:// resources and one prompt. The excerpt leaves out lines that print the absolute path of the folder it ran in.

┌────────────────────────────────────────────────────────────┐
│ Agents 3 · lab-docs MCP server over stdio (MCP 2025-11-25) │
└────────────────────────────────────────────────────────────┘
      check                                                                   detail                                                      
────  ──────────────────────────────────────────────────────────────────────  ────────────────────────────────────────────────────────────
PASS  server/discover -> -32601, client falls back to initialize              Method not found: server/discover                           
PASS  initialize echoes 2025-11-25                                            2025-11-25                                                  
PASS  capabilities: tools, resources, prompts                                 prompts,resources,tools                                     
PASS  serverInfo and instructions present                                     lab-docs, 219 chars of instructions                         
PASS  ping -> empty result (and the notification got no reply)                {}                                                          
PASS  tools/list: search_docs, get_doc                                        search_docs, get_doc                                        
PASS  every tool has an object inputSchema and readOnlyHint                                                                               
PASS  search_docs finds adr-0002 first                                        adr-0002-tax-after-discount, adr-0003-discount-codes        
PASS  search_docs: text content + structuredContent, isError false                                                                        
PASS  get_doc returns the Markdown                                            # ADR-0001: Money is integer cents                          
PASS  bad limit -> tool execution error (isError true), not a protocol error  limit must be an integer from 1 to 10 (got 50)              
PASS  path-like id -> isError, nothing read outside docs/                                                                                 
PASS  unknown tool -> JSON-RPC error -32602                                   Unknown tool: delete_doc                                    
PASS  resources/list: docs:// URIs                                            4 resources                                                 
PASS  resources/read returns contents[0].text                                                                                             
PASS  unknown resource -> -32002 with data.uri                                                                                            
PASS  prompts/list: review_against_adrs                                                                                                   
PASS  prompts/get returns a user message                                                                                                  
PASS  missing required prompt argument -> -32602                                                                                          
PASS  invalid JSON -> -32700 with id null                                                                                                 
PASS  unknown method -> -32601                                                                                                            
PASS  server exits 0 when stdin closes                                        exit 0                                                      
PASS  stdout carried only JSON-RPC messages                                   17 lines                                                    
…
PASS  unknown client version -> server answers its latest (2025-11-25)        2025-11-25                                                  

25/25 checks passed

Install in Claude Code (pick one scope; https://code.claude.com/docs/en/mcp):

…
  # pre-approve the two read-only tools in .claude/settings.json:
  {"permissions": {"allow": ["mcp__lab-docs__search_docs", "mcp__lab-docs__get_doc"]}}

  claude mcp get lab-docs      # status: ✔ Connected, or ⏸ Pending approval for a new .mcp.json server
  /mcp                         # in a session: status, tools, reconnect

Headless runs load project .mcp.json servers without asking. For a run that uses only this server
(from labs/, after --write-config; costs money):
  claude -p "..." --mcp-config agents-3/out/mcp.json --strict-mcp-config --tools "" \
    --allowedTools mcp__lab-docs__search_docs,mcp__lab-docs__get_doc --permission-mode dontAsk --max-turns 4 --max-budget-usd 0.05
  1. The client opens like a 2026-07-28-era client with server/discover, gets -32601 from this handshake-era server, and falls back to initialize.
  2. Version negotiation: the server echoes the version the client asked for when it supports it.
  3. Two kinds of error. A bad limit is a tool result with isError: true, which Claude reads and can retry; an unknown tool is a JSON-RPC protocol error, -32602.
  4. stdout is the transport: every line on it must be a JSON-RPC message. Logs go to stderr, which the next check (cut here) confirms.
  5. Asked for a version it doesn't know, the server answers with its own latest instead of failing.
  6. In Claude Code the tools become mcp__lab-docs__search_docs and mcp__lab-docs__get_doc. Allow them by those exact names.

The cut part of the output prints the install commands with your absolute path filled in. With /ABS/PATH standing for it, they read (from agents-3/README.md; they change your Claude Code config, so they aren't part of the offline lab):

# local scope (default): only you, this project; stored in ~/.claude.json
claude mcp add --transport stdio lab-docs -- python3 /ABS/PATH/labs/agents-3/mcp_server/server.py
# project scope: writes .mcp.json at the repo root (teammates approve it on first interactive use)
claude mcp add --transport stdio --scope project lab-docs -- python3 /ABS/PATH/labs/agents-3/mcp_server/server.py
claude mcp get lab-docs          # ✔ Connected, or ⏸ Pending approval for a new .mcp.json server
  • -v prints every JSON-RPC line the client sends (→) and receives (←), starting with the server/discover probe and its -32601.
  • --write-config writes agents-3/out/mcp.json, an .mcp.json-shaped file with your absolute path, for --mcp-config.
  • Talk to the server yourself. Garbage gets a parse error with id null on stdout, while the startup log goes to stderr:
    echo 'not json' | python3 agents-3/mcp_server/server.py
  • Break it on purpose, by hand: initialize, then call search_docs with limit: 50 and call a tool that doesn't exist. The first answer is a result with "isError":true; the second is an error with code -32602.
    printf '%s\n' \
      '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"me","version":"0"}}}' \
      '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
      '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search_docs","arguments":{"query":"tax","limit":50}}}' \
      '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"delete_doc","arguments":{}}}' \
      | python3 agents-3/mcp_server/server.py 2>/dev/null

Let Claude use the server. It costs money: one capped claude -p in a temp copy of tiny-app with --tools "" (no built-in tools), only this server (--strict-mcp-config), its two tools allowed by exact name, and --permission-mode dontAsk.

python3 agents-3/mcp_server/test_client.py --real \
    --model haiku --max-budget-usd 0.05

The default --max-turns is 4. The course's own run (v2.1.303) cost $0.0016 by Claude Code's estimate and showed two things: Claude called search_docs without a ToolSearch step, and the tool result it saw was the structuredContent JSON, not the text block. The transcript lands in agents-3/out/mcp_real_run.jsonl; trace it with python3 agents-1/loop_trace.py --transcript agents-3/out/mcp_real_run.jsonl. The budget can pass the cap by up to one response.

  • Protocol errors (-32700, -32601, -32602, -32002) versus tool execution errors (isError: true): only the second kind reaches Claude as something to act on.
  • Nothing but JSON-RPC on stdout. A debug print in a stdio server breaks the connection; log to stderr.
  • Tool names in Claude Code are mcp__<server>__<tool>; permission rules and --allowedTools use that form.
  • If a tool returns structuredContent, keep it model-readable: in the real run, that's what the model saw.

Lint skills before Claude Code reads them

A wrong skill rarely fails loudly: frontmatter off line 1 turns into skill text, YAML that doesn't parse loads with no fields, a misspelled field is ignored, a long description is cut in the listing, and a ! command with no allow rule aborts the invocation. Lint SKILL.md and .claude/commands/*.md files for those, against the documented rules.

  • Python 3.9+
  • standard library only
  • offline: skills_sample/good (3 files)
  • skills_sample/bad (9 files) and its EXPECTED.json
python3 agents-3/skill_lint.py
┌───────────────────────────────────────────────────────────────────────────────────────────┐
│ Agents 3 · skill_lint: documented skill rules, checked before Claude Code reads the files │
└───────────────────────────────────────────────────────────────────────────────────────────┘

good samples (agents-3/skills_sample/good)
command         kind     file                                   status  findings
──────────────  ───────  ─────────────────────────────────────  ──────  ────────
/release-notes  skill    .claude/skills/release-notes/SKILL.md  ok      0       
/review-diff    skill    .claude/skills/review-diff/SKILL.md    ok      0       
/quick-check    command  .claude/commands/quick-check.md        ok      0       
  listing: ~321 characters of names + descriptions in context (≈129 tokens at ~2.5 chars/token); not listed (disable-model-invocation): /release-notes

bad samples (agents-3/skills_sample/bad)
command              kind     file                                      status   findings
───────────────────  ───────  ────────────────────────────────────────  ───────  ────────
/review  pr <draft>  skill    .claude/skills/bad-name/SKILL.md          error    1       
/broken-yaml         skill    .claude/skills/broken-yaml/SKILL.md       error    3       
/dead-end            skill    .claude/skills/dead-end/SKILL.md          error    1       
/fragile-inject      skill    .claude/skills/fragile-inject/SKILL.md    error    7       
/greedy              skill    .claude/skills/greedy/SKILL.md            warning  2       
/late-frontmatter    skill    .claude/skills/late-frontmatter/SKILL.md  error    3       
/synced              skill    .claude/skills/synced/SKILL.md            error    2       
/typo-fields         skill    .claude/skills/typo-fields/SKILL.md       warning  4       
/with-paths          command  .claude/commands/with-paths.md            warning  2       
  ERROR    /review  pr <draft>    bad-name-chars: Claude Code refuses a name with control/zero-width/bidi/private-use characters, odd blanks, < or >: name 'review  pr <draft>' contains '<'; the / menu won't show it
  ERROR    /broken-yaml           yaml-error: the frontmatter may not parse; if Claude Code can't parse it, the skill loads with no fields set: line 2: ': ' inside an unquoted value; quote the value
  WARNING  /broken-yaml           missing-description: no description: Claude Code uses the first non-empty body line, which rarely says when to use the skill: falls back to 'Summarize the diff in five bullets.'
  INFO     /broken-yaml           weak-description: the description doesn't say when to use the skill (Claude matches on it): 'Summarize the diff in five bullets.'
  ERROR    /dead-end              uninvocable: disable-model-invocation: true and user-invocable: false together leave nobody able to invoke it
  WARNING  /fragile-inject        bad-effort: effort must be low, medium, high, xhigh or max: 'extreme'
  WARNING  /fragile-inject        bad-shell: shell must be bash or powershell: 'zsh'
  WARNING  /fragile-inject        fork-only: agent and background apply only with context: fork: background
  WARNING  /fragile-inject        inject-unapproved: a ! command with no matching allow rule aborts the invocation outside auto mode: !`./scripts/check.sh $1`: add Bash(./scripts/check.sh ...) to allowed-tools or a settings allow rule
  ERROR    /fragile-inject        missing-file: a ${CLAUDE_SKILL_DIR} path that doesn't exist: rules/missing.md
  WARNING  /fragile-inject        unmatched-arg: $name isn't declared in `arguments`, so it becomes an empty string: $target
  INFO     /fragile-inject        positional-no-hint: uses $ARGUMENTS / $N but has no argument-hint for autocomplete
  WARNING  /greedy                listing-truncated: description + when_to_use is truncated at 1,536 characters in the skill listing: 2,039 characters; everything after 1,536 is cut
  WARNING  /greedy                broad-allowed-tools: allowed-tools pre-approves broad access, and it isn't gated by workspace trust: Bash, Write
  ERROR    /late-frontmatter      frontmatter-not-line-1: the opening --- isn't line 1, so every field is ignored and the markers become skill text: line 1 is '<!-- Owner: platform team -->'
  WARNING  /late-frontmatter      missing-description: no description: Claude Code uses the first non-empty body line, which rarely says when to use the skill: falls back to '<!-- Owner: platform team -->'
  INFO     /late-frontmatter      weak-description: the description doesn't say when to use the skill (Claude matches on it): '<!-- Owner: platform team -->'
  ERROR    /synced                reserved-name: this name is reserved and the skill doesn't load: folder 'synced'
  INFO     /synced                weak-description: the description doesn't say when to use the skill (Claude matches on it): 'A skill in a folder named "synced", which Claude Code reserv'
  WARNING  /typo-fields           unknown-field: Claude Code ignores unknown fields without an error: 'allowed_tools' (did you mean 'allowed-tools'?)
  WARNING  /typo-fields           unknown-field: Claude Code ignores unknown fields without an error: 'user_invocable' (did you mean 'user-invocable'?)
  WARNING  /typo-fields           unknown-field: Claude Code ignores unknown fields without an error: 'when-to-use' (did you mean 'when_to_use'?)
  WARNING  /typo-fields           unknown-field: Claude Code ignores unknown fields without an error: 'tools' (did you mean 'allowed-tools'?)
  WARNING  /with-paths            ignored-in-command: command files accept every skill field except name and paths: 'name' in with-paths.md
  WARNING  /with-paths            ignored-in-command: command files accept every skill field except name and paths: 'paths' in with-paths.md
  listing: ~2,094 characters of names + descriptions in context (≈838 tokens at ~2.5 chars/token); not listed (disable-model-invocation): /dead-end

good samples are clean and every expected finding in bad/ was reported
  1. YAML that doesn't parse doesn't stop the skill from loading: it loads with no fields set, so its allowed tools, invocation control and description are all gone.
  2. disable-model-invocation: true keeps Claude from invoking it, user-invocable: false hides it from the / menu, and together nobody can run it.
  3. An injected ! command never prompts. Outside auto mode, one that no allow rule matches aborts the whole invocation, so pre-approve exactly what the skill runs.
  4. The listing cuts description + when_to_use at 1,536 characters, and allowed-tools isn't gated by workspace trust: a cloned repo's skill can grant itself Bash.
  5. One comment line above the opening --- and Claude Code reads no frontmatter at all; the markers become skill text.
  6. Misspelled fields are ignored without an error. Field names are lowercase-hyphenated, except when_to_use.

The two listing: lines estimate how much context the model-invocable descriptions take, at about 2.5 characters per token, the rough figure in Anthropic's models overview, so the token counts are approximate. For real numbers, /context reports the Skills row.

  • Point it at a repo, a .claude/skills folder, a plugin or one SKILL.md: python3 agents-3/skill_lint.py ~/code/myrepo. It exits 1 on errors (the bad samples alone do), and --strict also fails on warnings.
  • python3 agents-3/skill_lint.py agents-3/skills_sample/good --portable adds INFO findings for fields that claude.ai uploads and the Skills API reject, such as disable-model-invocation and argument-hint.
  • Break it: write a skill whose first line is blank. The linter reports frontmatter-not-line-1 and exits 1, and the description falls back to '---'. Delete the blank line (sed -i.bak '1d' /tmp/lab-skill/.claude/skills/hello/SKILL.md) and it lints clean.
    mkdir -p /tmp/lab-skill/.claude/skills/hello
    printf '\n---\nname: hello\ndescription: Say hello. Use when someone greets you.\n---\nSay hello back.\n' \
        > /tmp/lab-skill/.claude/skills/hello/SKILL.md
    python3 agents-3/skill_lint.py /tmp/lab-skill
  • Line 1 is ---, the YAML parses, and every field name is one Claude Code knows: otherwise the skill loads, just not the way you wrote it.
  • Every ! command has a matching allow rule in allowed-tools, scoped to exactly that command.
  • The key use case comes first in description, inside the 1,536-character cap.
  • Review allowed-tools in any repository's skills before running Claude Code there.

Validate a plugin and run its hook

Check the lab-review plugin kit (a skill, a subagent and a PostToolUse hook) against the documented manifest and component rules, lint its skills, flag agent fields plugins ignore, and run its hook on documented payloads. Three broken plugins in plugin_kit/bad/ show what each rule catches.

  • Python 3.9+
  • standard library only
  • offline: plugin_kit/kit/lab-review
  • 3 broken plugins in plugin_kit/bad/
python3 agents-3/plugin_validate.py
┌────────────────────────────────────────────────────────────┐
│ Agents 3 · plugin_validate: manifest, components and hooks │
└────────────────────────────────────────────────────────────┘

kit: plugin_kit/kit/lab-review
…
  skills: /lab-review:review
  agents: lab-review:test-auditor
  no findings
  hooks: PostToolUse[Edit|Write] -> python3 ${CLAUDE_PLUGIN_ROOT}/scripts/test_reminder.py

the kit's hook, run on documented PostToolUse payloads (common/hooks.py)
      payload                                  what Claude sees                                                      
────  ───────────────────────────────────────  ──────────────────────────────────────────────────────────────────────
PASS  Write tinyapp/pricing.py                 You changed pricing.py. Its tests are in tests/test_pricing.py: update
PASS  Write README.md                          success, no context (as expected)                                     
PASS  Write tinyapp/pricing.py (cwd tinyapp/)  You changed pricing.py. Its tests are in tests/test_pricing.py: update

bad/ignored-fields
…
  agents: agent-hooks:deployer
  INFO     plugin.json                        no-version: no version: users track the latest; setting one pins them to it until you change it
  WARNING  CLAUDE.md                          claude-md: CLAUDE.md at the plugin root is not loaded as project context; ship context as a skill
  ERROR    hooks/hooks.json Stop              if-wrong-event: `if` works only on tool events; on any other event the hook never runs: if: 'Bash(git *)'
  ERROR    hooks/hooks.json Stop              user-config-shell: a shell-form plugin hook that references ${user_config.*} fails instead of running; use exec form (args): ${CLAUDE_PLUGIN_ROOT}/scripts/notify.sh ${user_config.webhook}
  WARNING  hooks/hooks.json Stop              unquoted-placeholder: shell-form command uses a path placeholder without quotes; use exec form or quote it: ${CLAUDE_PLUGIN_ROOT}/scripts/notify.sh ${user_config.webhook}
  WARNING  hooks/hooks.json UserPromptSubmit  matcher-ignored: this event has no matcher support, so the matcher is silently ignored: 'deploy'
  ERROR    hooks/hooks.json UserPromptSubmit  hook-script-missing: the hook's script doesn't exist in the plugin: scripts/missing.py
  WARNING  hooks/hooks.json                   unknown-event: unknown hook event; the entry is ignored at runtime: PostEdit
  WARNING  agents/deployer.md                 agent-ignored-field: plugin subagents ignore this field for security reasons: permissionMode (bypassPermissions is never applied from a subagent file anyway)
  WARNING  agents/deployer.md                 agent-ignored-field: plugin subagents ignore this field for security reasons: hooks
  WARNING  agents/deployer.md                 agent-ignored-field: plugin subagents ignore this field for security reasons: mcpServers
  WARNING  agents/deployer.md                 agent-ignored-field: plugin subagents ignore this field for security reasons: initialPrompt

bad/paths
…
  skills: /path-mixup:a
  INFO     plugin.json                        no-version: no version: users track the latest; setting one pins them to it until you change it
  ERROR    plugin.json skills                 path-traversal: Path contains ".." which could be a path traversal attempt: ../shared-skills
  ERROR    plugin.json agents                 agents-not-md: `agents` takes .md files; directories aren't accepted: ./agents
  WARNING  agents/                            default-ignored: a default folder is ignored because the manifest replaces it: the manifest sets "agents"
  ERROR    plugin.json hooks                  path-not-found: Path not found: ./hooks/missing.json

bad/reserved
…
  commands: /claude-tools:today
  ERROR    .claude-plugin/skills              component-in-manifest-dir: only plugin.json goes inside .claude-plugin/; components saved there don't load
  ERROR    plugin.json name                   reserved-name: reserved: it passes as one of Anthropic's own (claude plugin init/tag refuse it): 'claude-tools'
  WARNING  plugin.json                        unknown-key: unrecognized top-level key: stripped at load, the plugin still loads: 'colour'
  ERROR    plugin.json version                bad-type: wrong type for a manifest field: expected str, got int
  ERROR    plugin.json author                 bad-type: wrong type for a manifest field: expected dict, got str
  ERROR    plugin.json homepage               bad-url: homepage must parse as a URL, or the plugin fails to load: 'not a url'
  ERROR    plugin.json commands               path-not-dot-slash: every component path is relative to the plugin root and must start with ./: commands/
  WARNING  commands/                          default-ignored: a default folder is ignored because the manifest replaces it: the manifest sets "commands"
  ERROR    hooks/hooks.json                   hooks-wrapper: a hooks file must carry the top-level "hooks" wrapper: top-level keys: ['PostToolUse']

Install / try it:
…
  /lab-review:review   @agent-lab-review:test-auditor   /reload-plugins after edits
  To share it: add it to a marketplace (autonomy-2) and `claude plugin install lab-review@<marketplace>`.

kit is clean, its hook works, and every expected finding in bad/ was reported
  1. Plugin components are namespaced: the skill is /lab-review:review and the subagent lab-review:test-auditor.
  2. The hook runs on documented payloads: it adds context after a write to pricing.py, stays silent for README.md, and still finds tests/ when the session's cwd is a subfolder.
  3. if is evaluated only on tool events. On Stop the hook never runs.
  4. Plugin subagents ignore permissionMode, hooks, mcpServers and initialPrompt, for security reasons.
  5. Only plugin.json goes inside .claude-plugin/; a skill saved there doesn't load.
  6. A hooks file needs the top-level "hooks" wrapper around its events; this one starts at PostToolUse.

The excerpt leaves out the lines that print the folder each plugin was read from. Try the kit for one session with claude --plugin-dir agents-3/plugin_kit/kit/lab-review (writes nothing to settings). With Claude Code installed, --with-claude also runs claude plugin validate, a local check with no model call; the README compares its findings with this script's.

  • Validate one plugin: python3 agents-3/plugin_validate.py agents-3/plugin_kit/bad/reserved lists the reserved claude-tools name and the manifest type errors, and exits 1. --strict fails on warnings too; the kit still passes.
  • Break the kit, in a copy: move its skills/ folder into .claude-plugin/. The validator reports component-in-manifest-dir, the skills: line disappears because nothing loads, and it exits 1:
    cp -R agents-3/plugin_kit/kit/lab-review /tmp/lab-plugin
    mv /tmp/lab-plugin/skills /tmp/lab-plugin/.claude-plugin/
    python3 agents-3/plugin_validate.py /tmp/lab-plugin
  • name is the only required manifest key, and every component path starts with ./ and stays inside the plugin.
  • Some settings simply don't do what they say: a plugin agent's permissionMode, if on a non-tool event, a matcher on UserPromptSubmit, CLAUDE.md at the plugin root.
  • A plugin hook runs in every session while the plugin is enabled, with your user permissions and outside the sandbox. Test it before you ship it.