Developer docs

Relay answers fixed questions about private data, so your app never holds the data.

In snippets, https://YOUR-RELAY is your Relay deployment and rk_... is your app's API key.

Start here

Four steps to a first answer. No account? Try the playground.

  1. Create an app, copy its key

    In the console, choose "People approve", then add your site's address under Settings. Sign-up needs an email, a password of 10 or more characters and a sign-up code (relay-dev locally).

  2. Create a link token

    On your server. subject is your own opaque ID for the person.

    curl -X POST https://YOUR-RELAY/api/v1/link-tokens \
      -H "Authorization: Bearer rk_..." \
      -H "content-type: application/json" \
      -d '{
        "subject": "user-4821",
        "operations": ["find_slots"],
        "origin": "https://app.example.com"
      }'
  3. Open the approval window

    On your page. The person connects a source, picks 1, 7, 30 or 90 days, and approves.

    <script src="https://YOUR-RELAY/sdk/relay.js"></script>
    <button id="connect">Connect your calendar</button>
    <script>
      document.getElementById("connect").addEventListener("click", async () => {
        // A promise is fine: the window opens at once, inside the click.
        const linkToken = fetch("/your-backend/relay-link", { method: "POST" })
          .then((r) => r.json())
          .then((j) => j.link_token);
    
        const outcome = await Relay.open({ linkToken });
        if (outcome.status === "granted") {
          // Send the grant id to your server and store it with your user.
          await fetch("/your-backend/relay-grant", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ grant_id: outcome.grant_id }),
          });
        }
        // outcome.status is "granted", "declined" or "closed"
      });
    </script>
  4. Ask the question

    On your server, with the grant ID.

    curl -X POST https://YOUR-RELAY/api/v1/operations/find_slots \
      -H "Authorization: Bearer rk_..." \
      -H "content-type: application/json" \
      -d '{
        "grant_id": "gr_...",
        "input": { "date_from": "2026-01-12", "window_days": 7, "slot_minutes": 60 }
      }'
    {
      "result": {
        "slots": [
          { "start": "2026-01-12T13:00:00.000Z", "end": "2026-01-12T14:00:00.000Z" },
          { "start": "2026-01-13T07:00:00.000Z", "end": "2026-01-13T08:00:00.000Z" },
          { "start": "2026-01-14T09:00:00.000Z", "end": "2026-01-14T10:00:00.000Z" }
        ]
      },
      "receipt_id": "ev_...",
      "cached": false,
      "contract": { "operation": "find_slots", "version": "1.0.0", "hash": "..." },
      "budget": { "bits_left": 120.59, "calls_left": 11, "resets_at": "2026-02-11T10:02:11.000Z" }
    }
Receipts and ending access

After approving, the person gets a private receipts link. It lists every answer and lets them end access and remove sources. Your app never receives that link.

Fetch the receipt of an answer

curl https://YOUR-RELAY/api/v1/receipts/ev_... \
  -H "Authorization: Bearer rk_..."

End a grant

curl -X DELETE https://YOUR-RELAY/api/v1/grants/gr_... \
  -H "Authorization: Bearer rk_..."

Afterwards every operation under the grant returns grant_revoked.

find_slots needs nothing registered. rank_options, aggregate and profile need definitions first, named in the link token.

Terms and secrets

App
Your product in the console. One API key, one mode: personal or company.
Operation
One of five fixed kinds of question. The console calls it a question.
Contract
An operation's public rules: input, output, limits. See Contracts.
Definition
What you register in advance: a candidate set, check, total or profile form.
Grant
Permission to run named operations: a person's approval, or a company's permission.
Budget
How much a grant may learn per operation in 30 days, in bits.
Receipt
The log entry of one released answer. Every result carries its ID.
SecretPrefixHeld byWhat it can do
API keyrk_Your server onlyEverything in the app API.
Link tokenrl_Your page, then the approval windowOpen one approval. 30 minutes, one use.
Grant IDgr_Your serverNothing without your API key.
Agent tokenrg_One AI agentCall one grant's operations over MCP.
Receipts linkrr_The personSee receipts, end access, remove sources.

Company quickstart

