Skip to main content
Glama

TokenSense

CI

Persistent project memory for coding agents. TokenSense remembers what was decided in past sessions (the choice, the reasons, the alternatives ruled out) and hands it back to Claude Code, Cursor, or any MCP or OpenAI/Anthropic-compatible client when it's relevant.

Agents start every session from zero. You either re-explain last week's decisions or paste history until the context window fills up. TokenSense captures each session as a compact, searchable memory, scoped to the project you're in, and compresses long sessions so you stop paying to resend them.

What it looks like

Session 1, in Claude Code: you settle on Redis Streams over Kafka for the order pipeline and call the design ZEPHYR-7. When the session ends, a hook stores it. Session 2, days later, in a fresh process:

> get_project_context("Which message broker did we pick for the order event pipeline?")

Context from past sessions in project 'orders-service':

- Decisions made:
  - Choose Redis Streams for order event pipeline due to volume (~2k events/sec) and existing infrastructure (Redis).
  - Set retention to 72 hours with design codename ZEPHYR-7.
- Alternatives considered and rejected:
  - Kafka: Too complex, involves new cluster, monitoring overhead, and requires a dedicated team of four
  ...

Real output from the end-to-end test run (check B2; only the project name is changed), summarized by a local 3B model.

Related MCP server: memora

Results

Measured end to end against real Postgres and a real summarizer (qwen2.5:3b); only the upstream LLM is faked. Reports: e2e, crossover.

Result

End-to-end checks (capture, MCP, proxy, isolation, races)

42 / 42 pass

Recall: prior-session decision returned in a new process

Pass, including the rejected alternative (5/5 runs)

Project isolation: another project's memory ever retrieved

Never (checked at the SQL level, on every test run)

Net tokens vs. resending full history, 50-exchange session

71% fewer

Break-even

~10 exchanges; shorter sessions are forwarded untouched

Net tokens saved versus session length

