API Reference

Context API Reference.

Complete reference for the Keel Context API. REST-based, JSON responses, under 200ms P95 latency.

Base URL

https://<instance>/api

Auth

Bearer token

Format

JSON

P95 latency

<200ms

DevelopersREST API Reference

Getting started

This guide is for developers integrating your own platform with Keel using an organization API key — no user login, no session. Just a key an org_admin generates for you in Settings → API Keys.

Base URL

text
https://<your-keel-instance>/api

Every path below is relative to /api. There is no version prefix today — this is the current, single, unversioned surface.

Workspace scoping

Your key may reach several workspaces. You must always name which workspace(s) each request targets — there is no default.

Endpoint groupFieldShape
Retrieval: /search, /context, /chatworkspacesarray of { workspace, document_ids? } objects, max 50
Ingestion: /ingest/*workspacesingular string — slug or UUID of the target workspace

Warning

If your key's allowed_workspace_ids pin has no active, REST-enabled workspaces left, every request fails with 403 NO_REACHABLE_WORKSPACE before any request validation runs.

Authentication

Every request needs two headers:

HeaderValueNotes
AuthorizationBearer &lt;your-api-key&gt;The raw key shown once at creation. Lost it? An org_admin must revoke and reissue — it cannot be retrieved.
Originhttps://your-platform.comRequired on every request, even server-to-server. Must match an allow-listed hostname on your key.
curl
curl https://your-keel-instance/api/search \
  -H "Authorization: Bearer kls_live_abc123..." \
  -H "Origin: https://myapp.example.com" \
  -H "Content-Type: application/json" \
  -d '{"query": "leave policy", "workspaces": [{"workspace": "support-docs"}]}' 

Scopes

read_only

Can call every retrieval endpoint (search, context, chat, evidence, ingest status). Cannot ingest.

read_write

Everything read_only can, plus the ingest endpoints. Required for pushing content.

Rate limiting

Default: 100 requests/minute per key (configurable by your org_admin). On exceeding:

json
HTTP 429
Retry-After: 60

{
  "status": "fail",
  "error_code": "RATE_LIMIT_EXCEEDED",
  "message": "Rate limit of 100 requests/min exceeded.",
  "request_id": "..."
}

Back off for at least the Retry-After value (seconds) before retrying.

Responses & errors

Success shape

json
{
  "status": "success",
  "data": { ...},
  "message": "..."
}

Error shape

json
{
  "status": "fail",
  "error_code": "SOME_ERROR",
  "message": "...",
  "request_id": "UUID"
}

422 validation errors additionally include a detail array with per-field Pydantic error objects.

Error codes

HTTPerror_codeMeaning
401UNAUTHORIZEDNo Authorization header, or it's malformed.
401INVALID_API_KEYKey doesn't exist, or has been revoked.
401ORIGIN_REQUIREDMissing Origin header.
401ORIGIN_NOT_ALLOWEDOrigin hostname isn't in the key's allowed_hosts.
403FORBIDDENA read_only key called an ingest endpoint.
403ORG_BLOCKEDYour organization has been blocked.
403NO_REACHABLE_WORKSPACEKey's org has no active, REST-enabled workspace in its pin.
404NOT_FOUNDResource doesn't exist in any reachable workspace.
413FILE_TOO_LARGEUpload exceeds the 500 MB limit.
415INVALID_FILE_TYPEFile bytes don't match an allowed type.
422VALIDATION_ERRORRequest body failed schema validation — see detail.
422MISSING_PARTChunked upload: a part is missing in storage. Re-upload from part_index=0.
429RATE_LIMIT_EXCEEDEDToo many requests this minute.
500INTERNAL_ERRORSomething broke on our side — include request_id when reporting.

Retrieval endpoints

read_only or read_write
POST/context
read_onlyread_write

Same retrieval as /search, but returns one assembled text block ready to drop into your own LLM prompt, plus evidence chunks for citation.

Request body: identical to /search.

Response data

json
{
  "context": "Employees are entitled to 26 weeks...\n\n---\n\n...",
  "evidence": [{ /* same shape as /search results */ }],
  "truncated": false,
  "token_count": 1842
}

