# Kruvi Data

An operational platform for AI agents, to run a business's day-to-day work:
- a database: define objects and fields, store records, query with read-only SQL;
- automations: code that runs when records change, or when you call it;
- a proxy for other services, using secrets your user stores and you never see.
No UI; you are the interface. (Prototype: no billing or webhooks yet.)

Base URL: https://uk1.data.kruvi.dev
All requests and responses are JSON. Errors look like
{"error": {"code": "...", "message": "..."}} and the message says how to fix the call.

## How this goes

1. Ask your user which email address to use, and sign up (below). Then
   build what your user needs in this conversation, using the temporary key
   you get back. Don't store the key.
2. Straight after signing up, tell your user to confirm their email: they
   click the link we send and accept the terms, within 24 hours.
3. When the setup is done, ask your user to connect Kruvi Data to their AI
   app for lasting access. In Claude: Settings > Connectors > Add custom
   connector, URL https://uk1.data.kruvi.dev/mcp, then sign in with the email they confirmed.
   That's secure OAuth: nothing to store, it renews itself, and the
   temporary key stops working. From then on, use the connector's tools.

If your user already has a workspace, skip to step 3.

## 1. Sign up (no auth)

POST /v1/signup  {"name": "Acme Plumbing", "email": "<your user's email>"}
-> {"tenant": {...}, "api_key": "kdata_uk1_...", "endpoint": "https://uk1.data.kruvi.dev", "credential": {...}}

This is a POST. If you can only fetch pages (GET), you can't sign up from
here: tell your user so plainly, and don't tell them an email is on its way.
They can ask an assistant that can send HTTP requests (Claude Code, for
example) to do the signup, then connect from here as in step 3.

Ask your user for the address, even if you think you know it, and read it
back to them before you send it. Don't take it from your context or their
account: the confirmation goes there, and it is the address they sign in
with. A typo or the wrong one means they never get the link.

Send the key on every other request: Authorization: Bearer <api_key>
The key is shown once, and it is a temporary key for getting started: use it
for this conversation, and don't save it to memory or notes, which are plain
text. Keys only work at their own cell's endpoint (uk1, eu1, ...); if you ever
get a 421 "wrong_cell" error, it contains the right endpoint.

Kruvi Data emails your user a confirmation link. Tell them now, before you
start building, and check the signup response's "confirmation_email":
- "sent": tell them which address it went to, that it comes from Kruvi Data
  with the subject "Confirm your Kruvi Data workspace for <name>", to check
  spam if it isn't there in a few minutes, and to click it within 24 hours.
- "failed": say so, and retry with POST /v1/confirmation/resend shortly.
Until they click it, you can build and test, but you can't invite anyone or
create keys. After 24 hours the key expires and the unconfirmed workspace is
deleted, so they would have to sign up again.

