# gotcontext.ai API Documentation

> Machine-readable Markdown export.  Point an LLM at this URL to ingest the
> full docs.  Human-readable rendering: https://gotcontext.ai/docs

Base URL: `https://api.gotcontext.ai`

## Authentication

All requests require an `Authorization` header.  Three modes are supported:

- **Clerk JWT** (browser sessions) — `Authorization: Bearer <jwt>`
- **API key** — `Authorization: Bearer gc_<32 hex chars>`.  Create keys in
  the dashboard at https://gotcontext.ai/dashboard/settings.
- **OAuth 2.1** (MCP only, enterprise) — see "Enterprise OAuth 2.1" below.

Keys are HMAC-SHA256 hashed server-side; the raw key is only shown once at
creation.

### Enterprise OAuth 2.1

The MCP endpoint accepts OAuth 2.1 JWT bearers with **RFC 8707 resource
indicator** binding. Clients obtain a token from the authorization server
with `resource=https://api.gotcontext.ai/mcp`; the server stamps that value
into the token's `aud` claim, and the MCP gateway rejects tokens where
`aud` doesn't match (prevents cross-server token theft).

Protected resource metadata is advertised per **RFC 9728** at:

```
GET /.well-known/oauth-protected-resource
```

Response:

```json
{
  "resource": "https://api.gotcontext.ai/mcp",
  "authorization_servers": ["https://clerk.gotcontext.ai"],
  "bearer_methods_supported": ["header"],
  "scopes_supported": ["mcp:tools", "mcp:read", "mcp:write"]
}
```

`gc_` API keys continue to work for MCP alongside OAuth — use whichever
your client supports.

## Core endpoints

### POST /v1/compress
Compress plain text before sending to an LLM.

Request body:

```json
{ "text": "<your document>", "fidelity": "balanced" }
```

Response body:

```json
{
  "compressed": "<skeleton>",
  "stats": {
    "original_tokens": 485,
    "compressed_tokens": 61,
    "savings_pct": 87.4,
    "compression_ratio": 7.95,
    "estimated_cost_saved": "$0.0013"
  }
}
```

Fidelity levels: `abstract` (5% kept) · `outline` (10%) · `balanced` (default, 20%) · `detailed` (40%) · `raw` (100%, no compression).

### POST /v1/compress-code
AST-aware code compression.  Request body mirrors `/v1/compress` plus an
optional `language` field (`python`, `javascript`, `typescript`, `java`,
`go`, `rust`, `cpp`).  Auto-detected from content when omitted.

### POST /v1/compress-code/structural (v1.5.0)

Structural code-context compression. Submit a file bundle; the server runs
tensor-grep blast-radius + BM25 on the sandboxed files and returns a
Reciprocal-Rank-Fusion-ranked context list. Intended for PR-diff-scale
payloads (<=1000 files, <=512 KB each, <=5 MB total). Measured 34% token
reduction on a 10-file corpus — see `benchmarks/blast_radius_smoke.py`.

Request body:

```json
{
  "files": [
    { "path": "src/app.py", "content": "def handle_request(): ..." }
  ],
  "focus_symbol": "handle_request",  // optional
  "query": "error handling",           // optional; defaults to focus_symbol
  "top_k": 25                           // optional; default 50, max 500
}
```

Response body:

```json
{
  "ranked_context": [
    {
      "path": "src/app.py",
      "score": 0.031,
      "rank": 1,
      "contributing_signals": ["bm25", "graph_distance"]
    }
  ],
  "stats": { "files_in": 10, "files_ranked": 5, "symbols_in": 23, "degraded": false },
  "message": null
}
```

**Errors:**
- `400 {error_code: "sensitive_content", marker_class: ...}` — file matched the secret-marker detector
- `400 {error_code: "bad_path"}` — traversal/absolute/null-byte in a submitted path
- `413` — per-file (>512 KB) or aggregate (>5 MB) cap exceeded
- `402` — free-tier plan; upgrade to Pro+
- `2xx` with `X-Degraded: true` — tensor-grep unavailable or subprocess timed out (never 500)

The corresponding MCP tool is `gc_blast_radius` with the same payload shape.

### POST /v1/batch-compress
Submit up to 50 documents per call.  Returns per-document results and an
aggregate summary.  Max 4 concurrent internally.

