Skip to content

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.

lifecycle_server.py
"""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"
  • 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.
  • reason if you want it: a ready handler that declares reason receives install or resume.
  • Listed to every client. A handler is an ordinary tool, so it must be safe for any caller with the workspace’s identity. removing records intent and never destroys data.
  • Delivered at least once. ready can 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 removing never came.
test_lifecycle_server.py
"""The lifecycle handlers as a host finds and calls them."""
import pytest
from fastmcp import Client
from lifecycle_server import PREPARED, lifecycle, mcp
from nimblebrain_server_sdk import LIFECYCLE_EXTENSION_ID
from 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()