Your company keeps its data and decides which questions agents may ask.

  1. Create a company app

    In the console, choose "Your company decides". Copy the API key.

  2. Connect your data

    Data tab: add a Postgres database or a REST API. Or skip this and use the built-in sample connector.

  3. Register checks and totals

    Questions tab: paste the definitions or load the example, then "Save questions". Or send them from your server.

    curl -X PUT https://YOUR-RELAY/api/v1/config \
      -H "Authorization: Bearer rk_..." \
      -H "content-type: application/json" \
      -d @relay-config.json
  4. Create a permission

    Access tab: a name, the kinds of question, and 1 to 365 days (default 90), then "Create permission".

    It covers every check and total registered at that moment, pinned by hash. Changed a definition? Create a new permission.

  5. Ask a check

    curl -X POST https://YOUR-RELAY/api/v1/operations/check \
      -H "Authorization: Bearer rk_..." \
      -H "content-type: application/json" \
      -d '{
        "grant_id": "gr_...",
        "input": { "check": "order-refundable", "params": { "order_id": "NW-1001" } }
      }'
    {
      "result": { "answer": true, "reason": "ok" },
      "receipt_id": "ev_...",
      "cached": false,
      "contract": { "operation": "check", "version": "1.0.0", "hash": "..." },
      "budget": { "bits_left": 19997.67, "calls_left": 4999, "resets_at": "..." }
    }
  6. Give an agent a token

    Press "Get agent token" next to the permission, or call the API. A new token retires the old one.

    curl -X POST https://YOUR-RELAY/api/v1/grants/gr_.../agent-token \
      -H "Authorization: Bearer rk_..."

    Add it to Claude Code

    claude mcp add --transport http relay https://YOUR-RELAY/api/mcp \
      --header "Authorization: Bearer rg_..."

The agent gets one tool per operation in the grant. It cannot read the records. "End access" in the console stops the permission and its token.

API reference

JSON in, JSON out. Every failure has this shape, with a matching HTTP status and error code.

{ "error": { "code": "grant_revoked", "message": "This grant was revoked" } }

Endpoints

EndpointAuthWhat it does
POST /api/v1/link-tokensAPI keyStart one approval for one person.
POST /api/v1/operations/{name}API keyRun one operation under a grant.
GET /api/v1/grants/{id}API keyStatus, scope and budget left.
DELETE /api/v1/grants/{id}API keyEnd a grant and its agent token.
POST /api/v1/grants/{id}/agent-tokenAPI keyIssue the token an agent uses.
GET /api/v1/receipts/{id}API keyReceipt of one released result.
GET /api/v1/configAPI keyRead the definitions and their hashes.
PUT /api/v1/configAPI keyReplace the whole configuration.
GET /api/v1/contractsNoneThe contract catalogue, with hashes.
GET /api/healthNoneLiveness check.
POST /api/mcpAgent tokenThe MCP server.

API key: Authorization: Bearer rk_..., from your server. Accounts, apps, connectors, permissions and branding are managed in the console only.

Parameters, bodies and errors

An empty body is read as {}. Responses carry cache-control: no-store. A missing or unknown key gives 401 unauthorized.

POST/api/v1/link-tokens

Personal-mode apps only. Status 201.

Errors: wrong_mode, invalid_operations, invalid_origin, origin_not_registered, missing_scope, unknown_id, invalid_return_url, invalid_subject

FieldRule
subjectRequired. Your ID for the person, 1 to 120 characters, stored as sent: use an opaque ID. Same subject, same person.
operationsRequired. One or more of find_slots, rank_options, aggregate, profile.
originRequired. A registered origin of the app.
candidate_sets, aggregates, profiles1 to 5 registered IDs each. Required when the matching operation is listed.
return_urlOptional. A page on the same origin, up to 500 characters, for the redirect fallback.

Server only: creating a link token needs your API key.

Request body

{
  "subject": "user-4821",
  "operations": ["rank_options", "aggregate", "profile"],
  "origin": "https://app.example.com",
  "candidate_sets": ["weekend-trips"],
  "aggregates": ["groceries"],
  "profiles": ["traveller"],
  "return_url": "https://app.example.com/settings/relay"
}

Response

{
  "link_token": "rl_...",
  "expires_at": "2026-01-12T10:30:00.000Z",
  "subject_id": "sub_...",
  "connect_url": "https://YOUR-RELAY/connect/rl_..."
}

POST/api/v1/operations/{name}

name is find_slots, rank_options, check, aggregate or profile. input must match the contract's input schema.

Errors: unknown_operation, grant_not_found, grant_revoked, grant_expired, operation_not_granted, wrong_mode, invalid_input, the operation's own input errors, over_contract_limit, budget_exhausted, no_source, source_unavailable, feed_unreachable, connector_missing, connector_mismatch, compute_failed, release_blocked

FieldMeaning
cachedTrue for a stored answer. It carries the original receipt ID and uses no budget.
budgetWhat is left for this grant and operation in the 30-day period.
contractThe rules that produced the result: operation, version, hash.

Response: as in Start here. Refused requests on your grants are logged; in personal mode the person sees them.

Request body

{ "grant_id": "gr_...", "input": { ... } }

GET/api/v1/grants/{id}

kind is person or policy. status is active, revoked or expired.

Errors: grant_not_found

Response

