ContextDB Cloud API

ContextDB API reference.

This API reference covers memory formation, explicit evolution, recall, confirmation, erasure, action evaluation, execution receipts, and Memory CI.

recall -> remember -> evaluate_action -> confirm if required -> re-evaluate -> host action -> report_execution

The Python client method evaluate_action calls POST /v1/recall_for_action. HTTP and MCP keep the recall_for_action name.

Base URL https://api.contextdb.ai
Authentication cdb_ memory · cbe_ Memory CI Server-side only
Format JSON over HTTPS OpenAPI 3.1

Cloud quickstart

Remember one detail. Check one action.

Create a free Cloud account, make one project key, and run this from server code. No card is required. Keep the key out of browsers and mobile apps.

  1. 1. Create an account and project. Create a free Cloud account, then copy the project key when it is shown once.
  2. 2. Add the key to server-side secrets.
    export CONTEXTDB_API_KEY="your-project-key"
  3. 3. Install the official Python client.
    pip install contextdb-cloud-client==0.2.0a2
quickstart.py
import asyncio
import os
from contextdb_cloud_client import CloudClient

async def main():
    async with CloudClient(
        "https://api.contextdb.ai",
        api_key=os.environ["CONTEXTDB_API_KEY"],
    ) as db:
        saved = await db.remember(
            "synthetic_customer_42",
            "Thursday afternoon is confirmed.",
            source="user_stated",
            confidence=0.95,
            idempotency_key="quickstart-remember-v1",
        )
        recalled = await db.recall(
            "synthetic_customer_42",
            "When is the visit?",
            min_memory_version=saved.memory_version,
            min_primary_wal_lsn=saved.primary_wal_lsn,
        )
        decision = await db.evaluate_action(
            "synthetic_customer_42",
            "book the visit",
        )
        print(recalled.memories[0].content, decision.outcome)
        if decision.outcome == "act":
            await db.report_execution(
                "synthetic_customer_42",
                decision.decision_id,
                "appointment.book",
                "succeeded",
                idempotency_key=f"receipt-{decision.decision_id}",
            )

asyncio.run(main())

Thursday afternoon is confirmed. act

ContextDB returns act, ask, or abstain. Your host still authenticates the end user, authorizes the business action, checks current state, and decides what runs. Cloud currently has no availability SLA.

Runnable framework starters

Copy a complete agent memory integration.

Each public starter installs the official ContextDB client, uses a stable server-side user partition, recalls before the model answers, and keeps evidence evaluation outside the prompt.

Framework Runtime Integration point Starter
OpenAI Agents SDK Python Runner.run · typed memory tool Copy the OpenAI starter →
LangGraph Python StateGraph model node Copy the LangGraph starter →
Vercel AI SDK TypeScript generateText · tool Copy the Vercel AI starter →
LiveKit Agents Python Per-turn voice recall Copy the LiveKit starter →
PyAI Omni TypeScript OmniAgent.bridge knowledge Copy the PyAI starter →
Validate the selected user_id, query, and expected act/ask/abstain outcome in the Playground before connecting a consequential side effect in a bounded alpha evaluation.

See the evidence path in Console

Follow one evidence evaluation from policy to host result.

Start with recall for action, then use the guides to inspect changing memory, release checks, and source syncs.

Expanded ask decision with one evidence ID and a skipped, policy-aligned host execution.
Synthetic demo Hosted Alpha Console trace connecting the policy result, evidence snapshot, and host-reported receipt.

Official Python and TypeScript SDKs

Install ContextDB Cloud in your backend.

Use the Python or server-only TypeScript SDK to add persistent, action-aware memory to voice, support, and workflow agents. Both clients cover recall, consistency tokens, evidence evaluation for proposed actions, execution receipts, and verifiable deletion.

Python SDK

For FastAPI, Django, workers, notebooks, and Python agent runtimes.

Install from PyPI
pip install contextdb-cloud-client==0.2.0a2
from contextdb_cloud_client import CloudClient

