Skip to content

This is the multi-page printable view of this section. .

Return to the regular view of this page.

Integrations

Connect Cortrix to your application, IDE, or agent.

Cortrix offers several access paths: the HTTP API, MCP, the Python SDK, framework adapters, and a built-in Agent.

1 - Choose an access path

Compare the HTTP API, MCP, the Python SDK, and the built-in Agent.

Cortrix has four access paths. This page helps you pick the one that fits your situation.

How to choose

Your situationChoose
You need precise control over requests, retries, authentication, and deployment, or you’re not using PythonHTTP API
You want an agent in your IDE, or another MCP-compatible client, to call CortrixMCP server
You’re writing a Python application, a RAG pipeline, or a test scriptPython SDK
You want local fixed-flow chat over what’s in Cortrix, without wiring up an agent frameworkBuilt-in Agent

HTTP API

Every other access path ends up calling the HTTP API. The contract is api/openapi.yaml in the repository. See the HTTP API reference for every endpoint.

Check that the service is ready:

curl -fsS http://127.0.0.1:8420/api/v1/system/health/ready

Run a query:

curl -fsS -H 'Content-Type: application/json' \
  -d '{
    "namespaces": ["demo"],
    "query": "What does semantic storage keep close to the agents that need it?",
    "top_k": 5,
    "rerank": true
  }' \
  http://127.0.0.1:8420/api/v1/query

When authentication is on, send your API key in the X-API-Key header.

MCP server

The MCP server exposes Cortrix’s HTTP API as a set of MCP tools covering health, query, upload, namespace management, memory, task status, directory watchers, and admin database import.

It supports local stdio transport only. There is no remote Streamable HTTP endpoint.

For setup, see MCP server.

Python SDK

The Python SDK provides a synchronous client, Cortrix, and an asynchronous client, AsyncCortrix. Both are fully typed and map the server’s structured errors to exceptions with fields.

It exposes resources for documents, namespaces, query, memory, directory watchers, authentication, tenants, system information, operations, and database import. For the status of each resource, see Python SDK.

For installation and usage, see Python SDK.

Built-in Agent

The built-in Agent is a FastAPI service that provides fixed-flow chat over Cortrix storage. It needs the agent_llm role configured, and it’s off by default in the quickstart.

Chat is the only mode.

See Built-in Agent.

Next steps

2 - MCP server

Let Claude Code, Cursor, and other MCP clients call Cortrix.

On this page you’ll install cortrix-mcp and connect it to an MCP client, so the agent in that client can query, upload documents, and manage memory.

cortrix-mcp exposes Cortrix’s HTTP API as 31 MCP tools: 29 regular tools and 2 admin tools. It talks HTTP directly to a running cortrix-server.

Prerequisites

  • A running Cortrix service. See the Quickstart.
  • Python 3.10 or later.
  • An MCP client that supports stdio transport.
Note

Only local stdio transport is supported. Cortrix doesn’t expose a remote or loopback Streamable HTTP MCP endpoint.

Install

Install the package from PyPI into a virtual environment:

python3 -m venv .venv
source .venv/bin/activate
pip install cortrix-mcp

This gives you the cortrix-mcp command, which is the entry point for the MCP stdio server. Confirm the install:

pip list | grep -E '^(cortrix-mcp|mcp) '
cortrix-mcp               1.0.0rc2
mcp                       2.3.0
Note

Cortrix is in pre-release, so pip installs the latest pre-release, 1.0.0rc2. The Docker image cortrix/mcp isn’t published to a registry yet. To run the server in a container, build the image from cortrix-mcp/ in a clone of the repository.

Configuration

All configuration is passed through environment variables:

