CastHQ for developers

Wait on the world

CastHQ is the shared record of when things happen and how sure anyone can be. Your agent subscribes to a condition on an event (its date confirmed, it is cancelled, it moved by more than three days) and CastHQ tells it when that becomes true. The work that follows stays in your runtime.

API reference

Every REST endpoint, interactive, from the OpenAPI document.

The spec

Change envelope, condition language, confidence and reconciliation rules, with JSON Schemas.

skill.md

Instructions for agents: how to look a date up, check it, and wait for it.

Before you start

  • Make a personal access token in Settings → Tokens with the scopes subscriptions:read and subscriptions:write, and export it as CASTHQ_TOKEN. An agent can get the same scopes over OAuth instead.
  • Every call goes to https://api.casthq.co (set CASTHQ_API to point somewhere else). Reading public events needs no token at all.
  • Errors are { "error": { "code", "message", "doc_url", "request_id" } }: branch on code. Send casthq-version: YYYY-MM-DD to pin a version.

Quickstarts

Each one is tested end to end against a live API, so it works as printed. Event ids are in every event's Markdown (/{topic}/{event}.md) and in the change feed.

Wait for a date to be confirmed

Subscribe to an event with a condition, then long-poll. The call returns when the producer confirms the day, or at once if it already has. Run it again with the same client_ref and it resumes where it stopped.

confirmed-date.sh
#!/usr/bin/env bash
# Wait until an event's date is confirmed, then print it.
#
#   export CASTHQ_TOKEN=chq_pat_…   # scopes: subscriptions:read, subscriptions:write
#                                   # (a test token, chq_pat_test_…, works on its sandbox)
#   ./confirmed-date.sh <event id>
#
# Safe to stop and run again: the same client_ref returns the same
# subscription and its cursor, so nothing that fired in between is lost.
set -euo pipefail
API="${CASTHQ_API:-https://api.casthq.co}"
: "${CASTHQ_TOKEN:?set CASTHQ_TOKEN to a personal access token}"
EVENT="${1:?usage: $0 <event id>}"
AUTH="Authorization: Bearer $CASTHQ_TOKEN"