async with CloudClient(
    "https://api.contextdb.ai",
    api_key="cdb_...",
) as db:
    saved = await db.remember(
        "caller-1",
        "Tuesday morning works best",
        source="user_stated",
        idempotency_key="call-42-preference",
    )

View contextdb-cloud-client on PyPI

TypeScript SDK

For Node.js servers, API routes, workers, and server actions. The package fails closed in browser runtimes.

Install from npm
npm install @contextdb/cloud@0.2.0-alpha.2
import { CloudClient } from "@contextdb/cloud";

const db = new CloudClient({
  baseUrl: "https://api.contextdb.ai",
  apiKey: process.env.CONTEXTDB_API_KEY!,
});

const saved = await db.remember(
  "caller-1",
  "Tuesday morning works best",
  { source: "user_stated" },
);

View @contextdb/cloud on npm

Which ContextDB SDK should I use?

Choose Python for Python agent runtimes and TypeScript for Node.js backends. Use pycontextdb instead when you want the Apache-2.0 local or self-hosted memory engine.

Can I use a ContextDB project key in browser code?

No. A cdb_ key is a server credential. Keep it in backend secret storage and call ContextDB only from trusted server code.

Build with your coding agent

Open a complete ContextDB integration prompt.

Each button copies the prompt and opens it prefilled. Nothing is sent until you review and submit it.

ContextDB integration prompt
Preview prompt
Integrate ContextDB Cloud into this repository.

Read:
- https://contextdb.ai/docs
- https://contextdb.ai/openapi.yaml

Use https://api.contextdb.ai and the server-side CONTEXTDB_API_KEY environment
variable. Never expose the project key in browser or mobile code.

Implement:
1. Recall customer memory when a call, chat, or agent session starts.
2. Write selected durable facts with their real source. For a
   production-shaped Hosted Alpha evaluation, submit structured turns to
   /v1/formation/jobs and poll the returned job ID. Use /v1/extract_memories
   only for short synchronous flows.
3. Use mode=propose for review or mode=commit for automatic validated writes.
4. Use /v1/evolve for explicit ADD, UPDATE, DELETE, or NOOP operations. Pass
   the returned memory version and WAL position into an immediate recall.
5. Call the Python client's evaluate_action before a booking, refund, plan
   change, or write. Its HTTP route and MCP tool are named recall_for_action.
6. Branch on act, ask, or abstain. On ask, the customer host authenticates and
   retains any end-user attestation, calls /v1/confirm for one returned pending
   memory ID, and re-evaluates. On abstain, do not act.
7. On act, apply current-state checks and authorization in the customer host,
   then run the host action.
8. Report succeeded, failed, or skipped with report_execution in the client,
   POST /v1/receipts over HTTP, and the decision_id.
9. Use /v1/forget for one scoped memory, one stable slot, or verified
   whole-partition erasure.
10. Test cross-user isolation, evolution evidence IDs, policy violations, and
    named formation failures.

Inspect the repository first and show the proposed integration points before editing.

If the selected app is not installed, the prompt is still copied.

Getting started

Authentication

Project keys begin with cdb_. They select an organization and project, and belong only in server-side secret storage. user_id selects an isolated customer-memory partition. It is not end-user authentication.

Memory CI tokens begin with cbe_. Each token is bound to one project, shown once, and stored hashed. It is accepted only by the four /evals/v1 operations. It cannot call memory routes or create, read, update, or delete Testbench cases and suites.

shell
export CONTEXTDB_API_KEY="your-project-key"
export CONTEXTDB_EVAL_TOKEN="your-evaluation-token"
export CONTEXTDB_BASE_URL="https://api.contextdb.ai"
Never put a project key in NEXT_PUBLIC_*, VITE_*, browser JavaScript, or a mobile binary. Keep the evaluation token in CI secret storage.

Errors

Errors are JSON and always include a request ID when the gateway handled the request.