Lasting access comes from your user adding Kruvi Data as a connector in their
AI app (https://uk1.data.kruvi.dev/mcp) and approving it in their browser (OAuth). The
connector holds access securely between conversations, so no key needs storing.
"credential.your_job" (in the signup response, GET /v1/whoami, and the
kdata-credential header) says whether that is available yet and what to do
until it is. POST /v1/credentials/self/revoke revokes the key you're using.

## 2. Define the schema

POST /v1/schema
{
  "objects": [
    {"name": "customer", "fields": [
      {"name": "name", "type": "text", "required": true},
      {"name": "email", "type": "email", "unique": true},
      {"name": "status", "type": "picklist", "values": ["lead", "active", "former"]}
    ]},
    {"name": "job", "fields": [
      {"name": "customer", "type": "reference", "references": "customer", "required": true},
      {"name": "scheduled_for", "type": "datetime"},
      {"name": "price", "type": "number"}
    ]}
  ]
}

- Declarative and safe to repeat: send the objects you want; anything already
  matching is left alone. Objects or fields you leave out are NOT removed.
- To remove, list them explicitly: "drop": ["job.price", "old_object"].
- "dry_run": true returns the plan without applying it.
- The data model belongs to your user: check with them before changing
  anything that already exists. A change that adds, alters or removes fields
  or objects that already exist returns 409 confirmation_required, listing
  the changes in plain words. Put them to your user; only if they agree, send
  the same request again with "confirm": true. New objects need no
  confirmation.
- Names: lowercase, digits and underscores. Every object gets id, created_at
  and updated_at automatically. Avoid SQL keywords (case, order, group...):
  they work, but SQL must then quote them ("case"), and you'll get a warning.
- Each object gets its own id prefix (id_prefix in the schema), so an id like
  cas_... always tells you which object it belongs to.
- Field types: text, long_text, email, url, phone, picklist, number, integer, boolean, date, datetime, reference, json.
  picklist needs "values"; reference needs "references". Optional: label,
  required, unique.
- Reference fields also have "on_delete", for when the record they point at
  is deleted: "restrict" (refuse the delete while anything still points at
  it), "set_null" (clear the reference) or "cascade" (delete this record
  too). Defaults: restrict for required references, set_null for optional
  ones. A required reference can't be set_null.
- Changing a field: send it again with the new definition. Picklist values,
  label, required and unique can change, and so can type within a family
  (text-like types with each other). Other type changes and renames aren't
  supported: add a new field, copy the data, drop the old one.

GET /v1/schema returns the current schema.

## 3. Records

POST   /v1/objects/{object}/records        one record, or an array of up to 200
GET    /v1/objects/{object}/records        ?limit=50&cursor=...&where={"status":"active"}
GET    /v1/objects/{object}/records/{id}
PATCH  /v1/objects/{object}/records/{id}   only the fields to change
DELETE /v1/objects/{object}/records/{id}   follows each reference's on_delete rule

Values: dates "YYYY-MM-DD", datetimes ISO 8601, booleans true/false, numbers as
JSON numbers, reference fields take the target record's id. Any field left out
is null (there are no defaults yet, so an unset boolean is null, not false).

Creating an array is all-or-nothing: if any record fails validation, nothing
is saved and the error names the failing index. Created records come back in
the order you sent them, so you can pair ids with your input.

## 4. Undo

Every write call creates a change set (returned as "change_set" in bulk and
delete responses, and in the kdata-change-set header otherwise).

GET  /v1/changes          newest first; ?object=&record_id=&limit=&before=
GET  /v1/changes/{id}     before/after state of every record it changed
POST /v1/undo             {"change_sets": ["cs_..."]} or {"since": "2026-09-26T10:00:00Z"}; "dry_run": true to preview

- All or nothing: if a record was changed after the change you're undoing,
  you get a 409 undo_conflict listing the later change sets. Include them,
  or use "since". Undoing an undo redoes it.
- The result gives records_restored (distinct records) and changes_reversed
  (per change, by kind). A delete that cascaded is undone in one go.
- Restores never trigger automations, and undoing a write also undoes what
  its automations changed.
- On the free plan, history covers 7 days or 10,000 changes, whichever is less;
  history_starts in GET /v1/changes shows how far back you can go.

Dropped objects and fields go to the trash with their data:
GET  /v1/trash              what can be restored, and when it expires
POST /v1/trash/{id}/restore

A deleted record stays restorable until its history expires. To erase it for
good (a person asked for their data to be erased), delete it, then:
POST /v1/objects/{object}/records/{id}/purge   {"confirm": true}

- Owner only, and it can't be undone. Without "confirm": true it changes
  nothing and returns 409 confirmation_required saying what would be erased:
  put that to your user first.
- It removes the record's changes from history (the rest of each change set
  stays undoable; list_changes shows purged_changes), its copies in the trash,
  and its values wherever automation runs, jobs, outside calls and proxy logs
  recorded them.