VariablePurposeDefault
CORTRIX_URLThe address of cortrix-serverhttp://127.0.0.1:8420
CORTRIX_NAMESPACEThe default namespacedefault
CORTRIX_API_KEYA Bearer token or API key for the target serverEmpty
CORTRIX_MCP_ADMINTurns on admin tools when the server accepts the caller as an adminfalse
CORTRIX_MCP_TIMEOUTHTTP timeout, in seconds30
CORTRIX_AGENT_IDThe agent identity sent as X-Agent-Id on every request. Allowed characters are [A-Za-z0-9_.:/-], up to 128 characters. An invalid value falls back to the defaultcortrix-mcp

The quickstart service has no authentication, so you don’t need CORTRIX_API_KEY. Its demo data lives in the demo namespace, so the examples below set the default namespace to demo.

Connect a client

Claude Code

Run this in your project directory. cortrix-mcp needs to be on your PATH. Otherwise, give the absolute path inside your virtual environment:

claude mcp add cortrix --scope project \
  --env CORTRIX_URL=http://127.0.0.1:8420 \
  --env CORTRIX_NAMESPACE=demo \
  -- cortrix-mcp
Added stdio MCP server cortrix with command: cortrix-mcp  to project config

This creates .mcp.json in the current directory:

.mcp.json
{
  "mcpServers": {
    "cortrix": {
      "type": "stdio",
      "command": "cortrix-mcp",
      "args": [],
      "env": {
        "CORTRIX_URL": "http://127.0.0.1:8420",
        "CORTRIX_NAMESPACE": "demo"
      }
    }
  }
}

Claude Code asks you to approve a project-scoped MCP server before using it. Start claude, approve cortrix, and then run /mcp to check the connection.

Tip

.mcp.json can contain absolute paths from your machine. The Cortrix repository’s .gitignore already ignores this file. Whether to commit it in your own project is up to you.

Cursor

Add this to ~/.cursor/mcp.json:

~/.cursor/mcp.json
{
  "mcpServers": {
    "cortrix": {
      "command": "cortrix-mcp",
      "env": {
        "CORTRIX_URL": "http://127.0.0.1:8420",
        "CORTRIX_NAMESPACE": "demo"
      }
    }
  }
}

Cline

Add this to cline_mcp_settings.json in your VS Code user directory:

cline_mcp_settings.json
{
  "mcpServers": {
    "cortrix": {
      "command": "cortrix-mcp",
      "env": {
        "CORTRIX_URL": "http://127.0.0.1:8420",
        "CORTRIX_NAMESPACE": "demo"
      },
      "disabled": false
    }
  }
}

Verify

Once connected, ask the agent to call cortrix_health. The result’s meta.category should be success:

{
  "data": { "status": "alive", "uptime_seconds": 195, "version": "1.0.0-rc.2" },
  "meta": {
    "retryable": false,
    "category": "success",
    "retry_after_ms": null,
    "structured_data": {
      "trace_id": "17912bb9-4f29-4a2f-9a35-e5ccd2ac28c8",
      "session_id": "mcp-session-da64d7e40fe9"
    }
  }
}

Then ask it to use cortrix_query to look up “What does semantic storage keep close to the agents that need it?”. It should return content from quickstart-demo.txt.

Tell the agent how to use Cortrix

Connecting the server gives the agent the tools. It doesn’t tell the agent which of your files are indexed, or that it should search them before it opens them. Add a short section like this to your project’s agent instructions, such as CLAUDE.md for Claude Code or AGENTS.md, and fill in the placeholders:

## Cortrix

The documents in <which files, for example "docs/ and design/"> are indexed in
Cortrix, namespace `<your-namespace>`. Search them through the `cortrix` MCP server.

- Before you open those files to answer a question, search with `cortrix_query`
  and pass `namespaces: ["<your-namespace>"]`. Start with the question itself, or
  the names and terms you need.
- Open a file only for what the hits leave open, and go to the files the hits point to.
- Cite from each hit's `metadata`: `doc_id`, `source_path`, and the fields this
  project sets at upload.

For the quickstart’s demo data, the namespace is demo.

When to turn off the agent’s own file tools