{
  "code": "invalid_request",
  "message": "request validation failed",
  "request_id": "f47ac10b-..."
}
StatusMeaning
400Malformed JSON, missing field, or validation failure
401Missing, unknown, or revoked project key
403Project is not entitled to the requested feature
404Missing target or target outside the caller's partition
413Body, batch, turns, or transcript exceeds a cap
429Client IP or project exceeded its request rate
502-504Formation provider returned a named terminal failure

Rate limits

Both buckets apply: 120 requests per minute per client IP (burst 30), then 600 requests per minute per authenticated project (burst 100).

HeaderMeaning
Retry-AfterSeconds to wait after a 429
X-RateLimit-LimitSustained requests per minute
X-RateLimit-RemainingTokens remaining in the burst bucket
X-RateLimit-Scopeip or project

Idempotent writes

Add an Idempotency-Key to remember, batch remember, confirmation, or formation commit requests. Every Evolution operation, every Formation job, every execution receipt, and whole-partition erasure require one. Use a new key for each logical mutation.

SituationResult
Same key + same requestOriginal status and JSON body replayed
Same key + different request409 idempotency_conflict
Identical request still runningWaits, then replays. A timeout returns 409.
Process stopped during write409 idempotency_ambiguous. Do not retry with a new key. Inspect current business state, then contact Support with the request ID if the result is still unclear.

Responses are encrypted in the metadata store and expire after 24 hours. Per-project retention is capped at 100,000 records and 256 MiB. Idempotency-Replayed is true on a replay. SDKs expose this as idempotency_key in Python and idempotencyKey in TypeScript.

Read your writes across runtimes

Remember, batch remember, evolve, confirm, and forget return a project-scoped memory_version and primary_wal_lsn. Pass them to the next ordinary recall when that read must include the mutation.

const saved = await contextdb.remember("customer-123", "Prefers Saturday", {
  source: "user_stated"
});

const recalled = await contextdb.recall("customer-123", "preferred day", {
  minMemoryVersion: saved.memory_version,
  minPrimaryWalLsn: saved.primary_wal_lsn
});

The current deployment has no read replica: the read pool and primary pool both connect to the primary. readConsistency: "replica_fallback" (or read_consistency over HTTP) remains an API consistency contract for bounded replica wait and primary fallback in a topology with a replica. It is not evidence of deployed read scaling. A token-bearing recall uses the primary, and an impossible floor fails with 503 consistency_unavailable. Evidence evaluation, confirmations, deletion, and pending-memory reads also use the primary.

System

Health and readiness

GET /health

Process liveness. No authentication and no dependency checks.

No authReturns 200
Response
{
  "ok": true,
  "service": "contextdb-cloud-gateway",
  "sdk_pin": "<release commit>"
}
GET /ready

Checks metadata, memory, connector, and Formation storage plus the required PII key.

No auth200 ready · 503 not ready
Response
{
  "ready": true,
  "checks": {
    "metadata_store": true,
    "memory_store": true,
    "connector_store": true,
    "formation_store": true,
    "pii_key": true
  }
}

Memory

Write and retrieve customer memory

POST/v1/remember

Store one already-sourced customer detail.

Project keyPII before embedding

Important fields

user_idrequired
Customer partition key
contentrequired
Durable detail, maximum 4,000 characters
sourcerequired
user_stated, agent_inferred, or third_party
confidence
Number from 0 to 1
action_relevant
Whether it may affect a later action
entity + attribute
Stable slot. A new value supersedes the current value and closes its validity window.
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/remember" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: remember-customer-123-preference-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "content": "Prefers Saturday morning appointments",
    "source": "user_stated",
    "confidence": 0.95,
    "action_relevant": true
  }'
200 response
{
  "memory": {"id": "mem_...", "content": "Prefers Saturday morning appointments"},
  "memory_version": 42,
  "primary_wal_lsn": "1A/2B"
}
POST/v1/evolve

Apply one explicit factual-memory operation. ADD stores a new fact. UPDATE supersedes a current target. DELETE removes a target or slot. NOOP records why memory should remain unchanged.

Project + user scoped Idempotency-Key required Atomic state + revision + audit