- Queued automation work that concerns it (409 pending_work) may be what
  passes the deletion on; wait for it, or send "cancel_pending_work": true.
- Copies of its values in other records are theirs: update or purge those
  too. Nightly backups keep it until they expire, within 14 days.

## 5. Automations

Code that runs when records change: to calculate values, keep totals up to
date, refuse writes that break a rule, or follow up once a write is saved.
Owner only.

POST /v1/automations
{"automations": [{
  "name": "line_total",
  "object": "invoice_line", "on": ["insert", "update"],
  "timing": "in_transaction",
  "reads": [], "writes": ["invoice"],
  "code": "export function run(changes, ctx) { ... }"
}]}

- Declarative like the schema: omitted automations are kept; remove with
  "drop": ["name"]. Changing or dropping an existing one changes how your
  user's data behaves: check with them first. Such requests return 409
  confirmation_required until you send "confirm": true, after they agree.
  "enabled": false switches one off without removing it.
- "timing" is required:
  - "in_transaction" runs inside the write, before it is saved. It can
    change records, and any error rejects the whole write. Its writes join
    the write's change set, so one undo reverses both.
  - "after_commit" runs once the write is saved, as a write of its own (with
    its own change set), and can't reject it. It runs once: if it fails, the
    failure is recorded and reported, not retried. Undoing a write cancels
    its after_commit jobs that haven't run yet.
- "order" (optional): where it runs among the automations a change
  triggers, lowest first. New automations go after all existing ones.
  after_commit jobs run one at a time per workspace, in the order their
  writes were saved.
- "reads" and "writes" list every other object the code touches. The trigger
  object is always both, and anything undeclared is refused. Writes to
  objects no running automation uses never wait for one.
- run(changes, ctx) is called once per write with every matching change (an
  import of 200 records is one call), each {op, object, id, before, after};
  before is null for inserts and after is null for deletes. For
  in_transaction, after is the record as it is now. For after_commit, it is
  the record as the write saved it, including what in_transaction
  automations changed, and ctx.get and ctx.find return those records the
  same way: nothing written since, by other automations or anyone else,
  comes into play. Other records are read as they are now.
- ctx.get(object, id), ctx.find(object, {field: value}, {limit}) (equality
  only), ctx.create(object, values), ctx.update(object, id, values),
  ctx.delete(object, id), ctx.reject(message, recordId) to refuse an
  in_transaction write with your message, and ctx.fetch for outside calls
  (below). console.log goes to the run log. The code itself never waits: no
  await, timers or pending promises.
- An automation's own writes don't trigger it again; other automations'
  writes do, up to 5 rounds within a write, and up to 10 writes in a chain
  of after_commit jobs and call handlers.

Outside calls:

    export function run(changes, ctx) {
      for (const c of changes) {
        ctx.update('job', c.id, { fx_status: 'pending' });
        ctx.fetch('https://api.rates.example/rate?from=' + c.after.currency, {
          headers: { authorization: 'Bearer {{secret.rates_key}}' },
          onSuccess: 'applyRate', onFailure: 'rateFailed', data: { jobId: c.id },
        });
      }
    }
    export function applyRate(result, ctx) {
      ctx.update('job', result.data.jobId, { fx_rate: result.body.rate, fx_status: 'done' });
    }
    export function rateFailed(result, ctx) {
      ctx.update('job', result.data.jobId, { fx_status: 'failed' });
    }

- ctx.fetch(url, {method, headers, body, basic_auth, onSuccess, onFailure,
  data, retries, idempotencyKey}) queues the call and returns its id at
  once. It is sent once the write is saved, and never if the write is
  rejected. Works from both timings.
- onSuccess (2xx) and onFailure (anything else, or no response) name
  functions the automation exports. They run later, each as a write of its
  own, as handler(result, ctx), with result {ok, status, headers, body,
  body_encoding, error, data, call_id, attempts}. data is yours (JSON, up to
  64 KB), to say what the call was for. Handlers can write and call out
  again.
