Chronos DB, self-hosted
Serve: HTTP API and clients
chronos serve: the HTTP API, tokens, the Postgres wire port, MCP, and the Python and TypeScript clients.
Self-hostedChronos DB is one binary you run yourself. Releases and install script. To put agents on a database you already run, with approvals: Chronos Gateway
Start a server
chronos serve opens a database folder and serves it on two ports until Ctrl-C or SIGTERM: an HTTP JSON API and the Postgres protocol. A new folder name makes a new database. A server must own its folder: it never joins another process that has the folder open.
chronos serve <folder> [--listen 127.0.0.1:7070] [--pg 127.0.0.1:5433|off] [--token T] [--admin-token A] [--safe | --unsafe] [--tls-cert cert.pem --tls-key key.pem | --insecure-no-tls] [--studio-api] [--refresh-every 5m] [--follow] [--source-file FILE]chronos serve mydbchronos: a new database: main is protected (protect_main): its rows change only by merging a world, even with the server's token. Work in a world (CREATE WORLD w; USE WORLD w), then MERGE WORLD wchronos: serving on http://127.0.0.1:7070 (POST /v1/<op>; GET /v1/health)chronos: postgres protocol on 127.0.0.1:5433 (psql postgres://127.0.0.1:5433/main)export CHRONOS_TOKEN=$(openssl rand -hex 24) # the guest'sexport CHRONOS_ADMIN_TOKEN=$(openssl rand -hex 24) # the database's own userchronos serve mydb --listen 10.0.0.5:7070 --pg 10.0.0.5:5433 --tls-cert cert.pem --tls-key key.pem- A new folder protects main. A folder
chronos servemakes starts withprotect_mainon: its rows change only by merging a world, for every token.CHRONOS_PROTECT_MAIN=offmakes a new folder without it. - Stopping closes the database cleanly. If closing fails, the server says so and the next open recovers from the log.
- Other
chronoscommands on the folder (the shell,chronos mcp,chronos studio,chronos import) join the running server over the folder’s Unix socket. Tokens and--safedo not apply there: the socket is for the OS user who owns the folder.
Flags
Flags may go anywhere on the line. A flag that takes a value and has none prints the usage and exits with code 2. An empty --token, --admin-token, --tls-cert or --tls-key, or its variable, counts as not given.
| Flag | Default | Effect |
|---|---|---|
| --listen <addr> | 127.0.0.1:7070 | the HTTP API’s address |
| --pg <addr>|off | 127.0.0.1:5433 | the Postgres protocol’s address; off turns it off |
| --token <T> | CHRONOS_TOKEN | the server token: the HTTP bearer token and the Postgres password. At least 24 characters; change-me is refused. A client that sends it is the guest. Needed for any address that is not loopback |
| --admin-token <A> | CHRONOS_ADMIN_TOKEN | the token that is the database’s own user over the network. At least 24 characters. It must differ from the server token |
| --safe | off | every client that is not an agent, a role with its password, or the admin token is the guest, loopback without a token too |
| --unsafe | off | the server token is the database’s own user, as before 0.4. Not with --safe |
| --tls-cert <file> | CHRONOS_TLS_CERT | PEM certificate chain. With --tls-key: HTTPS only, and TLS required on the Postgres port. Needed for any address that is not loopback, unless --insecure-no-tls |
| --tls-key <file> | CHRONOS_TLS_KEY | PEM private key (PKCS#8, PKCS#1 or SEC1) |
| --insecure-no-tls | off | listen on an address that is not loopback without TLS, with a warning at start: only where something else encrypts the connection (a VPN, a TLS proxy in front, a container port published only on 127.0.0.1) |
| --studio-api | off | also answer POST /studio/api/<op> on the HTTP port, for the admin token only. Needs an admin token |
| --refresh-every <time> | off | in an attached folder: main takes the source’s rows on a timer. A time such as 60s, 5m or 1h |
| --follow | off | in an attached folder: main takes the source’s changes as they happen, about a second after they commit |
| --source-file <file> | CHRONOS_SOURCE_FILE | in an attached folder: the file that holds the source’s connection string |
| --remote <url> | none | back the folder with object storage (a build with --features s3); --takeover replaces a dead owner’s lease |
| --anchor <file> | CHRONOS_ANCHOR | refuse the folder if its files were rolled back; --anchor-reset accepts it as it is once |
The server checks these before it listens, and exits with code 1 and a message when one fails:
| Message | When |
|---|---|
| refusing to listen on … without a token: pass --token or set CHRONOS_TOKEN | an address that is not loopback, and no server token |
| refusing to listen on … without TLS | an address that is not loopback, no certificate and key, and no --insecure-no-tls |
| refusing to start: the … is shorter than 24 characters | a server or admin token under 24 characters |
refusing to start: the … is the documented placeholder change-me | the placeholder older examples used |
| refusing to start: the server token and the admin token are the same | one string for both (compared after SASLprep) |
| refusing to start: --safe and --unsafe can’t both be given | both flags |
| refusing to start: --studio-api needs an admin token | --studio-api without one |
| TLS needs both --tls-cert and --tls-key | one without the other |
- Loopback means every address the name resolves to is a loopback one (
127.x.x.x,::1,localhost). Give numeric addresses to be sure. - Pass tokens in the environment, not on the command line. A token passed as
--tokenshows in the process list (ps) to every user of the machine. - Tokens are kept only in the process. Changing one takes a restart. So does a certificate change.
Tokens and who a client is
There is one identity model on every port: the database’s own user, agents and the guest. On the Postgres port, a role made with CREATE ROLE ... LOGIN PASSWORD that proves its own password is that role, with the privileges it was given.
| Who | How they are identified | Writes | Merges into main | Agents, settings, backups |
|---|---|---|---|---|
| The database’s own user | the shell; a loopback client when the server has no token at all; the admin token; the server token only with --unsafe | everything | yes | yes |
| An agent, default rights | its own token | only worlds it forked | no | no |
| An agent with more rights | its own token | what its can list allows | with merge_own (its worlds) or merge (any) | with admin |
| The guest | the server token; or no token on a server that has an admin token; with --safe, every client that is not an agent, a role with its password, or the admin token | only worlds guest forked, shared by every guest | no | no |
| Someone on the network | nothing | nothing: a token is required off loopback (HTTP 401, Postgres 28P01) | no | no |
- Reads are not restricted. Anyone who may read reads every world,
mainand the past included. There are no per-table, per-row or per-world read rights. An agent held to one tenant reads only that tenant’s rows, and masked columns show agents a stand-in. - The guest has no quotas, and all guests share one set of worlds: any of them can change or discard what another guest forked. Give each agent a token of its own.
- With
--tokenand no--admin-token, nobody over the network is the database’s own user: the shell on the database’s machine is. The server says so as it starts. - With
--admin-tokenand no--token(loopback only), a request with no token is the guest. - Failed logins slow down, per client address, on both ports together. After 10 wrong passwords or tokens the address waits 1 s before its next try, then 2 s, 4 s, up to 60 s. A try during the wait is refused at once (HTTP
429, Postgres28P01), the right password too. The count is forgotten 15 minutes after the address’s last failure.CHRONOS_LOGIN_FREE_TRIESchanges the 10. Clients behind one proxy share its address.
Default, safe and unsafe
The mode decides who a client is when it proves neither an agent’s token nor the admin token, and is not a role with its password.
| Mode | No token sent | The server token | The admin token |
|---|---|---|---|
| default | the database’s own user when the server has no token at all (loopback only); the guest when it has only an admin token; 401 when it has a server token | the guest | the database’s own user |
| --safe | the guest, on a server without a server token too | the guest | the database’s own user |
| --unsafe | as default | the database’s own user, as every server ran before 0.4 | the database’s own user |
- The default changed in 0.4. Before 0.4 the server token was the database’s own user. Since 0.4 it is the guest’s. A deployment that upgrades from 0.3 sets
CHRONOS_ADMIN_TOKENfor the people and the application that own the data, or passes--unsafeto run exactly as before. --unsafewarns at start on an address other machines can reach, unlessprotect_mainis on: the server token can then change main directly, with no world and no review.- Agents keep their own rights in every mode. A role that proves its own password is that role in every mode, never the guest.
HTTP requests
Every operation is POST /v1/<op> with a JSON body, and replies are JSON. Every operation takes branch, the world it works on (default main). Rows go in and come out as JSON objects.
curl -s https://db.internal:7070/v1/get \ -H "Authorization: Bearer $CHRONOS_ADMIN_TOKEN" \ -H 'Content-Type: application/json' \ -d '{"branch":"main","table":"users","id":"1"}'| Request | Gets |
|---|---|
| GET /v1/health | always answered, no auth |
| no header, server has no token at all (loopback only) | the database’s own user; the guest with --safe |
| no header, server has an admin token but no server token | the guest |
| no header, server has a server token | 401 missing token |
| the server token | the guest; the database’s own user with --unsafe |
| the admin token | the database’s own user |
| an enabled agent’s token | that agent |
| any other token (a typo, a disabled or dropped agent’s), even with no server token | 401 wrong token |
| any token, from an address that sent more than 10 wrong ones lately | 429 too many wrong tokens from this address until it has waited |
| an agent or the guest doing what it may not | 403 |
- The header is
Authorization: Bearer <token>: the wordBearer, one space, the token. - Bodies must be sent with
Content-Type: application/json(415otherwise) and aContent-Length(chunked bodies get411). At most 32 MB (413). Request headers at most 64 KB (431). - Web pages cannot use it. A request with an
Originheader gets403. Without a server token, theHostmust belocalhost,127.x.x.xor[::1](403otherwise, against DNS rebinding). - A request is checked from its headers (token,
Origin,Host) before its body is read. It must arrive within 2 minutes (CHRONOS_REQUEST_TIMEOUT, seconds). A connection idle for 60 seconds is closed. - At most 1000 connections at once (
503;CHRONOS_MAX_CONNECTIONS, lowered to what the process’s open-file limit holds). - Every response says
X-Content-Type-Options: nosniffandCache-Control: no-store, and over TLSStrict-Transport-Security: max-age=31536000. - Reading the past: any
branchthat is read (get,find,sql,diff) can be a world as it was:main@2026-09-20 10:00ormain@-1 hour. - A session’s transaction world (
_tx_…) named asbranch,from,intoorworldis404 no world.
Errors and statuses
{ "error": "no branch 'x'; see: branches, or create it with: fork x" }{ "error": { "message": "table \"userz\" does not exist", "code": "42P01" } }{ "error": { "message": "1 rows changed on both sides; nothing merged. Retry with resolve: ours or theirs, columns: true, or picks (see dry_run: true)", "conflicts": [ { "key": "users/1", "base": {…}, "ours": {…}, "theirs": {…}, "explain": "…" } ] } }error is a string, or an object with a message, plus code from the sql op and conflicts from a merge. Read error.message ?? error. The TypeScript and Python clients do this and raise ChronosError.
| Status | Meaning |
|---|---|
| 400 | bad input: a body that is not JSON or lacks a field, an invalid value; merging main; for sql, any SQLSTATE not listed below (40001 and 57014 included) |
| 401 | missing or wrong token |
| 403 | an agent or the guest may not (42501); _sonos tables; /metrics with an agent’s token; merge_outcomes with any but the admin token; any request with an Origin header; without a server token, a Host that is not loopback |
| 404 | no such world or row; for sql, 3D000 and 42P01; an unknown endpoint or operation |
| 405 | not POST (only /v1/health and /metrics take GET) |
| 409 | merge conflicts; a world that already exists or has forks; a stale world (55000); a constraint violation (23xxx); a merge whose result breaks a merge check (23514) |
| 411 | no Content-Length |
| 413 | a body over 32 MB; a query past its agent’s max_memory_mb (53200) |
| 415 | a body without Content-Type: application/json |
| 429 | an agent writing too fast or running max_concurrent requests; a fork past max_worlds; an address waiting after wrong tokens |
| 431 | request headers too large |
| 500 | storage error (58030; for sql, any 58xxx or XXxxx). The status line says Internal Server Error from 0.5.2, where it said Error |
| 502 | refresh when the source cannot be read. The status line says Bad Gateway from 0.5.2, where it said Error |
| 503 | the server already has 1000 connections |
| 507 | a write past the operator’s disk cap (53100, CHRONOS_MAX_DISK_BYTES) |
Rows and SQL
| Op | Body | Reply |
|---|---|---|
| get | table, id | {id, row}, or 404 |
| put | table, id, record (an object, the whole row) | {ok, version} |
| delete | table, id | {ok, version}, or 404 |
| batch | rows: [{table, id, record | null}]: all or nothing; null deletes | {ok, count, version} |
| find | table, where ({field: value}), text, vector with vector_field, limit (20), offset, ef (the vector graph’s beam) | {total, hits: [{id, score, row}], next_offset} |
| sql | sql (one or more statements), params (values for $1, $2, ...) | {results: [{command, columns, types, rows}], version}: one result per statement; types are the columns’ Postgres type names; version is the branch’s after a write |
curl -s localhost:7070/v1/sql -H 'Content-Type: application/json' \ -d '{"branch":"agent-7","sql":"select name from users where id = $1","params":[1]}'Values in sql results
Each row is an object of column to value. Numbers, text, booleans and json/jsonb come as their JSON kinds, with two exceptions so nothing is lost on the way to a client whose JSON numbers are doubles.
numericvalues come as strings with their scale, as Postgres shows them:"15.00","16.50","NaN". Read them with a decimal type, or as a number where a double is enough.real(float4) values come with float4’s shortest digits, as Postgres shows them:0.1, not the double’s0.10000000149011612. Rows fromget,findanddiffdo the same.- Times, dates and intervals are ISO 8601 strings;
byteais\x...hex. - Each
sqlcall is its own session:BEGIN ... COMMITmust be within one call.
Worlds, diff and merge
| Op | Body | Reply |
|---|---|---|
| fork | name, from (default main; a name or a world ID), meta (object) | {ok, world} |
| branches (or worlds) | {branches: [world]} | |
| world | branch (a name or a world ID) | world |
| set_meta | branch, meta (object; null removes a key) | world |
| discard | branch, cascade: true (and every world forked from it) | {ok}; with cascade {ok, discarded} |
| diff | branch, to, sql: true, count: true, limit, after, deletes, readers: true, version | {changes: [{key, before, after, columns}], version} |
| check_reads | branch | {branch, stale, changed: [{checked_against, changed}]}; 409 (55000) for a world that does not check its reads |
| merge | branch, resolve, version or confirm: true, columns: true, picks, only_tables, only_keys, into, target, dry_run: true, confirm_deletes | {merged}, and merge (its id) in an attached database, and version when the branch stays |
A world is {name, id, parent, depth, created, version, flagged, meta, owner, expires, active, pinned, checkpoints}.
diff
to: the changes frombranchtoto, any two worlds or moments. Without it, whatbranchchanged since its fork.versionin the reply is the branch’s, read before the diff. Merge with it to merge no more than you saw. Send the first page’sversionwith later pages: if the branch changed since, the page is409.sql: truereturns{sql: [...]}instead: statements that make the change. Not with pages.count: truealone returns{total, tables: {name: n}, summary: [{table, deleted, updated, inserted}], effects: [{id, channel, payload, by, queued}]}. It walks the diff once and keeps no rows.summarylists the tables that delete most first;effects, withoutto, is what the world’s merge would send (NOTIFY ON MERGE).limitandafterpage it:{changes, next}, the firstnchanges with key afterafter, in key order.nextis the cursor for the next page,nullon the last. Memory followsn, not the size of the diff. Pages concatenated equal the unpagedchanges.deletes:truepages through only the rows deleted,falseonly the others, so a review reads the deletes first.readers: trueaddsreaders: [{table, columns, kind, reader, detail}]andcoveragefor the whole diff, even on a page: what in the database reads the columns it changes.
merge
| Field | Effect |
|---|---|
| resolve | fail (the default), ours (the world’s values) or theirs (the parent’s) for rows both sides changed |
| version | merge only if the branch is at this version: the one its last write, or a diff, returned |
| confirm: true | after a crash, merge a flagged branch as it is now, once you have checked its diff |
| columns: true | rows both sides changed merge column by column; only a column both changed conflicts |
| picks | {"table/id": "ours" | "theirs" | row | null}: settle rows one by one; null deletes |
| only_tables, only_keys | arrays: merge just those; the branch stays |
| into | another world to merge into; the branch stays |
| target | a dry run’s: rows settled are settled against the world merged into as the dry run saw it, 409 if it changed |
| dry_run: true | change nothing and return the plan |
| confirm_deletes | the number of rows the merge deletes, when its merge policy’s confirm_deletes_over asks a person for it. A wrong or missing count is refused (409) with the real one |
A dry run returns {rows: [{key, outcome, detail, delete, base, ours, theirs, result, columns}], summary: [{table, deleted, updated, inserted}], conflicts, blocked, readers, coverage, version, target}. The rows it deletes come first (delete: true). columns is {here, there, both} for a row both sides changed. blocked names the checks that would fail. Pass version to merge to merge only what the dry run showed, and target too when the merge settles rows. confirm_deletes: {deletes, over, policy} appears when the person merging must give the count.
In a folder attached to a database, a dry run of a merge into main adds postgres: {source, at, error, triggers, summary, rows: [{key, changed, postgres}]}: the rows it would write as the source has them now, read only and rolled back.
curl -s -H 'Content-Type: application/json' localhost:7070/v1/fork -d '{"name":"agent-7"}'curl -s -H 'Content-Type: application/json' localhost:7070/v1/put -d '{"branch":"agent-7","table":"users","id":"1","record":{"name":"Ada L."}}'# {"ok":true,"version":1}curl -s -H 'Content-Type: application/json' localhost:7070/v1/merge -d '{"branch":"agent-7","version":1}'# {"merged":1}Proposals and evidence
From 0.6.0, a world’s merge can be proposed, approved and merged as a proposal, with evidence attached. The ops are attach_evidence, propose, proposals, decide_proposal, withdraw_proposal and merge_proposal; merge also takes operation, an id that makes a retried merge into main return its first result. MCP adds the tools propose, attach_evidence and explain_merge. Each body and reply is in Merges: proposals and the ledger.
History, undo and simulations
| Op | Body | Reply |
|---|---|---|
| history | branch, limit (100) | {events: [{at, world, event, rows}]}, newest first |
| checkpoint | branch, name | {ok, at} |
| restore | branch, at (a time, or a time ago like -10 minutes), or checkpoint instead of at | {ok, restored} |
| undo_merge | branch (the world that was merged), skip_changed: true | {ok, parent, at, undone, skipped} |
| undo_merge | ids (merge ids, in a folder attached to a database), skip_changed: true, dry_run: true, allow_cascade: true | {ok, dry_run, undone, skipped, already, merge, rows: [{merge, table, op, key, before, after, status, now}], cascades, effects_not_undone} |
| simulate | worlds, prefix, script, score, from (default main; or name@when), keep (a number, or "all": the default), order (desc or asc), seed (0), threads | {worlds: [{world, id, index, seed, score, error, kept}], base, at, timings: {fork_ms, run_ms, discard_ms, total_ms}}, best first |
| replay | world (one a simulation kept), as (keep the replay under this name) | {world, replay, identical, rows_differing, score, recorded_score, error} |
- Undo by world rebuilds the merge from the folder’s history, so the merge must be within the history window (1 hour for a new database).
- Undo by merge id works in an attached folder. Every row those merges wrote is put back through the source in one transaction.
statusisput_back,changedoralready;mergein the reply is the undo’s own id. Rows changed since answer409with code40001; a cascade that is not allowed answers409with2BP01. - Rows already put back, from 0.5.2: a row that is as it was before its merge is
already, counted inalready, neither undone nor skipped. It never refuses the undo. So a merge undone in part can be undone again once the rows left hold what the merge wrote, and undoing a merge twice writes nothing and is not an error.
Agents and their tokens
An agent has a name, an ID, a token, a list of what it may do (can) and quotas. Its token is shown once, when it is made. Only the token’s hash is stored, with a SCRAM-SHA-256 verifier of it for Postgres logins.
| Op | Body | Reply |
|---|---|---|
| create_agent | name, can (list), max_worlds, max_changes, writes_per_minute, world_ttl (ms), max_query_ms, max_concurrent, max_memory_mb, max_idle_ms, max_threads, priority ("normal" or "low"), policy (a merge policy’s name, or null), tenant ("org_id = 42" or {"org_id": 42}), valid_for (ms: its token stops working after) | {agent, token}: the token only now |
| alter_agent | the same, plus disabled | {agent} |
| drop_agent | name | {ok} |
| agents | {agents: [...]} | |
| audit | agent, limit (100) | {events: [{at, agent, world, action, rows}]} |
| merge_outcomes | by ("policy"; default by agent) | {since, outcomes: [{agent, policy, worlds, on_rules, no_policy, approved, rejected, discarded, open, partly_merged, before_window, conflicts, stale_reads, check_refusals, holds, rules_rate}]}; the admin token only |
curl -s localhost:7070/v1/create_agent \ -H "Authorization: Bearer $CHRONOS_ADMIN_TOKEN" -H 'Content-Type: application/json' \ -d '{"name":"bot","can":["read","fork","write_own"],"max_worlds":10,"world_ttl":86400000}'# {"agent":{...},"token":"chronos_4f…"}curl -s localhost:7070/v1/alter_agent -H "Authorization: Bearer $CHRONOS_ADMIN_TOKEN" \ -H 'Content-Type: application/json' -d '{"name":"bot","disabled":true}'| Capability | Allows |
|---|---|
| read | reading any world, main and the past included: queries, get, find, diff, history, merge dry runs |
| fork | forking main; forking another world also needs the right to change it |
| write_own | changing worlds it forked: rows, tables, discarding them, their metadata and named checkpoints |
| write | changing any world but main, other agents’ included, and discarding them |
| write_main | changing main directly |
| merge_own | merging worlds it forked into their parent, if it may change that parent (main needs write_main too) |
| merge | merging any world |
| restore | RESTORE WORLD; with merge too, UNDO MERGE and UNDO AGENT |
| outbox | working main’s outbox: CLAIM OUTBOX, ACK OUTBOX, RETRY OUTBOX |
| unmask | reading masked columns as they are |
| admin | everything: managing agents, ALTER SYSTEM, BACKUP, VERIFY, and the HTTP ops for these |
- A new agent gets
read, fork, write_own: it works in its own worlds, and a person reviews and merges. - Tokens are
chronos_and 64 hex digits. An agent’s token acts as that agent on every port: HTTP bearer, Postgres password with the agent’s name as the user, andPOST /mcp. - Over a quota, an agent is refused:
403pastmax_worldsormax_changes;429when writing too fast or runningmax_concurrentrequests;413when a query passes itsmax_memory_mb;400with code57014pastmax_query_ms. - Names: letters, digits,
_and-.guestandsystemare the database’s own. - The
agentsandauditops needadmin. In SQL,SHOW AGENTSandSHOW AUDITare reads: names, rights, quotas and actions, never tokens. - A disabled or dropped agent’s token gets
401. A dropped agent’s worlds stay, still its own.
Backup, verify and metrics
| Op | Body | Reply |
|---|---|---|
| backup | to (a new folder on the server) | {files, bytes} |
| verify | {pages, bytes, log_records}; from 0.6.0 also violations: [{world, problem}], the rows that break a constraint |
Both need admin for an agent. GET /metrics gives Prometheus’ text format. It takes the server token (the guest may read them) or the admin token; an agent’s token gets 403. Latencies are a summary, chronos_op_seconds with op and quantile labels. chronos_connections_open and chronos_last_statement_unix_ms tell an idle database from a busy one.
Attached folders
A folder made by chronos attach is a copy of tables in a database you already run. chronos serve on it needs the source’s connection string too: CHRONOS_SOURCE_URL, or a file named by --source-file or CHRONOS_SOURCE_FILE. It is never a command argument and is written nowhere in the folder.
At start the server checks that the source answers as the one the folder was copied from. If it does not, the server warns, worlds keep working, and merges into main are refused until it does.
| Flag or op | Does |
|---|---|
| --refresh-every 5m | main takes the source’s rows on a timer. A refresh reads every attached table whole, in one snapshot. The value is whole seconds (60 or 60s), minutes (5m) or hours (1h), more than zero. A refresh that fails is said and tried again after the same wait |
| --follow | main takes only the rows that changed, about a second after they commit. Beside Postgres it reads a logical replication slot, which needs wal_level = logical; beside MongoDB (from 0.5.1) a change stream on each attached collection. Not beside MySQL or MariaDB. A failure is said once until it changes, and tried again less often, up to every 60 seconds |
| --follow --refresh-every 1h | both: follow, and a whole refresh now and then |
| POST /v1/refresh | one refresh now. Replies {at, changed, tables: [{table, inserted, updated, deleted}], added, skipped}. 409 in a folder that is not attached, 502 when the source cannot be read. The database’s own user only |
| POST /v1/attached | what the folder is attached to. The database’s own user only |
- Both flags are refused (exit 2) in a folder that is not attached.
- A Postgres slot keeps Postgres’s WAL until it is read. While the server is stopped, WAL piles up on the source’s disk.
chronos refresh <folder> --unfollowdrops the slot when the folder will not be followed again.
What attached answers
In a folder that is not attached: {attached: false}. Otherwise {attached: true, source, kind, capabilities, undo: {ready, window_days}, copied_at, refreshed_at, as_of, pending, tables: [{name, source_table, postgres, inserts, key, columns: [{name, type}]}]}. It holds no secret.
| Field | Meaning |
|---|---|
| kind | postgres, mysql, mariadb or mongodb. A folder attached to MariaDB before 0.5.0 says mysql, and works the same |
| capabilities | what that source can do besides the write-back and the refresh: {follow, dry_run, check_reads, act_as, lazy_tenant, source_checks}, each true or false. A program can ask rather than learn from a refusal |
| undo | {ready, window_days}: whether merges can be undone by id, and for how many days (30 by default, CHRONOS_UNDO_WINDOW_DAYS). ready is false when the source’s table of merged rows is missing or the role cannot insert into it |
| as_of | how old main’s untouched rows may be: the last refresh, else the attach |
| tables[].source_table | the table’s name in the source’s SQL. postgres holds the same, under its older name |
| tables[].inserts | false for a table a world cannot add rows to, because its ids are the source’s to give in a way the folder cannot follow |
| tables[].key, columns | the key, and each column’s name and type |
For MongoDB, kind is mongodb and follow, dry_run and check_reads are true; each other capability is false. For MySQL, dry_run and check_reads are true. The guides say what each capability means: Beside Postgres, Beside MySQL and MariaDB, Beside MongoDB.
Versions
put, delete, batch and a writing sql return the branch’s version, the number of writes since its fork. Send the last one as merge’s version. Writes to a world other than main are not synced one by one, so a server crash can lose the latest of them. If it did, the merge answers 409 instead of merging less than you wrote.
After a crash, a branch that was open is flagged and cannot be merged without a version. Check its diff, then merge with confirm: true to take it as it is, or discard it. The TypeScript and Python clients track versions for you.
The Postgres port
The user name chooses how a client proves who it is. Tokens and passwords are proved with SCRAM-SHA-256, so they never cross the wire. Over TLS the proof is bound to the server’s certificate (SCRAM-SHA-256-PLUS), so channel_binding=require in libpq stops a server in the middle.
| Server started with | Client connects as | Gets |
|---|---|---|
| no token at all (loopback only) | any user but a role with a password, no password asked | the database’s own user |
| --token T | any user but a role or an agent, password=T | the guest (the database’s own user with --unsafe) |
| --token T --admin-token A | any user but a role or an agent, password=A | the database’s own user |
| any | user=<agent>, password=<its token> | that agent |
| any | user=<role>, password=<its password> | that role, with its privileges |
| --token T, or an agent user | a wrong or missing password | refused: 28P01 password authentication failed for user "..." |
| --safe | anyone who is not an agent, a role with its password, or the admin token | the guest |
psql "postgres://anyone:$CHRONOS_ADMIN_TOKEN@db.internal:5433/main" # the admin token: the database's own userpsql "postgres://anyone:$CHRONOS_TOKEN@db.internal:5433/main" # the server token: the guestpsql "postgres://bot:$BOT_TOKEN@db.internal:5433/agent_7" # agent bot, on its world agent_7- The database name is the world to start on:
main, a world’s name or ID, orname@whento read the past. An unknown one is3D000. - Without a server token, loopback is trust for every name but a role with a password, and such a login is a superuser. Role passwords protect something only on a server with a token.
- An agent’s name takes only its token, not the server’s or admin token. A role’s name takes only its password.
- Which names exist does not show before logging in. With a server token, every name gets the same SCRAM exchange, and a login that cannot succeed gets
28P01. - There is no
pg_hba.conf. - Messages up to 64 MB (a bigger one is answered
54000with the connection kept). Login must finish within 60 seconds (CHRONOS_LOGIN_TIMEOUT). - At most 1000 connections (
53300 sorry, too many clients already;CHRONOS_MAX_CONNECTIONS, per listener). - No idle timeout after login unless the session sets
idle_in_transaction_session_timeoutoridle_session_timeout. InsideCOPY ... FROM STDIN, a client that sends no data for 60 seconds is dropped and its COPY undone (CHRONOS_COPY_IDLE). - Server files are off.
COPY ... FROMorTOa path on the server, andlo_importandlo_export, needCHRONOS_ALLOW_SERVER_COPY=1, and an agent’s or the guest’s session never may.
TLS
CHRONOS_TOKEN=… chronos serve mydb --listen 10.0.0.5:7070 --pg 10.0.0.5:5433 --tls-cert cert.pem --tls-key key.pempsql "postgres://app:$CHRONOS_TOKEN@10.0.0.5:5433/main?sslmode=verify-full&sslrootcert=ca.pem"- HTTP becomes HTTPS only. Clients use
https://URLs. - Postgres requires TLS on every connection. One that does not start TLS is refused (
28000 this server requires TLS). psql’s default (sslmode=prefer) uses it; usesslmode=verify-fullwithsslrootcertto check the certificate too. - Files: PEM, the certificate chain first, then the key as PKCS#8, PKCS#1 or SEC1. TLS 1.2 and 1.3 (rustls).
- No client certificates. Clients are identified by token only.
- TLS protects tokens, it does not replace them. An address that is not loopback still needs a token.
- Without TLS, a Postgres client that asks for it is told no and carries on in plain text. That is why an address that is not loopback needs a certificate, or
--insecure-no-tls. - A certificate change takes a restart.
MCP
chronos serve answers MCP at POST /mcp, as the agent whose token the client sends. The client needs only that token: not the folder, not the chronos binary. This is how an agent in a container or on another machine connects.
claude mcp add --transport http chronos https://db.internal:7070/mcp --header "Authorization: Bearer $BOT_TOKEN"- It always acts as an agent. The agent’s rights decide which tools are listed and what they may change, its quotas apply, and what it does is in the audit trail.
- The server token is the guest here too. The admin token, no token on a server with no token at all, and the server token with
--unsafeget403: the database’s own user useschronos mcp <folder>on the database’s machine. - Transport: MCP’s Streamable HTTP, without its event stream. Each request’s body is one JSON-RPC message and the reply is the response’s JSON body (
200). A notification gets202with no body. A batch gets400(-32600), a body that is not JSON400(-32700),GET /mcp405. There are no session IDs. - Sizes: a message may be at most 8 MB (
413).findandhistorygive at most 1000 rows a call. - Capabilities:
toolsonly. No resources, no prompts.
On the database’s machine, chronos mcp <folder> serves the same tools over stdio. Without flags it runs in safe mode: the agent changes only worlds forked in the session, and merge, restore and undo_merge are not listed. See The chronos command.
Studio
Chronos Studio is a web UI built into the binary. It works beside a running chronos serve on the same folder: it connects to the server over the folder’s socket, and every call runs there.
chronos studio mydb # opens http://127.0.0.1:<free port>/#t=<session key> in your browserchronos studio mydb --port 7071 # a fixed portchronos studio mydb --no-open # print the link, don't open a browserchronos studio mydb --login # sign in with a database role instead- Without
--loginit listens on 127.0.0.1 only and acts as the database’s own user, for whoever holds the link. The link carries a random 256-bit key after#. Keep the link to yourself. - With
--loginthere is no key: people sign in with a database role and its password, and the Studio acts as that role. Off loopback it needs--tls-certand--tls-keyunless--insecure-no-tls. serve --studio-apiis for a service that hosts the Studio’s page itself. The server then also answersPOST /studio/api/<op>on its HTTP port: the/v1ops, plustables,status,sessionsand the imports, acting as the database’s owner. It takes the admin token only: the server token and an agent’s token get403, no token401. Without the flag the path is a404that names it. A call that names a path on the server’s machine (backup) is refused.
Python and TypeScript clients
Two clients for the HTTP API, one file each, with no dependencies. They speak POST /v1/<op>, not the Postgres port.
| Language | Get it | Needs |
|---|---|---|
| TypeScript / JavaScript | npm install @chronosdb/client (ESM, with its types), or copy clients/typescript/chronos.ts from the public repository | global fetch: Node 18+, browsers, edge runtimes |
| Python | copy clients/python/chronos.py from the public repository. It is not on PyPI yet | Python 3.9+, standard library only |
import { Chronos, ChronosError } from "@chronosdb/client";const db = new Chronos("http://127.0.0.1:7070", { token: process.env.CHRONOS_TOKEN });const agent = await db.fork("agent-7", { task: "fix names" });await agent.put("users", "1", { name: "Ada L." });const { rows } = await agent.sql("select count(*) as n from users");console.log(rows[0].n, await agent.diff());try { await agent.merge();} catch (e) { if (!(e instanceof ChronosError) || e.status !== 409) throw e; console.log(e.conflicts.map((c) => c.key)); await agent.merge("ours");}import osfrom chronos import Chronos, ChronosErrordb = Chronos("http://127.0.0.1:7070", token=os.environ.get("CHRONOS_TOKEN"))found = db.find("notes", where={"city": "blr"}, text="office", limit=5)agent = db.fork("agent-8")for hit in found["hits"]: agent.put("notes", hit["id"], {**hit["row"], "checked": True})print(agent.preview()["conflicts"])agent.merge()| Method | Op | Returns |
|---|---|---|
| get(table, id) | get | the row, or null / None |
| put(table, id, record) | put | nothing |
| delete(table, id) | delete | nothing; a missing row throws 404 |
| batch(rows) | batch | rows written; all or none |
| find(table, options) | find | {total, hits, nextOffset} (next_offset in Python) |
| sql(sql, params) | sql | the last statement’s {command, rows} |
| fork(name, meta?) | fork | a client on the new branch |
| branch(name) | none | a client on name |
| branches() | branches | the branches, _tx_ worlds left out |
| world() | world | this branch |
| setMeta(meta) | set_meta | this branch |
| diff() | diff | [{key, before, after, columns}] |
| discard() | discard | nothing |
| merge(resolve, options) | merge | changes merged |
| preview(resolve, options) | merge with dry_run | the plan: {rows, conflicts, blocked} |
| undoMerge(world, options) | undo_merge | {ok, parent, at, undone, skipped} |
| at(when) | none | a client reading the past; writes fail |
| history(limit = 100) | history | events, newest first |
| restore(at) | restore | rows written |
| simulate(worlds, prefix, script, score, options) | simulate | the worlds, best first |
| replay(world, as?) | replay | whether it came out identical |
- Python names are snake_case:
set_meta,undo_merge,vector_field,only_tables,only_keys,skip_changed. - A client is one branch.
fork,branchandatreturn a new client; the old one is unchanged. The constructor takesurl(defaulthttp://127.0.0.1:7070),tokenandbranch(defaultmain). - The version check is automatic.
mergesends the version from this client’s last write (0 right afterfork), so writes lost in a server crash fail with 409 instead of merging silently.confirm: truesends none and takes the branch as it is. - Merge options:
columns,picks,into,onlyTables,onlyKeys,confirm. - No timeouts or retries. Neither client sets one. Wrap calls if you need a limit.
- Errors: every reply that is not 2xx throws
ChronosErrorwithstatus, the server’s message andconflicts. It does not keep the SQLSTATE: use a Postgres driver when you need the code. A network error or a reply that is not JSON throws the runtime’s own error. - Not sent by the clients:
diff’stoandsql,discard’scascade,find’sef. Usesql("diff world ...")or the HTTP API for those.
Two more Python files sit beside chronos.py: chronos_langgraph.py (a LangGraph checkpointer and memory store on a branch) and chronos_pytest.py (a fixture that forks main for each test and discards it after; it reads CHRONOS_URL and CHRONOS_TOKEN).
Server limits
| Limit | Value | Change it with |
|---|---|---|
| HTTP body | 32 MB (413) | fixed |
| HTTP headers | 64 KB (431) | fixed |
| HTTP request must arrive within | 2 minutes | CHRONOS_REQUEST_TIMEOUT (seconds) |
| HTTP idle connection | closed after 60 seconds | fixed |
| Connections, per port | 1000 | CHRONOS_MAX_CONNECTIONS |
| MCP message | 8 MB (413) | fixed |
| Postgres message | 64 MB (54000) | fixed |
| Postgres login must finish within | 60 seconds | CHRONOS_LOGIN_TIMEOUT (seconds) |
| Wrong tokens before an address waits | 10 | CHRONOS_LOGIN_FREE_TRIES |
| Statement timeout | none | alter system set statement_timeout; an agent’s max_query_ms |
| Live worlds | no limit | alter system set max_worlds; an agent’s max_worlds |