Operation contract

add
Requires content and source. Does not accept a target.
update
Requires content, source, and either target_memory_id or an entity/attribute slot
delete
Accepts no content. Requires a target memory ID or slot.
noop
Accepts no content. Requires a bounded noop_reason.

UPDATE and DELETE fail closed when their target cannot be proven inside the authenticated project and requested user partition.

Correct a memory
curl -X POST "$CONTEXTDB_BASE_URL/v1/evolve" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: call-884-correction-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "operation": "update",
    "target_memory_id": "mem_old",
    "content": "Friday morning works best",
    "source": "user_stated"
  }'
200 response
{
  "requested_operation": "update",
  "applied_operation": "update",
  "outcome": "updated",
  "memory": {
    "id": "mem_new",
    "content": "Friday morning works best"
  },
  "previous_memory_ids": ["mem_old"],
  "deleted_memory_ids": [],
  "noop_reason": null,
  "memory_version": 42,
  "primary_wal_lsn": "1A/2B",
  "request_id": "..."
}

Pass the returned version and WAL position to the next recall when it must observe the change. Read the Memory Evolution guide or install the Python and TypeScript alpha clients.

POST/v1/remember_many

Store up to 100 sourced memory items in one request.

Project keyMaximum 100 items
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/remember_many" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: import-customer-123-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "items": [
      {"content": "Uses the Downtown clinic", "source": "user_stated"},
      {"content": "Last service visit was August 5", "source": "third_party"}
    ]
  }'
200 response
{"memories": [{"id": "mem_..."}, {"id": "mem_..."}]}
POST/v1/forget

Delete one memory, clear one entity/attribute slot, or erase and verify an entire user partition. Project scope comes from the server key.

Project + user scoped Hard deletion Partition verification

Choose exactly one mode

memory_id
Delete one memory. Missing or foreign IDs return 404.
entity + attribute
Clear the current stable slot
erase_partition=true
Delete raw, archived, and derived memories, then verify no residue
confirmation
Must exactly match user_id for partition erasure
Idempotency-Key
Required for partition erasure
Delete one memory
curl -X POST "$CONTEXTDB_BASE_URL/v1/forget" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: forget-memory-42-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "memory_id": "mem_42"
  }'
Whole-partition request
curl -X POST "$CONTEXTDB_BASE_URL/v1/forget" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: erase-customer-123-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "erase_partition": true,
    "confirmation": "customer-123"
  }'
200 response
{
  "mode": "partition",
  "deleted": 12,
  "verified": true,
  "request_id": "..."
}
POST/v1/extract_memories

Extract quote-backed memories from structured call or chat turns. propose returns candidates only. commit writes validated candidates through the scoped deduplication path.

Project key + formation entitlement PII before provider Named terminal result

Important fields

turns[]required
1-100 structured turns
speakerrequired
user, agent, or third_party
mode
propose (default) or commit
Idempotency-Key
Recommended header for commit. Ignored for propose.
source_id
Opaque call, chat, or interaction ID
max_memories
1-20, default 10
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/extract_memories" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "mode": "propose",
    "source_id": "call-456",
    "turns": [
      {"speaker": "user", "content": "I prefer Saturday mornings."},
      {"speaker": "agent", "content": "I will keep that in mind."}
    ]
  }'
Terminal response
{
  "run_id": "form_...",
  "status": "completed",
  "mode": "propose",
  "attempts": 1,
  "candidates": [{
    "content": "Customer prefers Saturday mornings",
    "quote": "I prefer Saturday mornings",
    "turn_indexes": [0],
    "source": "user_stated",
    "confidence": 0.95,
    "action_relevant": true
  }],
  "memories": [],
  "error_code": null,
  "request_id": "..."
}
Provider, timeout, queue, and storage failures also return this shape with a named status, even when the HTTP status is non-2xx.

Asynchronous Formation · Hosted Alpha

Turn completed conversations into governed memory off the realtime path.

POST/v1/formation/jobs

