π The fast, Pythonic way to build MCP servers and clients.
docs: consolidate developer and maintainer guidance (#5298)
nate nowack831cc3014e10
diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.mdindex 3274bf971..a3eb54996 100644--- a/.agents/skills/code-review/SKILL.md+++ b/.agents/skills/code-review/SKILL.md@@ -5,7 +5,7 @@ description: Review a complete FastMCP change for correctness, supported behavio# Review FastMCP code-Read AGENTS.md, CONTRIBUTING.md, the entire diff against the merge base, and prior review threads and replies. Trace the changed code in context, including callers and shared abstractions. Collect independent consequential findings in one pass.+Read AGENTS.md, the contribution policy in [the development guide](../../../docs/development/contributing.mdx), the entire diff against the merge base, and prior review threads and replies. Trace the changed code in context, including callers and shared abstractions. Collect independent consequential findings in one pass.Establish the intended contract from released docs, tests, history, and maintainer decisions. A reproducible behavior is not automatically a bug. Check whether the change fixes the cause where it occurs or adds compensation elsewhere.diff --git a/.agents/skills/fix-issue/SKILL.md b/.agents/skills/fix-issue/SKILL.mdindex c0327a72b..1739433ab 100644--- a/.agents/skills/fix-issue/SKILL.md+++ b/.agents/skills/fix-issue/SKILL.md@@ -5,7 +5,7 @@ description: Carry a selected FastMCP bug from reproduction through a scoped fix# Fix a selected issue-Read AGENTS.md and CONTRIBUTING.md. Read the issue's full discussion, relevant history, and associated PRs in all states. Evaluate existing contributions before writing a competing fix; use [review-issue](../review-issue/SKILL.md) when assignment is the next decision. Preserve contributor authorship when carrying existing work forward.+Read AGENTS.md and the contribution policy in [the development guide](../../../docs/development/contributing.mdx). Read the issue's full discussion, relevant history, and associated PRs in all states. Evaluate existing contributions before writing a competing fix; use [review-issue](../review-issue/SKILL.md) when assignment is the next decision. Preserve contributor authorship when carrying existing work forward.## Establish the contractdiff --git a/.agents/skills/review-issue/SKILL.md b/.agents/skills/review-issue/SKILL.mdindex a53fa06c2..c98f42186 100644--- a/.agents/skills/review-issue/SKILL.md+++ b/.agents/skills/review-issue/SKILL.md@@ -37,7 +37,7 @@ Assignment commits us to reviewing the PR, not to merging it. A gate closure is2. **Decide whether the issue describes a bug.** Reproduce the MRE, then ask whether the behavior violates a contract FastMCP intends to hold. Behavior that only appears by mutating construction-time state or relying on internals is a property of the code, not a defect. The code shows what FastMCP does, not what it promises, so ask the maintainer "is X supported?" when the contract is unclear. Check `main`, duplicates, and prior maintainer decisions in related issues and closed PRs. If the issue is not a bug, recommend declining without reviewing the PR.-3. **Check the category against CONTRIBUTING.md.** Simple bug fixes, docs, and auth providers are assignable. Enhancements need a maintainer-approved design in the issue first; approve the approach, then assign. Third-party integrations and sweeping changes without discussion are declined.+3. **Check the category against [the contribution policy](../../../docs/development/contributing.mdx#choose-a-contribution).** Simple bug fixes, docs, and auth providers are assignable. Enhancements need a maintainer-approved design in the issue first; approve the approach, then assign. Third-party integrations and sweeping changes without discussion are declined.4. **Investigate the PR in context.** Read the full diff, then open each touched file. Trace the values and functions it changes to where they are produced and consumed. From the MRE, state in one line what was broken, where, and whether this change fixes it there. Compare with how adjacent code handles the same case, and check that the tests fail without the fix. Treat style issues as review comments; a wrong layer, a broken adjacent path, or an unfixed MRE changes the verdict.@@ -63,7 +63,7 @@ gh issue edit N --repo PrefectHQ/fastmcp --add-assignee <login>Confirm the `require-issue-link` run passes and the PR reopens, then review it with [code-review](../code-review/SKILL.md) and follow it with [review-pr](../review-pr/SKILL.md). If the PR's head branch was deleted, assignment cannot reopen it; the workflow asks the author for a fresh PR.-**Decline:** with authorization, comment on the issue with the reason and the relevant CONTRIBUTING.md section. Write the body to a file first:+**Decline:** with authorization, comment on the issue with the reason and the relevant contribution-policy section. Write the body to a file first:```bashgh issue comment N --repo PrefectHQ/fastmcp --body-file /tmp/triage-reply.mddiff --git a/.agents/skills/triage/SKILL.md b/.agents/skills/triage/SKILL.mdindex b32ef5858..56a4167d5 100644--- a/.agents/skills/triage/SKILL.md+++ b/.agents/skills/triage/SKILL.md@@ -5,7 +5,7 @@ description: Find worthwhile FastMCP issues to work on in a backlog or release w# Find worthwhile work-Read AGENTS.md and CONTRIBUTING.md. Honor the requested scope. For "since the last patch," identify the release timestamp, then look for open issues created or substantively updated afterward. Use a bounded inventory internally; report truncation if it affects coverage.+Read AGENTS.md and the contribution policy in [the development guide](../../../docs/development/contributing.mdx). Honor the requested scope. For "since the last patch," identify the release timestamp, then look for open issues created or substantively updated afterward. Use a bounded inventory internally; report truncation if it affects coverage.Start from an inventory, then link each candidate to the PRs that mention it:diff --git a/AGENTS.md b/AGENTS.mdindex bd071721c..30a4239e1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -41,7 +41,7 @@ uv run prek run --all-files # Ruff + Prettier + ty## Skills-Repository skills live in `.agents/skills/`, with symlinks in `.claude/skills/` for Claude Code. [MAINTAINING.md](MAINTAINING.md) says which work is automated and which needs a person. Load the skill that matches the job:+Repository skills live in `.agents/skills/`, with symlinks in `.claude/skills/` for Claude Code. [The development guide](docs/development/contributing.mdx#maintenance-and-automation) says which work is automated and which needs a person. Load the skill that matches the job:| Job | Skill || --- | --- |@@ -68,7 +68,7 @@ When modifying MCP functionality, changes typically need to be applied across al## Development Rules-**Read `CONTRIBUTING.md` before opening issues or PRs.** It describes when PRs are appropriate, what we expect from enhancement proposals, and what we'll close without review.+**Read `CONTRIBUTING.md` and its linked guide at `docs/development/contributing.mdx` before opening issues or PRs.** The guide describes when PRs are appropriate, what we expect from enhancement proposals, and what we'll close without review.**Review closed contributor PRs.** When reviewing an issue, inspect every associated non-maintainer PR, including closed PRs. External PRs may be closed as part of the issue-link and assignment workflow, so closure alone is not a negative signal. Read `CONTRIBUTING.md` and the PR timeline and comments to understand its status before evaluating it.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 7cb0ea7cc..acc784b1e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,72 +1,5 @@# Contributing to FastMCP-FastMCP is an actively maintained, high-traffic project. We welcome contributions β but the most impactful way to contribute might not be what you expect.+Read the [contributing guide](docs/development/contributing.mdx) for accepted contributions, issue assignment, development setup, tests, and review expectations. The same guide is [published on gofastmcp.com](https://gofastmcp.com/development/contributing).-Participation is governed by our [Code of Conduct](CODE_OF_CONDUCT.md), and contributions are licensed under [Apache 2.0](LICENSE).--## The best contribution is a great issue--FastMCP is an opinionated framework, and its maintainers use AI-assisted tooling that is deeply tuned to those opinions β the design philosophy, the API patterns, the way the framework is meant to evolve. A well-written issue with a clear problem description is often more valuable than a pull request, because it lets maintainers produce a solution that isn't just correct, but consistent with how the framework wants to work. That matters more than speed, though it's faster too.--**A great issue looks like this:**--1. A short, motivating description of the problem or gap-2. A minimal reproducible example (for bugs) or a concrete use case (for enhancements)-3. A brief note on expected vs. actual behavior--That's it. No need to diagnose root causes, propose API designs, or suggest implementations. If you've done genuine investigation and have a non-obvious insight, include it.--## Using AI to contribute--We encourage you to use LLMs to help identify bugs, write MREs, and prepare contributions. But if you do, your LLM must take into account the conventions and contributing guidelines of this repo β including how we want issues formatted and when it's appropriate to open a PR. Generic LLM output that ignores these guidelines tells us the contribution wasn't made thoughtfully, and we will close it. A good AI-assisted contribution is indistinguishable from a good human one. A bad one is obvious.--Start your agent from [AGENTS.md](AGENTS.md). It holds the development workflow, the required checks, and the conventions reviewers expect. The repository also ships skills in [`.agents/skills/`](.agents/skills/) (linked into `.claude/skills/` for Claude Code) that walk an agent through common jobs: `fix-issue` carries a bug from reproduction to a PR, `python-tests` covers the test conventions, `docs` covers documentation pages, and `code-review` is the review your PR will get, so run it on your own change before opening one.--If you're driving an agent: do **not** have it post comments asking to be assigned to an issue or announcing that it intends to work on one. Those comments are ignored. If the agent intends to contribute, open a PR instead β it will be gated on assignment (see below). Comment on an issue only to propose a genuinely novel, differentiated solution, never to claim a task that's already described.--## When to open a pull request--An open issue is not an invitation to submit a PR, and it is not a queue you join by commenting. Issues track problems; who implements them and how is a separate decision maintainers make, and whoever opened the issue has first claim on it.--**Don't post drive-by comments claiming an issue** β "can I work on this?", "please assign me", "I'll take this." They don't affect who gets assigned, they're the most common form of noise we get, and automated versions are ignored. Whoever opens the issue has first claim on it; if that's you, a maintainer will assign you. If you want to implement something someone else reported, just open a PR β you don't need permission to try, and competing PRs are fine β but it's reviewed only if a maintainer assigns you to the issue, which usually won't happen if the reporter intends to handle it. The one comment worth posting is a genuinely different approach worth discussing; a substantive design proposal is welcome, a bare claim on the task is not.--**Issues labeled `prs welcome` skip the assignment gate.** When we apply that label, we're saying the reporter isn't implementing it and we'd take a PR from anyone. Open one directly β no assignment needed, and it won't be auto-closed. Still reference the issue (`Fixes #123`), since that's how the check knows which issue to look at.--**What assignment means.** Being assigned is a commitment on both sides: we'll review your work seriously, and you'll see it through. That means responding to review feedback yourself and being able to explain any part of your change and why you made it that way. Use whatever tooling you like to get there β but if you can't answer a question about your own diff, we'll unassign the issue so someone else can pick it up.--**Bug fixes** β PRs are welcome for simple, well-scoped bug fixes where the problem and solution are both straightforward. "The function raises `TypeError` when passed `None` because of a missing guard" is a good candidate. If the fix requires design decisions or touches multiple subsystems, open an issue with a design proposal instead.--**Documentation** β Typo fixes, clarifications, and improvements to examples are always welcome as PRs.--**Enhancements and features** β We welcome enhancement PRs, but our experience is that most contributors β even when using LLMs β implement fixes that address the one instance of a problem they encountered rather than understanding why the framework produces that problem and fixing it at the right layer. This creates branching, patch-style code that's difficult to maintain and makes it impossible to reason about the framework as a coherent system. For this reason, enhancements need a design proposal in the issue before code is written. The proposal doesn't need to be long β just enough to show you've thought about how the change fits into the framework, not just how it solves your immediate case.--**Integrations** β FastMCP generally does not accept PRs that add third-party integrations (custom middleware, provider-specific adapters, etc.). If you're building something for your users, ship it as a standalone package β that's a feature, not a limitation. Authentication providers are an exception, since auth is tightly coupled to the framework.--## PR guidelines--If you do open a PR:--- **Reference a tracked issue.** Every PR must reference an issue using an auto-close keyword (`Fixes #123`, `Closes #123`, or `Resolves #123`). You may open a linked PR before assignment, but the issue-link check passes only once a maintainer assigns you to the issue β unless it's labeled `prs welcome`, which waives the assignment requirement. If there isn't an issue, open one. This lets us deconflict effort and steer the approach before you invest time in code. External PRs that don't meet these conditions receive a failing check and the `missing-issue-link` label. PRs without a valid issue link are closed; linked PRs remain open while maintainers decide on assignment. Assignment automatically re-runs the check and reopens previously gate-closed PRs.-- **Leave "Allow edits by maintainers" enabled.** We frequently take a PR the last few steps ourselves rather than block on another round trip β tightening a test, adjusting naming, rebasing. It's enabled by default on PRs from personal forks; leave it that way. GitHub doesn't allow it at all for forks owned by an organization, so if you're contributing from one, expect us to land the final changes separately.-- **Target the right branch.** Open against `main` unless you're fixing something specific to a maintenance line, in which case target that branch directly (`release/3.x`, `release/2.x`).-- **If your PR was auto-closed, don't open a new one.** Edit the *existing* PR to add the issue link, get assigned to that issue, and it reopens on its own β the branch and history are preserved. A duplicate PR just starts you over and adds to the triage pile.-- **Keep it focused.** One logical change per PR. Don't bundle unrelated fixes or refactors.-- **Match existing patterns.** Follow the code style, type annotation conventions, and test patterns you see in the codebase. Run `uv run prek run --all-files` before submitting.-- **Write tests.** Bug fixes should include a test that fails without the fix. Enhancements should include tests for the new behavior.-- **Fix the cause, not the symptom.** If the bug is that a code path skips a step, the fix should make it stop skipping that step β not add compensation elsewhere. Workaround-style fixes will be sent back for revision.-- **Don't submit generated boilerplate.** We review every line. PRs that read like unedited LLM output β verbose descriptions, speculative changes, shotgun-style fixes β will be closed.--## Maintaining FastMCP--Maintainers use the same skills for the rest of the project's work: `triage` finds worthwhile issues, `review-issue` decides whether to assign an external contributor, `review-pr` follows a PR through CI and bot review, `review-security-report` evaluates vulnerability reports, and `release` cuts a release from notes preview to a verified docs deploy. The table in [AGENTS.md](AGENTS.md#skills) maps each job to its skill, and [MAINTAINING.md](MAINTAINING.md) lists what runs on its own. Skills stop before public actions such as commenting, assigning, merging, or tagging, and ask the maintainer driving them.--## What we'll close without review--To keep the project maintainable, we will close PRs that:--- Don't reference an issue or address a clearly self-evident bug-- Make sweeping changes without prior discussion-- Add third-party integrations that belong in a separate package-- Are difficult to review due to size, scope, or generated content--This isn't personal β contributing to a framework is different from contributing to an application. In an application, a fix that works is a good fix. In a framework, a fix that works but doesn't fit the framework's design creates maintenance burden that compounds over time. Every patch that works around a problem instead of solving it at the right layer makes the system harder for *everyone* to reason about β maintainers, contributors, and users. We hold contributions to this standard because the alternative is a codebase that's a series of patches rather than a coherent system. A good issue is often the best thing you can do for the project.+Agents should also read [AGENTS.md](AGENTS.md) and use the repository skills it lists. Report vulnerabilities privately through [SECURITY.md](SECURITY.md). Participation follows our [Code of Conduct](CODE_OF_CONDUCT.md), and contributions are licensed under [Apache 2.0](LICENSE).diff --git a/MAINTAINING.md b/MAINTAINING.mddeleted file mode 100644index d8d7b9114..000000000--- a/MAINTAINING.md+++ /dev/null@@ -1,32 +0,0 @@-# Maintaining FastMCP--FastMCP is maintained by a small team with a lot of automation. Automations handle the routine work: labeling, gating external PRs, releases. Maintainers make the calls that need judgment. This page says which is which.--**Current state:** [STATUS.md](https://github.com/PrefectHQ/fastmcp/blob/status/STATUS.md) on the `status` branch, regenerated twice a day, with the same data as [status.json](https://raw.githubusercontent.com/PrefectHQ/fastmcp/status/status.json).--## What runs on its own--Everything below runs as a GitHub Actions workflow in this repository, so its runs are public.--- **Contributions:** the issue-link gate holds an external PR until its author is assigned to an issue it links. Assigning the author reopens a PR the gate closed.-- **Issues:** new issues and PRs are labeled, and new issues are checked for duplicates. Issues marked as duplicates, and issues still missing a reproducible example after 7 days without a reply from the author, close on their own.-- **Pull requests:** a PR whose tests or static analysis fail gets an explanation, and maintainers can ask the bot to act with `/marvin`.-- **Health:** the test suite runs nightly against the newest dependency releases and opens an issue when it fails.-- **Releases:** a tagged release publishes all four packages to PyPI, and publishing the docs deploys gofastmcp.com.-- **Contributor queue:** twice a day, the status page reports how many gated PRs are waiting and for how long.--Maintainers also run a triage agent that may open **draft** PRs for bugs nobody has claimed. It never merges, comments, labels, or marks a PR ready, and it skips any issue that is assigned or already has a PR.--## What needs a person--- Assigning an external contributor, which reopens their gated PR.-- Merging, and marking an agent-opened draft ready.-- Any change to documented behavior or compatibility, and any new API.-- Cutting a release, including its title and notes.-- Classifying and disclosing security reports.--## For agents--Start at [AGENTS.md](AGENTS.md). It holds the workflow, the required checks, and a table of the repository's skills, one per job: triage, contributor review, fixing a bug, code review, following a PR, tests, docs, security reports, and releases.--`status.json` uses the schema `fastmcp-maintenance/1`. Each automation carries `state` (`ok`, `idle`, `degraded`, or `off`), `cadence`, `last_ok_day`, and counts over a stated `window`. Compare `as_of` and `cadence` before calling something broken: an automation with nothing to do reads `idle`, not `degraded`.diff --git a/README.md b/README.mdindex 920996af9..ec4bf0d80 100644--- a/README.md+++ b/README.md@@ -121,4 +121,4 @@ Documentation is also available in [llms.txt format](https://llmstxt.org/), whic## Contributing-We welcome contributions! See the [Contributing Guide](https://gofastmcp.com/development/contributing) for setup instructions, testing requirements, and PR guidelines.+Start with [CONTRIBUTING.md](CONTRIBUTING.md) for accepted contributions and the issue-assignment workflow, then follow the [Contributing Guide](https://gofastmcp.com/development/contributing) for setup and validation. Agents should read [AGENTS.md](AGENTS.md).diff --git a/SECURITY.md b/SECURITY.mdindex 656867d37..7b9d6ac9d 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -4,6 +4,7 @@| Version | Supported || ------- | ------------------ |+| 4.x | :white_check_mark: || 3.x | :white_check_mark: || 2.x | :x: || 1.x | :x: |diff --git a/docs/development/contributing.mdx b/docs/development/contributing.mdxindex e03ec37c7..96ca52276 100644--- a/docs/development/contributing.mdx+++ b/docs/development/contributing.mdx@@ -1,198 +1,97 @@---title: "Contributing"-description: "Development workflow for FastMCP contributors"+description: "Choose a contribution, set up FastMCP, and prepare it for review"icon: code-pull-request----Contributing to FastMCP means joining a community that values clean, maintainable code and thoughtful API design. All contributions are valued - from fixing typos in documentation to implementing major features.+A concise issue with a reproducible problem is often the most useful contribution. This guide covers which changes FastMCP accepts, how contributions enter review, and how to develop and validate a change.-## Design Principles+Report vulnerabilities privately through the [security policy](https://github.com/PrefectHQ/fastmcp/blob/main/SECURITY.md). Community participation follows the [Code of Conduct](https://github.com/PrefectHQ/fastmcp/blob/main/CODE_OF_CONDUCT.md).-Every contribution should advance these principles:+## Choose a contribution-- π **Fast** β High-level interfaces mean less code and faster development-- π **Simple** β Minimal boilerplate; the obvious way should be the right way-- π **Pythonic** β Feels natural to Python developers; no surprising patterns-- π **Complete** β Everything needed for production: auth, testing, deployment, observability+A useful bug report states the problem, includes a minimal reproducible example, and explains the expected behavior. Search existing issues and pull requests first, including closed PRs: the contribution gate may have closed a proposal while it waits for assignment.-PRs are evaluated against these principles. Code that makes FastMCP slower, harder to reason about, less Pythonic, or less complete will be rejected.+Simple, scoped bug fixes, documentation improvements, and authentication providers are welcome. Enhancements need a maintainer-approved design in an issue before implementation. Third-party integrations generally belong in a separate package. For a proposed in-repository community module, read [Contrib Modules](/patterns/contrib) and discuss its maintenance model first.-## Issues+FastMCP prioritizes readable Python, clear APIs, and fixes at the source of a problem. A working implementation can still be unsuitable if it changes an intentional contract or adds a workaround that the framework must maintain indefinitely.-### Issue First, Code Second+### Issues and assignment-**Every pull request requires a corresponding issue - no exceptions.** This requirement creates a collaborative space where approach, scope, and alignment are established before code is written. Issues serve as design documents where maintainers and contributors discuss implementation strategy, identify potential conflicts with existing patterns, and ensure proposed changes advance FastMCP's vision.+External PRs must link an issue with an auto-close keyword such as `Fixes #123`. The author must also be assigned to that issue, unless it carries the `prs welcome` label. You can open a linked PR before assignment; it waits with a failing gate check while maintainers evaluate it. A PR without a valid issue link is closed.-**FastMCP is an opinionated framework, not a kitchen sink.** The maintainers have strong beliefs about what FastMCP should and shouldn't do. Just because something takes N lines of code and you want it in fewer lines doesn't mean FastMCP should take on the maintenance burden or endorse that pattern. This is judged at the maintainers' discretion.+Assignment commits maintainers to reviewing a contribution, not to merging it. Assigning an author reruns the gate and can reopen their previously closed PR. Update that PR rather than opening a duplicate. The issue reporter has first claim on implementing the fix; an open issue does not by itself mean a maintainer has accepted a proposed solution.-Use issues to understand scope BEFORE opening PRs. The issue discussion determines whether a feature belongs in core, contrib, or not at all.+Do not post comments just to claim an issue or ask to be assigned. A concise report, a scoped linked PR, or a substantive design discussion gives maintainers something concrete to evaluate. The gate exempts maintainers and trusted contributors. Draft PRs are checked when marked ready for review.-### Writing Good Issues+### Working with an agent-FastMCP is an extremely highly-trafficked repository maintained by a very small team. Issues that appear to transfer burden to maintainers without any effort to validate the problem will be closed. Please help the maintainers help you by always providing a minimal reproducible example and clearly describing the problem.+AI assistance is welcome under the same standards as other contributions. You remain responsible for understanding the change, verifying its behavior, and responding to review. Avoid generated boilerplate that obscures the problem or substitutes speculation for a reproduction.-**LLM-generated issues will be closed immediately.** Issues that contain paragraphs of unnecessary explanation, verbose problem descriptions, or obvious LLM authorship patterns obfuscate the actual problem and transfer burden to maintainers.+Have your agent read [AGENTS.md](https://github.com/PrefectHQ/fastmcp/blob/main/AGENTS.md). It contains the required checks, repository conventions, and a table routing tasks to the [repository skills](https://github.com/PrefectHQ/fastmcp/tree/main/.agents/skills). Use the testing and review procedures on your own change before submitting it. Skills live in `.agents/skills/`, with discovery links in `.claude/skills/`.-Write clear, concise issues that:-- State the problem directly-- Provide a minimal reproducible example-- Skip unnecessary background or context-- Take responsibility for clear communication+## Set up the repository-Issues may be labeled "Invalid" simply due to confusion caused by verbosity or not adhering to the guidelines outlined here.--## Pull Requests--PRs that deviate from FastMCP's core principles will be rejected regardless of implementation quality. **PRs are NOT for iterating on ideas** - they should only be opened for ideas that already have a bias toward acceptance based on issue discussion.---### Development Environment--#### Installation--To contribute to FastMCP, you'll need to set up a development environment with all necessary tools and dependencies.+Use Python 3.10 or newer and [uv](https://docs.astral.sh/uv/). Fork the repository for an external contribution, clone your fork, then install the workspace dependencies and commit hooks:```bash-# Clone the repository-git clone https://github.com/PrefectHQ/fastmcp.git+git clone https://github.com/YOUR-USERNAME/fastmcp.gitcd fastmcp--# Install all dependencies including dev toolsuv sync--# Install prek hooksuv run prek install```-In addition, some development commands require [just](https://github.com/casey/just) to be installed.--Prek hooks will run automatically on every commit to catch issues before they reach CI. If you see failures, fix them before committing - never commit broken code expecting to fix it later.--### Development Standards--#### Scope--Large pull requests create review bottlenecks and quality risks. Unless you're fixing a discrete bug or making an incredibly well-scoped change, keep PRs small and focused.--A PR that changes 50 lines across 3 files can be thoroughly reviewed in minutes. A PR that changes 500 lines across 20 files requires hours of careful analysis and often hides subtle issues.--Breaking large features into smaller PRs:-- Creates better review experiences-- Makes git history clear-- Simplifies debugging with bisect-- Reduces merge conflicts-- Gets your code merged faster--#### Code Quality--FastMCP values clarity over cleverness. Every line you write will be maintained by someone else - possibly years from now, possibly without context about your decisions.--**PRs can be rejected for two opposing reasons:**-1. **Insufficient quality** - Code that doesn't meet our standards for clarity, maintainability, or idiomaticity-2. **Overengineering** - Code that is overbearing, unnecessarily complex, or tries to be too clever--The focus is on idiomatic, high-quality Python. FastMCP uses patterns like `NotSet` type as an alternative to `None` in certain situations - follow existing patterns.--#### Required Practices--**Full type annotations** on all functions and methods. They catch bugs before runtime and serve as inline documentation.--**Async/await patterns** for all I/O operations. Even if your specific use case doesn't need concurrency, consistency means users can compose features without worrying about blocking operations.+The workspace contains several distributions. Most framework code lives in `fastmcp_slim/fastmcp/`; `fastmcp_tasks/` and `fastmcp_remote/` hold the task and remote packages. Tests live under `tests/`, and the documentation source lives under `docs/`. Extend the tests nearest the behavior you change.-**Descriptive names** make code self-documenting. `auth_token` is clear; `tok` requires mental translation.+Target `main` for current development. Fixes specifically for older supported lines target their maintenance branch, such as `release/3.x` or `release/2.x`.-**Specific exception types** make error handling predictable. Catching `ValueError` tells readers exactly what error you expect. Never use bare `except` clauses.+## Implement and verify-#### Anti-Patterns to Avoid+Establish what the public API promises before writing a regression test. A test that fails on existing code only demonstrates a difference; docs, protocol requirements, history, and maintainer decisions establish whether that difference is a bug. If the intended behavior is unclear, settle that question in the issue.-**Complex one-liners** are hard to debug and modify. Break operations into clear steps.+Keep the change scoped to one problem and fix the causal code path. Avoid speculative explanations, sweeping unrelated changes, and generated boilerplate; maintainers may close contributions that do not meet these requirements. Trace the callers and adjacent behavior that share it. In particular, preserve supported explicit overrides when changing a default. Use full type annotations, specific exceptions, and the surrounding code's conventions.-**Mutable default arguments** cause subtle bugs. Use `None` as the default and create the mutable object inside the function.+For a bug fix, run the regression on unchanged code and confirm it fails for the reported reason, then run it with the fix. Assert the actual result and relevant types. Exercise neighboring supported behavior as well. The [Testing Guide](/development/tests) covers fixtures, protocol tests, HTTP helpers, and subprocess tests.-**Breaking established patterns** confuses readers. If you must deviate, discuss in the issue first.--### Prek Checks--```bash-# Runs automatically on commit, or manually:-uv run prek run --all-files-```--This runs three critical tools:-- **Ruff**: Linting and formatting-- **Prettier**: Code formatting-- **ty**: Static type checking--Pytest runs separately as a distinct workflow step after prek checks pass. CI will reject PRs that fail these checks. Always run them locally first.--### Testing--Tests are documentation that shows how features work. Good tests give reviewers confidence and help future maintainers understand intent.+Before committing, run these commands in order, followed by the static checks:```bash-# Run specific test directory-uv run pytest tests/server/ -v--# Run all tests before submitting PR+uv syncuv run pytest -n auto+uv run prek run --all-files```-Every new feature needs tests. See the [Testing Guide](/development/tests) for patterns and requirements.--### Documentation+Prek runs lint, formatting, typing, and other repository checks; pytest is separate. Hooks also run on commit. Fix failures before committing, and use a new commit rather than amending to repair a failed hook.-A feature doesn't exist unless it's documented. Note that FastMCP's hosted documentation always tracks the main branch - users who want historical documentation can clone the repo, checkout a specific tag, and host it themselves.--```bash-# Preview documentation locally-just docs-```+## Update documentation-Documentation requirements:-- **Explain concepts in prose first** - Code without context is just syntax-- **Complete, runnable examples** - Every code block should be copy-pasteable-- **Register in docs.json** - Makes pages appear in navigation-- **Version badges** - Mark when features were added using `<VersionBadge />`+Document new capabilities and changes to public behavior alongside the implementation. Explain the use case before the code, include imports, and keep examples runnable. Add new pages to `docs/docs.json` so they appear in navigation. When a setting changes, update `docs/more/settings.mdx`.-#### SDK Documentation+Edit source docstrings for API-reference changes. Do not manually edit `docs/python-sdk/`, `docs/public/schemas/`, or the generated MCP server configuration schema; automation maintains those outputs. The `docs/v2/` and `docs/v3/` trees are frozen version snapshots, apart from maintenance release changelog entries.-FastMCP's SDK documentation is auto-generated from the source code docstrings and type annotations. It is automatically updated on every merge to main by a GitHub Actions workflow, so users are *not* responsible for keeping the documentation up to date. However, to generate it proactively, you can use the following command:+Check documentation links and examples from the repository root:```bash-just api-ref-all+just docs-broken-links+uv run pytest tests/docs -n 0```-### Submitting Your PR--#### Before Submitting--1. **Run all checks**: `uv run prek run --all-files && uv run pytest -n auto`-2. **Keep scope small**: One feature or fix per PR-3. **Write clear description**: Your PR description becomes permanent documentation-4. **Update docs**: Include documentation for API changes--#### PR Description--Write PR descriptions that explain:-- What problem you're solving-- Why you chose this approach-- Any trade-offs or alternatives considered-- Migration path for breaking changes+[just](https://github.com/casey/just) provides convenience commands. Without it, run `npx --yes mint@latest broken-links` from `docs/`. Preview rendering with `just docs`, or run `npx --yes mint@latest dev` from that directory. The docs tests check Python syntax and FastMCP imports; execute changed examples too, since those checks do not prove behavior.-Focus on the "why" - the code shows the "what". Keep it concise but complete.+The live site serves `published-docs`, so merging a docs change into `main` does not publish it immediately. See [Releases](/development/releases#creating-releases) for the publication workflow.-#### What We Look For+## Submit and follow through-**Framework Philosophy**: FastMCP is NOT trying to do all things or provide all shortcuts. Features are rejected when they don't align with the framework's vision, even if perfectly implemented. The burden of proof is on the PR to demonstrate value.+Write a short PR description explaining the problem and the resulting behavior, with a focused example when it helps. Include the issue link and explain any compatibility decision. Keep "Allow edits by maintainers" enabled when available so maintainers can finish small adjustments without replacing your contribution.-**Code Quality**: We verify code follows existing patterns. Consistency reduces cognitive load. When every module works similarly, developers understand new code quickly.+Review the entire diff, not just your latest commit. A useful review checks the intended contract, root cause, supported behavior, tests, and documentation. Green CI is evidence that checks passed; it does not decide whether a behavior change belongs in FastMCP.-**Test Coverage**: Not every line needs testing, but every behavior does. Tests document intent and protect against regressions.+Read review-bot comments and maintainer replies, evaluate concrete findings, and respond to requested changes. A new push needs checks against that revision. Stay involved until the PR is resolved; assignment is a commitment to follow through.-**Breaking Changes**: May be acceptable in minor versions but must be clearly documented. See the [versioning policy](/development/releases#versioning-policy).+## Maintenance and automation-## Special Modules+The [maintenance status page](https://github.com/PrefectHQ/fastmcp/blob/status/STATUS.md) reports automation health and the contributor queue twice a day. Check its timestamp before treating a status as current. The accompanying `status.json` uses the `fastmcp-maintenance/1` schema; `idle` means there was nothing to do, while `degraded` means a run failed.-**`contrib`**: Community-maintained patterns and utilities. Original authors maintain their contributions. Not representative of the core framework.+Automation labels and deduplicates issues, enforces the contribution gate, explains CI failures, and checks new dependency releases nightly. Duplicate issues and reports still missing a reproduction after seven days without an author reply close automatically. Maintainers can request work with `/marvin`. A separate triage agent may open draft fixes for unclaimed issues; it does not assign contributors, comment, mark drafts ready, or merge.-**`experimental`**: Maintainer-developed features that may preview future functionality. Can break or be deleted at any time without notice. Pin your FastMCP version when using these features.\ No newline at end of file+Maintainers decide assignments, merge readiness, changes to supported behavior or APIs, releases, and security-report classification. Release publishing and docs deployment run automatically after the corresponding maintainer actions; see [Releases](/development/releases#creating-releases).diff --git a/docs/development/releases.mdx b/docs/development/releases.mdxindex f537703e2..541b256be 100644--- a/docs/development/releases.mdx+++ b/docs/development/releases.mdx@@ -1,81 +1,52 @@---title: "Releases"-description: "FastMCP versioning and release process"-icon: "truck-fast"+description: "Compatibility decisions, release branches, and documentation publishing"+icon: truck-fast----FastMCP releases frequently to deliver features quickly in the rapidly evolving MCP ecosystem. We use semantic versioning pragmatically - the Model Context Protocol is young, patterns are still emerging, and waiting for perfect stability would mean missing opportunities to empower developers with better tools.+FastMCP releases when changes are ready. Release notes describe the user-visible changes and any migration required. Maintainers choose the release scope and version; passing tests alone does not settle a compatibility decision.## Versioning Policy-### Semantic Versioning+Patch releases contain fixes and refinements without breaking supported public behavior. Minor releases add capabilities and may include deliberate breaking changes when their benefit justifies the disruption. Major releases cover larger changes to the framework and its APIs.-**Major (x.0.0)**: Complete API redesigns+### Breaking changes-Major versions represent fundamental shifts. FastMCP 2.x is entirely different from 1.x in both implementation and design philosophy.+Evaluate the intended behavior and the users affected before deciding how to ship a change. Compare the cost of migration with the complexity or incorrect behavior that retaining the old contract would preserve. A change described as a bug fix still needs this assessment; a breaking change does not automatically require waiting for the next major version.-**Minor (2.x.0)**: New features and evolution+Breaking changes in a minor release require a maintainer decision, clear release notes, and migration guidance. Provide deprecation warnings at least one minor release ahead when possible. Do not put a breaking change into a patch release merely because a regression test passes.-<Warning>-Unlike traditional semantic versioning, minor versions **may** include [breaking changes](#breaking-changes) when necessary for the ecosystem's evolution. This flexibility is essential in a young ecosystem where perfect backwards compatibility would prevent important improvements.-</Warning>+The public compatibility contract covers `FastMCP`, `Client`, `Context`, core MCP components and transports, and their public methods and documented behavior. Private implementation details do not have the same guarantee. Experimental APIs may change or disappear; pin versions when relying on them and read the release notes before upgrading.-FastMCP tracks the current MCP Protocol version while serving earlier handshake versions alongside it. Building on MCP SDK v2, a FastMCP server negotiates the protocol era each client speaks β the sessionless `2026-07-28` era and earlier session-based eras are both handled by the same server. New features and conventions from the spec flow through to FastMCP as they land; for the details of which capabilities are available on each era, see [Upgrading from FastMCP 3](/getting-started/upgrading/from-fastmcp-3#protocol-version-support).+FastMCP also supports multiple MCP protocol eras. Negotiating an older protocol does not select an older FastMCP implementation; see [protocol version support](/getting-started/upgrading/from-fastmcp-3#protocol-version-support).-**Patch (2.0.x)**: Bug fixes and refinements+### Production upgrades-Patch versions contain only bug fixes without breaking changes. These are safe updates you can apply with confidence.+Use a lockfile or an exact version pin for reproducible deployments. Review the changelog, test your supported workflows, and update the pin deliberately. For example, an exact dependency constraint has this form:-### Breaking Changes--We permit breaking changes in minor versions because the MCP ecosystem is rapidly evolving. Refusing to break problematic APIs would accumulate design debt that eventually makes the framework unusable. Each breaking change represents a deliberate decision to keep FastMCP aligned with the ecosystem's evolution.--When breaking changes occur:-- They only happen in minor versions (e.g., 2.3.x to 2.4.0)-- Release notes explain what changed and how to migrate-- We provide deprecation warnings at least 1 minor version in advance when possible-- Changes must substantially benefit users to justify disruption--The public API is what's covered by our compatibility guarantees - these are the parts of FastMCP you can rely on to remain stable within a minor version. The public API consists of:-- `FastMCP` server class, `Client` class, and FastMCP `Context`-- Core MCP components: `Tool`, `Prompt`, `Resource`, `ResourceTemplate`, and transports-- Their public methods and documented behaviors--Everything else (utilities, private methods, internal modules) may change without notice. This boundary lets us refactor internals and improve implementation details without breaking your code. For production stability, pin to specific versions.--<Warning>-The `fastmcp.server.auth` module was introduced in 2.12.0 and is exempted from this policy temporarily, meaning it is *expected* to have breaking changes even on patch versions. This is because auth is a rapidly evolving part of the MCP spec and it would be dangerous to be beholden to old decisions. Please pin your FastMCP version if using authentication in production.--We expect this exemption to last through at least the 2.12.x and 2.13.x release series.-</Warning>--### Production Use--Pin to exact versions:-```-fastmcp==4.0.0 # Good-fastmcp>=4.0.0 # Bad - will install breaking changes+```text+fastmcp==4.0.10```+This illustrates a pin, not a recommendation to remain on that release. Check the [release history](https://github.com/PrefectHQ/fastmcp/releases) for available updates and [SECURITY.md](https://github.com/PrefectHQ/fastmcp/blob/main/SECURITY.md) for security support and private reporting.+## Creating Releases-Our release process is intentionally simple:+Only maintainers cut releases. Use the repository's [release skill](https://github.com/PrefectHQ/fastmcp/blob/main/.agents/skills/release/SKILL.md) for the commands and verification steps. It is the maintained procedure; the sequence below explains how the pieces fit together.-1. Create GitHub release with tag `vMAJOR.MINOR.PATCH` (e.g., `v2.11.0`)-2. Generate release notes automatically, and curate or add additional editorial information as needed-3. GitHub releases automatically trigger PyPI deployments+1. Review changes since the last stable release on the target line and agree on the version, title, and handwritten notes.+2. Merge the changelog documentation PR on the release branch before tagging, so the entry is included in the release commit.+3. Create the GitHub release from that branch. Generate notes starting at the last stable tag, so intervening prereleases do not truncate the changelog.+4. Verify package publication and, for a current-major stable release, complete documentation publication.-Current-major releases target `main`. Maintenance releases target their release branch, such as `release/3.x` for 3.x patches and `release/2.x` for 2.x patches. Stable releases from `main` open a PR that syncs the release commit to `published-docs` after PyPI publishing succeeds; merging that PR publishes the live docs. Prereleases skip the automatic PR and use the same PR-based sync when their docs are ready to publish. Maintenance releases publish packages and GitHub release notes without repointing the live docs branch.+Current-major releases come from `main`. Maintenance releases come from the branch that owns their line, such as `release/3.x` or `release/2.x`. A branch's existence does not by itself promise ongoing security support; consult the security policy.-This automation lets maintainers focus on code quality rather than release mechanics.+Publishing a release triggers the package workflows. On the current line, `fastmcp-slim` publishes first, followed by the dependent `fastmcp-tasks`, `fastmcp-remote`, and `fastmcp` distributions. Verify the relevant workflows and package versions on PyPI rather than treating the GitHub release alone as completion. Published versions are immutable; a correction needs a new release.-### Release Cadence+## Publishing documentation-We follow a feature-driven release cadence rather than a fixed schedule. Minor versions ship approximately every 3-4 weeks when significant functionality is ready.+The live site serves the `published-docs` branch, not `main`. A stable release from `main` opens a PR that copies the release tree to `published-docs` after package publishing succeeds. A maintainer merges that PR, then verifies the `Deploy docs` workflow completed successfully.-Patch releases ship promptly for:-- Critical bug fixes-- Security updates (immediate release)-- Regression fixes+Prereleases do not open that publication PR automatically. Docs-only changes between releases can be published through a PR that synchronizes `main` to `published-docs`; follow the release skill's manual publication procedure. Do not push directly to the publication branch.-This approach means you get improvements as soon as they're ready rather than waiting for arbitrary release dates.+Maintenance releases update their own changelog and packages without repointing the current documentation site. The `docs/v2/` and `docs/v3/` trees preserve historical documentation; outside their release changelogs, they are frozen snapshots.diff --git a/docs/development/tests.mdx b/docs/development/tests.mdxindex d29974614..aa68ccbd2 100644--- a/docs/development/tests.mdx+++ b/docs/development/tests.mdx@@ -1,491 +1,252 @@---title: "Tests"-description: "Testing patterns and requirements for FastMCP"+description: "Verify FastMCP behavior through real clients, HTTP applications, and targeted regressions"icon: vial----import { VersionBadge } from "/snippets/version-badge.mdx"+Test the behavior a user relies on through the smallest boundary that exercises it. Most FastMCP tests can use a real server and client in memory. HTTP and subprocess helpers cover behavior that depends on those transports.-Good tests are the foundation of reliable software. In FastMCP, we treat tests as first-class documentation that demonstrates how features work while protecting against regressions. Every new capability needs comprehensive tests that demonstrate correctness.+## Run tests-## FastMCP Tests--### Running Tests+Install the repository dependencies before running tests:```bash-# Run all tests+uv syncuv run pytest -n auto--# Run specific test file-uv run pytest tests/server/test_auth.py--# Run with coverage-uv run pytest --cov=fastmcp--# Skip integration tests for faster runs-uv run pytest -m "not integration"--# Skip tests that spawn processes-uv run pytest -m "not integration and not client_process and not subprocess_heavy"```-Tests should complete in under 1 second unless marked as integration tests. This speed encourages running them frequently, catching issues early.--### Test Organization+During development, run the owning test module or select a behavior by name:-Our test organization mirrors the source package structure, creating a predictable mapping between code and tests. When you're working on `fastmcp_slim/fastmcp/server/auth.py`, you'll find its tests in `tests/server/test_auth.py`. In rare cases tests are split further - for example, the OpenAPI tests are so comprehensive they're split across multiple files.--### Test Markers--We use pytest markers to categorize tests that require special resources or take longer to run:--```python-from pathlib import Path-async def test_github_api_integration():- """Test GitHub API integration with real service."""- token = os.getenv("FASTMCP_GITHUB_TOKEN")- if not token:- pytest.skip("FASTMCP_GITHUB_TOKEN not available")-- # Test against real GitHub API- client = GitHubClient(token)- repos = await client.list_repos("prefecthq")- assert "fastmcp" in [repo.name for repo in repos]-[email protected]_process-async def test_stdio_transport():- """Test STDIO transport with separate process."""- # This spawns a subprocess- async with Client(Path("examples/simple_echo.py")) as client:- result = await client.call_tool("echo", {"message": "test"})- assert result.content[0].text == "test"+```bash+uv run pytest tests/client/client/test_client.py -n 0+uv run pytest tests/server -k list_tools -n 0```-A third marker, `subprocess_heavy`, exists specifically for Windows CI stability. See [Windows CI and Test Parallelism](#windows-ci-and-test-parallelism) below for when to use it and why it exists.--### Windows CI and Test Parallelism+Use `-n 0` for a single process when debugging. The full suite uses pytest-xdist for parallel execution. To run the same marker selection as the unit CI job:-Windows CI ran the unit suite serially for months. [#2715](https://github.com/PrefectHQ/fastmcp/pull/2715) tried enabling `pytest-xdist` parallelism there in December 2025; [#2726](https://github.com/PrefectHQ/fastmcp/pull/2726) reverted it the next day because "Windows tests continue to fail with intermittent worker crashes." [#4554](https://github.com/PrefectHQ/fastmcp/pull/4554) re-enabled it after removing most of the subprocess pressure that caused those crashes, taking the Windows unit step from roughly 460s to 175s.--That pressure came from three sources, all addressed by #4554: most HTTP tests moved in-process via `asgi_client` instead of binding real sockets, stdio lifecycle tests spawn a minimal stdlib responder (`tests/client/minimal_stdio_server.py`, ~0.03s to start) instead of a subprocess that runs `import fastmcp` (~0.7s), and roughly 80 real `sleep()` calls became deterministic waits on the condition each test actually cared about. Fewer, cheaper subprocesses competing under parallel workers left fewer chances for a worker to die.+```bash+uv run pytest -n auto -m "not integration and not client_process and not subprocess_heavy and not conformance"+```-#### The `subprocess_heavy` marker+The default timeout is five seconds, and `asyncio_mode = "auto"` enables async tests without `@pytest.mark.asyncio`. These settings and the registered markers live in [pyproject.toml](https://github.com/PrefectHQ/fastmcp/blob/main/pyproject.toml).-One class of test still spawns a full Python interpreter that imports FastMCP β checking that a bare install doesn't need optional dependencies, or that a decorator works from a fresh process. Each spawn pays a full interpreter's startup and memory footprint, and a 2-core Windows runner already running 2 xdist workers has little headroom left to absorb that. These tests carry `@pytest.mark.subprocess_heavy` and run in the existing serial `client_process` CI step instead of alongside the parallel workers β `.github/actions/run-pytest/action.yml` routes `client_process or subprocess_heavy` to that step (`MAX_PROCS=0`) and excludes both markers from the parallel unit step.+### Test organization and markers-If a test runs `subprocess.run([sys.executable, "-c", ...])`, or otherwise starts a fresh interpreter that imports `fastmcp`, mark it `subprocess_heavy`. A subprocess that runs a minimal stdlib script with no FastMCP import doesn't need the marker β it's the interpreter startup and import that's expensive, not the subprocess itself.+Extend the module that owns the behavior, using nearby tests and fixtures as the starting point. The test tree generally mirrors the library: authentication tests are under `tests/server/auth/`, client tests under `tests/client/`, and resource tests under `tests/resources/`.-#### This is a mitigation, not a proof+| Marker | Use |+| --- | --- |+| `integration` | Tests needing integration resources or longer execution; CI gives this group a longer timeout. |+| `client_process` | Tests spawning client processes through stdio. |+| `subprocess_heavy` | Tests starting a fresh Python interpreter that imports FastMCP. |+| `conformance` | MCP conformance tests requiring Node.js and npx. |-There is no root-cause diagnosis behind this fix, only a plausible one. During validation, one Windows run genuinely crashed a worker on `test_fastmcp_imports_without_legacy_httpx` β a fresh-interpreter test β with pytest-xdist reporting `worker 'gw1' crashed while running '...'` after execnet's channel saw `ConnectionResetError: [WinError 10054]`. Nothing in that log says *why* the worker died: memory exhaustion, handle exhaustion, and some Windows-specific `subprocess`/`execnet` interaction are all still consistent with what was observed. Marking the fresh-interpreter tests `subprocess_heavy` made the crash stop recurring, but "it stopped" is not the same as "we know why."+The [pytest CI action](https://github.com/PrefectHQ/fastmcp/blob/main/.github/actions/run-pytest/action.yml) runs `client_process` and `subprocess_heavy` serially and excludes them from parallel unit tests. A minimal stdlib subprocess does not need `subprocess_heavy` merely because it is a subprocess. Use the marker when the fresh interpreter imports FastMCP.-Treat the next Windows worker crash as a test of this diagnosis. **If it lands on a test that is not a fresh-interpreter spawner, the `subprocess_heavy` theory was wrong** β the real problem is subprocess-under-xdist on Windows more generally, and isolating one marker's worth of tests was never going to fix that. The fallback is one conditional back in `run-pytest/action.yml`, restoring the pre-#4554 behavior:+A marker selects a CI group; it does not itself change the local timeout. To reproduce the integration group's timeout locally:```bash-PARALLEL_FLAGS=""-if [ "$MAX_PROCS" != "0" ] && [ "${{ runner.os }}" != "Windows" ]; then- PARALLEL_FLAGS="--numprocesses auto --maxprocesses $MAX_PROCS --dist worksteal"-fi+uv run pytest -m integration --timeout=30 -n 0```-#### Two traps that aren't Windows-specific+## Write a regression that proves the contract-Two test-authoring bugs surfaced while validating this change. Neither is about Windows or parallelism, but both are worth watching for anywhere a real `sleep()` gets replaced with a wait:+First establish the promised behavior from the public API, docs, protocol, and relevant maintainer decisions. A reproducible result is not automatically a bug. Once the contract is clear, run the regression on the unchanged base and confirm that it fails for the intended reason, then run it with the fix. An import error or broken fixture is not evidence of the reported defect.-- **Match the wait condition to the assertion.** A test waited for "any callback fired," then asserted that a `completed` callback existed. That races, because an earlier `working` notification satisfies the wait before the `completed` one arrives. A deterministic wait is only as good as the condition it waits on β wait for the thing you actually assert.-- **Don't assert on incidental timing.** A crash-recovery test asserted "at least one concurrent request fails" while a subprocess restarts, which quietly depended on the restart being slow. Once restart got faster, recovery could beat every in-flight request and the test started failing because the behavior *improved*. Assert the invariant instead: no hang, and no result served by the dead process.+Assert values and types that distinguish the correct result from the bug. For example, Python equality treats `True` and `1` as equal, so a JSON type-preservation test needs a type assertion too. Avoid assertions that only check whether some result exists when the result's contents are the contract.-## Writing Tests+Keep each test focused on one behavior, with as many assertions as that behavior needs. Parameterize variations of the same contract; separate unrelated cases. Include omitted defaults and explicit overrides when both enter the changed branch.+Use function-scoped setup and temporary paths so tests work independently and in parallel. Prefer events or waits for the exact condition being asserted to arbitrary sleeps. When diagnosing a failure, separate an assertion failure from a worker crash or infrastructure error; reproduce a supposedly pre-existing failure on the unchanged base before calling it unrelated.-### Test Requirements+## Test through an in-memory client-Following these practices creates maintainable, debuggable test suites that serve as both documentation and regression protection.+`Client(server)` exercises real FastMCP dispatch and protocol behavior without opening a socket. This complete test checks how arguments and results travel through the client:-#### Single Behavior Per Test+```python+from fastmcp import Client, FastMCP-Each test should verify exactly one behavior. When it fails, you need to know immediately what broke. A test that checks five things gives you five potential failure points to investigate. A test that checks one thing points directly to the problem.-<CodeGroup>+async def test_add_returns_sum() -> None:+ server = FastMCP("Calculator")-```python Good: Atomic Test-async def test_tool_registration():- """Test that tools are properly registered with the server."""- mcp = FastMCP("test-server")-- @mcp.tool+ @server.tooldef add(a: int, b: int) -> int:return a + b-- tools = mcp.list_tools()- assert len(tools) == 1- assert tools[0].name == "add"-```-```python Bad: Multi-Behavior Test-async def test_server_functionality():- """Test multiple server features at once."""- mcp = FastMCP("test-server")-- # Tool registration- @mcp.tool- def add(a: int, b: int) -> int:- return a + b-- # Resource creation- @mcp.resource("config://app")- def get_config():- return {"version": "1.0"}-- # Authentication setup- mcp.auth = BearerTokenProvider({"token": "user"})-- # What exactly are we testing? If this fails, what broke?- assert mcp.list_tools()- assert mcp.list_resources()- assert mcp.auth is not None+ async with Client(server) as client:+ result = await client.call_tool("add", {"a": 2, "b": 3})++ assert result.data == 5+ assert type(result.data) is int```-</CodeGroup>+Save examples as a test module in the repository and run them with `uv run pytest path/to/test_example.py -n 0`. Use the existing fixture patterns for the subsystem instead of mocking the FastMCP method under test.-#### Self-Contained Setup+### Failure behavior-Every test must create its own setup. Tests should be runnable in any order, in parallel, or in isolation. When a test fails, you should be able to run just that test to reproduce the issue.+Assert the exception users receive, including a meaningful message when that is part of the behavior:-<CodeGroup>+```python+import pytest-```python Good: Self-Contained-async def test_tool_execution_with_error():- """Test that tool errors are properly handled."""- mcp = FastMCP("test-server")-- @mcp.tool- def divide(a: int, b: int) -> float:+from fastmcp import Client, FastMCP+from fastmcp.exceptions import ToolError+++async def test_division_by_zero_is_reported() -> None:+ server = FastMCP("Calculator")++ @server.tool+ def divide(a: float, b: float) -> float:if b == 0:raise ValueError("Cannot divide by zero")return a / b-- async with Client(mcp) as client:- with pytest.raises(Exception):- await client.call_tool("divide", {"a": 10, "b": 0})-```-```python Bad: Test Dependencies-# Global state that tests depend on-test_server = None--def test_setup_server():- """Setup for other tests."""- global test_server- test_server = FastMCP("shared-server")--def test_server_works():- """Test server functionality."""- # Depends on test_setup_server running first- assert test_server is not None+ async with Client(server) as client:+ with pytest.raises(ToolError, match="Cannot divide by zero"):+ await client.call_tool("divide", {"a": 10, "b": 0})```-</CodeGroup>--#### Clear Intent+### Reusable fixtures-Test names and assertions should make the verified behavior obvious. A developer reading your test should understand what feature it validates and how that feature should behave.+Build the server in a fixture and manage the client context in the test. This keeps connection ownership and cleanup visible:```python-async def test_authenticated_tool_requires_valid_token():- """Test that authenticated users can access protected tools."""- mcp = FastMCP("test-server")- mcp.auth = BearerTokenProvider({"secret-token": "test-user"})-- @mcp.tool- def protected_action() -> str:- return "success"-- async with Client(mcp, auth=BearerAuth("secret-token")) as client:- result = await client.call_tool("protected_action", {})- assert result.content[0].text == "success"-```--#### Using Fixtures+import pytest-Use fixtures to create reusable data, server configurations, or other resources for your tests. Note that you should **not** open FastMCP clients in your fixtures as it can create hard-to-diagnose issues with event loops.+from fastmcp import Client, FastMCP-```python-import pytest-from fastmcp import FastMCP, Client@pytest.fixture-def weather_server():- server = FastMCP("WeatherServer")-- @server.tool- def get_temperature(city: str) -> dict:- temps = {"NYC": 72, "LA": 85, "Chicago": 68}- return {"city": city, "temp": temps.get(city, 70)}-- return server+def weather_server() -> FastMCP:+ server = FastMCP("Weather")-async def test_temperature_tool(weather_server):- async with Client(weather_server) as client:- result = await client.call_tool("get_temperature", {"city": "LA"})- assert result.data == {"city": "LA", "temp": 85}-```+ @server.tool+ def temperature(city: str) -> int:+ return {"NYC": 72, "LA": 85}[city]-#### Effective Assertions+ return server-Assertions should be specific and provide context on failure. When a test fails during CI, the assertion message should tell you exactly what went wrong.-```python-# Basic assertion - minimal context on failure-assert result.status == "success"[email protected](("city", "expected"), [("NYC", 72), ("LA", 85)])+async def test_temperature(weather_server: FastMCP, city: str, expected: int) -> None:+ async with Client(weather_server) as client:+ result = await client.call_tool("temperature", {"city": city})-# Better - explains what was expected-assert result.status == "success", f"Expected successful operation, got {result.status}: {result.error}"+ assert result.data == expected```-Try not to have too many assertions in a single test unless you truly need to check various aspects of the same behavior. In general, assertions of different behaviors should be in separate tests.--#### Inline Snapshots+### Schema snapshots-FastMCP uses `inline-snapshot` for testing complex data structures. On first run of `pytest --inline-snapshot=create` with an empty `snapshot()`, pytest will auto-populate the expected value. To update snapshots after intentional changes, run `pytest --inline-snapshot=fix`. This is particularly useful for testing JSON schemas and API responses.+Use the repository's `inline-snapshot` conventions for complex structures. Inspect each generated expectation against the contract before accepting it. This example checks the schema returned through the protocol:```pythonfrom inline_snapshot import snapshot-async def test_tool_schema_generation():- """Test that tool schemas are generated correctly."""- mcp = FastMCP("test-server")-- @mcp.tool- def calculate_tax(amount: float, rate: float = 0.1) -> dict:- """Calculate tax on an amount."""- return {"amount": amount, "tax": amount * rate, "total": amount * (1 + rate)}-- tools = mcp.list_tools()- schema = tools[0].input_schema-- # First run: snapshot() is empty, gets auto-populated- # Subsequent runs: compares against stored snapshot- assert schema == snapshot({- "type": "object",- "properties": {- "amount": {"type": "number"},- "rate": {"type": "number", "default": 0.1}- },- "required": ["amount"]- })-```--### In-Memory Testing--FastMCP uses in-memory transport for testing, where servers and clients communicate directly. The majority of functionality can be tested in a deterministic fashion this way. We use more complex setups only when testing transports themselves.--The in-memory transport runs the real MCP protocol implementation without network overhead. Instead of deploying your server or managing network connections, you pass your server instance directly to the client. Everything runs in the same Python process - you can set breakpoints anywhere and step through with your debugger.+from fastmcp import Client, FastMCP-```python-from fastmcp import FastMCP, Client-# Create your server-server = FastMCP("WeatherServer")+async def test_tool_input_schema() -> None:+ server = FastMCP("Calculator")-def get_temperature(city: str) -> dict:- """Get current temperature for a city"""- temps = {"NYC": 72, "LA": 85, "Chicago": 68}- return {"city": city, "temp": temps.get(city, 70)}+ @server.tool+ def double(value: int) -> int:+ return value * 2-async def test_weather_operations():- # Pass server directly - no deployment neededasync with Client(server) as client:- result = await client.call_tool("get_temperature", {"city": "NYC"})- assert result.data == {"city": "NYC", "temp": 72}-```--This pattern makes tests deterministic and fast - typically completing in milliseconds rather than seconds.--### Mocking External Dependencies--FastMCP servers are standard Python objects, so you can mock external dependencies using your preferred approach:+ tools = await client.list_tools()-```python-from unittest.mock import AsyncMock--async def test_database_tool():- server = FastMCP("DataServer")-- # Mock the database- mock_db = AsyncMock()- mock_db.fetch_users.return_value = [- {"id": 1, "name": "Alice"},- {"id": 2, "name": "Bob"}- ]-- @server.tool- async def list_users() -> list:- return await mock_db.fetch_users()-- async with Client(server) as client:- result = await client.call_tool("list_users", {})- assert len(result.data) == 2- assert result.data[0]["name"] == "Alice"- mock_db.fetch_users.assert_called_once()+ assert tools[0].input_schema == snapshot(+ {+ "type": "object",+ "properties": {"value": {"type": "integer"}},+ "required": ["value"],+ "additionalProperties": False,+ }+ )```-### Testing Network Transports--In-memory testing covers most unit testing needs, but some behavior only exists over HTTP: middleware, authentication, session management, header handling, and SSE streaming. To test those, serve your server over HTTP with `asgi_client`.--#### Testing Over HTTP+The repository disables snapshot updates by default. For an intentional change, run the relevant module with `--inline-snapshot=fix` and review the diff. Use `--inline-snapshot=create` when populating a new empty snapshot.-<VersionBadge version="3.5.0" />+## Test HTTP behavior without a socket-`asgi_client` builds your server's real Starlette app, starts its lifespan, and hands you a connected `Client` that talks to it over the full HTTP stack. The one thing it skips is the socket: requests are dispatched straight into the ASGI application on the current event loop, so there is no port to bind, no uvicorn to start, and no connection to negotiate. Everything else β middleware, authentication, session management, SSE framing β runs exactly as it does in production.+Use `asgi_client` when the subject is HTTP routing, headers, authentication, or streaming. It builds the real application and starts its lifespan, then sends requests directly through ASGI in the same process:```pythonfrom fastmcp import FastMCPfrom fastmcp.utilities.tests import asgi_client-def create_test_server() -> FastMCP:- server = FastMCP("TestServer")++async def test_greet_over_http() -> None:+ server = FastMCP("Greeting")@server.tooldef greet(name: str) -> str:return f"Hello, {name}!"- return server+ async with asgi_client(server) as client:+ result = await client.call_tool("greet", {"name": "World"})-async def test_greet_over_http():- async with asgi_client(create_test_server()) as client:- greeting = await client.call_tool("greet", {"name": "World"})- assert greeting.data == "Hello, World!"+ assert result.data == "Hello, World!"```-Pass `transport="sse"` to exercise the SSE app instead of streamable HTTP, `path=` to serve on a custom path, `headers=` and `auth=` to configure the client's requests, and any other keyword argument to configure the `Client` itself.--```python-async def test_tenant_header_is_visible_to_tools():- async with asgi_client(- create_test_server(),- headers={"X-Tenant-ID": "acme"},- timeout=5,- ) as client:- await client.list_tools()-```+Pass `headers=` or `auth=` to configure requests, `path=` for a custom MCP route, or `transport="sse"` to exercise the SSE application. Other client options, such as `timeout=`, go to `Client`.-#### Sharing One Server Across Tests+### Multiple clients and raw requests-When several tests share a server but each needs its own client, use `asgi_server` in a fixture. It yields an `ASGIServer`, whose `client()` method produces a fresh client β with its own session β on demand.+Use `asgi_server` when a test needs several clients or raw HTTP responses. Each `client()` call creates its own client. `http_client()` returns an `httpx2.AsyncClient` bound to the same application; an ordinary network client cannot reach this in-process server.```python-import pytestfrom fastmcp import FastMCP-from fastmcp.utilities.tests import ASGIServer, asgi_server+from fastmcp.utilities.tests import asgi_server-async def http_server():- server = FastMCP("TestServer")-- @server.tool- def greet(name: str) -> str:- return f"Hello, {name}!"-- async with asgi_server(server) as running_server:- yield running_server--async def test_greet(http_server: ASGIServer):- async with http_server.client() as client:- greeting = await client.call_tool("greet", {"name": "World"})- assert greeting.data == "Hello, World!"--async def test_sessions_are_isolated(http_server: ASGIServer):- async with (- http_server.client(mode="legacy") as first,- http_server.client(mode="legacy") as second,- ):- assert await first.ping() is True- assert await second.ping() is True-```-Sessions belong to the handshake era of the MCP protocol, and so does `ping`, so a test that is about session behavior pins `mode="legacy"`. Every keyword argument `client()` doesn't consume itself is passed straight to `Client`. See [protocol negotiation](/clients/client#protocol-negotiation).+async def test_two_clients_share_the_application() -> None:+ server = FastMCP("Empty")-For assertions about raw HTTP β status codes, response headers, metadata endpoints β `http_client()` returns an `httpx.AsyncClient` bound to the same app. Because nothing is listening on the network, this is the only way to make raw requests; a plain `httpx.AsyncClient()` cannot reach the server.+ async with asgi_server(server) as running:+ async with running.client() as first, running.client() as second:+ assert await first.list_tools() == []+ assert await second.list_tools() == []-```python-async def test_unauthenticated_request_is_rejected(http_server: ASGIServer):- async with http_server.http_client() as http:- response = await http.post(http_server.url, json={"jsonrpc": "2.0", "id": 1})- assert response.status_code in (400, 401)+ async with running.http_client() as http:+ response = await http.get("/missing")+ assert response.status_code == 404```-If you need to build the client transport yourself, `transport()` returns a `StreamableHttpTransport` or `SSETransport` already wired to the in-process app.+A test specifically about legacy MCP sessions or `ping` should pass `mode="legacy"` to the client. The modern protocol era is sessionless; see [protocol negotiation](/clients/client#protocol-negotiation). For custom client transports, `running.transport()` returns a transport wired to the same application.-#### Testing on a Real Port+## Test external and process boundaries-<VersionBadge version="2.13.0" />+Mock external services at their boundary, while keeping the FastMCP path real. For outgoing HTTP requests, use `httpx2.MockTransport` and assert the method, URL, headers, or body that matter. Do not mock the framework function whose behavior the test is meant to verify.-`run_server_async` starts a real uvicorn server on a real TCP port as a task in the current process and yields its URL. Reach for it only when the subject of the test is the network itself β real sockets, TLS, or a server that must be reachable by something other than an in-process client.+Use `run_server_async` when the network itself is the subject: a socket, TLS, or a client outside the in-process application. It starts uvicorn in the current process and cleans it up on exit:```python-from fastmcp import FastMCP, Client+from fastmcp import Client, FastMCPfrom fastmcp.utilities.tests import run_server_async-async def test_server_binds_a_real_port():- server = FastMCP("TestServer")++async def test_server_accepts_network_requests() -> None:+ server = FastMCP("Empty")async with run_server_async(server) as url:- assert url.startswith("http://127.0.0.1:")async with Client(url) as client:assert await client.list_tools() == []```-#### Subprocess Testing (Special Cases)+Use `run_server_in_process` only when process isolation is part of the test. Follow nearby subprocess fixtures for startup, transport selection, and cleanup. Stdio lifecycle tests can use `tests/client/minimal_stdio_server.py` when a minimal MCP responder suffices; use a real FastMCP subprocess when its behavior is what you need to test.-For tests that require complete process isolation (like STDIO transport or testing subprocess behavior), use `run_server_in_process`:+## Check documentation examples-```python-import pytest-from fastmcp.utilities.tests import run_server_in_process-from fastmcp import FastMCP, Client-from fastmcp.client.transports import StreamableHttpTransport--def run_server(host: str, port: int) -> None:- """Function to run in subprocess."""- server = FastMCP("TestServer")-- @server.tool- def greet(name: str) -> str:- return f"Hello, {name}!"-- server.run(host=host, port=port)--async def http_server():- """Fixture that runs server in subprocess."""- with run_server_in_process(run_server, transport="http") as url:- yield f"{url}/mcp"--async def test_http_transport(http_server: str):- """Test actual HTTP transport behavior."""- async with Client(- transport=StreamableHttpTransport(http_server)- ) as client:- tools = await client.list_tools()- assert "greet" in [tool.name for tool in tools]-```--The `run_server_in_process` utility handles server lifecycle, port allocation, and cleanup automatically. Use this only when subprocess isolation is truly necessary, as it's slower and harder to debug than in-process testing. FastMCP uses the `client_process` marker to isolate these tests in CI.--### Documentation Testing--Documentation requires the same validation as code. The `just docs` command launches a local Mintlify server that renders your documentation exactly as users will see it:+Run the documentation checks from the repository root:```bash-# Start local documentation server with hot reload-just docs--# Or run Mintlify directly-mintlify dev+just docs-broken-links+uv run pytest tests/docs -n 0```-The local server watches for changes and automatically refreshes. This preview catches formatting issues and helps you see documentation as users will experience it.+The docs tests parse Python fences and resolve FastMCP imports. They do not execute every example or detect every missing non-import name, so run changed examples yourself. Use `just docs` to preview rendering. Without just, run `npx --yes mint@latest broken-links` or `npx --yes mint@latest dev` from `docs/`.++See the [Contributing Guide](/development/contributing#implement-and-verify) for the full checks required before committing.diff --git a/scripts/maintenance_status.py b/scripts/maintenance_status.pyindex 1c08e7402..ecb7119c0 100644--- a/scripts/maintenance_status.py+++ b/scripts/maintenance_status.py@@ -387,7 +387,7 @@ def build() -> dict:"automations": automations + operator_entries(),"needs_judgment": JUDGMENT,"docs": {- "maintaining": f"https://github.com/{REPO}/blob/main/MAINTAINING.md",+ "maintaining": f"https://github.com/{REPO}/blob/main/docs/development/contributing.mdx#maintenance-and-automation","agents": f"https://github.com/{REPO}/blob/main/AGENTS.md",},}@@ -407,7 +407,7 @@ def markdown(doc: dict) -> str:f"As of {doc['as_of']}. Generated twice a day by "f"[maintenance-status](https://github.com/{REPO}/actions/workflows/maintenance-status.yml); ""machine-readable as [status.json](status.json). "- f"How the project is run: [MAINTAINING.md]({doc['docs']['maintaining']}).",+ f"How the project is run: [Development guide]({doc['docs']['maintaining']}).","","| automation | state | last ok | runs on | cadence |","|---|---|---|---|---|",