An agent that also has its own tools for reading and searching files, such as Claude Code’s Read, Grep and Glob, may search Cortrix and then keep opening files on its own. Each extra turn sends the whole conversation again, so a long answer can cost several times more. For a session that only answers questions from the indexed documents, start Claude Code without those tools:

claude --disallowedTools "Read Grep Glob"

Keep them on in a session that also edits code: Claude Code reads a file before it edits it.

Tools

GroupTools
Corecortrix_health, cortrix_query, cortrix_upload, cortrix_list_documents, cortrix_list_namespaces, cortrix_create_namespace, cortrix_memory_search, cortrix_log_interaction, cortrix_list_interactions, cortrix_document_status, cortrix_add_watcher, cortrix_list_watchers
Extendedcortrix_cross_ns_query, cortrix_async_upload, cortrix_memory_search_filter, cortrix_memory_extract_trigger
Tasks and explaincortrix_memory_extract, cortrix_task_status, cortrix_cancel_task, cortrix_query_explain
Memory and operationscortrix_memory_get_audit, cortrix_memory_revoke_fact, cortrix_memory_opt_out, cortrix_batch_submit, cortrix_list_operations, cortrix_memory_list, cortrix_memory_create, cortrix_memory_edit, cortrix_memory_invalidate
Admincortrix_admin_db_credential_register, cortrix_admin_db_import_run

For each tool’s parameters and status, see MCP tools.

Response schema

Every tool returns two layers: data holds the result, and meta tells the agent whether the call can be retried.

When a tool, the backend, authentication, a timeout, or validation fails, the result comes back with isError=true and keeps code, retryable, category, retry_after_ms, and structured_data.

The adapter defines 6 stable error codes of its own:

Error codeRetryableCategorySuggested wait (ms)
CX_ERR_MCP_BACKEND_TIMEOUTYestransient1000
CX_ERR_MCP_BACKEND_UNAVAILABLEYestransient5000
CX_ERR_MCP_SCHEMA_VALIDATION_FAILNopermanent—
CX_ERR_MCP_TOOL_NOT_FOUNDNopermanent—
CX_ERR_MCP_AUTH_MISSINGNoauth—
CX_ERR_MCP_ADMIN_REQUIREDNoauth—

Errors that come from cortrix-server itself pass through unchanged.

Trace a call

Every backend request carries X-Session-Id, a fresh X-Trace-Id, and X-Agent-Id. The server adopts these identifiers, so you can use the session_id in a tool’s meta.structured_data to look up the server-side trace directly:

curl -fsS http://127.0.0.1:8420/api/v1/traces/<session_id>

Protocol compatibility

  • The modern protocol 2026-07-28, through server/discover.
  • The legacy protocol 2025-11-25, through the initialize handshake.
  • Python dependency: mcp>=2.0.0,<3.0.0.

Next steps

3 - Python SDK

Use the Cortrix client in a Python application.

On this page you’ll install the Cortrix Python SDK, connect to a local Cortrix service, and run a query.

The SDK provides a synchronous client, Cortrix, and an asynchronous client, AsyncCortrix, both fully typed. Its runtime dependency is httpx, plus typing-extensions on Python versions before 3.12.

Prerequisites

  • A running Cortrix service. See the Quickstart.
  • Python 3.9 or later.

Install

Install the package from PyPI into a virtual environment:

python3 -m venv .venv
source .venv/bin/activate
pip install cortrix

Confirm the installed version:

pip list | grep -E '^cortrix '
cortrix                   1.0.0rc2
Note

Cortrix is in pre-release, so pip installs the latest pre-release, 1.0.0rc2.

Your first query

Save this as check.py. It connects to the service the quickstart started and queries the demo namespace:

check.py
from cortrix import Cortrix

client = Cortrix(base_url="http://127.0.0.1:8420")

print(client.system.health())

results = client.search(
    "demo",
    "What does semantic storage keep close to the agents that need it?",
    top_k=5,
)
for item in results.results:
    print(round(item.rerank_score, 3), item.metadata["source_path"])