truncated: true means more relevant chunks existed than fit the context cap — reducing top_k won't help here, this is a fixed cap.

POST/chat
read_onlyread_write

Full RAG pipeline — embeds your question, retrieves chunks, adds graph context (up to 2 hops), answers with the LLM. One JSON response with the final answer.

Note

POST /chat/query (SSE streaming) is JWT-only today — not available to API-key callers. Use this non-streaming endpoint instead.

Request body

json
{
  "question": "How many days of parental leave do employees get?",
  "top_k": 10,
  "workspaces": [{ "workspace": "support-docs" }]
}

Response data

json
{
  "answer": "Employees are entitled to 26 weeks of paid parental leave...",
  "confidence": 0.79,
  "evidence": [{ /* same shape as /search results */ }],
  "conversation_id": null,
  "message_id": null
}

Note

No conversation memory for API-key callers. conversation_id/message_id are always null. Each call is answered fresh — include prior Q&A in question yourself if you need multi-turn context.

confidence is the mean cosine similarity of the top-3 retrieved chunks — a retrieval quality metric, not a trust score.

GET/evidence/{chunk_id}
read_onlyread_write

Fetch the complete text and metadata for a single chunk — use when the excerpt from /search, /context, or /chat isn't enough for citation.

Response data

json
{
  "chunk_id": "c3b0d1a2-...",
  "document_id": "d1f9e2b0-...",
  "document_name": "HR-Policy-2026.pdf",
  "chunk_text": "Full text of this chunk, not just the trimmed excerpt...",
  "chunk_index": 4,
  "section_ref": "Page 12, Section 4.2",
  "token_count": 487,
  "source_type": "manual_upload",
  "chunk_metadata": { "page_number": 12 }
}

404 NOT_FOUND if the chunk doesn't exist in any workspace your key can reach.

Ingestion endpoints

read_write only

All ingestion endpoints require a read_write key. Every one returns 202 Accepted immediately with a job_id — ingestion runs asynchronously.

Duplicate detection

All four push endpoints check for exact-content duplicates before queuing: Keel computes a SHA-256 hash of the raw content and looks for an existing completed document with the same hash in the same workspace. A duplicate call returns 202 normally but with status: "duplicate" — nothing is re-ingested. Deduplication is strictly per-workspace.

POST/ingest/file
read_write

Multipart upload. Recommended for files ≤10 MB — for larger files use the chunked endpoint below (up to the 500 MB hard limit either way).

Accepted types: PDF, DOCX, TXT, CSV, XLSX (required); PPTX, PNG, JPG (best-effort). Verified against actual file bytes, not just the extension.

curl
curl -X POST https://your-keel-instance/api/ingest/file \
  -H "Authorization: Bearer $KEEL_API_KEY" \
  -H "Origin: https://myapp.example.com" \
  -F "file=@./policy.pdf" \
  -F "workspace=support-docs"

Response (202)

json
{
  "documents": [{  /* large PDFs may be auto-split */
    "document_id": "d1f9e2b0-...",
    "job_id": "d1f9e2b0-...",
    "status": "queued",
    "name": "policy.pdf",
    "file_size": 481203,
    "created_at": "2026-07-13T10:15:00Z"
  }]
}
POST/ingest/file/part
read_write

Send the file as sequential 5 MB parts for files over 10 MB.

FieldTypeNotes
filebinaryRaw bytes of this part (≤5 MB)
part_indexinteger0-based; first call must be 0
total_partsintegerTotal number of parts you'll send
filenamestringOriginal filename (sent on every part)
document_idUUIDOmit on part_index=0 — response gives you one. Required on every subsequent part.
workspacestringRequired. Must be the exact same value on every part of one upload.

Warning

Send the same workspace on every part. If part 0 names one workspace and part 3 names another, part 3 is stored somewhere assembly will never look and the final part fails with 422 MISSING_PART. There's no partial recovery — re-upload from part_index=0.

