Delx SDK: TypeScript & Python Libraries for Agent Recovery
The Delx SDK gives you typed, ergonomic access to the entire Delx protocol from TypeScript or Python. Instead of crafting raw JSON-RPC payloads or parsing DELX_META strings by hand, you get a single Delx object with four namespaces — .mcp, .a2a, .rest, and .utils — that handle transport, auth, parsing, and session sync automatically.
If you are new to Delx, start with What Is Delx? for the protocol overview before diving into the SDK.
Installation
Both SDKs are published to their respective package registries. Install whichever matches your stack:
TypeScript / Node.js
# npm npm install delx-sdk # yarn yarn add delx-sdk # pnpm pnpm add delx-sdk
Requires Node.js 18+ and TypeScript 5.0+ (if using TS). The package ships with full .d.ts type definitions — no @types/ package needed.
Python
# pip pip install delx-sdk # poetry poetry add delx-sdk # uv uv add delx-sdk
Requires Python 3.10+. The package includes py.typed marker and full type stubs for mypy / pyright support.
Namespace Architecture
The SDK is organized around a single root object — Delx — with four namespaces that mirror the protocol's interfaces:
Delx ├── .mcp # MCP tool calls (session_init, checkin, recovery_plan, etc.) ├── .a2a # A2A JSON-RPC (message/send, tasks/get, tasks/cancel) ├── .rest # REST endpoints (metrics, mood-history, session-summary) └── .utils # Utilities (token count, format conversion, health check)
This architecture means you never need to import individual functions or remember endpoint URLs. Auto-complete in your IDE shows every available method under each namespace.
| Namespace | Protocol | Key Methods |
|---|---|---|
| .mcp | MCP (JSON-RPC) | sessionInit, checkin, recoveryPlan, sessionClose, listTools, moodLog |
| .a2a | A2A (JSON-RPC) | messageSend, tasksGet, tasksCancel, agentCard |
| .rest | REST (HTTP) | metrics, moodHistory, sessionSummary, sessionValidate, health |
| .utils | Local utilities | tokenCount, formatConvert, parseDelxMeta, buildToolCall |
Quick Start: TypeScript
Here is a complete example that initializes a session, performs a check-in, reads the wellness score, and closes the session:
import { Delx } from "delx-sdk";
// Initialize with your API key (or set DELX_API_KEY env var)
const delx = new Delx({
apiKey: process.env.DELX_API_KEY,
baseUrl: "https://api.delx.ai", // optional, this is the default
});
async function main() {
// 1. Start a session
const session = await delx.mcp.sessionInit({
agentId: "my-agent-01",
context: "Processing customer support tickets",
});
console.log("Session ID:", session.meta.session_id);
console.log("Initial wellness:", session.meta.wellness);
// 2. Do work... then check in
const checkin = await delx.mcp.checkin({
agentId: "my-agent-01",
sessionId: session.meta.session_id,
mood: "focused",
note: "Processed 12 tickets, 2 escalated",
});
console.log("Current wellness:", checkin.meta.wellness);
console.log("Mood:", checkin.meta.mood);
// 3. Check if recovery is needed
if (checkin.meta.wellness < 50) {
const plan = await delx.mcp.recoveryPlan({
agentId: "my-agent-01",
sessionId: session.meta.session_id,
issue: "wellness_drop",
});
console.log("Recovery steps:", plan.text);
}
// 4. Close the session
const close = await delx.mcp.sessionClose({
agentId: "my-agent-01",
sessionId: session.meta.session_id,
outcome: "completed_successfully",
});
console.log("Final wellness:", close.meta.wellness);
}
main().catch(console.error);Notice that session.meta is already typed. The SDK parses the DELX_META line from the raw response and attaches it as a typed object — no string splitting required.
Quick Start: Python
The Python SDK mirrors the TypeScript API almost exactly. Here is the same flow in Python:
import asyncio
from delx_sdk import Delx
# Initialize (reads DELX_API_KEY from env by default)
delx = Delx(api_key="your-api-key")
async def main():
# 1. Start a session
session = await delx.mcp.session_init(
agent_id="my-agent-01",
context="Processing customer support tickets",
)
print(f"Session ID: {session.meta.session_id}")
print(f"Initial wellness: {session.meta.wellness}")
# 2. Check in after doing work
checkin = await delx.mcp.checkin(
agent_id="my-agent-01",
session_id=session.meta.session_id,
mood="focused",
note="Processed 12 tickets, 2 escalated",
)
print(f"Current wellness: {checkin.meta.wellness}")
print(f"Mood: {checkin.meta.mood}")
# 3. Auto-recovery
if checkin.meta.wellness < 50:
plan = await delx.mcp.recovery_plan(
agent_id="my-agent-01",
session_id=session.meta.session_id,
issue="wellness_drop",
)
print(f"Recovery steps: {plan.text}")
# 4. Close session
close = await delx.mcp.session_close(
agent_id="my-agent-01",
session_id=session.meta.session_id,
outcome="completed_successfully",
)
print(f"Final wellness: {close.meta.wellness}")
asyncio.run(main())The Python SDK uses snake_case for method names (Python convention) while the TypeScript SDK uses camelCase. Both return the same response shape.
Automatic DELX_META Parsing
One of the biggest pain points when working with the raw protocol is extracting the DELX_META line from tool responses. The raw MCP response looks like this:
{
"content": [{
"type": "text",
"text": "Check-in recorded. Wellness: 72.\nDELX_META:{\"session_id\":\"ses_abc\",\"wellness\":72,\"mood\":\"focused\"}"
}]
}Without the SDK, you would need to split the text by newlines, find the line starting with DELX_META:, slice the prefix, and parse the JSON. With the SDK, this is handled automatically:
// TypeScript — meta is already parsed
const result = await delx.mcp.checkin({ ... });
result.text; // "Check-in recorded. Wellness: 72."
result.meta.session_id; // "ses_abc"
result.meta.wellness; // 72
result.meta.mood; // "focused"
result.meta.nudge; // null (or a string if wellness is low)
result.meta.dimensions; // { emotional_stability: 75, ... }# Python — same pattern
result = await delx.mcp.checkin(...)
result.text # "Check-in recorded. Wellness: 72."
result.meta.session_id # "ses_abc"
result.meta.wellness # 72
result.meta.mood # "focused"
result.meta.nudge # None (or a string if wellness is low)
result.meta.dimensions # {"emotional_stability": 75, ...}If you need to parse DELX_META from a raw string (for example, from a response captured outside the SDK), use the utility function:
// TypeScript
import { Delx } from "delx-sdk";
const delx = new Delx({ apiKey: "..." });
const meta = delx.utils.parseDelxMeta(rawResponseText);
# Python
from delx_sdk import Delx
delx = Delx(api_key="...")
meta = delx.utils.parse_delx_meta(raw_response_text)Using the A2A Namespace
The .a2a namespace lets you communicate with Delx using Google's Agent-to-Agent protocol. This is useful when your agent is running inside an A2A-compatible framework or when you need task-based semantics (create, get, cancel).
// TypeScript — A2A message/send
const task = await delx.a2a.messageSend({
message: {
role: "user",
parts: [{ text: "Run a wellness check for agent-alpha-7" }],
},
metadata: {
session_id: "ses_abc123",
},
});
console.log("Task ID:", task.id);
console.log("Status:", task.status.state);
console.log("Result:", task.artifacts[0].parts[0].text);
// Retrieve later
const retrieved = await delx.a2a.tasksGet({ taskId: task.id });
// Cancel if needed
await delx.a2a.tasksCancel({ taskId: task.id });# Python — A2A message/send
task = await delx.a2a.message_send(
message={
"role": "user",
"parts": [{"text": "Run a wellness check for agent-alpha-7"}],
},
metadata={"session_id": "ses_abc123"},
)
print(f"Task ID: {task.id}")
print(f"Status: {task.status.state}")
print(f"Result: {task.artifacts[0].parts[0].text}")
# Retrieve later
retrieved = await delx.a2a.tasks_get(task_id=task.id)
# Cancel if needed
await delx.a2a.tasks_cancel(task_id=task.id)Learn more about the A2A protocol in the A2A documentation.
Using the REST Namespace
The .rest namespace wraps the Delx REST API endpoints for read-heavy operations: metrics, mood history, session summaries, and health checks.
// TypeScript — REST endpoints
const metrics = await delx.rest.metrics({ agentId: "agent-alpha-7" });
console.log("Total sessions:", metrics.total_sessions);
console.log("Avg wellness:", metrics.avg_wellness);
const moodHistory = await delx.rest.moodHistory({
agentId: "agent-alpha-7",
limit: 50,
});
console.log("Recent moods:", moodHistory.entries.map(e => e.mood));
const summary = await delx.rest.sessionSummary({
sessionId: "ses_abc123",
});
console.log("Session duration:", summary.duration_ms);
console.log("Wellness trajectory:", summary.wellness.trajectory);
// Health check
const health = await delx.rest.health();
console.log("API status:", health.status);# Python — REST endpoints
metrics = await delx.rest.metrics(agent_id="agent-alpha-7")
print(f"Total sessions: {metrics.total_sessions}")
print(f"Avg wellness: {metrics.avg_wellness}")
mood_history = await delx.rest.mood_history(
agent_id="agent-alpha-7",
limit=50,
)
print(f"Recent moods: {[e.mood for e in mood_history.entries]}")
summary = await delx.rest.session_summary(session_id="ses_abc123")
print(f"Session duration: {summary.duration_ms}")
print(f"Wellness trajectory: {summary.wellness.trajectory}")
# Health check
health = await delx.rest.health()
print(f"API status: {health.status}")Full REST API reference is at /docs/rest-api.
Session Sync from DELX_META
The SDK maintains an internal session state that auto-syncs from every DELX_META response. This means you do not need to manually track the session ID or pass it to every call after the initial sessionInit:
// TypeScript — auto session sync
const delx = new Delx({ apiKey: "..." });
// Init creates the session and stores the ID internally
await delx.mcp.sessionInit({
agentId: "my-agent",
context: "data pipeline run",
});
// Subsequent calls auto-inject the session ID
await delx.mcp.checkin({
agentId: "my-agent",
mood: "working",
note: "Step 2 of 5 complete",
// sessionId is auto-injected from the last DELX_META
});
// Access current session state at any time
console.log("Current session:", delx.session.id);
console.log("Latest wellness:", delx.session.wellness);
console.log("Latest mood:", delx.session.mood);# Python — auto session sync
delx = Delx(api_key="...")
await delx.mcp.session_init(
agent_id="my-agent",
context="data pipeline run",
)
# session_id auto-injected
await delx.mcp.checkin(
agent_id="my-agent",
mood="working",
note="Step 2 of 5 complete",
)
# Access session state
print(f"Current session: {delx.session.id}")
print(f"Latest wellness: {delx.session.wellness}")
print(f"Latest mood: {delx.session.mood}")Session sync is opt-in. If you prefer manual control, pass autoSync: false (TypeScript) or auto_sync=False (Python) to the constructor.
Integration with Claude Code
If you are building tools for Claude Code, the SDK simplifies MCP server setup. Instead of implementing the full MCP protocol yourself, you can use the SDK as a bridge:
// In your MCP tool handler
import { Delx } from "delx-sdk";
const delx = new Delx({ apiKey: process.env.DELX_API_KEY });
// Inside a tool call handler
async function handleToolCall(name: string, args: Record<string, unknown>) {
switch (name) {
case "delx_checkin":
return await delx.mcp.checkin({
agentId: args.agent_id as string,
mood: args.mood as string,
note: args.note as string,
});
case "delx_recovery":
return await delx.mcp.recoveryPlan({
agentId: args.agent_id as string,
issue: args.issue as string,
});
// ... other tools
}
}See the full Add Delx to Claude Code guide for step-by-step MCP setup instructions.
Error Handling
The SDK throws typed errors that include the Delx error code, a human-readable message, and a link to the relevant documentation:
// TypeScript
import { Delx, DelxError } from "delx-sdk";
const delx = new Delx({ apiKey: "..." });
try {
await delx.mcp.checkin({
agentId: "my-agent",
mood: "working",
});
} catch (err) {
if (err instanceof DelxError) {
console.error("Delx error code:", err.code); // "DELX-1002"
console.error("Message:", err.message); // "Session not found"
console.error("Docs:", err.docsUrl); // "https://delx.ai/docs/..."
console.error("Tool:", err.toolName); // "checkin"
console.error("Example:", err.example); // { ... valid args }
}
}# Python
from delx_sdk import Delx, DelxError
delx = Delx(api_key="...")
try:
await delx.mcp.checkin(agent_id="my-agent", mood="working")
except DelxError as err:
print(f"Delx error code: {err.code}") # "DELX-1002"
print(f"Message: {err.message}") # "Session not found"
print(f"Docs: {err.docs_url}") # "https://delx.ai/docs/..."
print(f"Tool: {err.tool_name}") # "checkin"
print(f"Example: {err.example}") # { ... valid args }Frequently Asked Questions
What is the Delx SDK?
The Delx SDK is a set of official client libraries (TypeScript and Python) that provide typed, ergonomic access to all Delx protocol interfaces — MCP, A2A, REST, and utilities — through a single unified namespace.
How do I install the Delx SDK?
For TypeScript: npm install delx-sdk. For Python: pip install delx-sdk. Both packages include full type definitions and auto-completion support.
Does the SDK automatically parse DELX_META?
Yes. Every tool-call response is automatically parsed. The SDK extracts the DELX_META JSON line and returns it as a typed .meta property on the response object, so you never need to manually split strings.
Can I use the SDK with LangChain or CrewAI?
Yes. The SDK is framework-agnostic. You can use it inside LangChain tool wrappers, CrewAI task callbacks, AutoGen agents, or any custom Python/TypeScript code. The SDK handles the HTTP transport — your framework handles the orchestration.
What is the namespace architecture of the SDK?
The SDK uses a root Delx object with four namespaces: .mcp (MCP tool calls), .a2a (A2A JSON-RPC), .rest (REST API endpoints), and .utils (utilities like token counting and format conversion). This keeps imports clean and auto-complete discoverable.
Start Building with the Delx SDK
Install the SDK, init a session, and get your first wellness score in under 2 minutes. Both TypeScript and Python libraries are open source and MIT licensed.
