Library of Context
This server provides a local-first context/memory layer for AI agents, letting them shelve durable knowledge, search it, and build bounded, prompt-ready reading desks for model calls.
Persist concise books or chunked local documents with metadata, importance, collection, and shelf life (
library_shelve,library_shelve_document).Search the off-desk library by subject using hybrid ranking plus optional filters and minimum relevance (
library_consult).Manage per-session reading desks: refresh by subject, get the current snapshot, watch with periodic refresh, or stop watching (
library_desk_refresh,library_desk_get,library_desk_watch,library_desk_stop).Record conversation messages and build complete stateless model-input envelopes from recent turns plus a replacement desk (
library_message_record,library_prompt_build).Govern model calls through
prepare -> model -> commit, including protected context, release, status, and flush for durable, asynchronously indexed events (library_context_prepare,library_context_commit,library_context_protect,library_context_release,library_context_status,library_context_flush).Inspect storage-tier health, cache hit/miss counters, and embedding configuration (
library_stats).
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Library of Context Save this conversation and retrieve relevant context for my next question."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
The Library of Context
Virtual memory for artificial intelligence context: stored outside the model and size-limited inside it.
An artificial intelligence (AI) model can process only a limited amount of context in each request. Context is the information that the model receives.
A model counts text in units called tokens. Long conversations can exceed the model's token limit.
The host can remove old information or replace it with a shorter summary. The Library provides another method for calls through its context governor.
A context governor controls which stored information enters a model request. An event is one message, instruction, tool result, or other ordered item.
The governor stores each event in SQLite. SQLite is a database that stores its data in a local file.
The governor constructs a size-limited request from protected events, recent events, and retrieved records.
Think of the model context as a reading desk with limited space. The Library can hold more books than the desk.
The librarian selects only the books for the current task. A task change replaces the desk instead of adding another desk.
This project expandsaddressable context, which is stored information that the Library can retrieve. It does not change the model's context limit.
The project supports local prototypes and collaboration. It is not a production service for unrelated users or organizations.
See Capability Status for the support limits.
Why this is different from ordinary compaction
Conventional compaction replaces a growing transcript with a shorter continuation. This shorter form can omit details from the active work.
The Library uses reversible semantic paging. Semantic paging selects stored information by meaning and makes that information available to the model:
In this guide, durable means that SQLite retains the data after a process restart. A ring is an ordered memory area with a fixed capacity.
An embedder converts text into numeric representations for similarity searches. A cache keeps temporary copies of frequently used data.
traditional: growing transcript -> compacted transcript -> continue
Library: durable event log -> size-limited recent/protected context
| + relevant retrieved books
+-----------> fresh model request on every turnThe Library retains the original events for inspection and recovery. A summary can help a search without becoming the only stored copy.
The related-work landscape compares this design with other context-management methods. These methods include retrieval, prompt compression, compaction, agent memory, checkpoints, and long model contexts.
In this project, compaction means a shorter continuation that can omit details. Another storage layer must retain the originals to keep them independently retrievable.
Related MCP server: local-memory-mcp
Capabilities
A context governor that uses
prepare -> model call -> commit.SQLite storage for thread events and pending indexing tasks.
A size-limited recent ring for immediate access to newly stored events.
A size-limited work ring with SQLite recovery for excess or interrupted indexing work.
Protected context for instructions, decisions, active plans, and unresolved state.
Status positions for recorded, embedded, and indexed events.
Queue health and prompt-size status.
A new size-limited prompt envelope for each governed call.
Retrieval that combines numeric text similarity, full-text search, importance, and age.
A byte-limited cache in process random-access memory (RAM).
An optional local Redis cache for frequently used data.
Desk change reports named
swapped_in,swapped_out, andretained.Python, local Hypertext Transfer Protocol (HTTP), and command-line interface (CLI) integration.
A standard-input-and-output Model Context Protocol (MCP) server.
A built-in hashing embedder and an optional local Ollama embedder.
A recent ring retains the newest thread events. The Library can reconstruct cache data from SQLite.
The governor operates automatically when an agent gateway routes every turn through it. A gateway is software that sends requests between an agent and a model.
An MCP-only integration provides cooperative memory. The host can use storage and desk tools, but a tool cannot change the request that invoked it.
The Library does not use an undocumented internal compaction interface.
Architecture at a glance
flowchart LR
U[User or tool event] --> A[Durable SQLite append]
A --> E[(Thread event log)]
A --> O[(Pending indexing tasks)]
A --> R[Recent context ring]
O --> W[Size-limited work ring]
W --> I[Embed and index workers]
I --> S[(SQLite library and word-search index)]
I --> C[RAM and optional Redis cache]
R --> G[Context governor]
S --> G
P[Protected context] --> G
G --> D[Size-limited reading desk]
D --> M[Native model context]
M --> X[Assistant response]
X --> ALibrary metaphor | Implementation |
Reading desk | Size-limited prompt sent to the model |
Book | Public application programming interface (API) view of one |
Catalog | Stored set of searchable records and their descriptive data |
Nearby stacks | Process RAM and optional local Redis |
Shelves | Durable SQLite backing store |
Librarian | Context governor and retrieval policy |
Book cart | Size-limited ring for background work |
Checkout ledger | Durable thread event log and pending-work table |
Three terms identify the durable data models. The glossary defines other shared terms.
A context event is an ordered source item in one governed chat thread. It can contain a message, instruction, or tool result.
A context record is a searchable unit. It contains text, a numeric embedding, metadata, origin data, and a visibility scope.
A document can produce multiple context records.
A book is the public representation of one context record. The MCP and Library APIs use this term.
SQLite does not store a second book item.
Metadata describes a record, such as its source or document type. A visibility scope identifies the thread, project, or team that can retrieve it.
Indexing an event creates a record that is visible to its thread. The event preserves order and recovery state.
The record makes the event content searchable. The durable event reserves the record identifier.
A direct record write cannot replace this searchable copy.
Quick start
The default configuration requires Python 3.11 or a newer version. Redis is optional.
On Windows PowerShell:
git clone https://github.com/hwillGIT/library-of-context.git
cd library-of-context
py -3.11 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e .
.\.venv\Scripts\python.exe -m library_of_context quickstartOn macOS or Linux:
git clone https://github.com/hwillGIT/library-of-context.git
cd library-of-context
python3 -m venv .venv
.venv/bin/python -m pip install -e .
.venv/bin/python -m library_of_context quickstartThe quickstart tests protected context, prompt construction, event storage, search indexing, and cleanup. It uses a temporary database.
It does not use Redis, Docker, a cloud service, or a model API. Continue with the installation guide.
Add it to an agent you already run
Integration point | Behavior |
Existing MCP-capable agent | Provide cooperative storage, retrieval, and desk replacement |
Python or HTTP gateway that owns every model call | Control context size through |
Closed host with no MCP and no model-call hooks | No transparent integration |
See Add the Library to your agent for Codex, Python, and HTTP configuration examples.
Restart the client after you configure the MCP server. Alternatively, start a separate session.
The configuration does not affect a running chat.
How a chat maps to the Library
One chat thread has the stable identity ThreadKey(collection, session_id). Reuse the same pair for every turn in that chat.
Give each different chat a different session_id. Use a different collection for a separate project or privacy boundary.
A chat does not receive a separate SQLite database, Redis instance, cache, worker pool, or desk scheduler. One LibraryRuntime owns these process resources.
Each active chat uses a size-limited recent ring and an operation lock. It can also use a size-limited desk snapshot.
The Library removes idle thread state from RAM. It reconstructs the state from SQLite when the chat resumes.
Embedded MCP mode creates one runtime for each MCP server process. A daemon is a background process that owns shared resources.
Use the loopback daemon when several local agents must share one runtime:
agent A --thin MCP bridge--\
agent B --thin MCP bridge----> one loopback daemon -> one runtime -> one SQLite database
agent C --thin MCP bridge--/Every Library runtime takes the database owner lock before it opens SQLite. This lock permits only one runtime owner for each database.
Do not start two embedded processes for the same database. Do not combine an embedded process and a daemon for the same database.
Route all clients through one daemon instead.
The daemon accepts local loopback connections. A loopback address sends traffic only inside the local computer.
Every request requires a bearer token from a file that only the owner can read.
A bearer token is a secret value that grants access to its holder. The daemon rejects requests that originate in a browser.
The daemon has no Transport Layer Security (TLS) or authorization for individual users. Do not forward or expose its port.
See the agent integration guide for the daemon command and MCP configuration.
Run an automatically governed Python text agent
from library_of_context import GovernedTextAgent, LibraryOfContext
def call_my_model(messages: list[dict[str, str]]) -> str:
return my_model_client.generate(messages=messages)
with LibraryOfContext("data/library.sqlite", redis_url="") as library:
with library.open_context_governor(
"agent-thread-42",
token_budget=12_000,
recent_token_budget=4_000,
protected_token_budget=2_000,
) as context:
context.protect(
"Production changes require a canary wave.",
label="deployment-policy",
)
agent = GovernedTextAgent(
context,
call_my_model,
system_prompt="Work carefully and cite retrieved project evidence.",
)
response = agent.turn(
"Diagnose the deployment failure.",
turn_id="request-0001",
)
context.flush(timeout=5)
print(context.status()["watermarks"])The callback must send exactly the supplied messages. It must not append another transcript or continue a provider-managed conversation.
The built-in adapter supports text only. Structured tool calls, streams, attachments, and content with multiple media types require a custom conversion adapter.
See Context Governor for the complete protocol.
MCP integration
For a normal MCP agent, use the project-specific template in integrations/README.md. Merge the supplied agent instructions into the target project.
This configuration provides cooperative memory. It does not control the transcript that the host manages.
Run the standard-input-and-output server directly for inspection:
python -m library_of_context.mcp_server --no-redisA custom MCP gateway can use these tools when it controls every model call:
Tool | Use |
| Store the user turn and construct the size-limited next request |
| Record the assistant or tool result |
| Keep critical state available for every prompt |
| Return protected state to normal paging |
| Inspect completed event positions, queue pressure, and worker health |
| Wait until indexing reaches the recorded event position |
The Library provides storage, retrieval, reading-desk, stateless-session, and governor tools. A stateless session does not use provider-managed conversation history.
Enable gateway-only tools only in a host that sends the returned messages as the complete next model request.
Local HTTP API
python -m library_of_context --no-redis serveThe command prints the bearer-token file path. Every HTTP request must send the token as Authorization: Bearer <token>.
The default token file is <database-path>.daemon-token.
The governor endpoints are:
Method | Path | Purpose |
|
| Store the event and construct a size-limited prompt |
|
| Store an assistant response or tool result |
|
| Add protected context |
|
| Release protected context |
|
| Wait for background indexing to make records searchable |
|
| Inspect governor state and completed event positions |
The /books, /library/ingest, /catalog/query, and /desk/* routes provide lower-level Library operations. Their scope fields control thread, project, and team visibility.
The HTTP routes and Python API apply the same visibility rules. The server listens only on the local loopback address.
It authenticates local clients with one daemon bearer token. The token does not prove a user identity or team membership.
The Library treats supplied team identifiers as trusted routing data. The HTTP boundary has no TLS and rejects browser-origin requests.
Do not expose it directly to another computer.
Search and desk responses use size-limited excerpts and small record references. They omit embeddings, complete metadata, and complete book text.
Commit and protect responses acknowledge the stored event and state. They do not repeat event content or metadata.
The size-limited context field is ready for a prompt. Direct record administration routes return complete records.
Storage hierarchy
Recent ring: Store ordered events for one thread in RAM. Limit the ring by event count and estimated token count. Keep a marked, shortened RAM copy when one event exceeds the ring limit. Keep the complete event in SQLite. Apply a separate fixed limit when you construct a prompt. Preserve conversation order instead of least-recently-used order.
Process RAM: Cache frequently used books and search results within a byte limit.
Local Redis: Optionally cache books, queries, desks, and expiration times for one runtime.
SQLite: Store the required events, pending work, text, metadata, search index, and numeric vectors.
Redis contains temporary cache data. Each runtime uses a random, versioned keyspace.
A keyspace is the set of Redis keys that belong to one runtime. A restarted process starts with an empty cache.
The runtime ignores data from another runtime. The default Redis configuration is not a durable message broker.
A message broker transfers messages between independent processes. Do not use this Redis cache as the team event stream.
Free local Redis on Windows
Docker and a cloud account are not required. Windows Subsystem for Linux (WSL) runs a Linux environment on Windows.
The PowerShell installer creates the authenticated library-of-context-redis service in Ubuntu WSL. The service listens on port 6380.
The installer does not change the default Redis service in Ubuntu. It requires WSL 2 and an Ubuntu distribution.
It also requires systemd, which manages background services in Linux.
powershell -ExecutionPolicy Bypass -File .\scripts\install-local-redis.ps1
$env:LIBRARY_OF_CONTEXT_REDIS_URL = 'redis://:<password-printed-by-installer>@127.0.0.1:6380/0'
.\.venv\Scripts\python.exe -m library_of_context --db data/redis-check.sqlite doctorRun the environment assignment that the installer prints. The placeholder in the example is not a credential.
The dedicated instance uses a one-gibibyte least-frequently-used cache by default. It disables Redis persistence and keeps the required data in SQLite.
Use -MaxMemory, -Port, and -Password to override these settings.
doctor opens the configured SQLite database and checks each storage level. The example creates data/redis-check.sqlite.
Use --no-redis when SQLite and process RAM meet the workload requirements.
Performance limits
Prompt construction has a fixed size limit. A database transaction stores each event with its pending indexing task.
Full-text search returns a size-limited set of possible matches. Numeric vector retrieval compares every live record in a namespace.
Claims about large catalogs require measurements. Use a size-limited vector-search adapter when complete comparison exceeds an accepted limit.
An adapter is a component that connects the Library to an alternative search implementation.
Performance and Scaling defines measurements, service-level objectives, and benchmark questions. A service-level objective states a measurable target for system behavior.
Why These Improvements? compares alternatives and defines adoption conditions. The Roadmap identifies conditional work.
Documentation
Document | Purpose |
Invariants, tiers, consistency, and evolution | |
Primary-source comparison with adjacent context and memory approaches | |
Prepare/commit protocol and failure behavior | |
Implemented, experimental, planned, and unsupported boundaries | |
Didactic visual walkthrough | |
Measured evidence, non-functional requirements, and benchmark acceptance conditions | |
Rationale, counterarguments, alternatives, and adoption triggers | |
Local-first collaboration and promotion design | |
Milestones and open research questions | |
Required “why / why not / evidence” format for major proposals | |
Contract, migration, concurrent-operation, failure, review, and release checks | |
Required identity, visibility, ownership, and rollback rules | |
Development workflow and contribution areas | |
Threat model and vulnerability reporting |
Help shape the design
The project invites contributions to these design questions:
Which policy should protect context automatically, and who may release that context?
How should maintainers measure retrieval quality for agent threads rather than document question answering?
Which local approximate-nearest-neighbor search adapter works for 100,000 to 1,000,000 text parts?
How should branches inherit, supersede, and merge context?
Which knowledge is safe and useful to promote from a private thread to a team catalog?
Should the shared event transport use Redis Streams, NATS JetStream, or another message broker?
How should an access-control-list change remove prohibited local cache entries?
How can that removal keep cloud services outside the time-critical prompt path?
What token-pressure policy feels predictable to users across different model tokenizers?
See ROADMAP.md for more questions. Contributions can include benchmark results, design notes, adapters, failure tests, and technical criticism.
Contributing
Read CONTRIBUTING.md. Open a research question or design proposal.
Keep each pull request focused on one technical purpose. Useful contributions include reproducible retrieval benchmarks and approximate-nearest-neighbor search adapters.
A pull request proposes a set of repository changes for review. A benchmark is a repeatable measurement under a defined workload.
Other useful contributions include tokenizer integrations, privacy reviews, failure tests, and agent gateway adapters. A tokenizer divides text into model input units.
License
MIT © Library of Context contributors.
Available Tools
16 toolslibrary_consultARead-onlyIdempotent
Search the off-desk Library with hybrid vector, lexical, importance, and recency ranking without changing the reading desk.
Inputs: subject (required), max_books, collection, catalog_filters, +1 more.
library_context_commitB
Durably append the assistant or tool result after a governed model call. The outbox indexes it asynchronously while the recent ring makes it immediately visible.
Inputs: content (required), role, event_id, metadata, +8 more.
library_context_flushCIdempotent
Wait until this thread's durable outbox has been embedded and indexed through its recorded watermark.
Inputs: collection, session_id, timeout_seconds.
library_context_prepareB
Durably append a user turn, then return the complete bounded semantic-paging envelope for the next model call. Send only the returned messages to the model.
Inputs: user_message (required), focus, event_id, metadata, +10 more.
library_context_protectA
Persist critical instructions, decisions, active plans, or unresolved state as protected context that remains eligible for every governed prompt until released.
Inputs: content (required), role, label, event_id, +7 more.
library_context_releaseAIdempotent
Release one protected event so it can be paged normally. The durable event is retained.
Inputs: event_id (required), collection, session_id.
library_context_statusBRead-onlyIdempotent
Read context-governor watermarks, queue occupancy, prompt pressure, and worker health for one agent thread.
Inputs: collection, session_id.
library_desk_getARead-onlyIdempotent
Read the latest bounded reading desk snapshot for a session.
Inputs: collection, session_id.
library_desk_refreshARead-onlyIdempotent
Replace a session's bounded reading desk with books relevant to the current subject. Returns the prompt-ready context plus swapped-in, swapped-out, and retained IDs.
Inputs: subject (required), keep_open, max_books, collection, +3 more.
library_desk_stopAIdempotent
Stop periodic refresh for a reading-desk session. The current snapshot remains available.
Inputs: collection, session_id.
library_desk_watchBIdempotent
Refresh a reading desk immediately and periodically thereafter for a long-running task. A later focus change should call library_desk_refresh or start this tool again.
Inputs: subject (required), keep_open, max_books, collection, +4 more.
library_message_recordB
Shelve one conversation message for a virtual-context session. External model gateways should record assistant replies after each response.
Inputs: role (required), content (required), collection, importance, +1 more.
library_prompt_buildC
Build a complete stateless model-input envelope from bounded recent turns plus a replacement reading desk. Full history remains shelved on disk instead of growing the live prompt.
Inputs: max_books, collection, session_id, record_user, +4 more.
library_shelveA
Persist one concise book of context to the local Library. Use for durable decisions, constraints, findings, and user-approved memories—not transient chatter or secrets.
Inputs: text (required), source, book_id, catalog, +3 more.
library_shelve_documentADestructiveIdempotent
Chunk and persist a larger local text document as multiple books. Set replace_edition to replace prior chunks from the same source.
Inputs: text (required), source (required), catalog, collection, +4 more.
library_statsARead-onlyIdempotent
Inspect Library tier health, usage, cache hit/miss counters, and embedding configuration.
Inputs: collection.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 16 tools
The tools split into understandable areas (shelving, reading desk, context governor), but several pairs overlap in behavior: desk_refresh/desk_watch, context_prepare/prompt_build, and message_record/context_commit can all be confused without close reading. Descriptions mostly disambiguate them, but the boundaries are not immediately obvious from names alone.
The library_ prefix plus domain area gives a predictable feel, especially for the desk_* and context_* families. A few standalone verbs/nouns like library_shelve, library_consult, and library_stats break the noun_verb pattern, but these are minor deviations.
At 16 tools, the surface is slightly heavy and crosses the usual well-scoped range, though the three subsystems (library, desk, and context governor) explain most entries. A couple of prompt/recording tools could likely be consolidated without losing core functionality.
The context lifecycle is well covered: shelve/consult, desk refresh/get/watch/stop, and prepare/commit/protect/release/status/flush form coherent workflows. Missing direct book-level listing/removal or get-by-ID is a minor gap, but it does not create a dead end for the main use cases.
Maintenance
Related MCP Connectors
Cloud-hosted MCP server for durable AI memory
Cross-tool persistent memory and context for AI assistants over MCP.
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
One MCP server for the services your AI needs: memory, files, Microsoft 365, kanban and more.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceAn MCP server that extends AI agents' context window by providing tools to store, retrieve, and search memories, allowing agents to maintain history and context across long interactions.1MIT
- FlicenseNot gradedqualityDmaintenanceA local MCP server that provides semantic memory storage and retrieval for coding and AI agents, enabling durable context across chat sessions.39 npm4-
- AlicenseBqualityDmaintenanceMCP server providing context usage estimation, conversation compaction, and durable semantic memory via local embeddings and SQLite.179 npm3MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that provides persistent long-term memory for AI agents via local SQLite storage with low token overhead, enabling memory storage, retrieval, and management across sessions.1MIT