warmplane 0.23.0

Local control plane that keeps MCP sessions warm with compact capability/resource/prompt facades.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# TypeScript Integrators Guide

This guide explains how to drive a running Warmplane daemon from TypeScript over its HTTP REST API. It includes a minimal `WarmplaneClient` class you can drop into your project and build on.

---

## Prerequisites

- A running Warmplane daemon with at least one upstream MCP server configured.
- Node.js 18+ or Bun 1.0+ (both ship with native `fetch`).
- No external dependencies required — the client uses the built-in `fetch` API.

Start the daemon in a separate terminal:

```bash
warmplane daemon --config mcp_servers.json
```

---

## WarmplaneClient

A thin typed wrapper over `fetch`. No frameworks, no build step — just enough structure to avoid repeating URL construction and envelope parsing.

```typescript
// warmplane-client.ts

/** Standard Warmplane response envelope. */
interface Envelope<T = unknown> {
  ok: boolean;
  request_id: string | null;
  trace_id: string | null;
  data: T | null;
  error: EnvelopeError | null;
  retry: RetryInfo | null;
}

/** Error details within a response envelope. */
interface EnvelopeError {
  code: string;
  message: string;
  retryable: boolean;
}

/** Retry classification metadata. */
interface RetryInfo {
  classification: "safe" | "idempotent" | "unsafe" | null;
  upstream_execution_state: "not_started" | "completed" | "unknown" | null;
}

/** Compact capability entry from the catalog index. */
interface CapabilityEntry {
  id: string;
  summary: string;
  server: string;
  tags: string[];
  mode?: string;
}

/** Catalog listing response body. */
interface CatalogResponse {
  version: string;
  catalog_version: string;
  capabilities: CapabilityEntry[];
  ttl_ms?: number;
  cache_scope?: string;
}

/** Search result entry with relevance score. */
interface SearchResult {
  id: string;
  summary: string;
  server: string;
  tags: string[];
  score: number;
  match_types: string[];
}

/** Search response body. */
interface SearchResponse {
  version: string;
  catalog_version: string;
  capabilities: SearchResult[];
}

/** Batch call step definition. */
interface BatchStep {
  id: string;
  capability_id: string;
  args: Record<string, unknown>;
  continue_on_error?: boolean;
}

/** Context distillation options for limiting tool output. */
interface DistillOptions {
  /** JSONPath selector (e.g. `$.items[*].name`). */
  jsonpath?: string;
  /** Maximum output lines. */
  limitLines?: number;
  /** Maximum output bytes. */
  truncateBytes?: number;
}

/** Warmplane API error thrown on non-ok envelopes. */
class WarmplaneError extends Error {
  constructor(
    public readonly code: string,
    message: string,
    public readonly retryable: boolean,
  ) {
    super(`[${code}] ${message}`);
    this.name = "WarmplaneError";
  }
}

/**
 * Minimal Warmplane HTTP API client.
 *
 * Wraps `fetch` with a base URL pointing at a running daemon.
 * All methods return parsed response envelopes or throw typed errors.
 */
class WarmplaneClient {
  private readonly baseUrl: string;
  private cachedEtag: string | null = null;

  constructor(baseUrl = "http://127.0.0.1:9090") {
    this.baseUrl = baseUrl.replace(/\/+$/, "");
  }

  // ------------------------------------------------------------------
  // Internal helpers
  // ------------------------------------------------------------------

  private async get<T>(path: string, headers?: HeadersInit): Promise<Response> {
    return fetch(`${this.baseUrl}${path}`, { headers });
  }

  private async postJson<T>(path: string, body: unknown, headers?: HeadersInit): Promise<T> {
    const res = await fetch(`${this.baseUrl}${path}`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...headers },
      body: JSON.stringify(body),
    });
    return res.json() as Promise<T>;
  }

  private assertOk<T>(envelope: Envelope<T>): Envelope<T> {
    if (!envelope.ok && envelope.error) {
      throw new WarmplaneError(
        envelope.error.code,
        envelope.error.message,
        envelope.error.retryable,
      );
    }
    return envelope;
  }

  // ------------------------------------------------------------------
  // Catalog discovery
  // ------------------------------------------------------------------

  /**
   * Lists all capabilities from the compact catalog index.
   *
   * Performs conditional revalidation using `If-None-Match` when a
   * cached ETag is available. Returns `null` on 304 Not Modified.
   */
  async listCapabilities(): Promise<CatalogResponse | null> {
    const headers: Record<string, string> = {};
    if (this.cachedEtag) {
      headers["If-None-Match"] = this.cachedEtag;
    }

    const res = await this.get("/v1/capabilities", headers);

    if (res.status === 304) return null;

    const etag = res.headers.get("etag");
    if (etag) this.cachedEtag = etag;

    return res.json() as Promise<CatalogResponse>;
  }

  /** Fetches the full JSON Schema for a single capability. */
  async describeCapability(id: string): Promise<unknown> {
    const res = await this.get(`/v1/capabilities/${encodeURIComponent(id)}`);
    return res.json();
  }

  // ------------------------------------------------------------------
  // Tool execution
  // ------------------------------------------------------------------

  /**
   * Calls a capability tool and returns the response envelope.
   *
   * Optionally pass an `idempotencyKey` for safe retries of mutating
   * operations.
   */
  async callTool(
    capabilityId: string,
    args: Record<string, unknown>,
    idempotencyKey?: string,
  ): Promise<Envelope> {
    const headers: Record<string, string> = { "Content-Type": "application/json" };
    if (idempotencyKey) {
      headers["Idempotency-Key"] = idempotencyKey;
    }

    const res = await fetch(`${this.baseUrl}/v1/tools/call`, {
      method: "POST",
      headers,
      body: JSON.stringify({ capability_id: capabilityId, args }),
    });

    const envelope: Envelope = await res.json();
    return this.assertOk(envelope);
  }

  /**
   * Calls a capability with context distillation modifiers.
   *
   * Use `jsonpath` to select specific fields, `limitLines` to cap
   * output length, and `truncateBytes` for a hard byte budget.
   */
  async callToolDistilled(
    capabilityId: string,
    args: Record<string, unknown>,
    options: DistillOptions,
  ): Promise<Envelope> {
    const distilledArgs = { ...args };
    if (options.jsonpath) distilledArgs._jsonpath = options.jsonpath;
    if (options.limitLines) distilledArgs._limit_lines = options.limitLines;
    if (options.truncateBytes) distilledArgs._truncate_bytes = options.truncateBytes;

    return this.callTool(capabilityId, distilledArgs);
  }

  /**
   * Executes a chained batch of tool steps in a single round-trip.
   *
   * Steps can reference outputs from earlier steps using `$step_id.field`
   * variable interpolation syntax.
   */
  async batchCall(steps: BatchStep[]): Promise<unknown> {
    return this.postJson("/v1/tools/batch_call", { steps });
  }

  // ------------------------------------------------------------------
  // Search
  // ------------------------------------------------------------------

  /** Searches capabilities using hybrid lexical + semantic ranking. */
  async searchCapabilities(
    query: string,
    limit = 8,
    serverIds: string[] = [],
    tags: string[] = [],
  ): Promise<SearchResponse> {
    return this.postJson<SearchResponse>("/v1/capabilities/search", {
      query,
      limit,
      server_ids: serverIds,
      tags,
    });
  }

  // ------------------------------------------------------------------
  // Resources & Prompts
  // ------------------------------------------------------------------

  /** Lists all registered resources. */
  async listResources(): Promise<unknown> {
    const res = await this.get("/v1/resources");
    return res.json();
  }

  /** Reads an upstream resource by ID. */
  async readResource(resourceId: string): Promise<unknown> {
    return this.postJson("/v1/resources/read", { resource_id: resourceId });
  }

  /** Lists all registered prompt templates. */
  async listPrompts(): Promise<unknown> {
    const res = await this.get("/v1/prompts");
    return res.json();
  }

  /** Renders a prompt template with arguments. */
  async getPrompt(promptId: string, args: Record<string, unknown> = {}): Promise<unknown> {
    return this.postJson("/v1/prompts/get", { prompt_id: promptId, arguments: args });
  }

  // ------------------------------------------------------------------
  // SSE streaming
  // ------------------------------------------------------------------

  /**
   * Connects to the catalog mutation SSE stream.
   *
   * Yields parsed event data objects as they arrive. The caller should
   * iterate with `for await` and handle reconnection as needed.
   */
  async *watchCatalogUpdates(): AsyncGenerator<{ event: string; data: unknown }> {
    const res = await this.get("/v1/resources/updates");
    if (!res.body) return;

    const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
    let buffer = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += value;

      const parts = buffer.split("\n\n");
      buffer = parts.pop() ?? "";

      for (const part of parts) {
        const lines = part.split("\n");
        let event = "message";
        let data = "";

        for (const line of lines) {
          if (line.startsWith("event:")) event = line.slice(6).trim();
          else if (line.startsWith("data:")) data += line.slice(5).trim();
        }

        if (data) {
          try {
            yield { event, data: JSON.parse(data) };
          } catch {
            yield { event, data };
          }
        }
      }
    }
  }
}

export {
  WarmplaneClient,
  WarmplaneError,
  type Envelope,
  type EnvelopeError,
  type RetryInfo,
  type CapabilityEntry,
  type CatalogResponse,
  type SearchResult,
  type SearchResponse,
  type BatchStep,
  type DistillOptions,
};
```

