Integration Guide

End-to-end walkthrough: create an application, namespace, agent, permissions, and an API key — then store and search memories from your backend.

API keys are server-side credentials.

A ContextVault API key (cv_live_...) grants full machine access to your agent's permitted namespaces. It is shown only once at creation and cannot be recovered. Store it in a secrets manager and call ContextVault exclusively from your backend — never embed it in browser, mobile, or client-side code.

1Create an application

Sign in to the dashboard and create an application (or use the API). Each application is an isolated tenant boundary for namespaces, agents, and memories.

POST /v1/apps
curl -X POST https://contextvault-ahlx.onrender.com/v1/apps \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -b cookies.txt \
  -d '{"name": "Support Copilot", "slug": "support-copilot"}'

# 201 Created
{
  "id": "9f1c...",
  "user_id": "...",
  "name": "Support Copilot",
  "slug": "support-copilot",
  "created_at": "2026-12-05T00:00:00Z",
  "updated_at": "2026-12-05T00:00:00Z"
}

2Create a namespace

Namespaces are logical memory partitions inside an application. Create one per domain (e.g. support-knowledge, user-preferences).

POST /v1/apps/{application_id}/namespaces
curl -X POST https://contextvault-ahlx.onrender.com/v1/apps/9f1c.../namespaces \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -b cookies.txt \
  -d '{"name": "Support Knowledge", "slug": "support-knowledge"}'

# 201 Created
{
  "id": "4a2b...",
  "application_id": "9f1c...",
  "name": "Support Knowledge",
  "slug": "support-knowledge",
  "description": null,
  "created_at": "2026-12-05T00:00:00Z",
  "updated_at": "2026-12-05T00:00:00Z"
}

3Create an agent

Agents are machine identities that authenticate with API keys. Create one per workload (e.g. a support bot worker).

POST /v1/apps/{application_id}/agents
curl -X POST https://contextvault-ahlx.onrender.com/v1/apps/9f1c.../agents \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -b cookies.txt \
  -d '{"name": "support-worker", "description": "Handles support chat memory"}'

# 201 Created
{
  "id": "7d3e...",
  "application_id": "9f1c...",
  "name": "support-worker",
  "description": "Handles support chat memory",
  "is_active": true,
  "created_at": "2026-12-05T00:00:00Z",
  "updated_at": "2026-12-05T00:00:00Z"
}

4Grant namespace permissions

Permissions are explicit and least-privilege: an agent gets can_read, can_write, and can_delete per namespace. Nothing is granted automatically — unassigned namespaces are denied.

PUT /v1/agents/{agent_id}/namespaces/{namespace_id}/permissions
curl -X PUT https://contextvault-ahlx.onrender.com/v1/agents/7d3e.../namespaces/4a2b.../permissions \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -b cookies.txt \
  -d '{"can_read": true, "can_write": true, "can_delete": false}'

# 200 OK — permission record with namespace_name / namespace_slug

5Issue an API key

Issue a key for the agent. The raw key is returned exactly once — copy it into your secrets manager immediately. Only a prefix and an HMAC-SHA256 hash are stored server-side.

POST /v1/agents/{agent_id}/keys
curl -X POST https://contextvault-ahlx.onrender.com/v1/agents/7d3e.../keys \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -b cookies.txt \
  -d '{"name": "production", "expires_at": "2027-01-01T00:00:00Z"}'

# 201 Created — api_key shown ONCE
{
  "id": "...",
  "key_prefix": "cv_live_a1b2",
  "api_key": "cv_live_a1b2_9f8e7d6c5b4a...",
  "last_used_at": null,
  "expires_at": "2027-01-01T00:00:00Z",
  "revoked_at": null,
  "created_at": "2026-12-05T00:00:00Z"
}

Revoke a key any time with DELETE /v1/keys/{key_id}. Revoked and expired keys fail authentication immediately.

6Configure an HTTP client

All data-plane endpoints authenticate with Authorization: Bearer cv_live_.... No cookies or CSRF are involved — this is a machine API.

