Agent skill

MCP Session Lifecycle

by nteract in nteract/nteract

Understand the MCP server session lifecycle: proxy supervision, daemon watch loop, session state machine, rejoin/reconnect races, and room eviction.

BSD-3-ClauseAuto-check passedAgent Workflows

Install MCP Session Lifecycle

skills CLI
$ npx skills add nteract/nteract --skill mcp-session-lifecycle -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install nteract/nteract mcp-session-lifecycle --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/nteract/nteract.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/mcp-session-lifecycle .claude/skills/mcp-session-lifecycle && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
mcp-session-lifecycle
GitHub stars
179
Token cost
~3.5k tokens
SKILL.md length
1,677 words
Files
1
Skills in repo
10
Repo updated
First seen
Licence
BSD-3-Clause

At a glance

Understand the MCP server session lifecycle: proxy supervision, daemon watch loop, session state machine, rejoin/reconnect races, and room eviction.

  • Works in 5 steps: A daemon event wakes the watcher. Lagged… → A failed identity query alone is not… → Compare a live version with the startup… → …
  • Working on runt-mcp
  • SKILL.md covers Three Layers, Proxy Layer, Active and Parked Sessions and The Watch Loop State Machine, plus 7 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

MCP Session Lifecycle is an agent skill from nteract/nteract. Understand the MCP server session lifecycle: proxy supervision, daemon watch loop, session state machine, rejoin/reconnect races, and room eviction. Use when working on runt-mcp, runt-mcp-proxy, daemonwatch.rs, or any code that reads/writes the session Arc<RwLock<Option<NotebookSession.

Its SKILL.md is about 3.5k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Agent Workflows, covering MCP servers and Session handoff. It works with Model Context Protocol. The repository describes itself as: We're back! Now firing notebooks out of a t-shirt gun. The licence is BSD-3-Clause.

When your agent uses it

  • Working on runt-mcp
  • Any code that reads/writes the session Arc<RwLock<Option<NotebookSession

Example prompts

  • “/mcp-session-lifecycle”

Workflow steps

5 steps, taken from the first numbered list in SKILL.md.

  1. A daemon event wakes the watcher. Lagged delivery also requires a fresh
  2. A failed identity query alone is not proof of daemon loss. Without an
  3. Compare a live version with the startup baseline. A mismatch exits with 75;
  4. Remove active and parked local handles bound to a different incarnation, or
  5. Preserve the removed active session's best recovery target, preferring a

What it can do on your machine

Read from SKILL.md and the folder at commit 414222e. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

MCP Session Lifecycle loads about 3.5k tokens when it runs. Until then it costs about 78 tokens; SKILL.md has 1,677 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~78
When it runs · the whole SKILL.md, loaded when a task matches
~3.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from nteract/nteract at commit 414222e, republished under its BSD-3-Clause licence (© nteract). 1,677 words, ~3,475 tokens.