---

## Usage Examples

### 1. Discover and list capabilities

```typescript
const wp = new WarmplaneClient("http://127.0.0.1:9090");

// First call fetches the full catalog
const catalog = await wp.listCapabilities();
if (catalog) {
  console.log(`Catalog version: ${catalog.catalog_version}`);
  for (const cap of catalog.capabilities) {
    console.log(`  ${cap.id} — ${cap.summary}`);
  }
}

// Second call uses ETag — returns null on 304
const cached = await wp.listCapabilities();
if (cached === null) {
  console.log("Catalog unchanged (304 Not Modified)");
}
```

### 2. Describe a capability and call it

```typescript
const wp = new WarmplaneClient();

// Fetch full schema to understand required arguments
const schema = await wp.describeCapability("filesystem.read_file");
console.log("Schema:", JSON.stringify(schema, null, 2));

// Execute the tool
const result = await wp.callTool("filesystem.read_file", {
  path: "/tmp/example.txt",
});
console.log("Result:", JSON.stringify(result.data, null, 2));
```

### 3. Context distillation — limit large outputs

```typescript
const wp = new WarmplaneClient();

const result = await wp.callToolDistilled(
  "sqlite.read_query",
  { query: "SELECT * FROM users" },
  {
    jsonpath: "$.records[*].email",  // JSONPath filter
    limitLines: 10,                   // Max 10 lines
  },
);

console.log(JSON.stringify(result.data, null, 2));
```