### POST /v1/recommend
Recommend a fidelity level for a given document + target model context
window.  Supports Claude, GPT, Codex, Gemini, Llama, and Mistral families.

### GET/PUT /v1/settings/semantic-cache-threshold (v1.4.0)

Per-tenant cosine-similarity cutoff for the semantic dedup cache.
`threshold` is similarity in `[0.80, 0.99]`; pass `null` on PUT to reset to
the server-wide default (~0.95). `source` is `"user"` when a per-tenant
override is set, `"global"` otherwise.

```bash
GET  /v1/settings/semantic-cache-threshold
  → { "threshold": 0.95, "source": "global" }

PUT  /v1/settings/semantic-cache-threshold
  body: { "threshold": 0.92 }
  → { "threshold": 0.92, "source": "user" }
```

Suggested values: **0.95-0.97** factual/high-stakes; **0.92** balanced;
**0.85-0.90** FAQ/support.

### POST /v1/batch-queue
Durable async batch job.  Returns a `job_id`.  Stream progress via
`GET /v1/batch-queue/stream` (Server-Sent Events — see "Live monitor" below).

## Request / response additions (v1.4.0)

### CompressRequest.style

Optional `style` field on `POST /v1/compress`:
`"terse" | "normal" (default) | "verbose"`. When `"terse"`, the response
carries `system_prompt_suffix` and `style_suffix_version`; inject the suffix
into your downstream LLM's system prompt to reduce output verbosity. The suffix
is a versioned constant and does not affect compression fidelity.

### CompressResponse.system_prompt_suffix + style_suffix_version

Non-null only when the request set `style: "terse"`. The suffix is a
versioned constant; `style_suffix_version` lets client-side checksums
detect wording updates.

### Sensitive-content pre-flight refuse

`POST /v1/compress` and `POST /v1/compress-code/structural` refuse inputs
matching well-known secret markers (PEM headers, `AKIA` AWS keys, `sk-`
OpenAI keys, `.ssh/id_rsa`, dotenv-style `SECRET_KEY=`) with:

```json
{ "detail": { "error_code": "sensitive_content", "marker_class": "aws_access_key",
              "message": "…refusing to compress. Remove the secret value and retry." } }
```

The matched value is never echoed in the response or the structured log.

### X-Fidelity-Warning response header

Advisory header on `POST /v1/compress` responses listing structural
classes that dropped between input and output — any comma-separated
subset of `code_blocks`, `headings`, `urls`. Never fails the request; use
for dashboards / tenant-level alerting.

### UsageByCacheResponse.by_source

`GET /v1/usage/by-cache` now returns a `by_source` object splitting
semantic-cache hits by mechanism — the request-hash fastpath (exact)
vs. the embedding-distance fallback (semantic):

```json
{
  "semantic_cache": { "hits": 15, "misses": 35, ... },
  "by_source": { "exact_hits": 12, "semantic_hits": 3, "misses": 35 }
}
```

Invariant: `exact_hits + semantic_hits == semantic_cache.hits`.

## MCP server

Streamable HTTP at `https://api.gotcontext.ai/mcp`.  Same `gc_` key auth as
REST.  All paid tiers (Pro, Team, Enterprise) see the same 193 tools
covering compression, dialogue memory (AFM), context engineering (ACE),
knowledge management, multimodal ingestion, file sync, code analysis,
quality detection, and more. Free tier sees 23 core compression tools.

**v1.5.1 platform tool:** `gc_blast_radius` wraps
`POST /v1/compress-code/structural` with the same `{files, focus_symbol,
query, top_k}` input shape. Pro+ only; free-tier MCP calls receive a
text upgrade prompt.

Claude Desktop config:

```json
{
  "mcpServers": {
    "gotcontext": {
      "type": "http",
      "url": "https://api.gotcontext.ai/mcp?profile=core",
      "headers": { "Authorization": "Bearer gc_..." }
    }
  }
}
```

`?profile=core` ships 7 essential tools (~2K tokens) for a lean session start;
swap to `?profile=full` (or drop the query param) for the complete tool catalog
(~38K tokens). See https://gotcontext.ai/blog/reduce-claude-code-token-costs.

## Webhooks

Outbound HMAC-SHA256-signed webhooks on `compression.completed`.  Configure
at `/dashboard/webhooks`.

