# Trace Diet — HAR & Log Context Distiller API (v1.0.0)

> Shrink 5MB .har captures and 50,000-line crash logs by 95–99% while scrubbing live tokens before they hit your LLM context.

Deterministic context-window compression and secret-scrubbing engine for debugging agents: distills bloated Chrome DevTools / Playwright .har captures into typed API routes & failures, and collapses 50,000+ noisy plain-text/K8s/NDJSON log lines by 95–99% via Drain prefix-tree clustering.

## Why Agents Use This API Instead of DIY
Saves $0.25–$1.50 of wasted frontier-LLM input tokens per debugging turn, prevents live JWT/Cookie leakage into conversation history, folds multi-language stack traces accurately, and infers TypeScript API schemas in <40ms.

## Connection & Payment (x402 Default + Optional Bearer API Key)
- **MCP Server (Streamable HTTP):** `https://trace-diet.apikeg.com/mcp` (Registry ID: `com.apikeg/trace-diet` — `initialize`, `tools/list`, `resources/*`, and `prompts/*` are free)
- **OpenAPI 3.1 Spec:** [openapi.json](https://trace-diet.apikeg.com/openapi.json)
- **Full Schema & Examples:** [llms-full.txt](https://trace-diet.apikeg.com/llms-full.txt)
- **RFC 9727 API Catalog:** [.well-known/api-catalog](https://trace-diet.apikeg.com/.well-known/api-catalog)
- **x402 Bazaar Manifest:** [.well-known/x402.json](https://trace-diet.apikeg.com/.well-known/x402.json)
- **MCP Discovery Manifest:** [.well-known/mcp.json](https://trace-diet.apikeg.com/.well-known/mcp.json)
- **A2A Agent Card:** [.well-known/agent-card.json](https://trace-diet.apikeg.com/.well-known/agent-card.json)
- **Primary Payment (Zero Signup):** Cloudflare Monetization Gateway (`HTTP 402` / `x402` v2 with USDC on Base).
- **Optional Monthly API Key:** Pass `Authorization: Bearer ak_live_...` ($5 / $20 / $50 monthly per-product Stripe plans at [apikeg.com/account](https://apikeg.com/account)).
- **Free Preflight:** Append `?dry_run=true` (or header `X-Dry-Run: true`) to validate any request payload at `$0.00` cost.

## Tools & REST Endpoints
- [`distill_har_capture`](https://trace-diet.apikeg.com/tools/distill-har-capture.md) (`POST https://trace-diet.apikeg.com/v1/distill-har-capture`) — $0.002 base (up to $0.008 max ($0.002 base + $0.001 per 250KB of .har input, capped at $0.008), x402 variable settlement): Parses Chrome DevTools / Playwright .har captures, strips static assets (.js/.css/fonts/images), analytics beacons, and OPTIONS preflights, scrubs credentials (Authorization, Cookie, Set-Cookie, X-Api-Key, token params, JWTs) into [REDACTED:<type>], groups dynamic :id/:uuid routes and polling loops, surfaces 4xx/5xx failures and slowestEndpoints, and infers compact TypeScript request/response schemas.
- [`cluster_logs`](https://trace-diet.apikeg.com/tools/cluster-logs.md) (`POST https://trace-diet.apikeg.com/v1/cluster-logs`) — $0.002 base (up to $0.008 max ($0.002 base + $0.001 per 2,000 log lines, capped at $0.008), x402 variable settlement): Folds multi-line stack traces (JS/Java 'at ...', Python Traceback, Go panics, Java 'Caused by:'), parses plain-text, Docker/Kubernetes CRI, and NDJSON logs, pre-masks <UUID>/<IP>/<HEX>/<ISO_TS>/<URL>/<NUM>, and runs a fixed-depth Drain prefix-tree clusterer to collapse 50,000+ log lines by 95–99% with errorClusters highlighted first.

## Instant MCP Configuration
```json
{
  "mcpServers": {
    "trace-diet": {
      "type": "streamable-http",
      "url": "https://trace-diet.apikeg.com/mcp"
    }
  }
}
```

## Common Agent Use Cases
- compress Chrome HAR file for LLM agent MCP
- redact JWT Authorization cookies from HAR capture API
- infer TypeScript interfaces from network HAR requests
- Drain log clustering algorithm API MCP
- summarize 50000 Kubernetes Docker NDJSON logs for AI debugging
- reduce Playwright trace and log token usage

---

## Detailed Tool Specifications

### `distill_har_capture` — Distill & Scrub HAR Network Capture
- **REST Endpoint:** `POST https://trace-diet.apikeg.com/v1/distill-har-capture`
- **Tool Doc Page:** https://trace-diet.apikeg.com/tools/distill-har-capture
- **MCP Tool Name:** `distill_har_capture`
- **Pricing:** $0.002 base (up to $0.008 max ($0.002 base + $0.001 per 250KB of .har input, capped at $0.008), x402 variable settlement)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Replaces ad-hoc jq/Python HAR scripts that miss base64 bodies, leak Bearer JWTs/cookies into LLM prompts, or fail to merge nullable JSON types across repeated API calls.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "har": {
      "type": "object",
      "properties": {},
      "additionalProperties": true,
      "description": "Parsed HAR 1.2 JSON object containing log.entries (exported from Chrome DevTools, Playwright, or mitmproxy)."
    },
    "harJson": {
      "type": "string",
      "minLength": 2,
      "maxLength": 5000000,
      "description": "Raw serialized .har JSON text when passing unparsed file contents directly."
    },
    "includeStaticAssets": {
      "type": "boolean",
      "default": false,
      "description": "Keep static asset requests (.js, .css, .woff2, .png, .svg, .ico, images/fonts). Defaults to false."
    },
    "includeTelemetry": {
      "type": "boolean",
      "default": false,
      "description": "Keep analytics and telemetry beacons (Google Analytics, Segment, Datadog, Sentry, Mixpanel). Defaults to false."
    },
    "includeOptionsPreflight": {
      "type": "boolean",
      "default": false,
      "description": "Keep CORS OPTIONS preflight requests. Defaults to false."
    },
    "redactSecrets": {
      "type": "boolean",
      "default": true,
      "description": "Scrub Authorization, Cookie, Set-Cookie, X-Api-Key, api_key/token query params, and JWTs into [REDACTED:<type>]."
    },
    "inferSchemas": {
      "type": "boolean",
      "default": true,
      "description": "Infer compact TypeScript interfaces/types for JSON request and response payloads across endpoint calls."
    },
    "maxFailureBodyChars": {
      "type": "integer",
      "default": 512,
      "minimum": 64,
      "maximum": 4096,
      "description": "Maximum characters retained per 4xx/5xx/network failure body snippet."
    },
    "maxSlowestEndpoints": {
      "type": "integer",
      "default": 10,
      "minimum": 1,
      "maximum": 50,
      "description": "Maximum number of slowest endpoints ranked by p95 latency."
    },
    "allowedHosts": {
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1,
        "maxLength": 255
      },
      "maxItems": 50,
      "description": "Optional hostname allowlist (e.g. ['api.acme.com']) to isolate target traffic."
    }
  },
  "additionalProperties": false
}
```

#### Examples
**Distill Playwright checkout failure HAR** — Strips static bundles/GA beacons, scrubs live Bearer JWT + session cookies, groups /users/:id/orders/:uuid, and surfaces a 500 payment failure.
```bash
curl -X POST "https://trace-diet.apikeg.com/v1/distill-har-capture" \
  -H "Content-Type: application/json" \
  -d '{"redactSecrets":true,"inferSchemas":true,"includeStaticAssets":false,"includeTelemetry":false,"includeOptionsPreflight":false,"maxFailureBodyChars":512,"maxSlowestEndpoints":10,"har":{"log":{"version":"1.2","entries":[{"startedDateTime":"2026-11-30T08:15:00.000Z","time":412,"request":{"method":"POST","url":"https://api.shop.io/users/94821/orders/550e8400-e29b-41d4-a716-446655440000?api_key=live_secret","headers":[{"name":"Authorization","value":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5NDgyMSJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"}],"postData":{"mimeType":"application/json","text":"{\"sku\":\"PRO-ANNUAL\",\"Seats\":5}"}},"response":{"status":500,"statusText":"Internal Server Error","headers":[{"name":"Content-Type","value":"application/json"}],"content":{"mimeType":"application/json","text":"{\"error\":\"stripe_upstream_timeout\",\"retryable\":true}"}}}]}}}'
```
Expected result: 1 grouped endpoint POST https://api.shop.io/users/:id/orders/:uuid, 1 failure with redacted JWT + api_key, and inferred TypeScript Request/Error interfaces.

### `cluster_logs` — Cluster Noisy Logs via Drain Prefix-Tree
- **REST Endpoint:** `POST https://trace-diet.apikeg.com/v1/cluster-logs`
- **Tool Doc Page:** https://trace-diet.apikeg.com/tools/cluster-logs
- **MCP Tool Name:** `cluster_logs`
- **Pricing:** $0.002 base (up to $0.008 max ($0.002 base + $0.001 per 2,000 log lines, capped at $0.008), x402 variable settlement)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Avoids naive grep/head truncation that misses rare fatal stack traces buried at line 41,000, cutting 500k-token log dumps to ~2k tokens in <50ms.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "logs": {
      "type": "string",
      "minLength": 1,
      "maxLength": 5000000,
      "description": "Raw plain-text, Docker/Kubernetes CRI, or newline-delimited JSON (ndjson) log stream."
    },
    "lines": {
      "type": "array",
      "items": {
        "type": "string",
        "maxLength": 32768
      },
      "minItems": 1,
      "maxItems": 100000,
      "description": "Pre-split array of log lines (alternative to passing a single 'logs' string)."
    },
    "similarityThreshold": {
      "type": "number",
      "default": 0.6,
      "minimum": 0.2,
      "maximum": 1,
      "description": "Drain token-similarity threshold [0.2-1.0] required to merge a log line into an existing canonical template."
    },
    "treeDepth": {
      "type": "integer",
      "default": 4,
      "minimum": 3,
      "maximum": 8,
      "description": "Fixed Drain prefix-tree depth (length -> leading tokens -> leaf templates)."
    },
    "maxClusters": {
      "type": "integer",
      "default": 300,
      "minimum": 10,
      "maximum": 1000,
      "description": "Maximum canonical Drain clusters maintained before routing outliers to overflow."
    },
    "maxReturnedClusters": {
      "type": "integer",
      "default": 100,
      "minimum": 1,
      "maximum": 500,
      "description": "Maximum ranked clusters returned in the response payload."
    },
    "maxStackTraceChars": {
      "type": "integer",
      "default": 1500,
      "minimum": 128,
      "maximum": 8192,
      "description": "Maximum characters retained per cluster sampleStackTrace."
    }
  },
  "additionalProperties": false
}
```

#### Examples
**Cluster Kubernetes & Node.js crash stream** — Folds multi-line V8 stack traces and collapses repetitive healthcheck/query logs into canonical Drain templates.
```bash
curl -X POST "https://trace-diet.apikeg.com/v1/cluster-logs" \
  -H "Content-Type: application/json" \
  -d '{"similarityThreshold":0.6,"treeDepth":4,"maxClusters":300,"maxReturnedClusters":100,"maxStackTraceChars":1500,"logs":"2026-11-30T08:00:01.100Z INFO [http] GET /healthz from 10.244.1.8 completed in 2ms\n2026-11-30T08:00:02.100Z INFO [http] GET /healthz from 10.244.1.9 completed in 3ms\n2026-11-30T08:00:03.250Z ERROR [db] Deadlock detected for tx 550e8400-e29b-41d4-a716-446655440000 after 3 retries\n    at PoolClient.query (/srv/app/db.ts:118:13)\n    at OrderRepo.commit (/srv/app/orders.ts:74:9)"}'
```
Expected result: Highlights 1 ERROR cluster (with folded stack trace) ahead of 1 INFO template (<IP>, <NUM> masked).