print(results.meta.coverage_ratio, results.meta.namespaces_succeeded)

client.close()

Run it:

python check.py
{'status': 'alive', 'uptime_seconds': 70, 'version': '1.0.0-rc.2'}
0.993 quickstart-demo.txt
1.0 ['demo']

The quickstart service has no authentication, so there’s no api_key here. To connect to a service that requires one, use Cortrix(base_url=..., api_key="your-cortrix-api-key").

Warning

If every call raises CortrixError with status code 502 while curl to the same address works, a system proxy is usually intercepting requests to your own machine. Bypass the proxy for local addresses and try again:

NO_PROXY=127.0.0.1,localhost python check.py

Client options

OptionPurpose
base_urlThe service address. Defaults to http://localhost:8420
api_keyAn API key. Optional
tenant_idA tenant identifier. Optional
timeoutThe request timeout
max_retriesThe maximum number of automatic retries
http_clientPass in your own httpx.Client
client_idSent as the X-Client-Id header to tell callers apart
trace_id_providerA function that returns a W3C traceparent, for distributed tracing

client.search() maps to POST /query. The first argument can be a single namespace, a list of namespaces, or ["*"] for all of them:

results = client.search(["contracts", "support_docs"], "refund policy", top_k=10)
ParameterDefaultPurpose
top_k10How many results to return
rerankTrueWhether to rerank
include_sourcesFalseWhether to return source information
filtersNoneFilter conditions

coverage_ratio, namespaces_succeeded, and namespaces_failed in results.meta tell you whether a cross-namespace query fully succeeded.

Upload documents

client.namespaces.create("contracts", display_name="Contracts")
task = client.documents.upload("contracts", "/path/to/contract.pdf")
print(task.task_id, task.status)

Uploads are processed asynchronously and return a task. Track it with client.documents.status() or client.documents.task_progress().

Async client

The async client mirrors the sync client exactly. Every resource method has an async counterpart:

import asyncio
from cortrix import AsyncCortrix

async def main():
    async with AsyncCortrix(base_url="http://127.0.0.1:8420") as client:
        return await client.search(["demo"], "semantic storage")

asyncio.run(main())

Resources

ResourceMethods
client.documentsupload, list, get, status, task_progress, cancel_task, delete
client.namespacescreate, list, get, update, delete, set_permission
client.search(...)Semantic query
client.memorysearch, log, list, create, update, delete
client.watchersadd, list, remove, events
client.systemhealth, version, namespace_stats, agent_llm_config
client.ops.gcstatus, run, restore, purge
client.import_database(...) In developmentStart a database import manually
client.tenants In developmentlist, get, invite, update_role, quota, create

Resources marked In development have no documentation yet.

Handle errors

Every exception derives from CortrixError and carries structured fields, so you can decide whether to retry or report:

from time import sleep
from cortrix import Cortrix, CortrixError, RateLimitError

client = Cortrix(base_url="http://127.0.0.1:8420")
try:
    client.documents.upload("docs", "report.pdf")
except RateLimitError as e:
    sleep((e.retry_after_ms or 1000) / 1000)
except CortrixError as e:
    if e.category == "transient" and e.retryable:
        ...  # retry
    elif e.category == "permanent":
        print(e.error_code, e.structured_data)
    else:
        raise

The SDK retries automatically using the server’s hints. To decide whether to retry, it looks at the retryable field first and then at the HTTP status code. For the wait time it uses retry_after_ms, then the Retry-After header, then exponential backoff. Adjust the number of attempts with max_retries.

Operations

Runtime and maintenance operations live under client.ops:

status = client.ops.gc.status()
client.ops.gc.restore(["doc_abc"])
Caution

client.ops.gc.run() and client.ops.gc.purge() are destructive. purge() deletes data permanently and can’t be undone.

Next steps

4 - Framework adapters

