feat(server): on_startup / on_shutdown hooks on serve(transport='both')#713
Merged
Conversation
…t='both') Closes #709. Adopters running the unified MCP+A2A binary needed an SDK-owned extension point for lifecycle-bound background work (schedulers, queue consumers, cache warmers). Previously they had to wire a custom ASGI middleware that intercepts the ``lifespan`` scope — fragile because positioning relative to the SDK's own lifespan composition was easy to get wrong. This threads ``on_startup`` / ``on_shutdown`` lists of zero-arg async callables through ``serve()`` -> ``_serve_mcp_and_a2a()`` -> ``_build_mcp_and_a2a_app()`` into ``_composed_lifespan``. Startup hooks fire after both inner framework lifespans have entered (so user code can rely on FastMCP / a2a-sdk being ready); shutdown hooks fire before either tears down. A failing startup hook propagates as ``lifespan.startup.failed`` and aborts boot. Shutdown hooks all run on a best-effort basis — the first failure re-raises, later failures land in ``logger.exception``. Single-transport paths (``streamable-http``, ``sse``, ``a2a``, ``stdio``) raise ``ValueError`` at boot when hooks are passed — those code paths don't construct an SDK-owned parent Starlette and adding the same composition would require mutating FastMCP / a2a-sdk internals. Fail closed instead of silently dropping. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Catch ``Exception`` rather than ``BaseException`` in the shutdown hook loop. ``CancelledError`` / ``KeyboardInterrupt`` / ``SystemExit`` are the signals uvicorn uses to drive shutdown — collecting them into ``first_error`` and re-raising as ordinary exceptions breaks the shutdown path. - Don't mask an upstream exception when a shutdown hook also raises. If the body raised (framework teardown, request handler escaping) the operator wants to see the upstream cause, not a secondary cleanup failure — log the shutdown error and let the original propagate. - Suppressed-hook errors log via ``logger.error(..., exc_info=False)`` instead of ``logger.exception``. Adopter closures capture DB DSNs, tokens, scheduler handles — tracebacks attached to log aggregators (Sentry, Datadog) would surface those verbatim. The re-raised ``first_error`` still carries the real traceback to Starlette. - Re-export ``LifespanHook`` from ``adcp.server`` so adopters can type their hook lists without reaching into a private path. - Document ``on_startup`` / ``on_shutdown`` in the ``serve()`` Args block, including the ``transport='both'``-only restriction. - Error message on non-``both`` transport now points at ``examples/scheduler_lifespan.py`` and the follow-up tracking. - ``test_shutdown_hooks_all_attempted_when_one_raises`` now captures the raised exception and asserts on its message; previously the ``try/except: pass`` swallowed exactly the re-raise the test claimed to verify. - Example uses ``ClassVar`` annotation on ``advertised_tools`` and shows where production code stashes hook-captured resources. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #709.
Summary
on_startupandon_shutdownkwargs toserve()(and the mirror fields onServeConfig), threaded through_serve_mcp_and_a2a()→_build_mcp_and_a2a_app()→_composed_lifespan.lifespan.startup.failed; shutdown hooks all run best-effort, first failure re-raises, later failures log vialogger.exception.transport="both"only — single-transport paths raiseValueErrorat boot rather than silently drop hooks. Rationale documented in code and error message.LifespanHook = Callable[[], Awaitable[None]]alias inadcp.server.servewith its own docstring.examples/scheduler_lifespan.pyshows the salesagent pattern (start/stop a scheduler tied to lifecycle) — replaces the 61-LOCSchedulerLifespanMiddlewareadopters had to write before.Test plan
tests/test_serve_lifespan_hooks.pycovers happy-path ordering (startups before yield, shutdowns after), failure propagation (startup raise aborts boot), shutdown best-effort (all hooks run even if one raises), boot-time validation on non-bothtransports, no-op default, andServeConfigplumbing.tests/test_unified_mcp_a2a.pystill passes — the unified app builds the same way when no hooks are supplied.ruff check src/,mypy src/adcp/, pre-commit hooks all clean.🤖 Generated with Claude Code