Durably enqueue bounded structured turns. The gateway returns 202 immediately. A PostgreSQL-backed worker performs provider calls, extractive gates, retries, optional commit, and terminal persistence.

Formation entitlement Idempotency-Key required Structured text only
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/formation/jobs" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: call-456-formation-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "mode": "propose",
    "source_id": "call-456",
    "max_memories": 5,
    "deadline_seconds": 25,
    "turns": [
      {"speaker": "user", "content": "I prefer Saturday mornings."},
      {"speaker": "agent", "content": "I will keep that in mind."}
    ]
  }'
202 response
{
  "job_id": "frm_...",
  "status": "queued",
  "request_id": "..."
}
Reusing the same idempotency key with the same request returns the existing job. Reusing it with different turns or options fails closed.
GET/v1/formation/jobs/{job_id}

Poll one project-scoped job. Non-terminal states are queued, running, and retry_wait. Terminal states are succeeded and failed.

Content-free poll request Closed terminal reasons Attempts and known cost
curl "$CONTEXTDB_BASE_URL/v1/formation/jobs/frm_..." \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY"
Terminal response excerpt
{
  "job_id": "frm_...",
  "status": "succeeded",
  "mode": "propose",
  "terminal_reason": "completed",
  "provider_attempts": 1,
  "accepted_count": 1,
  "rejected_count": 0,
  "result": {
    "candidates": [{
      "content": "Customer prefers Saturday mornings",
      "source": "user_stated",
      "confidence": 0.95,
      "action_relevant": true,
      "accepted": true
    }],
    "memory_ids": []
  }
}
Formation is Hosted Alpha. There is no audio upload, cancellation, job listing, retention API, availability commitment, or public SLO.

Memory CI · Hosted Alpha

Run a pinned memory suite from CI.

These four operations use a project-bound cbe_ evaluation token, not a cdb_ memory key. The token is accepted only under /evals/v1 and cannot call memory routes or Testbench case CRUD.

Read the strict OpenAPI contract or its public source.

POST /evals/v1/projects/{project_id}/suites/{suite_id}/runs

Enqueue one immutable suite snapshot. The response is safe status and returns 202.

Evaluation token Idempotency-Key required 202 accepted

Baseline behavior

{}
Use the suite's pinned passing baseline
baseline_run_id
Select one passing run of this suite
null
Run without a baseline
Idempotency-Key
Same request returns the same run. Conflicting reuse returns 409.
cURL
curl -X POST \
  "$CONTEXTDB_BASE_URL/evals/v1/projects/$CONTEXTDB_PROJECT_ID/suites/$CONTEXTDB_EVAL_SUITE_ID/runs" \
  -H "Authorization: Bearer $CONTEXTDB_EVAL_TOKEN" \
  -H "Idempotency-Key: release-build-0001" \
  -H "Content-Type: application/json" \
  -d '{}'
202 safe status response
{
  "suite_run": {
    "id": "run_1",
    "suite_id": "suite_1",
    "baseline_run_id": "run_0",
    "project_id": "project_1",
    "status": "queued",
    "regression_status": "no_baseline",
    "counts": {
      "total": 4,
      "queued": 4,
      "running": 0,
      "passed": 0,
      "failed": 0,
      "error": 0,
      "cancelled": 0
    },
    "progress": {"completed": 0, "total": 4},
    "terminal_reason": null,
    "limits": {
      "max_cases": 50,
      "max_concurrency": 4,
      "wall_clock_seconds": 60,
      "case_timeout_seconds": 15,
      "max_case_result_bytes": 32768,
      "max_result_bytes": 2097152
    },
    "created_at": "2026-08-23T00:00:00Z",
    "started_at": null,
    "completed_at": null,
    "available_at": "2026-08-23T00:00:00Z",
    "deadline_at": "2026-08-23T00:05:00Z"
  }
}
GET /evals/v1/projects/{project_id}/runs/{run_id}

Poll aggregate status. Active states are queued, running, retry_wait, and cancelling. Terminal states are passed, failed, error, and cancelled. Regression state is no_baseline, unchanged, or regressed.