{
  "id": "gr_...",
  "kind": "person",
  "status": "active",
  "operations": ["find_slots"],
  "scope": { "candidate_sets": [], "aggregates": [], "profiles": [], "checks": [] },
  "expires_at": "2026-02-11T10:02:11.000Z",
  "budget": { "find_slots": { "bits_left": 120.59, "calls_left": 11, "resets_at": "..." } }
}

DELETE/api/v1/grants/{id}

Its agent token stops working too.

Errors: grant_not_found

Response

{ "id": "gr_...", "status": "revoked" }

POST/api/v1/grants/{id}/agent-token

Status 201. No body. One token per grant; a new one retires the old. For person and policy grants.

Errors: grant_not_found, grant_inactive

Response

{ "agent_token": "rg_...", "mcp_url": "https://YOUR-RELAY/api/mcp" }

GET/api/v1/receipts/{id}

Only receipts of your own app are returned.

Errors: receipt_not_found

Response

{
  "id": "ev_...",
  "at": "2026-01-12T10:02:15.000Z",
  "grant_id": "gr_...",
  "operation": "find_slots",
  "contract": { "operation": "find_slots", "version": "1.0.0", "hash": "..." },
  "output_hash": "<sha-256 of the released result>",
  "bits": 19.41,
  "log": { "position": 3, "hash": "...", "previous": "..." }
}

GET/api/v1/config

Each definition comes with the hash that grants pin.

Response

{
  "config": {
    "candidate_sets": {
      "weekend-trips": { "hash": "<16 hex characters>", "definition": { "title": "...", "items": [ ... ] } }
    }
  }
}

PUT/api/v1/config

Sections you leave out are removed. Body up to 400,000 characters. Responds like GET. A changed definition gets a new hash; grants pinning the old one get definition_changed.

Errors: invalid_config

Request body

{ "candidate_sets": { ... }, "checks": { ... }, "aggregates": { ... }, "profiles": { ... } }

GET/api/v1/contracts

Machine-readable contracts, each with its hash.

Response

{ "contracts": [ { "operation": "find_slots", "version": "1.0.0", "title": "...", "input": { ... }, "output": { ... }, "disclosure": { ... }, "hash": "..." }, ... ] }

GET/api/health

ai is model when a model key is configured and rules otherwise.

Response

{ "ok": true, "apps": 5, "ai": "rules", "google_calendar": false }

POST/api/mcp

JSON-RPC 2.0 over HTTP, one message per request. GET /api/mcp answers 405.

Approval window endpoints

Used by Relay's own pages at /connect/{link_token} and /r/{receipt_token}, not by you. The token in the path is the credential. A link that is no longer usable gives link_not_found, link_used or link_expired.

EndpointWhat it doesErrors
GET /api/connect/{token}All the window shows: app name and branding, operations with contract wording, scoped definitions, sources needed and connected.
POST /api/connect/{token}/sourcesConnect a source. Status 201. Body up to 4,200,000 characters, one object per request. timezone falls back to Europe/Berlin.too_many_sources, unknown_source, too_large, not_a_calendar, feed_unreachable, invalid_url, blocked_host, empty_file, not_text, not_a_bank_export
DELETE /api/connect/{token}/sources/{id}Remove a source. Returns { "ok": true }.source_not_found
POST /api/connect/{token}/proposeSuggest profile facts from the person's documents, for their review. Nothing goes to the app. engine is ai or rules.no_source
POST /api/connect/{token}/approveCreate the grant. Status 201. days is 1, 7, 30 or 90; anything else becomes 30. facts holds the ticked profile facts; unregistered values are dropped. The opening page then gets relay:granted with the grant ID.missing_source
POST /api/connect/{token}/denyDecline. The link is used up and the refusal is logged. Returns origin and return_url.
GET /api/oauth/google/start?token={link_token}Redirects to Google's sign-in for the free/busy permission only. Needs Google credentials on the deployment.google_not_configured
GET /api/oauth/google/callbackAuth: the one-time state value from the start step, valid 15 minutes. Stores the encrypted Google refresh token as a calendar source, then returns to the window.invalid_state, google_failed
POST /api/r/{token}/revokeThe person ends a grant. Body { "grant_id": "gr_..." }, returns { "ok": true }.not_found, grant_not_found
POST /api/r/{token}/disconnectThe person removes a source. Body { "connection_id": "con_..." }, returns { "ok": true }.not_found, source_not_found

Window state