Download SKILL.mdSave it as .claude/skills/mcp-session-lifecycle/SKILL.md (or your agent's skills folder).
name
mcp-session-lifecycle
description
Understand the MCP server session lifecycle: proxy supervision, daemon watch loop, session state machine, rejoin/reconnect races, and room eviction. Use when working on runt-mcp, runt-mcp-proxy, daemon_watch.rs, or any code that reads/writes the session Arc<RwLock<Option<NotebookSession>>>.

MCP Session Lifecycle

Use this skill when debugging session state, changing reconnection logic, working on the proxy, or reasoning about races between background rejoin and user-initiated tool calls.

Source checkpoint: 2026-09-04 at 6bff3e7b. The decision record is docs/adr/mcp-session-lifecycle.md. Read the source functions below rather than copying an abbreviated session struct or reconnect algorithm.

Three Layers

  • Process supervision: installed nteract-mcp and development mcp-supervisor use the runt-mcp-proxy library to supervise a runt mcp child. The library is not an executable entrypoint.
  • MCP session state: the child owns one active NotebookSession, a bounded map of parked sessions, explicit activation generations, and the daemon watch loop.
  • Daemon room state: runtimed owns notebook rooms, runtime state, kernels, recovery, and peer accounting. Kernel teardown and room reaping are separate.

The shipped MCP entrypoints use stdio. Multiple MCP clients can run separate children against the same daemon, including the same notebook room. Concurrent requests on one stdio connection share that child's active slot; they are not independent MCP clients. The daemon's multiplexed notebook frames are a separate protocol, not an HTTP MCP endpoint.

Entry points: crates/runt/src/lib.rs, crates/nteract-mcp/src/lib.rs, and crates/mcp-supervisor/src/main.rs.

Proxy Layer

McpProxy::track_session and session::extract_session_id track one preferred restart target, despite the field name last_notebook_id:

  • Successful connect/create calls prefer the child's canonical file path for local file-backed notebooks, falling back to a UUID. Hosted targets retain their URL identity.
  • Successful save_notebook promotes a local UUID target to the saved path.
  • Disconnecting the active notebook clears the handoff. Disconnecting another parked notebook preserves it. Failed calls do not replace the target.
  • Restart re-resolves the child executable and seeds NTERACT_MCP_REJOIN_NOTEBOOK. It does not reconstruct the parked map.
  • Exit 75 is an intentional daemon-upgrade handoff, separate from the normal crash budget. Other restarts are subject to the proxy's restart controls.
  • Daemon-version banners compare the old and new child's reported ServerInfo.server_info.title, not binary SHA. A banner says rejoin was requested; it does not prove that notebook readiness has completed.
  • The reconnect tool restarts the child, not the daemon.

See crates/runt-mcp-proxy/src/session.rs:17, crates/runt-mcp-proxy/src/proxy.rs:310, :962, and :1268. A closed-child forwarding failure is retried once; this is not an exactly-once mutation guarantee (proxy.rs:658).

Active and Parked Sessions

NteractMcp holds the active slot and parked map in crates/runt-mcp/src/lib.rs:119. NotebookSession in crates/runt-mcp/src/session.rs carries the handle, target, activation identity, readiness evidence, and local daemon incarnation when applicable.

Switching targets parks the previous peer instead of immediately disconnecting it. MAX_PARKED_SESSIONS is eight; overflow removes an entry by arbitrary HashMap iteration order. Parked peers keep their rooms from reaching zero peers, so they can keep kernels alive. Local switch-back establishes a fresh activation and removes the old parked peer after successful publication; parked-handle reuse is not a universal reconnect contract.

Most notebook tools operate on the active target. Exceptions include explicit parked-session disconnect and notebook-ID resource reads against connected or parked local sessions. A parked map does not provide independent active tool contexts for multiple MCP clients.

See park_session, install_activated_session, and disconnect_notebook in crates/runt-mcp/src/tools/session.rs:74, :742, and :949, and handle_for_notebook in crates/runt-mcp/src/resources.rs:285.

The Watch Loop State Machine

crates/runt-mcp/src/daemon_watch.rs:238 reconciles session ownership against a live daemon incarnation (pid + started_at), not a disconnect latch:

  1. A daemon event wakes the watcher. Lagged delivery also requires a fresh observation. The watcher directly calls query_daemon_info(socket_path); it does not decide from DaemonConnection's cached heartbeat info.
  2. A failed identity query alone is not proof of daemon loss. Without an explicit Disconnected event, defer reconciliation and retain the handles.
  3. Compare a live version with the startup baseline. A mismatch exits with 75; if startup had no daemon, the first live version establishes the baseline.
  4. Remove active and parked local handles bound to a different incarnation, or to no live incarnation after confirmed absence. Hosted sessions are excluded from this local ownership reconciliation.
  5. Preserve the removed active session's best recovery target, preferring a saved path. Local recovery requires a live daemon and empty slot; try the proxy handoff target first, then that preserved target.

Hosted proxy handoffs are attempted immediately at watcher entry, without a local daemon event or incarnation. Failed hosted recovery has a bounded retry timer independent of the local event stream. Both paths retain the explicit session intent epoch and publication slot guards; local recovery still checks daemon incarnation before and after connection/readiness.

A same-incarnation heartbeat leaves healthy bindings alone. A same-version restart changes incarnation and invalidates old local handles even if a Disconnected event was missed. Removing parked local handles does not enqueue recovery for every parked notebook.

See RecoveryState, reconcile_sessions, and watch. Focused tests in the same file cover same-incarnation heartbeats, lagged delivery, failed identity queries, stale parked handles, and tool-installed replacements.

The Session-Write Guard

Background rejoin connects outside the session lock. Local rejoin samples the expected daemon incarnation before and after connection/readiness. Then publish_rejoined_session checks the captured session_intent_epoch and slot emptiness under the same write lock that installs the session. Any already installed session wins, including one for the same notebook. Explicit disconnect advances the epoch under that lock so a completed background connection cannot resurrect the disconnected session.

Explicit connect/create activation has a separate generation owner: SessionActivation. Same-target in-flight connects share a result. Selecting a different canonical target supersedes the older attempt; A→B→A must not join stale A work. ActivationLease::install_in_slot_recovering rechecks ownership under the slot lock and restores the previous occupant if the installation commit is refused. A failed replacement does not invalidate the healthy installed session.

Use these production helpers, not a read-lock check followed by a separate write. See crates/runt-mcp/src/daemon_watch.rs:365, :493, :567, crates/runt-mcp/src/session_activation.rs:76, :225, and crates/runt-mcp/src/tools/session.rs:977.

Show full SKILL.md (768 more words)Show less

Session Access Pattern

An installed session is not a readiness guarantee. Acquire access through require_session_access! or require_handle! with the appropriate SessionRequirement. NteractMcp::session_access checks installed activation identity and delegates to NotebookSession::access; the returned handle is owned, so the slot lock is released before async work.

RequirementGate
ProjectionReadRetained projection or interactive document; use the bounded projection before interactivity
DocumentRead, DocumentMutationInteractive local document with the required readiness evidence
KernelControlInteractive document; a running kernel is not required to launch or restart it
RuntimeReadConnected, ready local RuntimeStateDoc
ExecuteInteractive document and ready runtime; execution keeps its causal required_heads gate

Retained projection reads do not authorize mutations or execution. Local sync failure, source degradation, runtime unreadiness, and superseded activation have distinct error paths. Use ensure_session_access_current after async work before continuing an operation on the captured active target. Do not keep a session lock across connection, file loading, projection, or sync waits.

See crates/runt-mcp/src/tools/mod.rs:18, crates/runt-mcp/src/lib.rs:273, crates/runt-mcp/src/session.rs:323, :485, and :595.

Local connect_notebook returns a retained control-plane projection while peers converge. create_notebook and background local rejoin still await session readiness. Do not apply the progressive-connect contract to all three paths. The response fields and historical API sketch are distinguished in docs/memos/mcp-connect-initial-projection.md.

Rejoin: File-Backed vs Ephemeral

Prefer a saved file path for automatic rejoin. The watcher verifies that the source file exists and calls connect_open(path). UUID-only attachment is also recoverable when the daemon has a resident room, a persistent UUID/path registry binding with available source, or a persisted untitled document. The registry is identity, not content: a missing source file is not permission to load a stale mirror or invent an empty notebook.

For a UUID target, call connect(uuid) and trust the daemon's attach-only admission. SyncError::NotebookUnavailable is definitive and records Evicted without retry. Do not use list_rooms as an existence precheck; an unlisted room may still be recoverable. Transient failures retain the recovery target for later attempts.

Daemon authority is not an atomic check-and-load guarantee. The legacy snapshot existence check at crates/runtimed/src/daemon.rs:3122 precedes awaited room creation. If that snapshot disappears and no journal is recovered, crates/runtimed/src/notebook_sync_server/room.rs:1945–1955 can create a fresh document. Keep this limitation distinct from the already-absent UUID refusal.

Persisted untitled notebooks are not the same as explicitly ephemeral notebooks. MCP create_notebook defaults to ephemeral=true; do not promise recovery after loss of its content merely because a UUID is known.

See crates/runtimed/src/daemon.rs:3041, crates/runt-mcp/src/daemon_watch.rs:485, :506, :615, and crates/runt-mcp/src/tools/session.rs:1602. The daemon integration tests at crates/runtimed/tests/integration.rs:4015 and :4054 cover refusal without a phantom room and saved-path recovery by UUID across restart.

Daemon Room Lifetime

Only the last peer leaving schedules kernel teardown, after keep_alive_secs (default 30 seconds). Room state, autosave, and file watchers remain resident. Teardown revalidates peer count and connection generation before destructive work; the destructive latch tells reconnecting peers not to reuse a doomed kernel.

The ghost-room reaper separately sweeps eligible peerless, kernel-less rooms every five minutes, with a 24-hour TTL and soft cap of 32. Removal requires the durability barrier and final admission checks; reconnects and reservations protect rooms from stale reaping decisions.

See crates/runtimed/src/notebook_sync_server/peer_eviction.rs:107, :269, and crates/runtimed/src/daemon.rs:484, :5834. Kernel teardown is not proof that a notebook has become unavailable.

Session Drop Tracking

last_session_drop is best-effort recovery context, not another session:

  • Switched: the old target was replaced and may still be parked.
  • Disconnected: stale local ownership was removed, recovery failed, or the user explicitly disconnected. Explicit disconnect cancels automatic rejoin.
  • Evicted: rejoin received a definitive unavailable refusal or found a missing saved source. It does not mean every kernel keepalive timeout deletes a room.

SessionDropInfo retains notebook ID, path, and rejoin target for no_session_error. See crates/runt-mcp/src/session.rs:636 and the recording sites in daemon_watch.rs and tools/session.rs.

Concurrent MCP Clients and Attribution

Separate MCP children sharing a daemon are implemented. Each child has its own active selection; the room can have multiple peers. The upstream handshake supplies the display label and an agent:<slug>:<session> operator suffix. The proxy preserves the suffix across child restarts. Attribution is not a separate authorization boundary for every same-user local client.

Multiple independently routed MCP clients inside one child are not implemented by the shipped stdio entrypoints. Neither concurrent request IDs nor parked notebooks provide that routing. See crates/runt-mcp/src/lib.rs:48, :119, :464, and crates/runt-mcp-proxy/src/proxy.rs:180, :227.

MCP Protocol Checkpoint

crates/mcp-transport/src/lib.rs supports both legacy initialize-based sessions and native MCP 2026-07-28 per-request negotiation. The first valid native request opens the lifecycle; invalid metadata must not start recovery or runtime setup. require_protocol, ProtocolSession::wait_for_native, and server_with_protocol keep the two modes distinct. A legacy initialized session cannot switch to native negotiation in place. Read this source and its wire tests before changing transport admission; support for the native lifecycle is not a blanket claim of complete protocol conformance.

© nteract, BSD-3-Clause. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .agents/skills/mcp-session-lifecycle of nteract/nteract.

Open the folder on GitHubat commit 414222e

Compare with similar skills

MCP Session Lifecycle next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

MCP Session Lifecycle compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
MCP Session Lifecycle this skillnteract/nteract179—~3.5kAutomated safety check: PassBSD-3-Clause
Memori MCP Memory UsageMemoriLabs/Memori17k—~3.8kAutomated safety check: PassMIT
Engraphis MemoryCoding-Dev-Tools/engraphis179—~3.7kAutomated safety check: PassApache-2.0
MemorixAVIDS2/memorix835—~516Automated safety check: PassApache-2.0
Engram MemoryPatdolitse/piia-engram162—~1.3kAutomated safety check: PassAGPL-3.0-or-later
Prism Startup Contextdcostenco/prism-coder157—~1.4kAutomated safety check: PassApache-2.0

Similar skills

  • Memori MCP Memory Usage

    MemoriLabs/Memori

    Teaches an MCP-connected agent when and how to call Memori's recall, summary, compaction, augmentation, feedback and quota tools to keep context across sessions.

    17k GitHub stars~3.8k tokensUpdated 5 days ago
    Agent WorkflowsAuto-check passed
  • Engraphis Memory

    Coding-Dev-Tools/engraphis

    Give the agent durable, scoped, explainable memory across sessions and repositories through the Engraphis MCP tools.

    179 GitHub stars~3.7k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Memorix

    AVIDS2/memorix

    A skill your agent uses when Claude Code needs Memorix shared memory, reasoning, Git Memory, mini-skills, session handoff, orchestration coordination, or integration troubleshooting.

    835 GitHub stars~516 tokensUpdated 6 days ago
    Agent WorkflowsAuto-check passed
  • Engram Memory

    Patdolitse/piia-engram

    Routes continuity and recall requests to Engram, a local-first MCP memory and identity layer that saves user-approved lessons, decisions and playbooks.

    162 GitHub stars~1.3k tokensUpdated 11 days ago
    Agent WorkflowsAuto-check passed
  • Prism Startup Context

    dcostenco/prism-coder

    Loads Prism session memory on the first user turn, greets the developer by their configured name and shows recent-session context at the configured depth.

    157 GitHub stars~1.4k tokensUpdated 3 days ago
    Agent WorkflowsAuto-check passed
  • Slm Mesh

    qualixar/superlocalmemory

    Cross-session peer coordination via the SLM mesh network. An agent skill from qualixar/superlocalmemory.

    227 GitHub stars~2.1k tokensUpdated today
    Agent WorkflowsAuto-check: notes

More from nteract/nteract

All 10 skills in this repo
  • Automerge Sync

    nteract/nteract

    Automerge sync protocol internals, document model (OpSet, ChangeGraph, fork/merge, save/load lifecycle), and higher-level protocol design patterns.

    179 GitHub stars~4.5k tokensUpdated today
    Auto-check passed
  • Daemon Dev

    nteract/nteract

    Develop, debug, and manage the runtimed daemon, Python bindings, and build system.

    179 GitHub stars~3k tokensUpdated today
    Auto-check passed
  • Execution Pipeline

    nteract/nteract

    The end-to-end cell execution pipeline from MCP tool call through daemon to kernel and back.

    179 GitHub stars~2.7k tokensUpdated today
    Auto-check passed
  • Nteract Diagnostics

    nteract/nteract

    Pull and triage submitted nteract diagnostics archives from Cloudflare using a diagnostics id/token.

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Repl

    nteract/nteract

    Use nteract notebooks as a persistent Python REPL. An agent skill from nteract/nteract.

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Testing

    nteract/nteract

    Run tests, verify changes, and collect diagnostics. An agent skill from nteract/nteract.

    179 GitHub stars~2.2k tokensUpdated today
    Auto-check passed

Categories

Questions about MCP Session Lifecycle

What does MCP Session Lifecycle do?

Understand the MCP server session lifecycle: proxy supervision, daemon watch loop, session state machine, rejoin/reconnect races, and room eviction. MCP Session Lifecycle is an agent skill from nteract/nteract. Understand the MCP server session lifecycle: proxy supervision, daemon watch loop, session state machine, rejoin/reconnect races, and room eviction.

When should I use MCP Session Lifecycle?

MCP Session Lifecycle fits situations like: working on runt-mcp; any code that reads/writes the session Arc<RwLock<Option<NotebookSession.

How do I install MCP Session Lifecycle in Claude Code?

Run `npx skills add nteract/nteract --skill mcp-session-lifecycle -a claude-code`. Or copy the skill folder (.agents/skills/mcp-session-lifecycle in nteract/nteract) into .claude/skills/mcp-session-lifecycle in your project. Claude Code loads it when a task matches its description.

How do I install MCP Session Lifecycle in Codex?

Run `npx skills add nteract/nteract --skill mcp-session-lifecycle -a codex`. Or copy the skill folder (.agents/skills/mcp-session-lifecycle in nteract/nteract) into .agents/skills/mcp-session-lifecycle in your project. Codex loads it when a task matches its description.

Can I use MCP Session Lifecycle in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add nteract/nteract --skill mcp-session-lifecycle -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/mcp-session-lifecycle, .gemini/skills/mcp-session-lifecycle, .github/skills/mcp-session-lifecycle and .opencode/skills/mcp-session-lifecycle in your project.

What does MCP Session Lifecycle need to run?

SKILL.md names no scripts, command-line tools or credentials: MCP Session Lifecycle is instructions for the agent only.

Does MCP Session Lifecycle access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is MCP Session Lifecycle safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does MCP Session Lifecycle use?

MCP Session Lifecycle is published under the BSD-3-Clause licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does MCP Session Lifecycle use?

About 3.5k tokens (SKILL.md is roughly 14k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to MCP Session Lifecycle?

Skills that share tags, products or a category with MCP Session Lifecycle: Memori MCP Memory Usage (MemoriLabs/Memori, 17k stars), Engraphis Memory (Coding-Dev-Tools/engraphis, 179 stars), Memorix (AVIDS2/memorix, 835 stars) and Engram Memory (Patdolitse/piia-engram, 162 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains MCP Session Lifecycle?

nteract (a GitHub organization) maintains it in nteract/nteract, which has 179 GitHub stars. The repository holds 10 skills in this directory. The repository was last updated on October 7, 2026.

Source: nteract/nteract on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.