- Calls follow the proxy's rules (section 8): {{secret.<name>}} where a
  value goes, each secret only to its hosts, https only, no redirects, and
  secret values redacted from what the handler sees.
- Each call is made once. "retries": 1 to 3 retries network errors,
  timeouts, 429 and 5xx, after 10 s, 1 minute and 5 minutes. A failure that
  no onFailure handles is reported in GET /v1/automations alerts.
- Calls count towards the workspace's daily limit on requests to other
  services (section 9). Beyond it they wait until midnight UTC, then go out.
- Delivery is at least once (a restart mid-call sends it again).
  "idempotencyKey": true sends the call id as an Idempotency-Key header, or
  give a header name instead.
- When a write must not go ahead without an outside value, mark the record
  (as above) and fill it in from the handler; or fetch the value yourself
  with proxy_request before writing.
- Limits per write (an after_commit job is a write): 2 s of CPU across all
  its automations (time in ctx calls isn't counted), 30 s in all, 2000
  changes made by automations. An after_commit automation stopped by these
  5 times in a row is switched off, and its jobs are held. Fix it and send
  it again (with "confirm": true) to resume them.

A rejected or failed write returns 422 (rejected_by_automation,
automation_failed or automation_limit) with a run_id. Successful writes
report their runs in automation_runs (or the kdata-automation-runs header),
and after_commit jobs they queued in "automations": {"queued": n} (or the
kdata-automations-queued header).

Stored functions ("timing": "on_call") run when called, not when records
change: for calculations that must come out the same every time (monthly
totals, commission, a report) and for actions (closing a month). Any key
can call them; the owner defines them.

    {"name": "expenses_by_person", "timing": "on_call",
     "description": "Total expenses per person for one month",
     "params": {"month": {"type": "string", "description": "YYYY-MM"}},
     "queries": {"totals": "SELECT person, SUM(amount) AS total FROM expense
                 WHERE strftime('%Y-%m', date) = :month GROUP BY person"},
     "code": "export function run({ params, results }, ctx) {
                return { month: params.month, people: results.totals }; }"}

- No object, on or order. A description is required: it is how agents
  know when to call it.
- params: name -> {type, required (default true), description}; types are
  string, number, integer, boolean and date ("YYYY-MM-DD"). Anything else is
  refused before it runs.
- queries: named read-only SQL, as query_sql, using params as :name. They
  run first. Each may return at most 1000 rows, or the call fails rather
  than answer from part of the data: total and group in SQL.
- code (optional): run({params, results}, ctx) with each query's rows in
  results. Its return value (JSON, at most 256 KB) is the answer; with no
  code, the answer is the results. ctx works as for other automations,
  except fetch. Writes need "writes", and make one change set, which undo
  reverses; ctx.reject refuses the call with your message.
- It acts as whoever calls it: their role's filters and hidden fields apply
  to the queries and to ctx reads, and its writes are checked as theirs.
- Calls count as automation runs. describe_schema lists the functions as
  "functions", with params and whether they write; agents are told to call
  them rather than work the answer out themselves.

POST /v1/automations/{name}/call  {"params": {...}} -> {result, automation,
                                 version, run_id, change_set}

GET /v1/automations              definitions, order, versions, last run,
                                 after_commit jobs (queued, held, failed),
                                 and alerts about failures to tell your user
GET /v1/automations/runs         ?automation=&status=&timing=&limit=&before=
GET /v1/automations/runs/{id}    with its outside calls, and the stack,
                                 console output and, for a blocked write, the
                                 original request (owner only; other keys see
                                 their own runs, briefly)

## 6. Members, integrations and roles

Roles are defined by the owner. Managing people is itself a role permission,
so the owner can delegate it:
"members": {"read": true, "invite": true, "update": true, "remove": true,
            "integrations": false, "assign_roles": ["receptionist"]}
A role can only hand out the roles in assign_roles, and only manage people
who hold one of them. Nobody can manage the owner, or themselves.
GET /v1/members lists everyone with their role, last_seen_at, and "secure":
false if they're still on a bearer key.


Roles are declarative and deny by default:

POST /v1/roles
{"roles": [{"name": "sales", "objects": {
  "account": {"read": true, "create": true, "update": true,
              "fields": {"credit_limit": "read", "internal_notes": "none"},
              "read_filter": "region = 'North America'",
              "create_check": "region = 'North America'"},
  "sale":    {"create": true, "create_check": "account IN (SELECT id FROM account)"}
}}]}

- Per object: read, create, update, delete. Per field: "none", "read" or
  "write"; "*" sets the default (also for fields added later).
- Filters are SQLite expressions: read_filter, update_filter (also checked
  after the change, so a key can't move a record out of its reach),
  delete_filter, create_check. They may use me() (the caller's member id) and
  me_email(), and may subquery other objects, which are filtered for the
  caller too.
- "sql": false stops a role using POST /v1/sql. Filters and hidden fields
  apply to SQL automatically.

POST   /v1/invites          {"email": "...", "role": "sales"}; Kruvi Data emails the
                            invitee a one-time code, which is not returned to you
POST   /v1/invites/accept   {"code": "kdata_inv_..."}; no auth; the invitee's
                            assistant redeems the code for its own key
POST   /v1/integrations     {"label": "CRM sync", "role": "crm_sync"}; a key for
                            another system, shown once
GET    /v1/members          members, integration keys, pending invites
PATCH  /v1/members/{id}     {"role": "..."}
DELETE /v1/members/{id}     removes them and revokes their keys immediately

Scoped keys see only their own change sets and can only undo those.
GET /v1/whoami tells any key which workspace and member it belongs to.

## 7. Read-only SQL

POST /v1/sql  {"sql": "SELECT status, count(*) AS n FROM customer GROUP BY status", "params": []}
-> {"columns": [...], "rows": [...], "truncated": false}

SQLite dialect. Each object is a table and each field a column. SELECT and
WITH only; at most 1000 rows and 3 seconds per query. Storage: dates and
datetimes are ISO text (so date() and julianday() work), booleans are 1/0/NULL,
json fields are text, reference columns hold the target's raw id. Use ?
placeholders with "params".

## 8. Secrets and the proxy

Never ask your user to paste an API key, password or token into the
conversation. Ask Kruvi Data to store it instead; you then use it without ever
seeing it.

POST /v1/secrets/requests  {"name": "stripe_key", "hosts": ["api.stripe.com"],
                            "description": "Stripe secret key, to read invoices"}
-> {"url": "https://uk1.data.kruvi.dev/secrets/set?request=...", ...}

Give your user the url. They open it in their browser, check the hosts and
paste the value (they sign in by email if needed). Hosts are exact names, or
api.example.com:8443 for another port. The secret is only ever sent to those,
and only your user can change them, by saving it again from a new request.

Where each customer has their own address (Salesforce, Shopify, Zendesk...),
ask your user for theirs, e.g. acme.my.salesforce.com. Avoid wildcards
(*.example.com, any subdomain): on such services they include other
companies' accounts, which could then receive the secret. If you do send one,
your user is warned and must confirm it. "allow_in_body": true asks your user to
also allow it in request bodies (some OAuth token endpoints need that); they
decide.

GET    /v1/secrets           names, descriptions, hosts; never values
DELETE /v1/secrets/{name}
POST   /v1/proxy             {"method": "GET", "url": "https://api.stripe.com/v1/invoices?limit=3",
                              "headers": {"authorization": "Bearer {{secret.stripe_key}}"}}
-> {"status": 200, "headers": {...}, "body": {...}, "body_encoding": "json", "redactions": 0, ...}

- {{secret.<name>}} works in header values, the URL path and query
  (URL-encoded for you), and "basic_auth": {"username", "password"}; in the
  body only if allowed. Every secret used must allow the URL's host.
- "body": an object or array is sent as JSON; a string is sent as it is.
- https only. Redirects aren't followed: you get the 3xx and its location.
- Any secret value found in a response is replaced with [REDACTED:<name>].
- 1 MB request, 2 MB response, 30 seconds, 60 requests a minute per key,
  and the workspace's daily limit on requests to other services (section 9).
- GET /v1/proxy/calls lists recent proxied requests (owner only).
- Roles can use secrets with "secrets": ["stripe_key"]; nobody can read them.

## 9. Limits

The free plan includes 10,000 records across all objects and 1,000
automation runs a month (one run is one automation handling one write).
Every response has a kdata-usage header, e.g. "records=8123/10000; status=warning".
GET /v1/usage gives the detail: how many more can be created, counts per
object, and advice written for you.

- warning (80%): tell your user when convenient.
- over (100%): writes still succeed within a small grace margin, so an
  import never fails halfway. Tell your user now.
- blocked (beyond 110%): creating records returns 402 limit_reached. Nothing
  else is blocked: reading, updating, deleting, SQL and undo all work, so you
  can always tidy up. Batches are all or nothing: check can_still_create
  before a large import.

Beyond the run limit's grace margin, writes that would run automations are
refused with 402 limit_reached; other writes still work. Automations are
never skipped instead, since they may be what keeps the data correct.

Requests to other services, through proxy_request and automations' ctx.fetch
together, are limited to 2,000 a day (UTC) on the free plan, with no grace
margin. usage shows outside_requests (today, limit, resets_at). Beyond the
limit, proxy_request returns 429 daily_limit_reached, and automations' calls
wait and go out after midnight UTC by themselves. Tell your user; don't retry
before resets_at. Plan bulk work (an import that calls an API per record)
with the limit in mind.

Data is never deleted because of a limit.

A free workspace that nobody uses for 12 months is deleted, with everything
in it. Its owner is emailed 28 and 7 days before, and any request made with
a key or connection to it keeps it. Paid workspaces are kept. If your user
mentions an email about this and wants to keep the workspace, making any
request is enough. The terms and policies are at https://uk1.data.kruvi.dev/legal.

A workspace used against the Acceptable Use Policy (for example, to send
requests to other services that nobody asked for) can be suspended. Every
request then returns 403 workspace_suspended with the reason, and its
automations wait; its data is kept. Its owner is emailed why: tell your user,
and don't retry until they say it has been lifted.

## 10. Export and closing (owner only)

Both happen in the owner's own browser: you get a link to hand over, and the
page needs them signed in as the owner (it emails a sign-in link if not).

- POST /v1/export (MCP: export_workspace) returns a link to download the
  whole workspace as one SQLite file: every object and record, history,
  members, roles and automations. Secret values are left out.
- POST /v1/close (MCP: close_workspace) returns a link to close the
  workspace, which deletes it and everything in it for everyone, straight
  away, and stops every key including yours. Only ask for it when your user
  has asked to close the whole workspace; to remove objects or records, use
  the schema and records instead. The page shows what will go, offers a copy
  first, and asks them to confirm. Backups keep it for up to 14 days.

Links last 24 hours; asking again replaces the earlier one.

## What's new

Kruvi Data keeps changing. GET /v1/whats-new lists what has changed since
your key last asked, grouped by deployment; ?since=YYYY-MM-DD lists
everything deployed since that day instead. If you come back to a workspace
after a while, check it, and tell your user about anything useful to them.

## MCP

The same operations are available as MCP tools over Streamable HTTP at
https://uk1.data.kruvi.dev/mcp (send the same Authorization header).

AI apps load the tool list when they connect. The whats_new tool also
returns every tool your key can use now, so you can tell if your list is out
of date; if a tool is missing, ask your user to refresh the connection.