{
  "app": { "name": "Luma Tutoring", "logo": null, "hide_relay": false },
  "origin": "https://app.example.com",
  "return_url": null,
  "expires_at": "...",
  "operations": [ { "operation": "find_slots", "title": "Find options", "gets": "...", "never_sees": "...", "source": "calendar", "compute": "rules" } ],
  "scope": { "candidate_sets": [], "aggregates": [], "profiles": [] },
  "needed": [ { "kind": "calendar", "connected": [ { "id": "con_...", "kind": "calendar_sample", "label": "Sample calendar", "added_at": "..." } ] } ],
  "google_calendar": false
}

Source bodies, one example per kind

{ "kind": "calendar_ics", "name": "work.ics", "text": "BEGIN:VCALENDAR...", "timezone": "Europe/Berlin" }
{ "kind": "calendar_feed", "url": "https://calendar.google.com/calendar/ical/.../basic.ics", "timezone": "Europe/Berlin" }
{ "kind": "calendar_sample", "timezone": "Europe/Berlin" }
{ "kind": "document", "name": "notes.txt", "text": "..." }
{ "kind": "documents_sample" }
{ "kind": "bank_csv", "name": "export.csv", "text": "Date;Amount;Description\n..." }
{ "kind": "transactions_sample" }
{ "id": "con_...", "kind": "calendar_ics", "label": "work.ics", "added_at": "..." }

Propose response

{ "profiles": { "traveller": { "facts": { "diet": "vegetarian", "budget": null }, "engine": "rules" } } }

Approve body and response

{ "days": 30, "timezone": "Europe/Berlin", "facts": { "traveller": { "diet": "vegetarian" } } }
{ "grant_id": "gr_...", "expires_at": "...", "origin": "https://app.example.com", "return_url": null, "receipt_url": "https://YOUR-RELAY/r/rr_..." }

Not part of the API: /api/demo/ and /api/playground/. They back the demos and the playground, calling the endpoints above with the demo apps' own API keys.

Browser SDK

Load /sdk/relay.js from your Relay deployment. One global, Relay. Apache-2.0.

Call or optionWhat it does
Relay.open({ linkToken })Opens the approval window. Returns a promise of the outcome.
linkTokenRequired. A string, or a promise of one.
display: "popup"Always use a pop-up window.
fallback: "redirect"Pop-up blocked? Open as a full page, then return to return_url.
baseUrlA Relay deployment other than the script's own.
Relay.completed()On the return_url page: returns the outcome, or null.
Page is onThe window opens as
Relay's own originA dialog in the page. Escape or a click outside closes it.
Any other originA pop-up window, 480 by 720.
OutcomeMeaning
{ status: "granted", grant_id }Approved. Send the grant ID to your server.
{ status: "declined" }Declined. Nothing was shared.
{ status: "closed" }Closed without a decision.
rejects with popup_blockedThe pop-up was blocked and no fallback was set.
rejects with linkToken is requiredNo link token, or the promise gave no string.
rejects with your error or link_failedThe linkToken promise rejected.
Pop-ups, redirects and safety
TopicWhat to know
Pop-up blockersCall Relay.open directly in a click handler. With a promise, the window opens at once and loads Relay when the token arrives.
Redirect fallbackThe person returns to return_url with relay_status and relay_grant in the address. Relay.completed() reads them once and removes them.
Check the grantAnyone could type a grant ID into that address. Read it with GET /api/v1/grants/{id} before you store it.
MessagesThe SDK trusts only messages from the Relay origin and the window it opened. The window answers only the link token's origin.
FramingOnly Relay's own pages may frame the approval page. The receipts page and the console refuse every frame.

Branding

Apps where people approve can show their own logo in the approval window. Set it in the console's Branding tab.

SettingHow
Upload a logoPNG, JPEG, WebP, SVG or ICO, up to 150 KB.
Fetch it from your websiteEnter the address. Relay reads the site once and keeps a copy of its icon.
Hide "Secured by Relay"Tick the box. The line leaves the window.

With a logo, the window shows your logo and app name in place of Relay's. There is no API for branding.

MCP for agents

POST /api/mcp speaks MCP as JSON-RPC 2.0 over HTTP, with an agent token (rg_...) bound to one grant.