Inbound provider webhooks:

- `POST /webhooks/clerk` — user lifecycle (Svix-signed)
- `POST /webhooks/polar` — subscription events (Svix-signed)
- `POST /v1/integrations/github/webhook` — push + pull_request (HMAC-SHA256)

## Live batch-queue monitor

`GET /v1/batch-queue/stream` — Server-Sent Events feed.  Events:

- `init` — one-shot snapshot of the user's latest 50 jobs
- `job.updated` — one per job whose status or progress changed
- `job.removed` — one per job that fell out of the snapshot
- `heartbeat` — approximately every 15 seconds

## Compression: REST vs MCP

There are two ways to compress with gotcontext.ai. They serve different
purposes — choosing the right one matters.

### REST `POST /v1/compress` — single-shot text compression

Use when: you have a string of text and want to compress it before sending
it to an LLM. Response includes `compressed`, `original_tokens`,
`compressed_tokens`, `savings_pct`, plus structural metadata (`levels`,
`stats`).

```bash
curl -X POST https://api.gotcontext.ai/v1/compress \
  -H "Authorization: Bearer $GC_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text":"...","fidelity":"balanced"}'
```

### MCP tools — context-aware agentic operations

The `gc_*` MCP tools are not general-purpose text compressors. They serve
specific agentic workflows:

- **`gc_blast_radius`** — Code-context compression. Submit
  `[{"path": "...", "content": "..."}]` plus an optional focus symbol.
  Returns a ranked context list for an LLM editing that area.
  Input schema: `{"files": [{"path": "string", "content": "string"}], "focus_symbol": "string", "top_k": 50}`.
  Pro+ only.
- **`gc_session_summary`** — Compress conversation history into a
  portable summary the agent can re-inject after `/clear`. Available on
  all plans including Free.
- **`gc_pre_flight`** — Pre-flight check before sending an expensive
  prompt: returns a verdict (`send_as_is`, `send_compressed`,
  `warn_context_limit`, `clear_first`), the compressed body inline, and
  a cost preview. Available on all plans including Free.
- **`gc_compress_manifest`** — Compress an MCP `tools/list` manifest.
  Useful when an agent wraps multiple MCP servers and needs to fit all
  tool descriptions into context. Pro+ only.

### Why the split?

REST compression is stateless and intended for single documents or batch
pipelines. MCP tools participate in a live Claude Code / Cursor / Codex
session, share session context, and compose with other tools. Use REST
for library/SDK work; use MCP tools when an LLM is driving.

### Common confusion

Customers sometimes look for a `gc_compress_text` MCP tool. It does not
exist — adding one would duplicate the REST endpoint without adding
MCP-specific value. If you need text compression in an MCP-only
environment, call `POST /v1/compress` via your client's HTTP fetch and
inject the response into the agent's context.

## Knowledge Hub (Pro tier)

The Knowledge Hub is gotcontext.ai's model-agnostic RAG layer with
**compressed retrieval** — the same answer quality at 5-20× lower token
cost than NotebookLM, Vectara, or vanilla LangChain RAG. Live for Pro+
keys: versioned items, per-project isolation, dashboard uploads,
visibility + sharing governance, and nine `gc_kb_*` MCP tools — plus
the agent-collaboration surfaces below (plan change-proposals and
cross-agent task delegation).

### MCP tools

| Tool | What it does |
|---|---|
| `gc_kb_ingest` | Chunk + embed a document into a project knowledge base (text, markdown, PDF) |
| `gc_kb_query` | Semantic retrieval; returns compressed answer-relevant chunks |
| `gc_kb_get` | Read a single KB item by id |
| `gc_kb_list` | List KB items in a project |
| `gc_kb_edit` | Update KB item metadata (title, tags); content is immutable per version |
| `gc_kb_diff` | Show delta between two versions of a KB item |
| `gc_kb_delete` | Soft-delete a KB item (preserves audit trail; restorable) |
| `gc_kb_set_visibility` | Set an item's visibility (private to the creating key, or project-wide) |
| `gc_kb_share` | Grant another of your API keys access to a specific item (per-key allowlist) |

All nine tools require a Pro+ `gc_` API key (or Clerk JWT) and are
project-scoped — each user's default project is auto-provisioned; the
keys table at `/dashboard/settings → API Keys` shows which project a
key is bound to.