Recalling memory costs tokens, and on very short sessions that cost exceeds the savings. stats reports the two separately, so neither can hide the other (decisions #13).

Quickstart (Claude Code, Cursor, any MCP client)

About five minutes, with no local Postgres and no pip install.

1. Get a free Postgres with pgvector. Neon: sign up, create a project, copy the connection string (postgresql://user:pass@ep-xxxx.region.aws.neon.tech/neondb?sslmode=require). TokenSense creates its own tables on first connect.

2. Install uv (brew install uv, or curl -LsSf https://astral.sh/uv/install.sh | sh).

3. Install Ollama and pull the embedding model (274 MB; embeddings run locally, since Anthropic has no embeddings API):

brew install ollama && brew services start ollama   # or install the app from ollama.com
ollama pull nomic-embed-text

4. Add .mcp.json to your project:

{
  "mcpServers": {
    "tokensense": {
      "command": "uvx",
      "args": ["--from", "tokensense[server] @ git+https://github.com/AayushKumbhare/tokensense", "tokensense", "serve", "--mcp"],
      "env": {
        "TOKENSENSE_DB_URL": "<your Neon connection string>",
        "ANTHROPIC_API_KEY": "<your Anthropic API key>"
      }
    }
  }
}

Restart your client. The agent now has get_project_context, save_context, end_session, switch_project and stats. Memory is scoped to the project (the git repo or folder name, or TOKENSENSE_PROJECT), so many projects can share one database. The Anthropic key is used only to summarize sessions, with Claude Haiku. It's an API key from console.anthropic.com, not your Claude Code login.

5. (Claude Code, recommended) Capture every session automatically. Add the hooks from Session capture so memory doesn't depend on the agent remembering to call end_session.

How it works

flowchart LR
    A["Claude Code / Cursor<br/>(MCP)"] --> E[TokenSense engine]
    H["Session hooks"] --> E
    P["Any OpenAI / Anthropic client<br/>(HTTP proxy)"] --> E
    E -- "summaries + embeddings" --> D[("Postgres + pgvector<br/>one project per scope")]
    D -- "relevant memory only" --> E
  • Capture: when a session ends, its conversation (not tool noise or thinking) is condensed into memory: decisions and their reasons, rejected alternatives, identifiers, open items. Small sessions are stored verbatim.

  • Recall: the query is embedded, the project's memory is searched, and only chunks that clear a calibrated relevance gate are returned.

  • Compression (proxy and SDK): long conversations keep recent turns verbatim and fold older ones into a rolling summary once they pass a token budget.

Details: docs/architecture.md. Every design choice and its evidence: docs/decisions.md.

See what your agents remember

tokensense ui opens a local page showing each project's memory: every stored session, what an agent would recall for a question and why, and a Forget button for memory that's wrong or out of date.

The memory browser showing which stored memories clear the relevance cutoff for a question

To open it on your own sessions, give it the same database URL as your .mcp.json:

TOKENSENSE_DB_URL='<the same URL as in .mcp.json>' \
  uvx --from 'tokensense[server] @ git+https://github.com/AayushKumbhare/tokensense' tokensense ui

The chart is the real retrieval: each memory placed by its similarity to the question, with the relevance cutoff as a line; only memories at or past it reach the agent. The page answers on localhost only. Full guide, including how to read each part and troubleshooting: docs/memory-browser.md.


Reference

Configuration

Every setting is an environment variable; .env.example lists them all with defaults. The ones you're most likely to change:

Variable

Default

TOKENSENSE_DB_URL

(required)

Any Postgres with pgvector

ANTHROPIC_API_KEY

For the default summarizer

TOKENSENSE_SUMMARIZATION_MODEL

claude-haiku-5-5

Any LiteLLM model

TOKENSENSE_EMBEDDING_MODEL

ollama/nomic-embed-text

After changing it, run tokensense reembed

OLLAMA_API_BASE

http://localhost:11434

Where Ollama listens

TOKENSENSE_HOST

127.0.0.1

Interface tokensense serve / ui listen on

TOKENSENSE_PROJECT

git repo / folder name

Pin the project explicitly

TOKENSENSE_WINDOW_TOKEN_BUDGET

2000

When long sessions start being compressed

Fully local, no API key, nothing leaves your machine: embeddings are already local; also summarize locally with ollama pull qwen2.5:3b (1.9 GB) and

"env": {
  "TOKENSENSE_DB_URL": "<your-db-url>",
  "TOKENSENSE_SUMMARIZATION_MODEL": "qwen2.5:3b"
}

A 3B local model drops more detail than a hosted one; benchmarks/summary_fidelity.py compares any two (decisions #12).

Changing the embedding model. Vectors from different models can't be compared, so the database records which model made them and refuses to start with another one. After changing TOKENSENSE_EMBEDDING_MODEL, run tokensense reembed once: it re-embeds all stored memory from its saved text. A model other than nomic-embed-text also needs calibrating for the relevance gate, or it uses plain top-5 retrieval.

Database

TokenSense needs a TOKENSENSE_DB_URL pointing at any Postgres with the pgvector extension available. It creates the extension, tables and indexes itself, and upgrades older schemas in place.

  • Hosted (recommended): Neon or Supabase; both support pgvector on the free tier. Neon's free tier doesn't pause on inactivity the way Supabase's does, which suits an MCP server that connects sporadically.

  • Self-hosted: cp .env.example .env, set TOKENSENSE_DB_PASSWORD, then docker compose up -d --wait (Postgres 17 + pgvector on localhost:5432). docker compose --profile server up -d --wait also runs the proxy in a container.

Sharing your instance with someone else. Don't hand out your TOKENSENSE_DB_URL: project isolation is enforced by TokenSense, not by the database, so that URL can read every project. Instead give each person their own database and role:

python scripts/create_user_database.py <your-owner-db-url> <their-name>

This prints a connection string whose role owns one new database and has no grants on yours (verified with a live permission denied test).

Upgrading from a pre-multi-project install: python scripts/migrate_add_project_id.py <db-url>.

Session capture (Claude Code hooks)

On MCP the host owns the conversation, so for reliable capture let Claude Code hand TokenSense the transcript. Add to .claude/settings.json (also in .claude/settings.json.example):

{
  "hooks": {
    "SessionEnd": [
      { "hooks": [{ "type": "command", "command": "TOKENSENSE_DB_URL=<your-db-url> ANTHROPIC_API_KEY=<your-key> uvx --from 'tokensense[server] @ git+https://github.com/AayushKumbhare/tokensense' tokensense ingest-transcript" }] }
    ],
    "PreCompact": [
      { "hooks": [{ "type": "command", "command": "TOKENSENSE_DB_URL=<your-db-url> ANTHROPIC_API_KEY=<your-key> uvx --from 'tokensense[server] @ git+https://github.com/AayushKumbhare/tokensense' tokensense ingest-transcript" }] }
    ]
  }
}

SessionEnd is the main capture point. PreCompact snapshots the session just before Claude Code compacts its context, which is exactly when memory matters most. Capture is idempotent per session (a later capture replaces the snapshot), keeps only conversation text, and always exits 0, so a capture failure never breaks Claude Code. It also works standalone: tokensense ingest-transcript <path-to-transcript.jsonl>.

If tokensense is installed on your PATH (pipx install), drop the uvx --from ... wrapper here and in .mcp.json.

HTTP proxy

For clients that aren't MCP hosts: point any OpenAI- or Anthropic-compatible client's base URL at TokenSense and it gets memory with no code changes.

export TOKENSENSE_DB_URL=<your-db-url>
uvx --from 'tokensense[server] @ git+https://github.com/AayushKumbhare/tokensense' tokensense serve   # localhost:8317
curl localhost:8317/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01" \
  -H "x-tokensense-project: my-project" -H "x-tokensense-session: my-session" \
  -d '{"model": "claude-sonnet-5", "max_tokens": 1024,
       "messages": [{"role": "user", "content": "What did we decide last session?"}]}'
  • /v1/messages (Anthropic) and /v1/chat/completions (OpenAI). Streaming and tool calls work.

  • Your API key is forwarded per request and never stored or logged.

  • The response body is the provider's, untouched. TokenSense adds X-TokenSense-Project, -Session, -Retrieved and -Tokens-Saved headers.

  • Earlier history is replaced by a compressed window; the current exchange (including tool calls and images) is forwarded exactly as sent.

  • GET /stats?project=<name> reports savings; POST /sessions/<id>/end stores a session's memory now instead of after 30 minutes idle.

Python SDK

from tokensense import TokenSenseClient

client = TokenSenseClient(provider="anthropic", api_key="...", db_url="postgresql://...")
project = client.project("react-dashboard")
project.add_document("api_spec.md")  # optional: pin a file into the session
response = project.chat(messages=[{"role": "user", "content": "Let's work on the auth flow"}])
project.end_session()  # store this session's memory
print(client.stats())

Documents added to a session ride along verbatim while the provider's prompt cache for them is live, then fall back to retrieved chunks (decisions #6).

Troubleshooting

Symptom

Fix

EmbeddingModelMismatch: This database holds N stored vectors but no record...

You're upgrading from a version that used OpenAI embeddings by default. Run tokensense reembed once (with the same TOKENSENSE_DB_URL); nothing is lost.

EmbeddingModelMismatch: This database's vectors were made with X...

Set TOKENSENSE_EMBEDDING_MODEL back to X, or run tokensense reembed to switch the database to the new model.

OllamaUnavailable: Could not embed with ollama/nomic-embed-text

Start Ollama (the app, or ollama serve) and run ollama pull nomic-embed-text. In Docker, set OLLAMA_API_BASE=http://host.docker.internal:11434.

Missing Anthropic API Key

Set ANTHROPIC_API_KEY in the same env block (or hook command) as TOKENSENSE_DB_URL.

Existing schema stores N-dim embeddings but this build expects 768

The database was created by an early build that stored 1536-dimension vectors; reembed can't change the column size. Back up what you need, drop the tables, and let TokenSense recreate them (decisions #4).

No module named 'psycopg'

You're on a build older than this fix; update. Driverless postgresql:// URLs now use the bundled psycopg2.

Neon connection fails with an SSL or "insecure connection" error

Keep ?sslmode=require on the end of the connection string.

MCP tools don't appear

Restart the client after editing .mcp.json. In Claude Code, approve the server when prompted (or check enabledMcpjsonServers).

Hook ran but get_project_context finds nothing

The hook prints session too thin to store for sessions under 2 turns. Otherwise check the hook and the MCP server use the same TOKENSENSE_DB_URL and resolve to the same project (get_project_context names the project it searched).

get_project_context returns irrelevant memory

With a non-default embedding model that hasn't been calibrated, retrieval is plain top-5. Calibrate it, or set TOKENSENSE_MIN_SIMILARITY.

Development

make setup && cp .env.example .env && make db && make check

CONTRIBUTING.md covers the test tiers, the end-to-end simulation, benchmarks and calibration. CHANGELOG.md tracks user-visible changes. MIT licensed.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Enables efficient AI workflow orchestration by chaining multi-step LLM operations while keeping intermediate results out of the context window, reducing token usage by 90%+ and supporting multiple AI providers.
      7
      1
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Persistent memory system for LLMs with lossless transcript management, enabling memory recall and full session history search across all conversations.
      1
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Virtual Infinite Context for Agents and LLMs - maintains a continuous rolling context window, surfacing relevant memories while respecting token budgets.
      6
      MIT