Request headers
Authorization: Bearer cv_live_a1b2_9f8e7d6c5b4a...
Content-Type: application/json
# Optional: Idempotency-Key on POST /v1/memories for safe retries

Machine endpoints live under /v1: GET /v1/agents/me introspects the agent and its permissions; memory endpoints are listed below.

7Create a memory

POST /v1/memories → 201 Created
curl -X POST https://contextvault-ahlx.onrender.com/v1/memories \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "namespace_id": "4a2b...",
    "subject_id": "user_123",
    "content": "User prefers concise email summaries.",
    "metadata": {"source": "onboarding"},
    "tags": ["preference"],
    "importance_score": 0.7,
    "expires_at": "2027-06-01T00:00:00Z"
  }'

{
  "id": "c0ffee...",
  "application_id": "9f1c...",
  "namespace_id": "4a2b...",
  "created_by_agent_id": "7d3e...",
  "subject_id": "user_123",
  "content": "User prefers concise email summaries.",
  "metadata": {"source": "onboarding"},
  "tags": ["preference"],
  "importance_score": 0.7,
  "version": 1,
  "expires_at": "2027-06-01T00:00:00Z",
  "created_at": "2026-12-05T00:00:00Z",
  "updated_at": "2026-12-05T00:00:00Z"
}

Embeddings are generated synchronously — the response only returns after the vector is stored. Idempotency-Key makes retries safe: same key + same payload replays the original response (X-Idempotency-Replayed: true); same key + different payload returns 409.

8Search memories

POST /v1/memories/search runs hybrid retrieval — pgvector cosine similarity + PostgreSQL full-text search — fused with Reciprocal Rank Fusion. Only namespaces with explicit can_read permission are searched.

POST /v1/memories/search → 200 OK
curl -X POST https://contextvault-ahlx.onrender.com/v1/memories/search \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "email preferences",
    "namespace_id": "4a2b...",
    "subject_id": "user_123",
    "tags": ["preference"],
    "limit": 10,
    "offset": 0
  }'

{
  "query": "email preferences",
  "items": [
    {
      "memory_id": "c0ffee...",
      "namespace_id": "4a2b...",
      "subject_id": "user_123",
      "content": "User prefers concise email summaries.",
      "metadata": {},
      "tags": ["preference"],
      "importance_score": 0.7,
      "created_at": "2026-12-05T00:00:00Z",
      "updated_at": "2026-12-05T00:00:00Z",
      "expires_at": "2027-06-01T00:00:00Z",
      "relevance_score": 0.0328
    }
  ],
  "total": 1,
  "limit": 10,
  "offset": 0,
  "has_more": false
}

Filters: namespace_id, subject_id, tags, created_after, created_before, expires_before. Omit namespace_id to search every readable namespace.

9Update and delete memories

PATCH /v1/memories/{memory_id}
curl -X PATCH https://contextvault-ahlx.onrender.com/v1/memories/c0ffee... \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "User prefers bullet-point email summaries.",
    "expected_version": 1
  }'

# 200 OK — version increments to 2; the embedding is regenerated
# only when content changes.

curl -X DELETE https://contextvault-ahlx.onrender.com/v1/memories/c0ffee... \
  -H "Authorization: Bearer $API_KEY"

# 204 No Content — hard delete; embeddings cascade.

expected_version enables optimistic locking — a stale version returns 409. Use GET /v1/memories to list memories with filters (namespace_id, subject_id, tags, created_after/before, expires_before, limit, offset).

10Handle errors and rate limits

Error & rate-limit reference
401 Unauthorized
  Invalid, expired, or revoked API key — or inactive agent.
  {"detail": "Invalid API key"}  +  WWW-Authenticate: Bearer

403 Forbidden
  Valid key but insufficient namespace permission
  (missing can_read / can_write / can_delete).

404 Not Found
  Memory, namespace, or agent does not exist inside your
  application — cross-tenant ids look identical to missing ones.

409 Conflict
  Idempotency-Key reused with a different payload, an
  in-flight duplicate request, or an expected_version mismatch.