Content-free status Closed enums No case details
cURL
curl \
  "$CONTEXTDB_BASE_URL/evals/v1/projects/$CONTEXTDB_PROJECT_ID/runs/$CONTEXTDB_EVAL_RUN_ID" \
  -H "Authorization: Bearer $CONTEXTDB_EVAL_TOKEN"
Safe status has exactly these fields: id, suite_id, baseline_run_id, project_id, status, regression_status, counts, progress, terminal_reason, limits, created_at, started_at, completed_at, available_at, and deadline_at.
POST /evals/v1/projects/{project_id}/runs/{run_id}/cancel

Request cooperative cancellation. A queued run can become cancelled before dispatch. Active work can remain cancelling until it reaches a safe stopping point.

202 accepted Cooperative cancellation Safe status response
cURL
curl -X POST \
  "$CONTEXTDB_BASE_URL/evals/v1/projects/$CONTEXTDB_PROJECT_ID/runs/$CONTEXTDB_EVAL_RUN_ID/cancel" \
  -H "Authorization: Bearer $CONTEXTDB_EVAL_TOKEN"
GET /evals/v1/projects/{project_id}/runs/{run_id}/export/{format}

Export a terminal run as json or junit. Exports contain opaque IDs, hashes, statuses, bounded failure codes, counts, attempts, latency, and outcomes.

Terminal runs only JSON or JUnit Content-free
cURL
curl \
  "$CONTEXTDB_BASE_URL/evals/v1/projects/$CONTEXTDB_PROJECT_ID/runs/$CONTEXTDB_EVAL_RUN_ID/export/json" \
  -H "Authorization: Bearer $CONTEXTDB_EVAL_TOKEN" \
  -o memory-ci.json
Exports omit suite names, case names, queries, assertions, raw failures, and memory content.

Public CLI and reusable Action

Install the exact package or pin the Action release.

The Apache-2.0 contextdb-memory-ci==0.1.0a1 package was published through PyPI trusted publishing with attestations. The exact registry artifact passed a fresh isolated install, import, version, and --help check. The reusable Action is public in the memory-ci-action-v0.1.0 prerelease.

Install from PyPI

shell
pip install contextdb-memory-ci==0.1.0a1

Keep CONTEXTDB_EVAL_TOKEN in CI secret storage. Read the CLI source and usage.

Use the pinned GitHub Action

workflow step
- name: Run ContextDB Memory CI
  uses: atomsai/contextdb-clients@memory-ci-action-v0.1.0
  with:
    token: ${{ secrets.CONTEXTDB_EVAL_TOKEN }}
    project-id: ${{ vars.CONTEXTDB_PROJECT_ID }}
    suite-id: ${{ vars.CONTEXTDB_EVAL_SUITE_ID }}

The Action installs exactly contextdb-memory-ci==0.1.0a1. Store the cbe_ token in GitHub Secrets. Project and suite IDs can use GitHub Variables.

ExitMeaning
0Passed and unchanged, or a no-baseline pass only when explicitly allowed
1Failed behavior or a regression
2Operational error, cancellation, timeout, malformed response, output failure, or no baseline by default

Omit the baseline input to use the suite's pinned passing baseline. JSON and JUnit artifacts are content-free: no suite or case names, queries, assertions, raw failures, credentials, or memory content. The public strict contract defines the accepted status and export fields.

The hosted service uses one dedicated single-instance Evals process beside the Console API on the same VM. Leases, attempts, deadlines, and bounded recovery are covered by real-PostgreSQL CI. This is process isolation on one VM, not a worker fleet, HA, or failover. There is no scheduling, availability SLA, or crash-resume availability claim. Action shell and metadata tests do not establish an Action run inside GitHub against production.

POST/v1/recall

Retrieve relevant memory for conversational grounding.

Project keyMaximum top_k 50
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/recall" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "query": "What should I know before this call?",
    "top_k": 5
  }'