MethodResult
initializeServer info and the tools capability. Echoes the client's protocol version; default 2025-06-18.
tools/listOne tool per operation in the grant, named after it. Schemas come from the contract.
tools/callRuns the operation like the REST API. Result in structuredContent and as JSON text in content.
pingAn empty result.
notifications/initialized, notifications/cancelledStatus 202, no body.
curl -X POST https://YOUR-RELAY/api/mcp \
  -H "Authorization: Bearer rg_..." \
  -H "content-type: application/json" \
  -d '{
    "jsonrpc": "2.0", "id": 1, "method": "tools/call",
    "params": {
      "name": "check",
      "arguments": { "check": "order-refundable", "params": { "order_id": "NW-1001" } }
    }
  }'
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [{ "type": "text", "text": "{\"answer\":true,\"reason\":\"ok\"}" }],
    "structuredContent": { "answer": true, "reason": "ok" },
    "isError": false,
    "_meta": { "receipt_id": "ev_...", "cached": false, "budget": { "bits_left": 19997.67, "calls_left": 4999, "resets_at": "..." } }
  }
}
Failures and rules
CaseWhat the agent gets
An operation is refused (for example budget_exhausted)A normal tool result with isError: true and the text code: message.
Missing, unknown or revoked tokenHTTP 401 and JSON-RPC error -32001.
A tool name that is not in the grantJSON-RPC error -32602.
Unknown methodJSON-RPC error -32601.
Body is not JSON, or is a batchHTTP 400 with -32700 or -32600.
  • Stateless. One message per request; batches are refused.
  • Only agent tokens are accepted. API keys are not. OAuth sign-in for MCP is not built.
  • A tool's description is the contract's summary plus what this grant allows.
  • _meta of a result carries receipt_id, cached and budget.

Configuration

Four sections, each mapping an ID to a definition. Register them in the console or with PUT /api/v1/config.

SectionOperationModeSize
candidate_setsrank_optionsPersonal3 to 20 items
checkscheckCompany1 to 15 conditions, up to 4 parameters
aggregatesaggregatePersonal or company2 to 7 boundaries
profilesprofilePersonal1 to 8 attributes, 2 to 12 options each

Up to 30 entries per section. IDs: lowercase letters, digits, - and _, up to 40 characters. title: up to 80 characters, defaults to the ID. Grants pin each definition by hash, so a changed definition needs a new approval.

Candidate set

The options rank_options orders. The person sees the labels in the approval window.

// input
{ "candidate_set": "weekend-trips", "top_k": 2 }
// result
{ "ranking": ["dolomites-hut", "elbe-cycling"] }
Definition and fields
{
  "candidate_sets": {
    "weekend-trips": {
      "title": "Weekend trips this autumn",
      "items": [
        { "id": "dolomites-hut", "label": "Hut-to-hut hike in the Dolomites", "description": "Three days of mountain trails and alpine huts. Train to Bolzano." },
        { "id": "lisbon-food", "label": "Lisbon food weekend", "description": "Markets, seafood restaurants and pastry tours in the old town." },
        { "id": "elbe-cycling", "label": "Cycling the Elbe valley", "description": "Two easy days by bike from Dresden with vineyard stops." }
      ]
    }
  }
}
FieldRule
items3 to 20.
idUnique within the set.
labelUp to 80 characters.
descriptionOptional. Cut at 300 characters.

Check

Reads one record and tests conditions in order. The first failure gives the reason code.

// input
{ "check": "order-refundable", "params": { "order_id": "NW-1001", "customer_id": "C-204" } }
// result when every condition passes
{ "answer": true, "reason": "ok" }
// result when a condition fails: the fail code of the first one that failed
{ "answer": false, "reason": "outside_30_day_window" }
// result when no record was found
{ "answer": false, "reason": "not_found" }
Definition and fields

With a database connector

{
  "checks": {
    "order-refundable": {
      "title": "Is this order refundable?",
      "connector": "con_...",
      "query": "select status, total, delivered_at, final_sale, country from orders where order_id = $1 and customer_id = $2",
      "params": {
        "order_id": { "pattern": "NW-[0-9]{4}" },
        "customer_id": { "pattern": "C-[0-9]{1,8}" }
      },
      "conditions": [
        { "field": "status",       "op": "eq",          "value": "delivered",        "fail": "not_delivered_yet" },
        { "field": "total",        "op": "lte",         "value": 1500,               "fail": "needs_second_check" },
        { "field": "country",      "op": "in",          "value": ["DE", "FR", "IT"], "fail": "country_not_covered" },
        { "field": "final_sale",   "op": "is_false",                                 "fail": "final_sale_item" },
        { "field": "delivered_at", "op": "within_days", "value": 30,                 "fail": "outside_30_day_window" }
      ]
    }
  }
}
FieldRule
connectorA connector ID from the console (con_...) or sample.
queryDatabase connectors. One SELECT of up to 1,000 characters, no ;, no comments. No words that write or change things, such as insert, update, delete, drop, alter, create, grant, truncate, copy, call, do or set, and no information_schema. The first row is used. On Postgres it runs in a read-only transaction.
pathREST connectors, in place of query. Placeholders in braces are filled with the URL-encoded parameter values. The API must answer with a JSON object. A 404 counts as "no record".
paramsUp to 4, each with a pattern: a regular expression of up to 120 characters the whole value must match. Passed to the query as $1, $2 and so on, in listed order. The caller sends exactly these, as text of up to 64 characters.
conditions1 to 15. field is a column name, or a dotted path such as billing.overdue for nested JSON.
failThe reason code: lowercase letters, digits and _, up to 40 characters. ok and not_found are reserved.
Fail codesAt most 14 different ones. An answer may carry 4 bits, which is 16 reason codes including ok and not_found. More is refused with over_contract_limit.