Use Cortrix from LangChain, Claude Tools, and OpenAI function calling.

On this page you’ll install cortrix-skills, call its tools directly, and turn them into tool definitions that Claude, OpenAI, or LangChain understand.

cortrix-skills provides a CortrixToolKit with 29 methods that map one-to-one to the MCP server’s regular tools, with the same names and semantics. Three adapters turn the toolkit into each framework’s native tool format, so you don’t write tool glue by hand. Admin tools are out of scope for this package.

Prerequisites

  • A running Cortrix service. See the Quickstart.
  • Python 3.9 or later, in a virtual environment.

Install

Install the package from PyPI. It brings in the Python SDK as a dependency:

pip install cortrix-skills
pip list | grep -E '^cortrix'
cortrix                   1.0.0rc2
cortrix-skills            1.0.0rc2

The framework SDKs are optional dependencies. Building Claude or OpenAI tool definitions needs no framework SDK at all, because the definitions are plain JSON. Install a framework’s package when you need it, for example pip install anthropic.

Call the tools directly

skills_check.py
from cortrix_skills import CortrixToolKit
from cortrix_skills.adapters import as_claude_tools, as_openai_functions

with CortrixToolKit(base_url="http://127.0.0.1:8420", default_namespace="demo") as kit:
    result = kit.cortrix_query(
        query="What does semantic storage keep close to the agents that need it?",
        top_k=3,
    )
    print(type(result).__name__, str(result)[:80])

    claude_tools = as_claude_tools(kit)
    print(len(claude_tools), claude_tools[0]["name"], sorted(claude_tools[0].keys()))
    print(len(as_openai_functions(kit)))