### Agent plan collaboration (change-proposals)

Turn a document into a `plan` (create it with `gc_kb_ingest(type='plan')`)
that agents edit like a pull request. An agent proposes a change against a
specific version; the proposal is signed with the agent's A2A peer identity;
nothing lands until the human owner merges it. Peers cannot write to a plan
via `gc_kb_edit`; only `gc_plan_propose` can.

| Tool | What it does |
|---|---|
| `gc_plan_propose` | Submit a signed change-proposal (`item_id, base_version_id, diff, title`) against a plan version |
| `gc_plan_list_proposals` | Owner-scoped inbox; filter by `item_id` or `status` |
| `gc_plan_get_proposal` | Fetch one proposal's full diff, rationale, and status |
| `gc_plan_decide` | Merge or reject an open proposal (owner-only); a stale base is refused, never auto-resolved |
| `gc_plan_blame` | Per-version author + proposal trail for a plan item |

Each merge creates a new version with the contributing agent recorded against
it, so `gc_plan_blame` gives a full attributed history. All five require a
project-bound Pro+ `gc_` key. Review the same inbox in the dashboard at
`/dashboard/knowledge/agents`.

### Cross-agent task delegation (A2A)

One of your agents hands a unit of work to another of your agents over the
Linux Foundation Agent2Agent (A2A) protocol. The requester creates a task
assigned to a registered peer; it stays a draft until you, the owner, approve
it. The assignee then claims it with an Ed25519-signed proof of its identity,
does the work, and returns a signed result you can verify came from that peer.

| Tool | What it does |
|---|---|
| `gc_a2a_task_create` | Create a task (`assignee_peer_id, task_type, title, payload, requester_peer_id?`); lands as a draft. `task_type`: research / action / debate_position |
| `gc_a2a_task_approve` | Draft to pending (owner gate); pass `requester_peer_id` if the key is not peer-bound |
| `gc_a2a_task_inbox` | Assignee polls for approved tasks assigned to it |
| `gc_a2a_task_claim` | Claim a pending task with a signed proof (`task_id, from_peer_id, proof_jws`) + a time-boxed lease |
| `gc_a2a_task_complete` | Return a signed result (`..., result_payload`); the proof binds the result hash |
| `gc_a2a_task_status` | Poll one task's state |
| `gc_a2a_task_cancel` | Owner cancels |

Claim and complete are also on the REST API for a remote peer to call directly,
signed-proof-gated (no key needed): `POST /a2a/v1/tasks/claim` and
`POST /a2a/v1/tasks/complete`. Pro+ for the owner-side tools.

### REST mirror

