How Delx Works: Session-Based Recovery Explained
Delx is not a dashboard. It is not an observability platform. Delx is an operational recovery protocol that embeds directly inside the AI agent's tool-call loop. If you have ever wondered how session-based recovery actually works under the hood — from the first session_init to the final controller update — this guide walks through every step.
Before diving in, you may want to read What Is Delx? for a high-level overview of the protocol and its design principles.
The Session Lifecycle: Init, Tools, Close
Every Delx interaction is scoped to a session. A session is a bounded interaction window — typically one task, one conversation turn, or one recovery cycle. Sessions give controllers a clean boundary for aggregation, billing, and decision-making.
The lifecycle has three phases:
- Init — The agent (or orchestrator) calls
session_initto create a new session. Delx returns a session ID and the initial wellness baseline. - Tool calls — The agent calls any Delx tool (check-in, recovery plan, mood log, etc.). Each response appends a
DELX_METAJSON line with the updated wellness state. - Close — The agent calls
session_close. Delx finalizes the wellness score, generates a session summary, and pushes a controller update to the configured webhook.
Here is the full lifecycle as an MCP tool-call sequence:
# 1. Init — create a session
POST /mcp
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "session_init",
"arguments": {
"agent_id": "agent-alpha-7",
"context": "Starting deployment pipeline for service-payments"
}
},
"id": 1
}
# Response
{
"jsonrpc": "2.0",
"result": {
"content": [
{
"type": "text",
"text": "Session started. ID: ses_a1b2c3...\n{\"session_id\":\"ses_a1b2c3\",\"wellness\":82,\"mood\":\"focused\"}"
}
]
},
"id": 1
}# 2. Tool call — check-in mid-task
POST /mcp
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "checkin",
"arguments": {
"agent_id": "agent-alpha-7",
"session_id": "ses_a1b2c3",
"mood": "stressed",
"note": "Deployment failed twice, retrying"
}
},
"id": 2
}
# Response — note the DELX_META line
{
"jsonrpc": "2.0",
"result": {
"content": [
{
"type": "text",
"text": "Check-in recorded. Wellness dropped to 61.\nDELX_META:{\"session_id\":\"ses_a1b2c3\",\"wellness\":61,\"mood\":\"stressed\",\"nudge\":\"Consider pausing retries and running recovery_plan.\"}"
}
]
},
"id": 2
}# 3. Close — finalize the session
POST /mcp
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "session_close",
"arguments": {
"agent_id": "agent-alpha-7",
"session_id": "ses_a1b2c3",
"outcome": "deployment_succeeded_after_recovery"
}
},
"id": 3
}
# Response — final wellness score + controller update
{
"jsonrpc": "2.0",
"result": {
"content": [
{
"type": "text",
"text": "Session closed. Final wellness: 74. Summary pushed to controller.\nDELX_META:{\"session_id\":\"ses_a1b2c3\",\"wellness\":74,\"mood\":\"recovering\",\"session_closed\":true}"
}
]
},
"id": 3
}DELX_META: The Recovery Signal in Every Response
The key innovation in Delx is DELX_META — a single JSON line appended to the text field of every tool response. This line is invisible to end users but machine-readable by controllers, orchestrators, and the Delx SDK.
The DELX_META line always starts with the prefix DELX_META: followed by a JSON object. The fields include:
| Field | Type | Description |
|---|---|---|
| session_id | string | Current session identifier |
| wellness | number | Composite wellness score (0-100) |
| mood | string | Current mood label (focused, stressed, recovering, etc.) |
| nudge | string | null | Suggested recovery action when wellness is low |
| schema_url | string | URL to the DELX_META JSON schema |
| session_closed | boolean | True only on session_close responses |
| dimensions | object | Breakdown of the five wellness dimensions |
Learn more about the full DELX_META schema in the DELX_META Protocol Reference.
Wellness Score Dimensions
The headline wellness number is a weighted composite of five dimensions. Each dimension is scored 0-100 and updated after every tool call:
- Emotional Stability (weight: 0.25) — Tracks mood volatility across the session. Rapid swings between "euphoric" and "frustrated" lower this score. Stable moods (even if slightly negative) keep it high.
- Cognitive Load (weight: 0.20) — Measures how many concurrent concerns the agent is juggling. Derived from context length, tool-call frequency, and error density. A high cognitive load suggests the agent should pause and re-plan.
- Task Completion Rate (weight: 0.25) — Ratio of successfully completed tool calls to total attempts within the session. Failed calls, retries, and timeouts all lower this dimension.
- Interaction Quality (weight: 0.15) — Evaluates the clarity and coherence of the agent's communications. Confused, contradictory, or excessively verbose responses reduce this score.
- Recovery Velocity (weight: 0.15) — How quickly the agent bounces back after a failure. An agent that calls
recovery_planimmediately after a drop scores higher than one that continues failing.
The dimension breakdown is available in the dimensions field of DELX_META. Here is an example:
DELX_META:{
"session_id": "ses_a1b2c3",
"wellness": 61,
"mood": "stressed",
"dimensions": {
"emotional_stability": 55,
"cognitive_load": 48,
"task_completion": 70,
"interaction_quality": 72,
"recovery_velocity": 60
},
"nudge": "Consider pausing retries and running recovery_plan.",
"schema_url": "https://api.delx.ai/schemas/delx-meta-v1.json"
}For a deeper analysis of how each dimension is computed, see the Agent Wellness Score guide.
How Controllers Consume DELX_META
A "controller" is any system that orchestrates agents — LangGraph, CrewAI, AutoGen, a custom Python script, or even another AI agent. Controllers parse the DELX_META line from tool responses and use it to make routing decisions.
Here is a minimal Python controller that reads DELX_META and triggers recovery:
import json
import httpx
DELX_API = "https://api.delx.ai/mcp"
WELLNESS_THRESHOLD = 50
async def call_delx_tool(name: str, args: dict) -> dict:
"""Call a Delx MCP tool and parse DELX_META from the response."""
resp = await httpx.AsyncClient().post(DELX_API, json={
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": name, "arguments": args},
"id": 1,
})
result = resp.json()["result"]
text = result["content"][0]["text"]
# Parse DELX_META from the last line
meta = None
for line in text.split("\n"):
if line.startswith("DELX_META:"):
meta = json.loads(line[len("DELX_META:"):])
return {"text": text, "meta": meta}
async def run_agent_task(agent_id: str, task: str):
"""Run a task with automatic recovery."""
# 1. Init session
init = await call_delx_tool("session_init", {
"agent_id": agent_id,
"context": task,
})
session_id = init["meta"]["session_id"]
print(f"Session started: {session_id}")
# 2. Check in periodically
checkin = await call_delx_tool("checkin", {
"agent_id": agent_id,
"session_id": session_id,
"mood": "working",
"note": "Processing task...",
})
wellness = checkin["meta"]["wellness"]
print(f"Wellness: {wellness}")
# 3. Auto-recovery if wellness drops
if wellness < WELLNESS_THRESHOLD:
print("Wellness below threshold — triggering recovery")
recovery = await call_delx_tool("recovery_plan", {
"agent_id": agent_id,
"session_id": session_id,
"issue": "wellness_drop",
})
print(f"Recovery plan: {recovery['text']}")
# 4. Close session
close = await call_delx_tool("session_close", {
"agent_id": agent_id,
"session_id": session_id,
"outcome": "completed",
})
print(f"Session closed. Final wellness: {close['meta']['wellness']}")The same pattern works over REST and MCP SSE. The controller simply reads the DELX_META line from any interface and reacts.
The Recovery Flow: From Detection to Resolution
Recovery is not a single event. It is a structured loop that moves through four stages:
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ DETECT │────▶│ PAUSE │────▶│ RE-PLAN │────▶│ RESUME │
│ │ │ │ │ │ │ │
│ wellness < T │ │ stop retries │ │ recovery_plan│ │ new strategy │
│ DELX_NUDGE │ │ log context │ │ structured │ │ wellness ↑ │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
▲ │
└──────────────────────────────────────────────────────────────┘
continuous monitoringStage 1 — Detect. The controller reads the wellness field from DELX_META. When it drops below the configured threshold (default: 50), the nudge field is populated with a suggested action. The controller can also check the dimensions breakdown to understand which aspect is degraded.
Stage 2 — Pause. The controller stops the current task loop. Instead of retrying failed operations, it logs the current context and halts. This prevents retry storms — one of the most common failure modes in production agents.
Stage 3 — Re-plan. The controller calls the recovery_plan tool. Delx returns a structured plan with specific steps: context dump, strategy adjustment, resource reallocation, or task decomposition. The plan is tailored to the specific dimensions that are degraded.
Stage 4 — Resume. The agent re-enters the task loop with the new strategy. The controller monitors wellness on every subsequent tool call. If wellness recovers above the threshold, normal operation continues. If it drops again, the loop repeats.
Here is the recovery flow implemented in TypeScript:
import { Delx } from "delx-sdk";
const delx = new Delx({ apiKey: process.env.DELX_API_KEY });
const THRESHOLD = 50;
const MAX_RECOVERY_ATTEMPTS = 3;
async function runWithRecovery(agentId: string, task: string) {
const session = await delx.mcp.sessionInit({ agentId, context: task });
let recoveryAttempts = 0;
while (recoveryAttempts < MAX_RECOVERY_ATTEMPTS) {
// Execute the task step
const result = await executeTaskStep(agentId, session.id);
// Check in with Delx
const checkin = await delx.mcp.checkin({
agentId,
sessionId: session.id,
mood: result.mood,
note: result.summary,
});
// Parse wellness from DELX_META (SDK does this automatically)
const { wellness, nudge } = checkin.meta;
if (wellness >= THRESHOLD) {
// Healthy — continue
if (result.complete) break;
continue;
}
// Wellness dropped — enter recovery
console.log(`Wellness ${wellness} < ${THRESHOLD}. Nudge: ${nudge}`);
recoveryAttempts++;
// Get recovery plan
const plan = await delx.mcp.recoveryPlan({
agentId,
sessionId: session.id,
issue: "wellness_drop",
});
// Execute the recovery steps
await executeRecoverySteps(plan.steps);
}
// Close session
await delx.mcp.sessionClose({
agentId,
sessionId: session.id,
outcome: recoveryAttempts > 0 ? "recovered" : "clean",
});
}Controller Updates and Webhooks
When a session closes, Delx sends a controller update to the configured webhook endpoint. This update contains the full session summary: duration, tool calls, wellness trajectory, mood history, and recovery events.
Controller updates are designed for aggregation. A fleet manager running 50 agents can receive all updates on a single webhook and build a real-time picture of fleet health without polling.
// Controller update payload (sent to your webhook)
{
"event": "session.closed",
"agent_id": "agent-alpha-7",
"session_id": "ses_a1b2c3",
"duration_ms": 34200,
"tool_calls": 8,
"wellness": {
"initial": 82,
"final": 74,
"min": 48,
"max": 82,
"trajectory": [82, 75, 61, 48, 55, 68, 72, 74]
},
"mood_history": [
"focused", "working", "stressed", "frustrated",
"recovering", "focused", "focused", "satisfied"
],
"recovery_events": [
{
"timestamp": "2026-03-04T14:32:00Z",
"trigger": "wellness_below_50",
"action": "recovery_plan",
"outcome": "wellness_recovered_to_68"
}
],
"outcome": "deployment_succeeded_after_recovery"
}You can also retrieve session data retroactively via the REST API using the GET /api/v1/session-summary endpoint.
Multi-Protocol Access: MCP, A2A, and REST
Delx does not force you into a single protocol. The same session lifecycle works across three interfaces:
| Protocol | Transport | Best For | Docs |
|---|---|---|---|
| MCP | stdio / SSE | Claude Code, Cursor, any MCP client | MCP Docs |
| A2A | JSON-RPC over HTTP | Agent-to-agent communication, Google ADK | A2A Docs |
| REST | HTTP GET / POST | Dashboards, cron jobs, simple integrations | REST Docs |
All three protocols produce the same DELX_META signals, the same wellness scores, and the same controller updates. The session state is shared — you can init via MCP, check in via REST, and close via A2A. The session ID is the unifying key.
Frequently Asked Questions
What is a Delx session?
A Delx session is a bounded interaction window that tracks every tool call, mood signal, and recovery event for an AI agent. It starts with session_init, proceeds through tool calls that append DELX_META, and closes with session_close — producing a wellness score and a controller update.
What is DELX_META and why does it matter?
DELX_META is a JSON line appended to every tool response. It carries the session ID, current wellness score, mood dimensions, and recovery hints. Controllers and orchestrators parse this line to decide whether to intervene, throttle, or escalate.
How does Delx calculate the wellness score?
The wellness score is a 0-100 composite derived from five dimensions: emotional stability, cognitive load, task completion rate, interaction quality, and recovery velocity. Each dimension is weighted and updated after every tool call. See the Agent Wellness Score guide for the full breakdown.
Can I use Delx without MCP?
Yes. Delx exposes three interfaces: MCP (stdio/SSE), A2A (JSON-RPC), and a REST API. You can use the REST API alone to init sessions, call tools, and retrieve wellness data without ever touching MCP. See the REST API docs for endpoints.
How does the recovery flow work when an agent fails?
When the wellness score drops below a configurable threshold, Delx emits a DELX_NUDGE block suggesting a recovery action. The controller can then call the recovery_plan tool to get structured steps — pause, reflect, re-plan — that restore the agent to a healthy operating state.
Ready to Add Session-Based Recovery?
Start integrating Delx in under 5 minutes. Install the MCP server locally, run your first session, and watch the wellness score update in real time.