javascript
const CHUNK_SIZE = 5 * 1024 * 1024;
let documentId;

for (let i = 0; i < totalParts; i++) {
  const form = new FormData();
  form.append("file", fileBlob.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE));
  form.append("part_index", i);
  form.append("total_parts", totalParts);
  form.append("filename", "large-report.pdf");
  if (documentId) form.append("document_id", documentId);
  form.append("workspace", "support-docs");

  const res = await fetch("https://your-keel-instance/api/ingest/file/part", {
    method: "POST",
    headers: { "Authorization": `Bearer ${apiKey}`, "Origin": "https://myapp.example.com" },
    body: form,
  });
  const { data } = await res.json();
  documentId ??= data.document_id ?? data.documents?.[0]?.document_id;
}
POST/ingest/text
read_write

Push plain text directly — from a CMS, scraped page, or support ticket body. No file involved.

json
{
  "title": "Q3 Support Ticket #4821",
  "text": "Customer reported an issue with...",
  "tags": ["support", "q3-2026"],
  "metadata": { "ticket_id": "4821" },
  "workspace": "support-docs"
}
FieldTypeConstraints
titlestring1–512 chars, required
textstring1–2,000,000 chars, required
tagsstring[]optional, ≤20
metadataobjectoptional, arbitrary JSON
workspacestringworkspace slug or UUID — required for an API key

Response: a single IngestStatusResponse object (text pushes are never auto-split).

POST/ingest/record
read_write

Push a structured JSON record — CRM records, ticket objects, log entries — serialized to text and run through the same pipeline.

json
{
  "title": "CRM Record — Acme Corp",
  "fields": {
    "account_name": "Acme Corp",
    "arr": 120000,
    "renewal_date": "2027-01-15"
  },
  "tags": ["crm"],
  "workspace": "support-docs"
}

fields is required and must be non-empty. Response: a single IngestStatusResponse object.

GET/ingest/status/{job_id}
read_onlyread_write
json
{
  "document_id": "d1f9e2b0-...",
  "job_id": "d1f9e2b0-...",
  "status": "completed",
  "name": "policy.pdf",
  "source_type": "manual_upload",
  "file_size": 481203,
  "created_at": "2026-07-13T10:15:00Z",
  "error_message": null
}
queued→processing→parsing→tagging→chunking→embedding→entity_extraction→graph_mapping→finalizing→completed/failed/duplicate

Tip

Suggested polling interval: every 2–5 s for small documents; every 10–15 s for large files. Don't poll faster than once per second.

Webhooks

Register a webhook so Keel notifies your backend directly when ingestion reaches a terminal state (completed or failed) — instead of polling GET /ingest/status.

Registering an endpoint

Registration is org_admin-only. An org_admin signs in to get a session JWT, then calls POST /api/webhooks with that token — a one-time setup step, not something your API key does.

curl
curl -X POST https://your-keel-instance/api/webhooks \
  -H "Authorization: Bearer <org_admin JWT access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My platform ingestion notifier",
    "url": "https://myapp.example.com/webhooks/keel",
    "event_types": ["ingestion.completed", "ingestion.failed"],
    "allowed_workspace_ids": []
  }'

Warning

Store the secret immediately. Keel keeps only an encrypted copy and cannot show the raw value again. If you lose it, revoke the endpoint (DELETE /api/webhooks/{id}) and register a new one.

Webhook payloads

ingestion.completed

json
{
  "event": "ingestion.completed",
  "document_id": "d1f9e2b0-...",
  "workspace_id": "a7e6c1d4-...",
  "status": "completed",
  "name": "policy.pdf",
  "chunk_count": 42
}

ingestion.failed

json
{
  "event": "ingestion.failed",
  "document_id": "d1f9e2b0-...",
  "workspace_id": "a7e6c1d4-...",
  "status": "failed",
  "error_type": "ParseError",
  "step_failed": "parsing"
}

Note

There is no ingestion.duplicate event — duplicates are decided synchronously at upload time and never enter the async pipeline.

