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
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
https://<your-keel-instance>/apiEvery 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 group | Field | Shape |
|---|---|---|
| Retrieval: /search, /context, /chat | workspaces | array of { workspace, document_ids? } objects, max 50 |
| Ingestion: /ingest/* | workspace | singular 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:
| Header | Value | Notes |
|---|---|---|
Authorization | Bearer <your-api-key> | The raw key shown once at creation. Lost it? An org_admin must revoke and reissue — it cannot be retrieved. |
Origin | https://your-platform.com | Required on every request, even server-to-server. Must match an allow-listed hostname on your key. |
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_onlyCan call every retrieval endpoint (search, context, chat, evidence, ingest status). Cannot ingest.
read_writeEverything 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:
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
{ "status": "success", "data": { ...}, "message": "..." }
Error shape
{ "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
| HTTP | error_code | Meaning |
|---|---|---|
| 401 | UNAUTHORIZED | No Authorization header, or it's malformed. |
| 401 | INVALID_API_KEY | Key doesn't exist, or has been revoked. |
| 401 | ORIGIN_REQUIRED | Missing Origin header. |
| 401 | ORIGIN_NOT_ALLOWED | Origin hostname isn't in the key's allowed_hosts. |
| 403 | FORBIDDEN | A read_only key called an ingest endpoint. |
| 403 | ORG_BLOCKED | Your organization has been blocked. |
| 403 | NO_REACHABLE_WORKSPACE | Key's org has no active, REST-enabled workspace in its pin. |
| 404 | NOT_FOUND | Resource doesn't exist in any reachable workspace. |
| 413 | FILE_TOO_LARGE | Upload exceeds the 500 MB limit. |
| 415 | INVALID_FILE_TYPE | File bytes don't match an allowed type. |
| 422 | VALIDATION_ERROR | Request body failed schema validation — see detail. |
| 422 | MISSING_PART | Chunked upload: a part is missing in storage. Re-upload from part_index=0. |
| 429 | RATE_LIMIT_EXCEEDED | Too many requests this minute. |
| 500 | INTERNAL_ERROR | Something broke on our side — include request_id when reporting. |
Retrieval endpoints
read_only or read_write/searchReturns raw matching chunks ranked by similarity. Use this to build your own answer/UI on top of the raw matches.
Request body
{ "query": "What is the parental leave policy?", "top_k": 10, "min_similarity": 0.65, "workspaces": [ { "workspace": "support-docs" }, { "workspace": "hr-policies", "document_ids": ["d1f9e2b0-..."] } ] }
| Field | Type | Default | Constraints |
|---|---|---|---|
query | string | — required | 1–4000 chars |
top_k | integer | 10 | 1–25 |
min_similarity | float | 0.65 | 0.0–1.0 |
workspaces | array of {workspace, document_ids?} | — required | ≤50 entries; document_ids per entry ≤200 UUIDs |
Warning
Breaking change: workspaces used to be a flat array of strings. It's now an array of objects with per-entry document_ids. The old flat-array shape is no longer accepted.
Response data
{ "results": [ { "chunk_id": "c3b0d1a2-...", "document_id": "d1f9e2b0-...", "workspace_id": "a7e6c1d4-...", "document_name": "HR-Policy-2026.pdf", "section_ref": "Page 12, Section 4.2", "excerpt": "Employees are entitled to 26 weeks...", "similarity": 0.83, "source": "vector", "matched_entity": null, "hop_count": null } ], "total": 1 }
source: "graph" means the chunk was surfaced via graph expansion — matched_entity and hop_count (1 or 2) explain the path. Normal similarity hits have source: "vector" and both fields null.
/contextSame 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
{ "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.
/chatFull 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
{ "question": "How many days of parental leave do employees get?", "top_k": 10, "workspaces": [{ "workspace": "support-docs" }] }
Response data
{ "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.
/evidence/{chunk_id}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
{ "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 onlyAll 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.
/ingest/fileMultipart 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 -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)
{ "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" }] }
/ingest/file/partSend the file as sequential 5 MB parts for files over 10 MB.
| Field | Type | Notes |
|---|---|---|
file | binary | Raw bytes of this part (≤5 MB) |
part_index | integer | 0-based; first call must be 0 |
total_parts | integer | Total number of parts you'll send |
filename | string | Original filename (sent on every part) |
document_id | UUID | Omit on part_index=0 — response gives you one. Required on every subsequent part. |
workspace | string | Required. 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.
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; }
/ingest/textPush plain text directly — from a CMS, scraped page, or support ticket body. No file involved.
{ "title": "Q3 Support Ticket #4821", "text": "Customer reported an issue with...", "tags": ["support", "q3-2026"], "metadata": { "ticket_id": "4821" }, "workspace": "support-docs" }
| Field | Type | Constraints |
|---|---|---|
title | string | 1–512 chars, required |
text | string | 1–2,000,000 chars, required |
tags | string[] | optional, ≤20 |
metadata | object | optional, arbitrary JSON |
workspace | string | workspace slug or UUID — required for an API key |
Response: a single IngestStatusResponse object (text pushes are never auto-split).
/ingest/recordPush a structured JSON record — CRM records, ticket objects, log entries — serialized to text and run through the same pipeline.
{ "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.
/ingest/status/{job_id}{ "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 }
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 -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
{ "event": "ingestion.completed", "document_id": "d1f9e2b0-...", "workspace_id": "a7e6c1d4-...", "status": "completed", "name": "policy.pdf", "chunk_count": 42 }
ingestion.failed
{ "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.
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
GET /documentsJWT-only — does not accept an API key (401). Document list/inventory via key is a known gap being tracked.
POST /chat/querySSE streaming — JWT-only. Use non-streaming POST /chat instead.
POST /api/webhooksWebhook 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:
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
| Tool | Maps to | Notes |
|---|---|---|
keel_search | POST /search | Raw chunk hits — use when you want evidence, not a synthesized answer. |
keel_ask | POST /chat | Synthesized answer + confidence + evidence. Stateless — no conversation memory. |
keel_get_evidence | GET /evidence/{chunk_id} | Full chunk text/metadata for a citation. |
keel_ingest_text | POST /ingest/text | Push plain text for ingestion. |
keel_ingest_record | POST /ingest/record | Push a structured JSON record. |
keel_ingest_file | POST /ingest/file (+ chunked) | File bytes passed base64-encoded; uploads over 10 MB chunked transparently server-side. |
keel_check_ingest_status | GET /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.