With a REST connector

{
  "checks": {
    "subscription-active": {
      "title": "Is this subscription active?",
      "connector": "con_...",
      "path": "/subscriptions/{subscription_id}",
      "params": { "subscription_id": { "pattern": "sub-[a-z0-9]{6,20}" } },
      "conditions": [
        { "field": "state", "op": "eq", "value": "active", "fail": "not_active" },
        { "field": "billing.overdue", "op": "is_false", "fail": "payment_overdue" }
      ]
    }
  }
}
Condition operators
OperatorThe condition passes when
eqEquals value. Different types compare as text.
neDoes not equal value.
gtAs a number, greater than value.
gteAs a number, greater than or equal to value.
ltAs a number, less than value.
lteAs a number, less than or equal to value.
inOne of the entries of value, a list. Compared as text.
not_inNone of the entries of value, a list.
is_truetrue, "true" or 1. No value.
is_falsefalse, "false", 0, null or missing. No value.
existsPresent, and not null or empty text. No value.
within_daysA time (milliseconds, ISO date or database timestamp) at most value days ago.
older_than_daysA time more than value days ago.

Personal total

A range, computed from the person's bank export.

// input
{ "aggregate": "groceries" }
// result: the value is at least 250 and below 350
{ "bucket": 2, "from": 250, "to": 350 }
// lowest range: below 150
{ "bucket": 0, "from": null, "to": 150 }
// highest range: 500 or more
{ "bucket": 4, "from": 500, "to": null }
Definition and fields
{
  "aggregates": {
    "groceries": {
      "title": "Groceries per month",
      "kind": "personal",
      "direction": "spend",
      "category": "groceries",
      "months": 3,
      "metric": "monthly_average",
      "buckets": [150, 250, 350, 500]
    }
  }
}
FieldRule
directionspend or income.
categoryall or one of groceries, eating_out, transport, housing, utilities, subscriptions, shopping, travel, health, other. For income, every incoming amount counts.
months1, 3, 6 or 12. A month is 30 days back from now.
metricmonthly_average (the default) or total.
buckets2 to 7 increasing numbers: the boundaries between ranges, so 4 boundaries give 5 ranges. A value equal to a boundary falls into the range above it.

Company total

A head count from your database, hidden when the group is too small.

