Skip to content

Architecture and Contributing

Mcdavid Obioha edited this page Dec 1, 2026 · 3 revisions

Architecture and Contributing

Kera is a TypeScript workspace with a reusable core engine and thin interface adapters for MCP stdio, the Terminal CLI, and the Local Dashboard.


Repository layout

Path Responsibility
packages/core/ Configuration, proxy, capture, SQLite, replay, redaction, compression, providers, and tunnels.
packages/mcp/ MCP stdio adapter: validate tool arguments with Zod, call KeraService, and format bounded results.
packages/cli/ Terminal commands, interactive feed, and dashboard startup.
packages/dashboard/ Loopback API, live SSE feed, and browser assets bundled with the CLI build.
tests/unit/ Pure unit tests for redaction, providers, compression, config, replay guards, diffs, and tunnel parsing.
tests/integration/ Proxy/capture, SQLite, replay, and service integration tests.
packages/*/tests/ Runtime registry, built CLI, dashboard API, and spawned MCP stdio tests.
skills/ Reusable agent skills (engineering-workflow, webhook-debugging).
docs/ Design, architecture, setup, configuration, providers, security, development, publishing, roadmap.

Core vs. adapter boundary

  1. Core engine (packages/core/) owns HTTP proxying, raw byte/header capture, SQLite persistence, replay execution, destination/loop guards, redaction, compression, provider detection, and the tunnel provider. It has no knowledge of MCP transport or CLI formatting.
  2. Application service (packages/core/src/services/kera-service.ts) exposes:
    • listRequests
    • inspectRequest
    • replayRequest
    • diffPayloads
    • clearTraffic
    • getTunnelStatus
  3. MCP adapter (packages/mcp/) validates tool inputs, delegates to KeraService, and formats structured results. It must not contain SQL, proxy, replay, provider, redaction, or tunnel process logic.

MCP handlers return structured data plus a JSON text representation. List output is capped at 24 KiB of summaries; the whole tool result is capped at 64 KiB.


Startup lifecycle

dist/index.js
   │
   ├─ parseStartupArguments()
   ├─ loadConfig()
   │    ├─ flags > KERA_* > defaults
   │    ├─ validate target/host/port/limits
   │    ├─ reject self-target
   │    ├─ enforce tunnel => listenHost === 127.0.0.1
   │    └─ prepare ~/.kera with 0700
   ├─ openDatabase(~/.kera/traffic.db)   WAL + migrations
   ├─ startProxyServer()                 bind 127.0.0.1:4000
   ├─ if --tunnel: CloudflaredTunnel.start(listenPort)   async
   ├─ KeraService(repository, config, tunnel)
   ├─ MCP Server + StdioServerTransport
   └─ stdout: JSON-RPC only / stderr: diagnostics
  • Running dist/index.js directly starts the MCP process. Importing the package keeps the library API side-effect free.
  • If the listening port is already bound, startup fails with an actionable EADDRINUSE message.
  • A tunnel failure does not prevent the proxy, database, or MCP server from starting.
  • With logLevel info or debug, Kera prints a readiness line to stderr.

Shutdown

On SIGINT, SIGTERM, or stdin closure:

  1. Kera stops accepting MCP calls and HTTP connections.
  2. Active tool calls are allowed to finish.
  3. The tunnel child is closed (SIGTERM, then SIGKILL after 2 seconds).
  4. Active HTTP connections get up to 5 seconds to drain.
  5. SQLite is closed.
  6. Queued stdout replies get up to 1 second to flush.

This prevents a stalled MCP client from holding the process open indefinitely.


Proxy and capture lifecycle

  1. Hono and @hono/node-server accept HTTP on listenHost/listenPort.
  2. A request with any x-kera-hop header receives 508 Loop Detected before Kera reads the body or sends 100 Continue. It is not forwarded or captured.
  3. The proxy assigns a UUID and start time.
  4. Kera forwards the original method, origin-form path, and raw query using Node's raw HTTP bindings. Only the configured target origin is used. Upstream redirects are returned, not followed.
  5. Both directions remove connection-specific headers, including fields named by Connection. Outbound requests get the upstream Host, x-kera-hop: 1, and fresh framing.
  6. Both bodies stream with backpressure. Capture retains up to maxBodyBytes per body while counting all observed bytes. A truncation flag means the limit was exceeded. Interrupted streams record an error and received byte count.
  7. The upstream deadline defaults to 30 seconds. Kera returns 502 for upstream failure or 504 for timeout before downstream headers are sent. After headers, an interrupted response is closed.
  8. On response finish or disconnect, the capture service derives provider metadata from request headers and available bytes, then inserts the row through RequestRepository.
  9. A SQLite write error is logged to stderr with the capture ID and does not change the HTTP response.

Normalization rules

  • Raw payloads: stored verbatim as Uint8Array / SQLite BLOB.
  • Headers: lowercase names, multi-value headers preserved as Record<string, string | string[]>. Repeated values such as set-cookie stay separate.
  • Bodies: empty capture stores NULL with size zero. A truncated body stores the retained prefix and the original size.
  • Redaction: applied to output, never written over raw capture bytes.

Tunnel lifecycle (Milestone 7)

config.tunnel === true
        │
        ▼
CloudflaredTunnel.start(listenPort)
        │
        ├─ spawn cloudflared
        │    (config disabled, no autoupdate, metrics loopback,
        │     --url http://127.0.0.1:<port>)
        ├─ status: starting
        ├─ parse stdout/stderr for trycloudflare.com URL
        ├─ require "Registered tunnel connection"
        ├─ status: active
        └─ get_tunnel_url reads status via KeraService

Interface:

export interface TunnelProvider {
  start(localPort: number): Promise<{ url: string; close(): Promise<void> }>;
  getUrl(): string | null;
  getStatus(): TunnelStatus;
}

TunnelStatus is one of:

{ state: 'idle' | 'starting' }
{ state: 'active'; url: string }
{ state: 'failed'; message: string }

Behavior:

  • Only one Quick Tunnel may be starting or active at a time.
  • Startup allows 30 seconds for a URL plus edge registration.
  • Accepted URLs must match a validated https://*.trycloudflare.com hostname.
  • TUNNEL_*, CLOUDFLARED_*, and NO_TLS_VERIFY are filtered from the child environment.
  • Both child streams are logged to Kera's stderr, with recognized URL credentials/query secrets masked.
  • KeraService.getTunnelStatus() maps provider status and includes a redacted targetUrl when active.
  • get_tunnel_url is registered even when tunneling is disabled; it reports status rather than failing.
  • Local capture remains available if cloudflared is missing, offline, or exits.

SQLite schema and migrations

Open with openDatabase(config.dataDir), then create new RequestRepository(database, config.maxStoredRequests). The caller owns the connection and closes it with database.close().

  • SQLite uses WAL mode.
  • Migrations run inside a write transaction and advance PRAGMA user_version only when the schema changes commit.
  • An up-to-date database needs no migration write lock.
  • Schema version 1 creates the requests table.
SQLite type Columns
TEXT PRIMARY KEY id
TEXT NOT NULL method, path, raw_query, request_headers_json
TEXT (nullable) provider, event_type, response_headers_json, error_message, replayed_from_id
INTEGER NOT NULL timestamp, request_body_size, request_body_truncated, response_body_size, response_body_truncated
INTEGER (nullable) response_status, duration_ms
BLOB (nullable) request_body, response_body

Details:

  • timestamp is Unix epoch milliseconds.
  • duration_ms is elapsed milliseconds when available.
  • Body sizes are original byte counts; truncation flags are 0 or 1.
  • When a BLOB exists, its length equals the original size for an untruncated body or is smaller for a truncated body.
  • replayed_from_id is optional metadata, so it remains usable after retention removes the original row.
  • Indexes cover timestamp, response_status, provider, and path.
  • listSummaries() projects metadata without loading header/body BLOBs and supports limit (default 100), status (null for no response), provider, and literal path substring filters.
  • getById() loads and validates the full record.
  • deleteOlderThan(minutes) deletes strictly older rows; deleteAll() removes all rows.

Retention

  • Inserts and pruning commit together in one transaction.
  • Every persisted row counts, including failures and replay captures.
  • The newest timestamps are retained; later inserts win timestamp ties.
  • Default ring buffer: 1000 rows.
  • prune() applies the limit to existing rows and returns the number removed.

MCP tool architecture

packages/mcp/src/server.ts registers:

Tool Service call
list_requests service.listRequests
inspect_request service.inspectRequest
replay_request service.replayRequest
diff_payloads service.diffPayloads
clear_traffic service.clearTraffic
get_tunnel_url service.getTunnelStatus
get_status Core runtime registry (listRuntimeInstances)
stop_server Core runtime registry (stopRuntimeInstances)

Shared behavior:

  • Zod schemas are strict; unknown fields are rejected.
  • Invalid inputs return a generic INVALID_ARGUMENTS error without echoing caller input.
  • Results include structuredContent and a JSON text representation.
  • Errors return { ok: false, error: { code, message } }.
  • The 64 KiB result cap returns OUTPUT_LIMIT rather than a truncated envelope.
  • Captured content is treated as untrusted data.

See MCP Tools Reference for every schema and output shape.


Development commands

Prerequisites: Node.js 20+ (22 recommended), pnpm 10 pinned in package.json, Git >=2.40. A C++ toolchain may be needed if better-sqlite3 must compile for your OS/Node ABI.

git clone https://github.com/mcdavidobioha/kera.git
cd kera
git switch -c fix/my-change
pnpm install
Command Purpose
pnpm run build Bundle ESM output and TypeScript declarations into dist/
pnpm run dev Run Kera directly in TypeScript
pnpm run typecheck Strict TypeScript checking
pnpm run lint Style, strict typing, and no-console (stdout isolation)
pnpm run format Format source and docs
pnpm run format:check Verify formatting without mutating files
pnpm test Run unit and integration suites
pnpm run check Lint + format check + typecheck + tests + build

If you switch Node major versions and hit a SQLite native-module mismatch:

pnpm rebuild better-sqlite3

Run pnpm run check before opening a pull request.


Testing strategy

Tests are deterministic and local; they do not call Stripe, GitHub, or other live services.

Unit

  • Redaction of headers (case-insensitive, multi-value), query values, nested JSON, and diagnostic URLs.
  • Provider detection from headers and bodies.
  • Compression, truncation markers, HTML summaries, and JSON compaction.
  • JSON payload diffs, including nested objects, arrays, and masked fields.
  • Configuration parsing, validation, tunnel host rules, and self-loop rejection.
  • Replay URL/address/redirect validation.
  • Retention and pruning.
  • cloudflared URL parsing, readiness, timeouts, shutdown, and diagnostic redaction.

Integration

  • Proxy forwards method, path, query, normalized multi-value headers, and raw bytes.
  • Response status/headers/body captured without mutating binary data.
  • Upstream timeout (504) and failure (502) are captured.
  • x-kera-hop aborts circular forwarding.
  • SQLite persists across restart.
  • Migrations work from empty and prior schemas.
  • Replay uses the configured target and stores replayed_from_id.
  • Replay rejects unsafe destinations and redirects.
  • MCP tools return bounded, redacted output.
  • Milestone 7: tunnel disabled state, missing cloudflared, diagnostics kept off stdout, get_tunnel_url active payload, and child reaping on shutdown.

End-to-end / smoke

  • Start a fixture app.
  • Start Kera in a separate process.
  • Send a webhook through Kera.
  • Confirm the app receives it.
  • Connect over MCP stdio, list, inspect, replay, and inspect the replay.
  • Confirm stdout contains only valid MCP protocol traffic.
  • Inspect pnpm pack --dry-run and run the clean-environment npx handshake.

Contribution guidelines

  1. Read AGENTS.md, docs/DESIGN.md, and the active roadmap phase.
  2. Stay within the active milestone; do not pull Phase 2/3 work into Phase 1.
  3. Keep core logic in packages/core/ and adapters thin.
  4. Avoid any; narrow unknown at boundaries with Zod or guards.
  5. Validate every external input: flags, env vars, tool args, URLs, headers, SQLite rows.
  6. Preserve raw bytes and multi-value headers.
  7. Keep redaction centralized.
  8. Treat captured data as untrusted.
  9. Never write to stdout; use console.error (stderr).
  10. Add or update tests for every behavior change. Every bug fix needs a regression test.
  11. Update README.md and docs/ with behavior/config/tool changes.
  12. Run pnpm run check.
  13. Inspect git status / git diff for secrets, .env, .db, and stray files.
  14. Use a conventional commit message and a focused PR.
  15. Include a changeset (pnpm changeset) for user-facing changes.
  16. Never force-push or bypass hooks.

PR checklist

  • Scope matches the active milestone.
  • Core/adapter boundary respected.
  • Schema/config docs updated.
  • Tests cover success, edge, and failure paths.
  • stdout isolation preserved (no console.log).
  • No secrets, databases, or customer payloads committed.
  • pnpm run check passes locally.
  • Changeset included when publishable.

Use templates/PULL_REQUEST_CHECKLIST.md before submitting.


See Roadmap, Configuration and Flags, and the repository architecture guide.

Clone this wiki locally