dict {'results': [{'child_id': '01M409ADX4M34WZD0EWVRYEMQJ', 'parent_id': '', 'co
29 cortrix_health ['description', 'input_schema', 'name']
29

CortrixToolKit is lazy: it makes no network request until you call a method.

ParameterDefaultDescription
base_url—Required unless you pass client
api_keyNoneA Cortrix API key
default_namespace"default"Used when a method doesn’t name a namespace
client—Pass in an existing cortrix.Cortrix client

Connect a framework

The three examples below come from cortrix-skills/README.md in the repository. They need a key for the matching LLM service, and the full round trip with a model hasn’t been tested for this page.

Claude Tools

from anthropic import Anthropic
from cortrix_skills import CortrixToolKit
from cortrix_skills.adapters import as_claude_tools
from cortrix_skills.adapters.claude import dispatch_claude_tool_use

kit = CortrixToolKit(base_url="http://127.0.0.1:8420", default_namespace="demo")
tools = as_claude_tools(kit)

client = Anthropic(api_key="your-anthropic-api-key")
resp = client.messages.create(
    model="claude-...", max_tokens=4096, tools=tools,
    messages=[{"role": "user", "content": "What does semantic storage keep close to agents?"}],
)
for block in resp.content:
    if block.type == "tool_use":
        tool_result = dispatch_claude_tool_use(kit, block)
        # append tool_result to the messages of the next messages.create(...) call

OpenAI function calling

from openai import OpenAI
from cortrix_skills import CortrixToolKit
from cortrix_skills.adapters import as_openai_functions
from cortrix_skills.adapters.openai import dispatch_openai_tool_call

kit = CortrixToolKit(base_url="http://127.0.0.1:8420", default_namespace="demo")
tools = as_openai_functions(kit)

client = OpenAI(api_key="your-openai-api-key")
resp = client.chat.completions.create(
    model="gpt-4o-mini", tools=tools,
    messages=[{"role": "user", "content": "What does semantic storage keep close to agents?"}],
)
for call in resp.choices[0].message.tool_calls or []:
    content = dispatch_openai_tool_call(kit, call)
    # content is a JSON string for a message with role "tool"

LangChain

pip install 'cortrix-skills[langchain]'
from cortrix_skills import CortrixToolKit
from cortrix_skills.adapters import as_langchain_tools

kit = CortrixToolKit(base_url="http://127.0.0.1:8420", default_namespace="demo")
tools = as_langchain_tools(kit)   # 29 StructuredTools

Error handling

Cortrix errors pass through unchanged from the Python SDK. This package adds no error codes of its own. Every error carries code, retryable, category, retry_after_ms, and structured_data, and each adapter surfaces them in its framework’s native shape:

FrameworkHow an error appears
LangChainA ToolException whose message is these fields as JSON
Claude ToolsA tool_result with is_error=True whose content is these fields as JSON
OpenAIThese fields as JSON, returned as the tool message content

An agent can use them to decide for itself whether to retry, wait, or report, without parsing free text.

Next steps

5 - Built-in Agent

Run the fixed-flow local chat service.

The built-in Agent is a FastAPI service that provides fixed-flow RAG chat over Cortrix storage. It queries cortrix-server through the public Python SDK and has no privileged channel:

Web UI chat -> Cortrix Agent (:8001) -> Python SDK -> cortrix-server (:8420)
                                    -> configured LLM provider
Note

The setup steps and interface details on this page come from cortrix-agent/README.md in the repository. The built-in Agent needs a working LLM service, and it hasn’t been tested for this page. The quickstart leaves the built-in Agent off by default.

Current scope

The built-in Agent has one mode: chat, a fixed RAG flow with no autonomous tool selection. It’s in preview.

Persisting configuration through PUT /config/agent_llm hasn’t been verified for this documentation.

Prerequisites

  • A running Cortrix service.
  • Python 3.
  • Credentials for an LLM service, for the agent_llm role.

Start the service

cd cortrix-agent
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
cp .env.example .env
.venv/bin/uvicorn main:app --port 8001 --reload

Put your LLM service configuration in .env. Keep real keys only in ignored local files such as .env, and don’t commit them.

Health check

curl http://localhost:8001/health

The expected response shape:

{
  "status": "ready",
  "cortrix_server": "unknown",
  "llm_reachable": true
}

In v1.0.0-rc.2, cortrix_server is always "unknown": this endpoint doesn’t check the Cortrix server. Use the server’s own readiness endpoint for that. If llm_reachable is false, check the LLM service configuration.

Chat interface

POST /chat streams the answer over server-sent events:

curl -N -X POST 'http://localhost:8001/chat?explain=true' \
  -H 'Content-Type: application/json' \
  -H 'X-Cortrix-Namespace: default' \
  -d '{"message": "find privacy documents", "session_id": "s-001"}'
InputLocationNotes
messageRequest bodyThe user message
session_idRequest bodyAn optional session identifier
AuthorizationHeaderAn optional Bearer token, depending on the server’s authentication mode
X-Cortrix-Tenant-IdHeaderAn optional tenant identifier
X-Cortrix-NamespaceHeaderOptional. Names the namespace
explain=trueQuery parameterReturns extra explanation metadata
debug=trueQuery parameterReturns more detail on failure

Example SSE frames:

data: {"chunk": "Based on"}
data: {"chunk": " the retrieved documents..."}
data: {"meta": {"session_id": "s-001", "chunk_ids": [], "rag_status": "success"}}
data: [DONE]

Errors come back as structured SSE error events with a code, a message, retryability, a category, an optional retry delay, and structured data.

Other endpoints

EndpointPurpose
GET /sessions/{id}Returns the recent turns a session keeps in memory
GET /configReturns the current LLM configuration with the API key masked
GET /config/providersReturns the LLM provider catalog used by the configuration UI
PUT /config/agent_llmUpdates the LLM configuration. Persisting it isn’t a verified capability yet
GET /healthReturns service status, backend reachability, and LLM reachability

Next steps

6 - pgcortrix

Call Cortrix from PostgreSQL with SQL.
In development

In development. Not supported yet.

What to do instead

Call Cortrix from your application with the HTTP API or the Python SDK.

Next steps