tokensense
Runs embeddings locally via Ollama (nomic-embed-text by default) and can also perform session summarization with a local model such as qwen2.5:3b for a fully offline, no-API-key setup.
Acts as an OpenAI-compatible HTTP proxy, injecting relevant project memory into requests and compressing long conversations (rolling summary of older turns) for any OpenAI-compatible client.
Persists memories, embeddings, and session metadata in a Postgres database with the pgvector extension, creating and upgrading its own schema and scoping memory per project.
Supported as a hosted Postgres/pgvector backend for storing project memory, alongside other hosted Postgres providers.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
TokenSense
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 |
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-text4. 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" --> ECapture: 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.

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 uiThe 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 | |
| (required) | Any Postgres with pgvector |
| For the default summarizer | |
|
| Any LiteLLM model |
|
| After changing it, run |
|
| Where Ollama listens |
|
| Interface |
| git repo / folder name | Pin the project explicitly |
|
| 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, setTOKENSENSE_DB_PASSWORD, thendocker compose up -d --wait(Postgres 17 + pgvector onlocalhost:5432).docker compose --profile server up -d --waitalso 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:8317curl 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,-Retrievedand-Tokens-Savedheaders.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>/endstores 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 |
| You're upgrading from a version that used OpenAI embeddings by default. Run |
| Set |
| Start Ollama (the app, or |
| Set |
| The database was created by an early build that stored 1536-dimension vectors; |
| You're on a build older than this fix; update. Driverless |
Neon connection fails with an SSL or "insecure connection" error | Keep |
MCP tools don't appear | Restart the client after editing |
Hook ran but | The hook prints |
| With a non-default embedding model that hasn't been calibrated, retrieval is plain top-5. Calibrate it, or set |
Development
make setup && cp .env.example .env && make db && make checkCONTRIBUTING.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…
This server cannot be deployed
Maintenance
Related MCP Connectors
Persistent memory and knowledge graphs for AI agents. Hybrid search, context checkpoints, and more.
Persistent memory layer for AI clients: store, recall, and correct context across tools.
Cross-LLM persistent memory: store context once, recall it from any AI model.
Universal memory for AI agents and tools. Save, organize and search context anywhere.
Related MCP Servers
AlicenseAqualityDmaintenanceEnables 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.71MIT- AlicenseAqualityBmaintenancePersistent memory with knowledge graph visualization, semantic/hybrid search, importance scoring, and cloud sync (S3/R2) for cross-session context management.44750MIT
- FlicenseNot gradedqualityDmaintenancePersistent memory system for LLMs with lossless transcript management, enabling memory recall and full session history search across all conversations.1-
- AlicenseNot gradedqualityDmaintenanceVirtual Infinite Context for Agents and LLMs - maintains a continuous rolling context window, surfacing relevant memories while respecting token budgets.6MIT