# 1. Subscribe. If the date is already confirmed, it fires at once.
sub=$(curl -sS --fail-with-body "$API/v1/subscriptions" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{
    "target": "event:'"$EVENT"'",
    "condition": { "fact": "schedule", "confidence": { "becomes_at_least": "confirmed" } },
    "client_ref": "confirmed-date-'"$EVENT"'"
  }' | jq -r '.data.id')
echo "subscribed $sub"

# 2. Long-poll: each call waits up to 20 s for a firing.
while :; do
  firing=$(curl -sS --fail-with-body "$API/v1/subscriptions/$sub/events?wait=20" -H "$AUTH" |
    jq -c '.data[0] // empty')
  [ -n "$firing" ] && break
done

# 3. A firing carries the change that made the condition true, with the
#    event's state just after it (an initial firing: the state at creation).
jq -r '(.change.data.after // .state) as $s |
  "fired \(.id)\nstate \($s.state), schedule \($s.facts.schedule)"' <<<"$firing"
curl -sS --fail-with-body "$API/v1/events/$EVENT/status" -H "$AUTH" |
  jq -r '"date \(.data.date.words) (\(.data.date.precision))"'

Run: ./confirmed-date.sh <event id>

From an agent, over MCP

wait_for answers straight away with the event's state now; get_events returns the firing once it is cancelled. Any MCP client makes these same two calls once https://api.casthq.co/mcp is added as a server.

cancelled-mcp.sh
#!/usr/bin/env bash
# The same wait over MCP, the way an agent does it: wait_for once, then
# get_events until it fires. Here: tell me if the event is cancelled.
#
#   export CASTHQ_TOKEN=chq_pat_…   # or an OAuth access token; scopes: subscriptions:read, subscriptions:write
#   ./cancelled-mcp.sh <event id>
#
# An MCP client (Claude, Cursor, the Agents SDK) makes these same two tool
# calls for you once /mcp is added as a server; curl shows what goes over
# the wire.
set -euo pipefail
API="${CASTHQ_API:-https://api.casthq.co}"
: "${CASTHQ_TOKEN:?set CASTHQ_TOKEN to a personal access token}"
EVENT="${1:?usage: $0 <event id>}"

# One JSON-RPC tool call. /mcp is stateless: no session to open first.
# The answer comes as one server-sent event; its text is the tool's JSON.
tool() {
  curl -sS --fail-with-body "$API/mcp" \
    -H "Authorization: Bearer $CASTHQ_TOKEN" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json, text/event-stream" \
    -d "$(jq -n --arg name "$1" --argjson args "$2" \
      '{jsonrpc: "2.0", id: 1, method: "tools/call", params: {name: $name, arguments: $args}}')" |
    sed -n 's/^data: //p' | jq -r '.result.content[0].text'
}

# 1. wait_for answers at once: the event's state now, and the firing if the
#    condition already holds (an event cancelled before you asked fires).
answer=$(tool wait_for '{
  "target": "event:'"$EVENT"'",
  "condition": { "status": { "becomes": "cancelled" } },
  "client_ref": "cancelled-'"$EVENT"'"
}')
sub=$(jq -r '.subscription.id' <<<"$answer")
echo "subscribed $sub (status now: $(jq -r '.subscription.currentState.status' <<<"$answer"))"

# 2. Not yet: poll get_events. It resumes where the last call stopped.
firing=$(jq -c '.firings[0]? // empty' <<<"$answer")
while [ -z "$firing" ]; do
  sleep 2
  firing=$(tool get_events '{"subscription": "'"$sub"'"}' | jq -c '.data.subscriptionEvents.firings[0] // empty')
done

jq -r '"fired \(.id)\nstatus \(.change.data.after.status // .state.status)"' <<<"$firing"

Run: ./cancelled-mcp.sh <event id>

Two hours before it starts

A timer condition: fires two hours before the event's start, and moves with the date if the start moves. In test mode, advance the sandbox's test clock and it fires at once instead of in two hours.

before-start.sh
#!/usr/bin/env bash
# Be told two hours before an event starts. If its date moves, the timer
# moves with it; the firing id says which date it was for.
#
#   export CASTHQ_TOKEN=chq_pat_…   # scopes: subscriptions:read, subscriptions:write
#   ./before-start.sh <event id>
#
# In test mode (a test token, chq_pat_test_…, on a sandbox event) you do not
# wait two real hours: advance the sandbox's test clock and it fires at once:
#
#   curl -X POST "$CASTHQ_API/v1/test_clocks/<clock id>/advance" \
#     -H "Authorization: Bearer $CASTHQ_TOKEN" -H "Content-Type: application/json" \
#     -d '{"by": "PT23H"}'
set -euo pipefail
API="${CASTHQ_API:-https://api.casthq.co}"
: "${CASTHQ_TOKEN:?set CASTHQ_TOKEN to a personal access token}"
EVENT="${1:?usage: $0 <event id>}"
AUTH="Authorization: Bearer $CASTHQ_TOKEN"

sub=$(curl -sS --fail-with-body "$API/v1/subscriptions" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{
    "target": "event:'"$EVENT"'",
    "condition": { "time": { "anchor": "start", "offset": "-PT2H" } },
    "client_ref": "before-start-'"$EVENT"'"
  }' | jq -r '.data.id')
echo "subscribed $sub"

while :; do
  firing=$(curl -sS --fail-with-body "$API/v1/subscriptions/$sub/events?wait=20" -H "$AUTH" |
    jq -c '.data[0] // empty')
  [ -n "$firing" ] && break
done

# A timer firing: which timer, for which start time, and the event's state then.
jq -r '"fired \(.id)\nstart \(.timer.anchor_value), timer \(.timer.offset_seconds)s\nstatus \(.state.status)"' <<<"$firing"

Run: ./before-start.sh <event id>

Watch a topic for new events

A continuous subscription on a topic and its sub-topics: one firing each time an event becomes publicly listed. Firing ids are stable, so a restart never repeats one.

announced.sh
#!/usr/bin/env bash
# Watch a topic: print each event as it is announced (becomes publicly
# listed), for as long as you leave it running.
#
#   export CASTHQ_TOKEN=chq_pat_…   # scopes: subscriptions:read, subscriptions:write
#   ./announced.sh <topic slug or id> [how many to wait for]
#
# A continuous subscription with a cursor: every firing has a stable id, so
# a restart (same client_ref) picks up where it stopped without repeats.
set -euo pipefail
API="${CASTHQ_API:-https://api.casthq.co}"
: "${CASTHQ_TOKEN:?set CASTHQ_TOKEN to a personal access token}"
TOPIC="${1:?usage: $0 <topic> [count]}"
COUNT="${2:-0}" # 0 = forever
AUTH="Authorization: Bearer $CASTHQ_TOKEN"

sub=$(curl -sS --fail-with-body "$API/v1/subscriptions" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{
    "target": "topic:'"$TOPIC"'",
    "condition": { "listed": { "becomes": true } },
    "mode": "continuous",
    "client_ref": "announced-'"$TOPIC"'"
  }' | jq -r '.data.id')
echo "subscribed $sub"

seen=0
cursor=""
while [ "$COUNT" -eq 0 ] || [ "$seen" -lt "$COUNT" ]; do
  page=$(curl -sS --fail-with-body "$API/v1/subscriptions/$sub/events?wait=20${cursor:+&cursor=$cursor}" -H "$AUTH")
  cursor=$(jq -r '.next_cursor' <<<"$page")
  while read -r firing; do
    [ -z "$firing" ] && continue
    event=$(jq -r '.event' <<<"$firing")
    title=$(curl -sS --fail-with-body "$API/v1/events/$event/status" -H "$AUTH" | jq -r '.data.event.title')
    echo "fired $(jq -r '.id' <<<"$firing"): announced \"$title\""
    seen=$((seen + 1))
  done < <(jq -c '.data[]' <<<"$page")
done

Run: ./announced.sh <topic>

Try a condition first

The dry run replays a condition over an event's history and lists the changes it would have fired at. No token needed.

test-condition.sh
#!/usr/bin/env bash
# Try a condition before you wait on it: replay it over an event's history
# and see which changes it would have fired at. Anonymous: no token needed
# for a public event. A test token (CASTHQ_TOKEN=chq_pat_test_…) also reads
# its sandbox's events.
#
#   ./test-condition.sh <event id>
set -euo pipefail
API="${CASTHQ_API:-https://api.casthq.co}"
EVENT="${1:?usage: $0 <event id>}"
AUTH=()
[ -n "${CASTHQ_TOKEN:-}" ] && AUTH=(-H "Authorization: Bearer $CASTHQ_TOKEN")

curl -sS --fail-with-body "$API/v1/conditions/test" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d '{
    "target": "event:'"$EVENT"'",
    "condition": { "change": "schedule" }
  }' |
  jq '.data | {
    fired: [.fired[] | "\(.id) \(.type) at \(.time)"],
    scanned,
    would_fire_now: .initial.would_fire_now
  }'

Run: ./test-condition.sh <event id>

More ways in

  • MCP, read-only, no sign-in: https://api.casthq.co/mcp/public. Read and write, OAuth: https://api.casthq.co/mcp.
  • The change feed, cursor-paged, as CloudEvents: GET https://api.casthq.co/v1/changes?format=cloudevents.
  • For models: llms.txt and skill.md; any event as Markdown at its URL plus .md.
  • Not yet: signed webhook delivery, timer conditions ("2 hours before start"), test-mode keys and official SDKs. The conditions for them already validate.

Errors

Every REST error's doc_url points at its row here. Codes are stable within a version and new ones may be added; retryable says whether the same request can succeed later.

invalid_request · 400
The request is malformed: a parameter or the body failed validation. param names the field when one is to blame.
invalid_id · 400
An id names the wrong kind of thing: a TypeID whose prefix is not the one this parameter takes (expected an event_ id, got topic_…). param names the parameter, expected the kind it takes and got the id sent. See docs/api/ids/README.md.
invalid_api_version · 400
The casthq-version header (or the version pinned on the key) is not a version this API serves.
invalid_idempotency_key · 400
The Idempotency-Key header is empty, longer than 255 characters, or not printable ASCII.
invalid_token · 400
A signed token in the URL (one-click unsubscribe) is missing or invalid.
invalid_signature · 400
A webhook's signature did not verify.
missing_signature · 400
A webhook arrived without its signature header.
dependency_cycle · 400
The dependency would close a cycle: the event it would depend on already depends on it, directly or through others. path lists the events around the cycle (event_ ids), starting and ending with the dependent.
dependency_limit · 400
The dependency would pass a limit: a chain deeper than 16, more than 32 events one event depends on, more than 1,000 direct dependents of one event from one owner (limit: "dependents"; counted per private namespace, else per owning org or user, so other owners are unaffected), or more than 10,000 direct dependents of one event from the dependent's world, the public record or one private namespace (limit: "dependents_total"). limit names it, and the message says which.
target_too_large · 400
A topic with more than 5,000 upcoming dated events is too large for a time condition, which arms a timer on every one of them (limit: 5000). Subscribe to a child topic instead. On a series: target, the condition's lead needs more than 64 occurrences materialised ahead (limit: 64): use a shorter lead, or one occurrence.
question_too_long · 400
An Ask question is over the length limit.
unauthenticated · 401
No valid credential was sent.
token_invalid · 401
Not a token CastHQ issued (or one already deleted after expiry).
token_expired · 401
The token has expired. Ask the user for a new one.
token_revoked · 401
The token was revoked (for an OAuth app: the user disconnected it).
dpop_invalid · 401
The OAuth access token is DPoP-bound and the request does not prove possession of its key: no DPoP proof, one for another request or key, or one already used. Send a fresh proof with every request (RFC 9449).
dpop_required · 401
This endpoint (/mcp) accepts only DPoP-bound OAuth access tokens. Get the token with a DPoP proof at /api/auth/oauth2/token and send it as Authorization: DPoP <token> with a proof (RFC 9449).
email_unverified · 403
The token's account has not verified its email address, so the token acts for nobody. The account's owner follows the link in the verification email (signing in again sends a new one); the token then works again.
session_required · 403
This endpoint needs a signed-in person; a token cannot use it.
reauth_required · 403
Step-up: the operation (changing members or access, deleting the account, minting a sensitive token, or an Agent card that does one of those) needs a sign-in or re-authentication within the last 15 minutes. Re-authenticate with POST /api/auth/reauthenticate/passkey or /reauthenticate/password (or sign in again), then retry; for an Agent card, action carries it, still pending.
forbidden · 403
The credential is valid but may not do this.
review_required · 403
The event's organization requires review before changes to it go live (approval before publishing), and this credential is not a reviewer in a signed-in session. Make the change with the GraphQL updateEvent, which holds it for a reviewer, or ask a reviewer to make it.
insufficient_scope · 403
The key or token lacks a scope. required names it.
livemode_mismatch · 403
Test and live data do not mix: a test-mode credential (chq_test_, chq_pat_test_, an OAuth test client) reached live data or a mutation test mode does not offer, or a live credential reached test data. Use a credential of the matching mode.
subscription_limit_reached · 403
The account holds as many live subscriptions as its tier allows. The limit counts per account (verified identity), across all its keys and apps. limit, used and tier say where it stands; delete or let some expire, or raise it: Free (a verified email; Settings › Authentication sends the link) covers one developer, and the Team plan on an organization (or any paid plan) gives a larger allowance its members share. upgrade_url links to the plans; GET /v1/usage shows the limits.
plan_required · 403
The organization's plan does not include this. Private namespaces are a paid feature (test mode is free); an existing namespace stays readable when a plan lapses, but takes no new events or grants. The audit log export is Enterprise. Agent and Ask are part of every paid plan, never Free or a personal workspace; public Ask needs the topic's owner on a paid plan. Delivery and reach analytics and choosing a webhook endpoint's event types are Pro and up; SSO and SCIM are Team and up.
plan_limit_reached · 403
A counted plan limit is used up: limit and used say where the org stands. Seats (members plus pending invitations; agents are not counted) refuse one more invitation, and outgoing webhook endpoints (an org's: one on Free; a person's and their apps': three on Free, upgrade_url says where to raise it) one more endpoint; nobody and nothing is removed. Upgrade the plan or free one. Followers are never a limit. Settings › Billing lists every limit and what happens at it.
namespace_limit_reached · 403
The plan's number of private namespaces, or of events across them, is used up (or a namespace's 500 grants). Upgrade the plan.
user_grant_required · 403
An app acting for itself (OAuth client credentials) cannot write to the public record. Have a user connect the app and act with their token.
token_not_accepted · 403
Personal access tokens are not accepted on this path.
cross_site_request · 403
A write authenticated by a session cookie came from an untrusted origin, or without Content-Type: application/json. Browsers on casthq.co are trusted; API clients authenticate with an Authorization header, which this check does not apply to.
not_found · 404
No such resource, or one the caller may not see (the two are indistinguishable on purpose).
gone · 410
The id was published once and is no longer served: withdrawn from the public record, or a change of an event that is no longer listed. The body carries a tombstone (urn, kind, reason, since); the id will keep answering this, never a 404.
context_not_found · 404
Ask: the event or topic the question is about does not exist.
method_not_allowed · 405
The path exists but not with this method. See the Allow header.
request_timeout · 408 · retryable
The request took too long (usually a slow database); retry.
idempotency_key_reused · 409
This Idempotency-Key was already used with a different request.
secret_shown_once · 409
This Idempotency-Key already ran a request whose response carried a secret (a new token, key, webhook secret, claim token or feed URL). Secrets are shown once and never stored, so it cannot be replayed: use the secret from the first response, or rotate or create a new one with a new key.
client_ref_reused · 409
This client_ref already names a subscription with a different target, filter, condition, mode, initial, ack_mode or settle window. subscription is its id and fields what differs; use a new client_ref, or delete that subscription first.
subscription_expired · 409
The subscription's lease ran out. Renew it (POST /v1/subscriptions/{id}/renew), or create it again with the same client_ref: either resumes the same id and cursor.
firing_claimed · 409 · retryable
Another runner holds a live claim on this firing (ack_mode explicit), and the request did not carry that claim's token. Retry after Retry-After seconds, when the claim lapses; or ack with the token from your own claim.
claim_lost · 409
The claim token is no longer the firing's: its lease ran out and another runner claimed it, it was released, or the firing was already acked (a different outcome than the first ack: the first ack wins). Your work may have run twice; use the firing id as your idempotency key so that it is harmless.
ack_not_enabled · 409
The subscription's ack_mode does not take this: claims and acks need explicit, a cursor commit needs cursor. param is ack_mode. The mode is chosen at create.
action_not_pending · 409
Agent: the card was already confirmed, rejected or expired. A confirm is single-use; action carries the card as it stands.
action_stale · 409
Agent: the card changed since it was shown (edited elsewhere, or what it touches was updated and the card re-rendered). Show action again and confirm with its varsHash.
undo_unavailable · 409
Agent: the change has no Undo or Revert on offer (none exists for it, its 10 minutes have passed, or what it changed moved on). Make the change in the dashboard. action carries the card as it stands.
strong_confirmation_required · 409
Agent: the card is confirm_strong (outward or public consequences, or untrusted text in the conversation); confirm it from the card with strong: true.
idempotency_key_in_progress · 409 · retryable
A request with this Idempotency-Key is still running; retry shortly.
action_expired · 410
Agent: the card was not confirmed within 30 minutes and can no longer run. Ask Agent again.
payload_too_large · 413
The body is over the limit. limit gives it in bytes.
unsupported_media_type · 415
The body's content type is not accepted: a JSON body must be sent as application/json, an upload as an accepted image type.
unreadable_image · 422
The image's dimensions could not be read.
image_role_mismatch · 422
The image does not fit the requested role (aspect or size). requirements says what does.
rate_limited · 429 · retryable
Too many requests. Wait for Retry-After seconds. An API rate limit also carries upgrade_url, the plans page.
spend_cap_reached · 429
Agent has used the workspace's monthly replies or the daily or monthly allowance of the person or the workspace, or public Ask has used its daily allowance (the whole deployment's, or this network's). The message says which and when it resets; Retry-After gives the seconds.
internal · 500 · retryable
Something failed on our side. Quote request_id when reporting it.
handler_failed · 500 · retryable
A webhook was valid but could not be applied; the sender should retry.
not_configured · 503
This endpoint is not configured in this environment.
agent_restricted · 403
An owner or admin of this organization has limited Agent to owners and admins. The member keeps the read-only dashboard Ask and their own conversations.
agent_unavailable · 503
Agent, the dashboard agent, is not available in this environment (not switched on, or no model configured), or its writes are paused for now.
ask_unavailable · 503
Ask is not available in this environment.
service_unavailable · 503 · retryable
The database is unreachable for a moment. Nothing was read or written; retry after Retry-After seconds. A subscription pull answers this, never an empty page, so an empty page always means caught up.

Questions

api@casthq.co