Every MCP tool is mirrored at `/v1/projects/{project_id}/knowledge/*` for
clients that prefer HTTP. Same auth, same payload shapes, same project
scoping. See the [OpenAPI schema](https://api.gotcontext.ai/api/docs) for
the full surface.

### Compressed retrieval — what makes it different

A typical RAG tool retrieves chunks and stuffs them verbatim into the
prompt. The Knowledge Hub retrieves chunks AND compresses them through
the same semantic-modulator engine that powers `POST /v1/compress` —
preserving meaning while dropping 80-95% of tokens. Net effect: a 50K-token
context window can hold the SAME answer-relevant information as a
200-500K window of un-compressed retrieval.

Live benchmark comparison (compressed vs uncompressed retrieval, same
corpus, same answer quality scoring) ships at
[/benchmarks/compression](https://gotcontext.ai/benchmarks/compression)
once the v0 quality-score harness completes (currently shows pricing-only).

### Dashboard

Auth-gated at [`/dashboard/knowledge`](https://gotcontext.ai/dashboard/knowledge).
File upload + KB browse + query playground. Public marketing page +
side-by-side benchmark vs NotebookLM is planned (Phase 4 per the
product roadmap).

## Plan tiers

All paid plans (Pro, Team, Enterprise) include the same 193 MCP tools
and the same compression engine. Plans differ on **monthly compression
volume, embedding fidelity, and enterprise wraparound** (self-hosted
deployment, OIDC/SSO, audit-log export, dedicated SLA, named support,
custom contract). Not on which tools you can call.

- **Free** — 1,000 compressions/month, 23 core compression tools, TF-IDF
  embeddings. For validating compression on your own inputs.
- **Pro ($49/mo)** — 50,000 compressions/month, all 193 MCP tools,
  accelerated ONNX embeddings (3-5x faster), priority queue (2 reserved
  compression slots), webhook notifications, queue monitor, priority
  support.
- **Team ($99/mo)** — 100,000 compressions/month (pooled across seats),
  all 193 MCP tools, priority queue (4 reserved slots), async batch
  queue, compression projects, RBAC roles (owner/admin/operator/viewer),
  GitHub integration, MCP tool compression, advanced analytics + CSV
  export, 300 req/min.
- **Enterprise ($199/mo)** — 500,000+ compressions/month, all 193 MCP
  tools, priority queue (8 reserved slots), **self-hosted Docker image
  (run in your VPC)**, **OIDC federation** (Okta, Auth0, Azure AD,
  Keycloak), **SSO/SAML**, **SBERT embedding tier** (highest semantic
  fidelity), **audit-log export** (NDJSON/CSV) for SOC2 evidence,
  standard SLA + email support, **DPA / IP indemnity / custom MSA /
  annual invoice billing**, 500 req/min API rate limit.
- **Enterprise (custom pricing)** — everything in Business PLUS
  custom rate limits and quotas scoped per contract, configurable
  payload retention with a zero-retention mode in self-hosted, and
  uptime + support terms negotiated per contract. Talk to sales via
  the pricing page contact form.

## Errors

Standard HTTP status codes.  Error responses:

```json
{ "detail": "<human-readable message>" }
```

Rate-limit responses include `X-RateLimit-Remaining` and `Retry-After`.
When upstream dependencies (Redis / Polar) degrade, responses include
`X-Degraded: redis` or similar.

## SDKs

Official clients — zero config beyond an API key.

### TypeScript / Node

```bash
npm install @gotcontext/sdk
```

```ts
import { GotContext } from "@gotcontext/sdk";
const gc = new GotContext({ apiKey: process.env.GOTCONTEXT_API_KEY! });
const out = await gc.compress({ text: document, fidelity: "balanced" });
console.log(out.compressed_text);
```

Works in Node 18+, Bun, Deno, Cloudflare Workers. Zero runtime dependencies.

### Python

```bash
pip install gotcontext
```

```python
from gotcontext import GotContext
gc = GotContext(api_key=os.environ["GOTCONTEXT_API_KEY"])
out = gc.compress(document, fidelity="balanced")
print(out.compressed_text)
```

Also ships `AsyncGotContext` for `asyncio` codebases.

### Claude Code plugin

Install the official gotcontext plugin into Claude Code in two lines:

```
/plugin marketplace add oimiragieo/gotcontext-plugin
```

Bundles 9 outcome-oriented skills — `shrink-for-claude`,
`extract-api-surface`, `review-pr-diff`, `ingest-docs`,
`batch-compress`, `session-summary`, `pre-flight`,
`compress-mcp-manifest`, `quick-start` — plus a pre-configured MCP server pointing at
`https://api.gotcontext.ai/mcp`.  Set `GOTCONTEXT_API_KEY` in your
environment before the first run.

## Observability

`GET /metrics` exposes Prometheus metrics for private scrape targets
(Grafana Cloud, a co-located Prometheus, etc.). No auth — do not expose it
to the public internet without a scrape-side allowlist.

Key MCP metric families:

- `mcp_tool_calls_total{tool,status}` — counter; status ∈ { `ok`, `error`, `denied` }
- `mcp_tool_duration_seconds{tool}` — histogram (11 buckets, 10ms → 60s)
- `mcp_sessions_active` — gauge of in-flight Streamable HTTP sessions

Example Grafana Cloud scrape config:

```yaml
- job_name: gotcontext
  scrape_interval: 30s
  metrics_path: /metrics
  scheme: https
  static_configs:
    - targets: ['api.gotcontext.ai']
```

## Resources

- Human docs (HTML): https://gotcontext.ai/docs
- OpenAPI 3 spec: https://api.gotcontext.ai/api/openapi.json
- Swagger UI: https://api.gotcontext.ai/api/docs
- Python SDK: https://pypi.org/project/gotcontext/
- Changelog: https://gotcontext.ai/changelog
- Status: https://gotcontext.ai/status
