# Thanaton & Ananke: Comprehensive API & Tool Reference

> **API Version:** v1.0.0  
> **Base URL:** `http://127.0.0.1:8080` (or `http://<target-host>:8080`)  
> **Auth Scheme:** HTTP Bearer Token (`Authorization: Bearer <API_KEY>`)  
> **Content-Type:** `application/json`  

---

## Table of Contents
1. [Authentication & Headers](#1-authentication--headers)
2. [System & Telemetry Endpoints](#2-system--telemetry-endpoints)
3. [Sandbox Lifecycle Endpoints](#3-sandbox-lifecycle-endpoints)
4. [Execution & PTY Streaming Endpoints](#4-execution--pty-streaming-endpoints)
5. [Filesystem Endpoints](#5-filesystem-endpoints)
6. [Embedded Database (SQL) Endpoints](#6-embedded-database-sql-endpoints)
7. [Scale-to-Zero & State Endpoints](#7-scale-to-zero--state-endpoints)
8. [CLI Reference (`thanaton` / `ananke`)](#8-cli-reference)
9. [Model Context Protocol (MCP) Server Reference (51 Tools)](#9-mcp-server-reference)
10. [Error Codes & Diagnostics](#10-error-codes--diagnostics)
11. [Mnemon-DB Serverless PostgreSQL Engine Reference (`:9090`)](#11-mnemon-db-serverless-postgresql-engine-reference-9090)

---

## 1. Authentication & Headers

All requests to `/v1/*` endpoints require standard HTTP Bearer token authentication in the `Authorization` header.

```http
Authorization: Bearer sk_live_your_api_key_here
Content-Type: application/json
```

- If `Authorization` header is missing: Returns `401 Unauthorized`.
- If Bearer token is invalid or inactive: Returns `403 Forbidden`.
- In local development / test mode, `test-key` or any key prefixed with `sk_live_` is permitted.

---

## 2. System & Telemetry Endpoints

### 2.1 Health Check (`GET /healthz` or `GET /v1/health`)
Verifies daemon health and state engine readiness.

- **Method:** `GET`
- **Path:** `/healthz` or `/v1/health`
- **Auth:** None
- **Response (200 OK):**
```json
{
  "status": "ok",
  "service": "ananked",
  "version": "1.0.0"
}
```
- **Example cURL:**
```bash
curl -s http://127.0.0.1:8080/healthz
```

---

### 2.2 Prometheus Metrics (`GET /metrics`)
Exposes live operational telemetry in Prometheus text format.

- **Method:** `GET`
- **Path:** `/metrics`
- **Auth:** None
- **Response (200 OK):**
```text
# HELP thanaton_sandboxes_total Total microVM sandboxes tracked in state engine
# TYPE thanaton_sandboxes_total gauge
thanaton_sandboxes_total 4
# HELP thanaton_sandboxes_running Currently active running sandboxes
# TYPE thanaton_sandboxes_running gauge
thanaton_sandboxes_running 2
# HELP thanaton_sandboxes_frozen Currently frozen sandboxes (cgroup paused)
# TYPE thanaton_sandboxes_frozen gauge
thanaton_sandboxes_frozen 1
# HELP thanaton_sandboxes_sleeping Currently sleeping sandboxes (scale-to-zero)
# TYPE thanaton_sandboxes_sleeping gauge
thanaton_sandboxes_sleeping 1
# HELP thanaton_host_rss_bytes Host resident memory in bytes
# TYPE thanaton_host_rss_bytes gauge
thanaton_host_rss_bytes 27361280
```
- **Example cURL:**
```bash
curl -s http://127.0.0.1:8080/metrics
```

---

## 3. Sandbox Lifecycle Endpoints

### 3.1 Spawn Sandbox (`POST /v1/sandboxes`)
Creates a new hardware-isolated Linux MicroVM.

- **Method:** `POST`
- **Path:** `/v1/sandboxes`
- **Auth:** Bearer Token
- **Request Body (JSON):**

| Field | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `runtime` | string | No | `"microvm"` | Virtualization runtime (`"microvm"`). |
| `memory_mb` | integer | No | `128` | Guest RAM allocation in megabytes (64 – 2048). |
| `vcpus` | integer | No | `1` | Guest virtual CPUs (1 – 4). |
| `ttl_seconds` | integer | No | `1800` | Auto-reap timeout if idle (default 30 mins). |

- **Response (201 Created):**
```json
{
  "id": "sbx-019a4e82",
  "status": "ready",
  "runtime": "microvm",
  "vcpus": 1,
  "memory_mb": 128,
  "ip": "172.16.0.2",
  "created_at": 1730721600.123
}
```
- **Example cURL:**
```bash
curl -s -X POST http://127.0.0.1:8080/v1/sandboxes \
  -H "Authorization: Bearer sk_live_test" \
  -H "Content-Type: application/json" \
  -d '{"runtime": "microvm", "memory_mb": 128, "vcpus": 1}'
```

---

### 3.2 List Sandboxes (`GET /v1/sandboxes`)
Returns all active, frozen, or sleeping sandboxes for the authenticated tenant.

- **Method:** `GET`
- **Path:** `/v1/sandboxes`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
[
  {
    "id": "sbx-019a4e82",
    "status": "running",
    "runtime": "microvm",
    "vcpus": 1,
    "memory_mb": 128,
    "created_at": 1730721600.123
  }
]
```

---

### 3.3 Get Sandbox Details (`GET /v1/sandboxes/{id}`)
Fetches detailed state and resource allocation for a specific sandbox.

- **Method:** `GET`
- **Path:** `/v1/sandboxes/{id}`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "id": "sbx-019a4e82",
  "status": "running",
  "runtime": "microvm",
  "vcpus": 1,
  "memory_mb": 128,
  "ip": "172.16.0.2",
  "created_at": 1730721600.123
}
```

---

### 3.4 Destroy Sandbox (`DELETE /v1/sandboxes/{id}`)
Terminates the microVM, removes network TAP interfaces, and wipes temporary scratch files.

- **Method:** `DELETE`
- **Path:** `/v1/sandboxes/{id}`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "status": "destroyed",
  "id": "sbx-019a4e82"
}
```
- **Example cURL:**
```bash
curl -s -X DELETE http://127.0.0.1:8080/v1/sandboxes/sbx-019a4e82 \
  -H "Authorization: Bearer sk_live_test"
```

---

## 4. Execution & PTY Streaming Endpoints

### 4.1 Execute Shell Command (`POST /v1/sandboxes/{id}/exec`)
Executes an arbitrary command or script inside the hardware-isolated microVM.

- **Method:** `POST`
- **Path:** `/v1/sandboxes/{id}/exec`
- **Auth:** Bearer Token
- **Request Body (JSON):**

| Field | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `command` | string | Yes | — | Shell command to execute inside sandbox. |
| `timeout_ms` | integer | No | `5000` | Execution timeout in milliseconds (max 60000). |
| `working_dir` | string | No | `"/root"` | Working directory inside sandbox. |

- **Response (200 OK):**
```json
{
  "exit_code": 0,
  "stdout": "Hello from MicroVM\n",
  "stderr": "",
  "duration_ms": 11.4
}
```
- **Example cURL:**
```bash
curl -s -X POST http://127.0.0.1:8080/v1/sandboxes/sbx-019a4e82/exec \
  -H "Authorization: Bearer sk_live_test" \
  -H "Content-Type: application/json" \
  -d '{"command": "echo \"Hello from MicroVM\"", "timeout_ms": 5000}'
```

---

### 4.2 Attach Interactive PTY Session (`POST /v1/sandboxes/{id}/pty`)
Allocates a pseudo-terminal for interactive shell sessions.

- **Method:** `POST`
- **Path:** `/v1/sandboxes/{id}/pty`
- **Auth:** Bearer Token
- **Request Body:** `{"command": "bash", "rows": 24, "cols": 80}`
- **Response (200 OK):**
```json
{
  "session_id": "pty-019a4e82-f19b",
  "status": "attached"
}
```

---

## 5. Filesystem Endpoints

### 5.1 Write File (`POST /v1/sandboxes/{id}/files/write`)
Writes binary or text content directly into the guest microVM filesystem.

- **Method:** `POST`
- **Path:** `/v1/sandboxes/{id}/files/write`
- **Auth:** Bearer Token
- **Request Body (JSON):**

| Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `path` | string | Yes | Absolute target path inside the sandbox (e.g. `"/root/main.py"`). |
| `content` | string | Yes | Text or encoded file content. |
| `mode` | string | No | File permission bits (default `"0644"`). |

- **Response (200 OK):**
```json
{
  "status": "ok",
  "path": "/root/main.py",
  "bytes_written": 27
}
```

---

### 5.2 Read File (`GET /v1/sandboxes/{id}/files/read`)
Reads file contents from the sandbox.

- **Method:** `GET`
- **Path:** `/v1/sandboxes/{id}/files/read?path={path}`
- **Auth:** Bearer Token
- **Query Parameter:** `path` (e.g. `/root/main.py`)
- **Response (200 OK):**
```json
{
  "path": "/root/main.py",
  "content": "print('execution complete')",
  "size": 27
}
```

---

## 6. Embedded Database (SQL) Endpoints

### 6.1 Execute In-Sandbox SQL (`POST /v1/sandboxes/{id}/sql`)
Executes isolated SQLite queries inside the sandbox's private embedded database. Ideal for database exams, SQL assessment labs, and local relational state without external DB infrastructure.

- **Method:** `POST`
- **Path:** `/v1/sandboxes/{id}/sql`
- **Auth:** Bearer Token
- **Request Body (JSON):**
```json
{
  "query": "CREATE TABLE students (id INT PRIMARY KEY, name TEXT); INSERT INTO students VALUES (1, 'Mohit'); SELECT * FROM students;"
}
```
- **Response (200 OK):**
```json
{
  "rows": [
    [1, "Mohit"]
  ],
  "columns": ["id", "name"],
  "row_count": 1,
  "duration_ms": 1.2
}
```

---

## 7. Scale-to-Zero & State Endpoints

### 7.1 Hibernate / Freeze Sandbox (`POST /v1/sandboxes/{id}/sleep` or `/freeze`)
Suspends microVM execution via Cgroups v2 `cgroup.freeze`. Host CPU drops to 0.0%, while preserving complete memory and filesystem state.

- **Method:** `POST`
- **Path:** `/v1/sandboxes/{id}/sleep` or `/v1/sandboxes/{id}/freeze`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "status": "sleeping",
  "id": "sbx-019a4e82",
  "latency_ms": 3.07
}
```

---

### 7.2 Resume / Wake Sandbox (`POST /v1/sandboxes/{id}/wake` or `/unfreeze`)
Restores frozen microVM execution back to running state in < 4 milliseconds.

- **Method:** `POST`
- **Path:** `/v1/sandboxes/{id}/wake` or `/v1/sandboxes/{id}/unfreeze`
- **Auth:** Bearer Token
- **Response (200 OK):**
```json
{
  "status": "running",
  "id": "sbx-019a4e82",
  "latency_ms": 2.91
}
```

---

## 8. CLI Reference (`thanaton` / `ananke`)

The Developer CLI is installed at `sdk/cli/thanaton` (or symlinked to `/usr/local/bin/thanaton`):

### Commands Summary:
```bash
# Display help & version
thanaton --help

# Spawn sandbox
thanaton spawn [--memory MEM_MB] [--vcpus VCPUS]

# Execute arbitrary command inside sandbox
thanaton exec <sandbox_id> [--] <command...>

# Read file from sandbox
thanaton read <sandbox_id>:<remote_path>

# Write file to sandbox
thanaton write <sandbox_id>:<remote_path> "<content>"

# Copy file between host and sandbox
thanaton cp <local_path> <sandbox_id>:<remote_path>

# List all sandboxes
thanaton list [--json]

# Hibernate / Sleep sandbox
thanaton sleep <sandbox_id>

# Wake / Resume sandbox
thanaton wake <sandbox_id>

# Pause / Freeze sandbox
thanaton freeze <sandbox_id>

# Resume / Unfreeze sandbox
thanaton unfreeze <sandbox_id>

# Terminate and wipe sandbox
thanaton destroy <sandbox_id>
```

---

## 9. MCP Server Reference (`ananke_mcp.py`)

The Model Context Protocol (MCP) server enables AI agents (Claude Desktop, Cursor, LangChain) to discover and call Thanaton sandbox tools natively over JSON-RPC 2.0.

### Starting the MCP Server:
```bash
python sdk/mcp/ananke_mcp.py
```

### Registered Tools Schema:

#### `thanaton_spawn_sandbox`
- **Input Schema:**
  - `memory_mb` (integer, optional, default: 128)
  - `vcpus` (integer, optional, default: 1)
- **Output:** Returns JSON object with created sandbox `id` and `ip`.

#### `thanaton_exec_command`
- **Input Schema:**
  - `sandbox_id` (string, required)
  - `command` (string, required)
  - `timeout_ms` (integer, optional, default: 5000)
- **Output:** Returns stdout, stderr, and exit code.

#### `thanaton_run_code`
- **Input Schema:**
  - `sandbox_id` (string, required)
  - `language` (string, required: e.g. `"python"`, `"bash"`, `"javascript"`)
  - `code` (string, required)
- **Output:** Formatted execution output.

#### `thanaton_list_sandboxes`
- **Input Schema:** `{}`
- **Output:** Array of sandbox metadata objects.

#### `thanaton_sleep_sandbox` / `thanaton_wake_sandbox`
- **Input Schema:**
  - `sandbox_id` (string, required)
- **Output:** Success message and latency in milliseconds.

#### `thanaton_destroy_sandbox`
- **Input Schema:**
  - `sandbox_id` (string, required)
- **Output:** Confirmation string.

---

## 10. Error Codes & Diagnostics

| HTTP Status | Condition | Example Error Response |
| :--- | :--- | :--- |
| **400 Bad Request** | Missing required parameters or malformed JSON payload. | `{"error": "Missing required field: command"}` |
| **401 Unauthorized** | Missing `Authorization` header. | `{"error": "Missing Authorization header"}` |
| **403 Forbidden** | Invalid Bearer token. | `{"error": "Invalid API key"}` |
| **404 Not Found** | Sandbox ID not found or already deleted. | `{"error": "Sandbox sbx-019a4e82 not found"}` |
| **422 Unprocessable** | Parameter value out of bounds (e.g. `memory_mb` > 4096). | `{"error": "Requested memory exceeds host ceiling"}` |
| **504 Gateway Timeout** | Command execution exceeded `timeout_ms`. | `{"error": "Execution timed out after 5000ms"}` |
| **Exit Code 137** | Linux Kernel OOM Killer terminated the process inside sandbox. | Process killed; host protected. |


---

## 11. Mnemon-DB Serverless PostgreSQL Engine Reference (`:9090`)

> **Daemon Base URL:** `https://db.nephis.theeducode.com` (or `http://127.0.0.1:9090`)  
> **L4 PgWire Proxy:** `127.0.0.1:5432`  
> **Auth Scheme:** HTTP Bearer Token (`Authorization: Bearer <API_KEY>`) — supports `nephis_live_...` and legacy `mnm_live_...`

### 11.1 One-Click Branch Reset (`POST /v1/tenants/branch/reset`)
Resets a developer or preview database branch back to the exact snapshot state of its parent branch in `<50ms` using atomic XFS reflink pointer re-assignment.

- **Request Body:**
```json
{
  "tenant_id": "tenant-app-prod",
  "branch_id": "pr-42-preview"
}
```
- **Response (200 OK):**
```json
{
  "status": "ok",
  "duration_ms": 14.82,
  "branch_id": "pr-42-preview",
  "reset_to_branch": "main"
}
```

### 11.2 Schema Diff & Migration DDL (`GET /v1/tenants/branch/diff`)
Inspects PostgreSQL system catalogs (`information_schema` and `pg_catalog`) between two branches and generates executable migration DDL statements.

- **Query Parameters:**
  - `tenant_id`: Tenant identifier (required)
  - `branch_id`: Branch to inspect (required)
  - `parent_branch`: Base branch (optional, defaults to `main`)
- **Response (200 OK):**
```json
{
  "diff": "--- parent (main)\n+++ branch (pr-42-preview)\n+ Table: audit_logs\n+ Column: users.phone (text)",
  "migration_ddl": "CREATE TABLE audit_logs (id serial PRIMARY KEY, event text);\nALTER TABLE users ADD COLUMN phone text;"
}
```

### 11.3 Continuous Point-in-Time Recovery (`POST /v1/tenants/branch/time-travel`)
Spawns an instant branch from any historical point in time within the retention window by replaying archived Lethe WAL records.

- **Request Body:**
```json
{
  "tenant_id": "tenant-app-prod",
  "new_branch": "pitr-incident-investigation",
  "target_time": "2026-11-13T10:00:00Z",
  "parent_branch": "main"
}
```
- **Response (200 OK):**
```json
{
  "status": "ok",
  "branch_id": "pitr-incident-investigation",
  "target_time": "2026-11-13T10:00:00Z",
  "replayed_wal_records": 1480,
  "duration_ms": 32.14,
  "database_url": "postgresql://postgres:secret@db.nephis.theeducode.com:5432/pitr-incident-investigation?sslmode=require"
}
```

### 11.4 ParadeDB BM25 Full-Text Search (`POST /v1/tenants/search`)
Executes full-text queries using ParadeDB BM25 (`pg_search` extension with `@@@` operator) on Graviton4 nodes, with transparent fallback to PostgreSQL native `tsvector` GIN indexes on standard nodes.

- **Request Body:**
```json
{
  "tenant_id": "tenant-app-prod",
  "table": "documents",
  "query": "serverless postgresql branching",
  "columns": ["id", "title", "content"]
}
```
- **Response (200 OK):**
```json
{
  "rows": [
    {"id": 1, "title": "Nephis Architecture", "content": "31ms serverless postgresql branching with ParadeDB BM25"}
  ],
  "index_mode": "bm25",
  "query": "serverless postgresql branching"
}
```

### 11.5 Managed PostgREST RESTful Data API Engine (`/rest/v1/...`)
Auto-generated RESTful HTTPS interface for querying and mutating tables with zero database driver overhead:

- **Query Rows:** `GET /rest/v1/{tenant}/{table}?id=eq.1&order=id.desc`
- **Insert Rows:** `POST /rest/v1/{tenant}/{table}`
- **Update Rows:** `PATCH /rest/v1/{tenant}/{table}?id=eq.1`
- **Delete Rows:** `DELETE /rest/v1/{tenant}/{table}?id=eq.1` *(Note: Unfiltered batch deletes are rejected with 400 Bad Request to prevent accidental catastrophic data wipes)*

### 11.6 Branching S3-Compatible Object Storage (`/storage/v1/...`)
Copy-on-write file and media storage engine that branches alongside database schemas with zero disk duplication:

- **Upload Object:** `PUT /storage/v1/{tenant}/{branch}/object/{key}`
- **Download Object:** `GET /storage/v1/{tenant}/{branch}/object/{key}` *(Falls through to parent branch if unmutated)*
- **Delete Object:** `DELETE /storage/v1/{tenant}/{branch}/object/{key}`

### 11.7 CLI Quick Reference (`mnemon`)

```bash
# Branching & Isolation
mnemon branch <tenant_id> <new_branch> [--parent main]
mnemon diff <tenant_id> --branch <branch_id>
mnemon reset <tenant_id> <branch_id>
mnemon time-travel <tenant_id> <new_branch> --time 2026-11-13T10:00:00Z

# Search & Query
mnemon search <tenant_id> <table> <query> [--columns id,title,content]
mnemon sql <tenant_id> "SELECT count(*) FROM users;"

# Scale-to-Zero & Cgroups
mnemon freeze <tenant_id>
mnemon resume <tenant_id>
```

### 11.8 GitHub Actions Preview Bot (`nephis/mnemon-preview-db@v1`)

```yaml
- name: Spawn Mnemon-DB Preview Branch
  id: mnemon
  uses: nephis/mnemon-preview-db@v1
  with:
    api-key: ${{ secrets.MNEMON_API_KEY }}
    tenant-id: 'my-app'
```