Require a write token
{
  "user_id": "customer-123",
  "query": "What should I know before this call?",
  "min_memory_version": 42,
  "min_primary_wal_lsn": "1A/2B",
  "read_consistency": "primary"
}
200 response
{"context": "- Prefers Saturday mornings", "memories": [{"id": "mem_..."}]}

Actions

Evaluate evidence before the tool runs

POST/v1/recall_for_action

Record a durable evidence evaluation for a proposed action and return what the policy says: act, ask, or abstain. Use the returned decision_id when the host reports what happened. In the Python client this operation is evaluate_action. The HTTP route and MCP tool are both named recall_for_action.

Project keyDecision recorded
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/recall_for_action" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "query": "Book the Saturday service appointment",
    "top_k": 5
  }'
200 response
{
  "decision_id": "54a81b8e-52bb-4e57-b4ac-ab78657e89d1",
  "outcome": "ask",
  "memories": [],
  "pending_confirmation_ids": ["mem_pending"]
}
GET POST /v1/pending_confirmations

List action-relevant memories waiting for an explicit yes.

Project keyGET query or POST JSON
GET
curl "$CONTEXTDB_BASE_URL/v1/pending_confirmations?user_id=customer-123" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY"
200 response
{"memories": [{"id": "mem_pending", "content": "Saturday might work", "requires_confirmation": true}]}
POST/v1/confirm

Confirm one exact pending memory after the customer host authenticates and retains any end-user attestation. API and MCP authenticate the project credential, not the end user. The confirmation record binds that caller and project context to the scoped memory. It does not prove objective truth. Re-evaluate the action after confirming.

Project keyScoped memory ID
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/confirm" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: confirm-mem-pending-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "memory_id": "mem_pending"
  }'
200 response
{"memory": {"id": "mem_pending", "confirmed": true, "requires_confirmation": false}}
POST/v1/receipts

Close the loop after the host executes, fails, or skips an action. ContextDB stores the host report. It does not inspect the downstream system. Executing after ask or abstain is retained as a policy violation.

Project + user scoped Idempotency-Key required Structured metadata only
cURL
curl -X POST "$CONTEXTDB_BASE_URL/v1/receipts" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Idempotency-Key: receipt-54a81b8e-v1" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "customer-123",
    "decision_id": "54a81b8e-52bb-4e57-b4ac-ab78657e89d1",
    "action_name": "appointment.book",
    "status": "succeeded",
    "external_ref": "appt-8842"
  }'
200 response
{
  "decision_id": "54a81b8e-52bb-4e57-b4ac-ab78657e89d1",
  "outcome": "act",
  "receipt": {
    "id": "7ea64cc8-b53e-47e8-819a-84baf550888a",
    "action_name": "appointment.book",
    "status": "succeeded",
    "policy_alignment": "aligned",
    "external_ref": "appt-8842"
  }
}

Protocol

Model Context Protocol

POST/mcp

Stateless JSON-RPC endpoint exposing remember, recall, recall_for_action, pending confirmations, confirm, and scoped forget as MCP tools. Whole-partition erasure stays on HTTP and the console.

Project keyJSON-RPC 2.0
tools/list
curl -X POST "$CONTEXTDB_BASE_URL/mcp" \
  -H "Authorization: Bearer $CONTEXTDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

Read the MCP integration guide →

Runnable examples

Start from a working agent.

  • PyAI Omni

    Voice · TypeScript

    Realtime voice with host-gated tools.

    Open repository
  • LiveKit Agents

    Voice · Python

    The example runs appointment tools and Formation when the session ends.

    Open repository
  • Pipecat

    Voice · Python

    Daily pipeline and fail-closed handlers.

    Open repository
  • Web chat

    Chat · TypeScript

    Server-only ContextDB credentials and memory calls.

    Open repository

Related control-plane features

Webhooks and the operator console

Register signed decision webhooks and manage keys, approvals, members, and projects in ContextDB Cloud. Webhook payloads carry decisions, structured execution receipts, and memory IDs, never memory content.

See how decisions and approvals work →