Repository navigation
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.
| 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 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. -
Application service (
packages/core/src/services/kera-service.ts) exposes:listRequestsinspectRequestreplayRequestdiffPayloadsclearTrafficgetTunnelStatus
-
MCP adapter (
packages/mcp/) validates tool inputs, delegates toKeraService, 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.
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.jsdirectly 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
EADDRINUSEmessage. - A tunnel failure does not prevent the proxy, database, or MCP server from starting.
- With
logLevelinfoordebug, Kera prints a readiness line tostderr.
On SIGINT, SIGTERM, or stdin closure:
- Kera stops accepting MCP calls and HTTP connections.
- Active tool calls are allowed to finish.
- The tunnel child is closed (
SIGTERM, thenSIGKILLafter 2 seconds). - Active HTTP connections get up to 5 seconds to drain.
- SQLite is closed.
- Queued stdout replies get up to 1 second to flush.
This prevents a stalled MCP client from holding the process open indefinitely.
- Hono and
@hono/node-serveraccept HTTP onlistenHost/listenPort. - A request with any
x-kera-hopheader receives508 Loop Detectedbefore Kera reads the body or sends100 Continue. It is not forwarded or captured. - The proxy assigns a UUID and start time.
- 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.
- Both directions remove connection-specific headers, including fields named by
Connection. Outbound requests get the upstreamHost,x-kera-hop: 1, and fresh framing. - Both bodies stream with backpressure. Capture retains up to
maxBodyBytesper body while counting all observed bytes. A truncation flag means the limit was exceeded. Interrupted streams record an error and received byte count. - The upstream deadline defaults to 30 seconds. Kera returns
502for upstream failure or504for timeout before downstream headers are sent. After headers, an interrupted response is closed. - On response finish or disconnect, the capture service derives provider metadata from request
headers and available bytes, then inserts the row through
RequestRepository. - A SQLite write error is logged to
stderrwith the capture ID and does not change the HTTP response.
-
Raw payloads: stored verbatim as
Uint8Array/ SQLiteBLOB. -
Headers: lowercase names, multi-value headers preserved as
Record<string, string | string[]>. Repeated values such asset-cookiestay separate. -
Bodies: empty capture stores
NULLwith size zero. A truncated body stores the retained prefix and the original size. - Redaction: applied to output, never written over raw capture bytes.
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.comhostname. -
TUNNEL_*,CLOUDFLARED_*, andNO_TLS_VERIFYare 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 redactedtargetUrlwhen active. -
get_tunnel_urlis registered even when tunneling is disabled; it reports status rather than failing. - Local capture remains available if
cloudflaredis missing, offline, or exits.
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_versiononly when the schema changes commit. - An up-to-date database needs no migration write lock.
- Schema version 1 creates the
requeststable.
| 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:
-
timestampis Unix epoch milliseconds. -
duration_msis elapsed milliseconds when available. - Body sizes are original byte counts; truncation flags are
0or1. - When a BLOB exists, its length equals the original size for an untruncated body or is smaller for a truncated body.
-
replayed_from_idis optional metadata, so it remains usable after retention removes the original row. - Indexes cover
timestamp,response_status,provider, andpath. -
listSummaries()projects metadata without loading header/body BLOBs and supports limit (default 100), status (nullfor 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.
- 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.
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_ARGUMENTSerror without echoing caller input. - Results include
structuredContentand a JSON text representation. - Errors return
{ ok: false, error: { code, message } }. - The 64 KiB result cap returns
OUTPUT_LIMITrather than a truncated envelope. - Captured content is treated as untrusted data.
See MCP Tools Reference for every schema and output shape.
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-sqlite3Run pnpm run check before opening a pull request.
Tests are deterministic and local; they do not call Stripe, GitHub, or other live services.
- 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.
-
cloudflaredURL parsing, readiness, timeouts, shutdown, and diagnostic redaction.
- 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-hopaborts 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 offstdout,get_tunnel_urlactive payload, and child reaping on shutdown.
- 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
stdoutcontains only valid MCP protocol traffic. - Inspect
pnpm pack --dry-runand run the clean-environmentnpxhandshake.
- Read
AGENTS.md,docs/DESIGN.md, and the active roadmap phase. - Stay within the active milestone; do not pull Phase 2/3 work into Phase 1.
- Keep core logic in
packages/core/and adapters thin. - Avoid
any; narrowunknownat boundaries with Zod or guards. - Validate every external input: flags, env vars, tool args, URLs, headers, SQLite rows.
- Preserve raw bytes and multi-value headers.
- Keep redaction centralized.
- Treat captured data as untrusted.
- Never write to
stdout; useconsole.error(stderr). - Add or update tests for every behavior change. Every bug fix needs a regression test.
- Update
README.mdanddocs/with behavior/config/tool changes. - Run
pnpm run check. - Inspect
git status/git difffor secrets,.env,.db, and stray files. - Use a conventional commit message and a focused PR.
- Include a changeset (
pnpm changeset) for user-facing changes. - Never force-push or bypass hooks.
- Scope matches the active milestone.
- Core/adapter boundary respected.
- Schema/config docs updated.
- Tests cover success, edge, and failure paths.
-
stdoutisolation preserved (noconsole.log). - No secrets, databases, or customer payloads committed.
-
pnpm run checkpasses locally. - Changeset included when publishable.
Use templates/PULL_REQUEST_CHECKLIST.md before submitting.
See Roadmap, Configuration and Flags, and the repository architecture guide.
- MCP Tools Reference
- Webhook Providers and Plugins
- Security and Privacy
- Privacy and Data Handling
- Architecture and Contributing
- Roadmap
- GitHub repository
- Issues
- Releases
- npm:
kera-mcp·kera-terminal - Glama listing
-
Official MCP Registry (
io.github.mcdavidobioha/kera) - Contributing guide
- Security policy