// result when the number is 36
{ "bucket": 1, "from": 25, "to": 50 }
// result when the number is below min_group: too few to show
{ "bucket": -1, "from": null, "to": null }
Definition and fields
{
  "aggregates": {
    "at-risk-customers": {
      "title": "Customers at high churn risk",
      "kind": "company",
      "connector": "sample",
      "query": "select count(*)::int as n from demo_customers where churn_risk = 'high'",
      "buckets": [25, 50, 100],
      "min_group": 10
    }
  }
}
FieldRule
queryNo parameters. Must start with SELECT count( and return one number in the first column of the first row. The query rules of checks apply.
min_groupDefault 10, and not below 10. A number below it gives "too few to show" (bucket is -1).
kindpersonal needs a person's grant, company a permission. Otherwise the call fails with wrong_mode.

Profile form

Relay suggests a value per attribute from the person's documents. The person ticks what to share.

// input
{ "profile": "traveller" }
// result: the person ticked diet and left budget unticked
{ "facts": { "diet": "vegetarian" } }
Definition and fields
{
  "profiles": {
    "traveller": {
      "title": "Your travel basics",
      "attributes": [
        {
          "key": "diet",
          "label": "Diet",
          "options": [
            { "id": "none", "label": "No restrictions" },
            { "id": "vegetarian", "label": "Vegetarian", "hints": ["veggie"] },
            { "id": "vegan", "label": "Vegan" }
          ]
        },
        {
          "key": "budget",
          "label": "Usual budget",
          "options": [
            { "id": "low", "label": "Budget", "hints": ["hostel", "cheap"] },
            { "id": "mid", "label": "Mid-range" },
            { "id": "high", "label": "Premium", "hints": ["luxury", "five-star"] }
          ]
        }
      ]
    }
  }
}
FieldRule
attributes1 to 8.
options2 to 12 per attribute.
labelUp to 60 characters.
hintsUp to 12 words per option. They help the rule-based suggestion when no AI model is configured.

Connectors

Personal sources

The person adds these in the approval window. Up to 12 per person and app, every stored secret encrypted.

SourceUsed byWhat Relay stores
Calendar file (.ics)find_slotsEvent timing only. No titles, attendees, locations or descriptions.
Live calendar addressfind_slotsThe address only.
Google Calendar sign-infind_slotsA refresh token limited to free/busy.
Document uploadrank_options, profileThe text.
Bank export (CSV)aggregateDate, signed amount and category per row.
Sample dataAll personal operationsNo personal data.
Formats and limits
SourceDetails
Calendar fileStored per event: start, duration, time zone, repeat rule, skipped dates. The rest is dropped while parsing. Up to 5,000 events. Cancelled and "free" events are ignored. All-day events count only when marked busy.
Live calendar addressPrivate https feeds from Google Calendar, Outlook, iCloud, Proton Calendar, Fastmail, Cal.com and Zoho. Fetched on each operation, up to 5 MB, 8 seconds.
Google Calendar sign-inOffered when the deployment has Google credentials. Reads busy times of the primary calendar.
Document uploadText files (.txt, .md, .csv, .json), up to 400,000 characters per file. One computation uses at most 24,000 characters across all documents.
Bank exportNeeds a date and an amount column (or debit and credit). Common German, Italian, Spanish and English column names are recognised. Up to 20,000 rows. Description and merchant text are dropped after categorising.
Sample dataA built-in sample calendar, sample notes and a sample bank history.
UploadsThe approval window accepts files of up to 4 MB.

Company connectors

Added on the app's Data tab in the console.

ConnectorUsed byWhat Relay stores
Postgrescheck, aggregateThe connection string.
REST / JSON APIcheckThe base address and one optional auth header.
Sample tables (sample)check, aggregateNothing.
Rules and limits
ConnectorDetails
PostgresRegistered SELECT queries only, values as parameters, each in a read-only transaction. Use a read-only database user too. The host must be a public host name; IP addresses and private network names are refused.
REST / JSON APIhttps only. GET requests to the registered path. Response up to 1 MB, 8 seconds, redirects are not followed.
Sample tablesTwo built-in demo tables, demo_orders and demo_customers.
Connector IDShown in the console, starting with con_.

Error codes

Branch on error.code. Messages are for people and may change.

Requests and auth
CodeHTTPWhen
unauthorized401API key or agent token missing, unknown or revoked.
invalid_json400Body is not a JSON object.
too_large400Body, uploaded file or fetched response is too large.
internal_error500Unexpected failure inside Relay. No detail returned.
unknown_operation404No operation with that name.
wrong_mode400Operation, link or definition does not fit the app's mode.
receipt_not_found404No released operation with that receipt ID for this app.
Grants and budgets
CodeHTTPWhen
grant_not_found404Does not exist, or belongs to another app. Same answer for both.
grant_revoked403Ended by the person, the app or the console.
grant_expired403Past its end date.
grant_inactive403Agent token requested for a revoked or expired grant.
operation_not_granted403The grant does not cover that operation.
not_in_grant403The definition exists; this grant does not cover it.
definition_changed403The definition changed after the grant was created.
over_contract_limit403One answer could reveal more than the contract allows.
budget_exhausted42930-day budget or call count used up. Carries bits_left, calls_left and resets_at.
Running an operation
CodeHTTPWhen
invalid_input400Input does not match the contract's input schema. The message names the field.
invalid_timezone400find_slots: unknown time zone.
invalid_date400find_slots: date_from is not a real date.
window_out_of_range400find_slots: date_from is before today or more than 60 days ahead.
invalid_params400check: parameters are not exactly the registered ones, or a value does not match its pattern.
unknown_candidate_set404rank_options: candidate set not registered.
unknown_aggregate404aggregate: total not registered.
unknown_profile404profile: form not registered.
unknown_check404check: check not registered.
no_source409The person has not connected the kind of source needed.
source_unavailable400 or 502A live source could not be read: Google access expired, or the company database or API failed.
feed_unreachable400A live calendar address could not be read or returned no calendar.
connector_missing409The connector named in the definition no longer exists.
connector_mismatch400A query with a REST connector, or a path with a database connector.
compute_failed502Unexpected failure. Nothing was released.
release_blocked502The result failed the release check. Nothing was released.
Link tokens and configuration
CodeHTTPWhen
invalid_operations400The operation list is empty or names an operation the mode does not allow. Also for permissions.
invalid_origin400origin is not a web address.
origin_not_registered403origin is not a registered origin of the app.
invalid_return_url400return_url is not a web address, is on another origin, or exceeds 500 characters.
invalid_subject400subject is empty or longer than 120 characters.
missing_scope400A list of IDs is missing: 1 to 5 per link token. For a permission: no checks or totals are registered.
unknown_id400An ID in the scope list is not registered for this app.
invalid_config400A definition is not valid. The message says which and why.
Approval window and receipts
CodeHTTPWhen
link_not_found404The link token is not valid.
link_used403Already approved or declined.
link_expired403Older than 30 minutes.
missing_source400Approval sent before a needed source was connected.
too_many_sources400The person already has 12 sources.
unknown_source400Source kind not supported.
source_not_found404The source to remove is not connected.
not_a_calendar400The upload is not an .ics calendar.
empty_file / not_text400The uploaded document is empty or not a text file.
not_a_bank_export400No date and amount columns, or no transactions, in the CSV.
invalid_url / blocked_host400Address is not https, carries credentials, points to a private network, or is not an allowed calendar provider.
google_not_configured400The deployment has no Google credentials.
google_failed / invalid_state400Google sign-in did not complete, or the attempt is older than 15 minutes.
not_found404Receipts page: the receipts link is not valid.

These need a new approval or permission: grant_revoked, grant_expired, not_in_grant, definition_changed, operation_not_granted. Console forms show the message only.

Limits

Disclosure budgets come from the contracts.

OperationMax per answerNew answers / 30 daysTotal / 30 daysSame answer for
find_slots23 bits12140 bits24 hours
rank_options13 bits20130 bits24 hours
check4 bits5,00020,000 bits1 hour
aggregate4 bits3060 bits24 hours
profile30 bits660 bits24 hours
How budgets are counted
  • Per person, per app and per operation. A new approval by the same person does not reset them.
  • The 30-day period starts when the person first appears for the app.
  • In company mode the budget is per permission.
  • Charged before data is read. A request that then fails in fetch or compute still counts.
  • The same question inside the contract's time window returns the stored answer and uses no budget.
  • Time windows follow the UTC clock: a 24-hour window is one UTC day, a 1-hour window is one clock hour.
Sizes and counts
ThingLimit
Request body200,000 characters. Configuration: 400,000. Source upload: 4,200,000.
Link token30 minutes, one use, 1 to 5 IDs per section.
return_url500 characters, same origin.
Grant lifetimePerson: 1, 7, 30 or 90 days. Permission: 1 to 365 days, default 90.
Origins per app10. https only; http is accepted for localhost and 127.0.0.1.
Subject ID120 characters
Definitions30 per section. Sizes per kind are under Configuration.
Sources per person and app12
find_slotsStart date today to 60 days ahead. Window 3, 7 or 14 days. Slots of 30, 45 or 60 minutes on a 30-minute grid, 08:00 to 20:00 in the person's time zone. None within two hours from now. Up to 3 slots. Weekdays only unless days is all.
rank_optionstop_k from 1 to 3.
Agent tokensOne per grant.
Branding logo150 KB.
Console session14 days.

Self-hosting

One Next.js application. Needs Node.js 22.12 or newer.

npm install
cp .env.example .env.local     # optional: every value has a development default
npm run dev                    # http://localhost:3210
npm test                       # all tests, on an in-memory database
npm run redteam                # only the attack tests in tests/attacks
npm run typecheck
Development defaults
Not setWhat happens
DATABASE_URLAn embedded Postgres-compatible database in ./.relay-data.
RELAY_MASTER_KEYA fixed development key. It is not secret. Do not put real data into a development server.
SIGNUP_CODEThe sign-up code is relay-dev.

The five demo apps and their sample tables are created on first use. The test runner sets the Node.js minimum.

Environment variables
VariablePurposeIn production
RELAY_MASTER_KEY64 hex characters. Wraps the keys that encrypt stored sources. Generate with openssl rand -hex 32.Required; Relay does not run without it. Keep it stable and backed up: sources cannot be read without it.
DATABASE_URLPostgres connection string.Use Postgres. Tables are created on first connection.
APP_URLPublic address. Used in approval links, receipts links, the MCP address and the Google redirect.Set it to your https address.
SIGNUP_CODEThe code a new client needs to create a console account.Without it nobody can create an account.
ANTHROPIC_API_KEYKey for the AI model used by rank_options and profile suggestions.Optional. Without a key these run on rules.
RELAY_MODELModel name. Default claude-haiku-5-5.Optional.
GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRETTurn on Google Calendar sign-in, limited to free/busy.Optional. Redirect address at Google: APP_URL/api/oauth/google/callback.
RELAY_LLMoff turns the model off even when a key is set.Optional.
RELAY_LLM_BASE_URLPoints model calls at another address.Optional.
RELAY_DATA_DIRMoves the embedded database.Optional.
Production notes
  • Serve Relay over https on its own origin. The approval, receipts and console pages limit framing and forbid caching.
  • Relay calls only public https hosts. Addresses pointing into a private network are refused.
  • Not built: billing, email receipts and OAuth for MCP. See Trust for the full list.