Documentation

API Reference — LeanCTX

REST API endpoints, authentication, rate limiting, and TypeScript SDK reference for the LeanCTX Team Server.

The LeanCTX Team Server exposes a REST API for programmatic access to sessions, events, tools, and knowledge. All endpoints are available when the Team Server is running.

Authentication

All API requests require a bearer token in the Authorization header. Create tokens with the CLI:

$ lean-ctx team token create --scope read,write --name "ci-bot"
 Token: lctx_t_a3f8c2...

Include the token in every request:

Authorization: Bearer lctx_t_a3f8c2...

Token Scopes

ScopeAccess
searchRead tools: ctx_read, ctx_search, ctx_tree, ctx_overview, etc.
graphGraph tools: ctx_graph, ctx_impact, ctx_callgraph, etc.
artifactsctx_artifacts, ctx_semantic_search with artifacts
indexGraph index builds, semantic reindex
eventsSubscribe to SSE event stream
sessionMutationsctx_session writes, ctx_handoff, ctx_workflow
knowledgectx_knowledge writes, ctx_knowledge_relations
auditMetrics, full-payload events, audit log

REST Endpoints

Tool Execution

Execute any MCP tool via REST:

POST /v1/tools/call

Request:
{
  "name": "ctx_read",
  "arguments": {
    "path": "src/lib/auth.ts",
    "mode": "map"
  },
  "workspaceId": "my-team",
  "channelId": "feat/auth"
}

Response:
{
  "content": [{
    "type": "text",
    "text": "exports: authenticate(), validateToken()\\ndeps: jsonwebtoken, bcrypt\\ncached — 180 tokens (was 4,200)"
  }],
  "isError": false,
  "meta": {
    "tokens_saved": 4020,
    "cache_hit": false,
    "duration_ms": 12
  }
}

Session Management

GET  /v1/session?workspaceId=my-team&channel=feat/auth
POST /v1/session/mutate
GET  /v1/session/list?workspaceId=my-team

Event Stream (SSE)

Subscribe to real-time events via Server-Sent Events. Events include versioning, causal lineage, and consistency levels:

GET /v1/events?workspaceId=my-team&channelId=feat/auth&since=0

Response (SSE stream):
id: 42
event: tool_call_recorded
data: {"id":42,"workspaceId":"my-team","channelId":"feat/auth","kind":"tool_call_recorded","actor":"cursor","timestamp":"2026-05-05T13:00:00Z","version":42,"parentId":null,"consistencyLevel":"local","payload":{"tool":"ctx_read"}}

id: 43
event: session_mutated
data: {"id":43,"workspaceId":"my-team","channelId":"feat/auth","kind":"session_mutated","actor":"cursor","timestamp":"2026-05-05T13:00:01Z","version":43,"parentId":42,"consistencyLevel":"strong","payload":{"tool":"ctx_session","action":"save","reasoning":"Auth refactor checkpoint"}}

Event Types

KindConsistencyTrigger
tool_call_recordedlocalAny tool invocation completes
session_mutatedstrongSession state modified
knowledge_rememberedeventualKnowledge fact written
artifact_storedeventualArtifact persisted
graph_builtlocalGraph index updated
proof_addedstrongEvidence ledger appended

Context Summary

GET  /v1/context/summary?workspaceId=my-team  # Materialized view: agents, decisions, conflicts

Event Search & Lineage

GET  /v1/events/search?q=auth+strategy&workspaceId=my-team  # FTS5 full-text search
GET  /v1/events/lineage?id=42&depth=10                      # Causal chain traversal

Health & Metrics

GET /health            # Health check
GET /v1/metrics        # JSON metrics snapshot (requires audit scope)

Rate Limiting

The Team Server applies per-token rate limits:

EndpointLimit
/v1/tools/call100 req/min per token
/v1/events5 concurrent SSE connections
/v1/knowledge/*60 req/min per token

Rate limit headers are included in all responses: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset.

TypeScript SDK

The SDK wraps all REST endpoints with type-safe methods:

// Install
npm install @anthropic/lean-ctx-sdk

// Usage
import { LeanCtx } from "@anthropic/lean-ctx-sdk";

const ctx = new LeanCtx({
  baseUrl: "http://localhost:7700",
  token: process.env.LEANCTX_TOKEN,
  workspace: "my-team",
});

// Read a file
const result = await ctx.tools.call("ctx_read", {
  path: "src/lib/auth.ts",
  mode: "map",
});

// Subscribe to events
for await (const event of ctx.events.subscribe()) {
  console.log(event.type, event.data);
}

// Error handling
try {
  await ctx.tools.call("ctx_read", { path: "/etc/passwd" });
} catch (e) {
  if (e instanceof LeanCtxError) {
    console.error(e.code, e.message);
  }
}

SDK Methods

MethodDescription
ctx.tools.call(name, args)Execute any MCP tool
ctx.tools.list()List available tools
ctx.session.get(channel)Get session state
ctx.session.list()List active sessions
ctx.knowledge.search(query)Search knowledge base
ctx.knowledge.remember(fact)Store a fact
ctx.events.subscribe(opts)SSE event stream (async iterator)
ctx.status()Server status

HTTP MCP Contract

LeanCTX also exposes a small, stable HTTP surface for direct system-to-system access to the tool registry, mirroring MCP semantics over plain HTTP.

Loopback vs Non-Loopback

  • Loopback bind (127.0.0.1 / localhost / ::1): auth token is optional.
  • Non-loopback bind (e.g. 0.0.0.0): requires --auth-token.
  • Host header is checked unless disabled. Use --allowed-host to add hostnames.

Error Codes

StatusCodeMeaning
401unauthorizedMissing/invalid Bearer token
400host_deniedHost header not allowed
429rate_limitedRPS guard triggered
429concurrency_limitedIn-flight guard triggered
400tool_errorTool execution rejected/failed
504request_timeoutTool call exceeded timeout

Direct curl Examples

# Start server on loopback (no auth required)
lean-ctx serve --host 127.0.0.1 --port 8080

# Health check
curl http://127.0.0.1:8080/health

# Manifest + tool list
curl http://127.0.0.1:8080/v1/manifest
curl "http://127.0.0.1:8080/v1/tools?offset=0&limit=50"

# Call a tool
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"name":"ctx_tree","arguments":{"path":".","depth":2}}' \
  http://127.0.0.1:8080/v1/tools/call