### 4. Multi-step chained batch call

```typescript
const wp = new WarmplaneClient();

const result = await wp.batchCall([
  {
    id: "step1",
    capability_id: "db.get_customer",
    args: { customer_id: "cust_123" },
  },
  {
    id: "step2",
    capability_id: "stripe.get_invoice",
    args: { invoice_id: "$step1.latest_invoice_id" },
    continue_on_error: false,
  },
]);

console.log(JSON.stringify(result, null, 2));
```

### 5. Search capabilities with hybrid ranking

```typescript
const wp = new WarmplaneClient();

const results = await wp.searchCapabilities("find production error logs", 5);

for (const cap of results.capabilities) {
  console.log(`[${cap.score.toFixed(2)}] ${cap.id} — ${cap.summary}`);
}
```

### 6. Idempotent tool call with retry safety

```typescript
const wp = new WarmplaneClient();
const key = "payment-charge-ord-42";

// First call executes upstream
const r1 = await wp.callTool(
  "payments.charge",
  { amount: 100, currency: "USD" },
  key,
);
console.log("First:", r1.retry);

// Second call with same key returns cached result — no re-execution
const r2 = await wp.callTool(
  "payments.charge",
  { amount: 100, currency: "USD" },
  key,
);
console.log("Second:", r2.retry);
```

### 7. Watch catalog updates via SSE

```typescript
const wp = new WarmplaneClient();

for await (const event of wp.watchCatalogUpdates()) {
  console.log(`[${event.event}]`, JSON.stringify(event.data, null, 2));
}
```

---

## Error Handling

All methods that return envelopes throw `WarmplaneError` when `ok` is `false`. The error carries a typed `code` you can match against:

```typescript
import { WarmplaneError } from "./warmplane-client";

try {
  await wp.callTool("nonexistent.tool", {});
} catch (err) {
  if (err instanceof WarmplaneError) {
    switch (err.code) {
      case "TOOL_NOT_FOUND":
        console.error("Tool does not exist — check capability ID");
        break;
      case "POLICY_DENIED":
        console.error("Blocked by security policy");
        break;
      case "APPROVAL_PENDING":
        console.error("Awaiting operator approval");
        break;
      case "CIRCUIT_OPEN":
        console.error("Upstream circuit breaker tripped — retry later");
        break;
      default:
        console.error(`Unexpected error: ${err.message}`);
    }

    if (err.retryable) {
      console.log("This error is transient — safe to retry");
    }
  }
}
```

### Standard Error Codes

| Code | HTTP | Meaning |
|:---|:---:|:---|
| `TOOL_NOT_FOUND` | 404 | Capability ID does not exist or is policy-blocked |
| `INVALID_ARGS` | 400 | Arguments failed JSON schema validation |
| `POLICY_DENIED` | 403 | Blocked by deny rule |
| `APPROVAL_PENDING` | 202 | Intercepted by HITL — awaiting operator decision |
| `CIRCUIT_OPEN` | 503 | Upstream circuit breaker tripped |
| `UPSTREAM_TIMEOUT` | 504 | Upstream exceeded `toolTimeoutMs` |

See the [User Guide](USER-GUIDE.md) for the complete error code table and the [Whitepaper](WHITEPAPER.md) for architectural context.

---

## Runtime Compatibility

The client uses only standard Web APIs (`fetch`, `ReadableStream`, `TextDecoderStream`) and works out of the box with:

- **Bun** ≥ 1.0
- **Node.js** ≥ 18 (native fetch)
- **Deno** ≥ 1.28
- **Browsers** (for dashboard or admin UI integrations)

No polyfills, no build step, no bundler configuration required.

---

## Next Steps

- **Typed error codes**: Extend `WarmplaneError.code` to a string union type for exhaustive switch matching.
- **Retry middleware**: Wrap `callTool` with automatic retry logic that respects `retryable` and `classification` fields.
- **HITL integration**: Poll `GET /v1/approvals` to build operator approval workflows.
- **Audit queries**: Use `GET /v1/audit/events` to pull execution history for compliance reporting.