Lifecycle
ai.nimblebrain/lifecycle tells a server it has been made available to a workspace (ready) and that it is about to be removed (removing). The protocol, its delivery guarantees and what the user sees are in the lifecycle extension. The SDK advertises the extension and marks one tool per event.
"""A server the host tells when a workspace gains it and when it is about to be removed."""
from fastmcp import FastMCP
from nimblebrain_server_sdk import CHANGES, add_lifecycle_extension
mcp = FastMCP("notes")lifecycle = add_lifecycle_extension(mcp)
PREPARED: set[str] = set()
@lifecycle.handler("ready", annotations=CHANGES)async def workspace_ready(reason: str | None = None) -> str: """Prepare this workspace. `reason` is `install` or `resume`.""" PREPARED.add("workspace") # idempotent: the host may deliver `ready` more than once return f"ready ({reason or 'unspecified'})"
@lifecycle.handler("removing", annotations=CHANGES)async def workspace_removing() -> str: """Record that this workspace is being removed. Never destroy data here.""" PREPARED.discard("workspace") return "removal recorded"The rules
Section titled “The rules”- Refused at import: a handler that requires an argument, or a second handler for one event.
- Synchronous: a handler is registered without task support, since the host calls it directly and waits.
reasonif you want it: areadyhandler that declaresreasonreceivesinstallorresume.- Listed to every client. A handler is an ordinary tool, so it must be safe for any caller with the workspace’s identity.
removingrecords intent and never destroys data. - Delivered at least once.
readycan arrive twice on a fresh install. Make each handler idempotent. - Not correct by the events alone. Most MCP hosts never send them. Set up lazily on first use too, and sweep for state whose
removingnever came.
Test it
Section titled “Test it”"""The lifecycle handlers as a host finds and calls them."""
import pytestfrom fastmcp import Clientfrom lifecycle_server import PREPARED, lifecycle, mcp
from nimblebrain_server_sdk import LIFECYCLE_EXTENSION_IDfrom nimblebrain_server_sdk.testing import Mode
@pytest.mark.parametrize("mode", ["auto", "legacy"])async def test_the_host_finds_each_handler_by_its_marker_and_calls_it(mode: Mode) -> None: assert lifecycle.handlers == {"ready": "workspace_ready", "removing": "workspace_removing"} async with Client(mcp, mode=mode) as client: marked = { tool.meta[LIFECYCLE_EXTENSION_ID]["event"]: tool.name for tool in await client.list_tools() if tool.meta and LIFECYCLE_EXTENSION_ID in tool.meta } assert marked == lifecycle.handlers ready = await client.call_tool(marked["ready"], {"reason": "install"}) assert ready.data == "ready (install)" assert PREPARED == {"workspace"} await client.call_tool(marked["removing"], {}) assert PREPARED == set()Related
Section titled “Related”- Lifecycle extension: delivery, failure semantics, and why a handler must be safe for any caller
- API reference