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)

Agent Registry

HTTP-backed agent registration and lifecycle management. These endpoints power the Remote Agent Bus.

POST /v1/agents/register

Request:
{
  "agent_type": "claude",
  "role": "review",
  "project_root": "/home/user/my-project"
}

Response:
{
  "agent_id": "d4e5f6",
  "status": "active",
  "registered_at": "2026-05-17T10:00:00Z"
}
POST /v1/agents/heartbeat

Request:
{ "agent_id": "d4e5f6" }

Response:
{ "ok": true, "ttl_seconds": 60 }
GET  /v1/agents/list

Response:
{
  "agents": [
    {
      "agent_id": "d4e5f6",
      "agent_type": "claude",
      "role": "review",
      "status": "active",
      "last_heartbeat": "2026-05-17T10:05:00Z"
    }
  ]
}
POST /v1/agents/deregister

Request:
{ "agent_id": "d4e5f6" }

Response:
{ "ok": true, "deregistered_at": "2026-05-17T10:10:00Z" }
GET  /v1/agents/events  # SSE stream of agent registry changes

Response (SSE stream):
event: agent_joined
data: {"agent_id":"d4e5f6","agent_type":"claude","role":"review"}

event: agent_left
data: {"agent_id":"a1b2c3","reason":"heartbeat_timeout"}

Audit & References

GET  /v1/audit/events?limit=50  # Cross-project boundary events + audit trail

Response:
{
  "events": [
    {
      "timestamp": "2026-05-17T10:00:00Z",
      "kind": "cross_project_read",
      "agent_id": "a1b2c3",
      "source_project": "/home/user/api",
      "target_path": "/home/user/shared/types.ts",
      "action": "blocked"
    }
  ],
  "total": 142
}
GET  /v1/references/{id}  # Resolve a reference result by ID

Response:
{
  "id": "ref_a7f3c2",
  "type": "file_content",
  "path": "src/auth.ts",
  "content": "export function authenticate() ...",
  "created_at": "2026-05-17T09:30:00Z",
  "expires_at": "2026-05-17T10:30:00Z"
}

Discovery

GET  /.well-known/mcp-server.json  # MCP Server Card

Response:
{
  "name": "lean-ctx",
  "version": "3.6.2",
  "capabilities": ["tools", "resources", "prompts"],
  "tool_categories": ["read", "search", "shell", "knowledge", "agent", "session"],
  "security": {
    "sandbox": true,
    "secret_detection": true,
    "shell_allowlist": true,
    "signed_handoffs": true
  },
  "transport": ["stdio", "http"],
  "a2a_compatible": true
}

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 @leanctx/sdk

// Usage
import { LeanCtx } from "@leanctx/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