Verifying the signature

Recompute HMAC-SHA256 over {timestamp}.{raw_body} using your stored secret. Always compare against raw request bytes before JSON parsing, using constant-time comparison.

javascript
import crypto from "node:crypto";

function verifyKeelWebhook(rawBody, signatureHeader, timestampHeader, secret) {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${timestampHeader}.`)
    .update(rawBody)
    .digest("hex");
  const provided = signatureHeader.replace(/^sha256=/, "");
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(provided));
}

Retries & endpoint health

1st retry

30s

2nd retry

60s

3rd retry

120s

4th retry

240s

Your endpoint must return a 2xx within 5 seconds. After 5 attempts the delivery is marked failed_permanently. After 10 consecutive fully-exhausted deliveries, Keel sets the endpoint is_active: false. Re-enable with PATCH /api/webhooks/{id} {"is_active": true}.

Limitations today

GETGET /documents

JWT-only — does not accept an API key (401). Document list/inventory via key is a known gap being tracked.

POSTPOST /chat/query

SSE streaming — JWT-only. Use non-streaming POST /chat instead.

POSTPOST /api/webhooks

Webhook registration is org_admin-only and not yet in the Keel UI. Requires a direct admin JWT call.

Full example

Push a document, wait for ingestion to finish, then ask a question about it:

javascriptingest-then-query.js
const BASE = "https://your-keel-instance/api";
const HEADERS = {
  "Authorization": `Bearer ${process.env.KEEL_API_KEY}`,
  "Origin": "https://myapp.example.com",
  "Content-Type": "application/json",
};
const WORKSPACE = "support-docs";

// 1. Push a document
const ingestRes = await fetch(`${BASE}/ingest/text`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({
    title: "Refund Policy",
    text: "Refunds are processed within 14 days...",
    workspace: WORKSPACE,
  }),
});
const { data: { job_id } } = await ingestRes.json();

// 2. Poll until done (or "duplicate")
let status = "queued";
while (status !== "completed" && status !== "failed" && status !== "duplicate") {
  await new Promise((r) => setTimeout(r, 3000));
  const statusRes = await fetch(`${BASE}/ingest/status/${job_id}`, { headers: HEADERS });
  ({ data: { status } } = await statusRes.json());
}
if (status === "failed") throw new Error("Ingestion failed");

// 3. Ask about it
const chatRes = await fetch(`${BASE}/chat`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({ question: "How long do refunds take?", workspaces: [{ workspace: WORKSPACE }] }),
});
const { data } = await chatRes.json();
console.log(data.answer, data.confidence, data.evidence);

MCP server

Keel also exposes an MCP server — Claude Desktop, Claude Code, and claude.ai can connect directly to your Keel workspace over the Model Context Protocol (Streamable HTTP transport).

Connecting

Ask whoever runs your Keel deployment for the MCP server URL (path /mcp) and a bearer token. Authentication is two layers: your MCP bearer token gates the transport itself; internally, the MCP server uses a shared organization read_write API key to call Keel's REST API.

Available tools

ToolMaps toNotes
keel_searchPOST /searchRaw chunk hits — use when you want evidence, not a synthesized answer.
keel_askPOST /chatSynthesized answer + confidence + evidence. Stateless — no conversation memory.
keel_get_evidenceGET /evidence/{chunk_id}Full chunk text/metadata for a citation.
keel_ingest_textPOST /ingest/textPush plain text for ingestion.
keel_ingest_recordPOST /ingest/recordPush a structured JSON record.
keel_ingest_filePOST /ingest/file (+ chunked)File bytes passed base64-encoded; uploads over 10 MB chunked transparently server-side.
keel_check_ingest_statusGET /ingest/status/{job_id}Poll any keel_ingest_* tool's returned job_id.

Every keel_ingest_* tool still requires an explicit workspace argument, validated against the shared key's reach exactly like the REST endpoints.

Getting help

Include the request_id from any error response when reporting an issue — it's the fastest way for us to find the exact request in our logs.