422 Unprocessable Content
  Validation failure (blank content, bad slug, naive datetime,
  oversized payload, etc.).

429 Too Many Requests
  Per-agent fixed-window rate limit exceeded.
  Retry-After: <seconds>
  X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset

503 Service Unavailable
  Embedding provider unavailable or search storage error — retry
  with backoff.

Rate limits are fixed 60-second windows per agent (default 60 req/min, configurable). Honor Retry-After and exponential backoff for 5xx responses. Monitor your usage on the Activity page.

Minimal integrations

Both examples read credentials from environment variables — never hard-code keys.

Python (httpx)
"""Minimal ContextVault integration (Python 3.10+).

API keys are SERVER-SIDE credentials. Never ship them to browser or
mobile client code — call ContextVault from your backend only.
"""
import os
import uuid

import httpx

BASE_URL = os.environ["CONTEXTVAULT_BASE_URL"]      # e.g. https://api.example.com
API_KEY = os.environ["CONTEXTVAULT_API_KEY"]        # cv_live_... issued once

client = httpx.Client(
    base_url=BASE_URL,
    headers={"Authorization": f"Bearer {API_KEY}"},
    timeout=30.0,
)

# 1. Create a memory (namespace_id comes from your app setup).
namespace_id = os.environ["CONTEXTVAULT_NAMESPACE_ID"]
memory = client.post(
    "/v1/memories",
    headers={"Idempotency-Key": str(uuid.uuid4())},
    json={
        "namespace_id": namespace_id,
        "subject_id": "user_123",
        "content": "User prefers concise email summaries.",
        "tags": ["preference"],
        "metadata": {"source": "onboarding"},
    },
).json()
print("created:", memory["id"])

# 2. Hybrid search (pgvector + full-text, fused with RRF).
results = client.post(
    "/v1/memories/search",
    json={"query": "email preferences", "limit": 5},
).json()
for item in results["items"]:
    print(item["memory_id"], item["relevance_score"], item["content"][:80])

# 3. Update (optimistic locking via expected_version).
client.patch(
    f"/v1/memories/{memory['id']}",
    json={"content": "User prefers bullet-point email summaries.",
          "expected_version": memory["version"]},
)

# 4. Delete.
client.delete(f"/v1/memories/{memory['id']}")
TypeScript (Node fetch)
/**
 * Minimal ContextVault integration (TypeScript / Node 18+).
 *
 * API keys are SERVER-SIDE credentials. Never expose them in
 * browser or client-side code — call ContextVault from your backend.
 */

const BASE_URL = process.env.CONTEXTVAULT_BASE_URL!;
const API_KEY = process.env.CONTEXTVAULT_API_KEY!; // cv_live_... shown once

async function cvFetch(path: string, init?: RequestInit) {
  const res = await fetch(`${BASE_URL}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${API_KEY}`,
      ...(init?.headers ?? {}),
    },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => null);
    throw new Error(`ContextVault ${res.status}: ${body?.detail ?? res.statusText}`);
  }
  return res.status === 204 ? null : res.json();
}

// Create a memory.
const memory = await cvFetch("/v1/memories", {
  method: "POST",
  headers: { "Idempotency-Key": crypto.randomUUID() },
  body: JSON.stringify({
    namespace_id: process.env.CONTEXTVAULT_NAMESPACE_ID,
    subject_id: "user_123",
    content: "User prefers concise email summaries.",
    tags: ["preference"],
  }),
});

// Hybrid search.
const results = await cvFetch("/v1/memories/search", {
  method: "POST",
  body: JSON.stringify({ query: "email preferences", limit: 5 }),
});

// Update + delete.
await cvFetch(`/v1/memories/${memory.id}`, {
  method: "PATCH",
  body: JSON.stringify({ content: "Updated summary preference." }),
});
await cvFetch(`/v1/memories/${memory.id}`, { method: "DELETE" });

Machine auth details, session/CSRF model, and endpoint reference: docs/api.md in the repository.