Skip to main content
Glama
mcp-context-window

mcp-context-window

mcp-context-window

一个为本地模型提供外部上下文缓冲区的 MCP 服务器:可持久化的会话记忆,模型可以向其中写入笔记;以及大型文档,模型可以分页浏览而无需一次性完整加载。

基于 MCP TypeScript SDK v2 构建,针对 2026-07-28 协议修订版。通过 stdio(LM Studio、Claude Desktop 或任何派生本地进程的宿主)或 Streamable HTTP 运行。


先读这个:MCP 服务器能做什么、不能做什么

没有任何 MCP 服务器能查看或修改你的上下文窗口。 MCP 严格遵循请求/响应模式——宿主调用工具,工具给出回答。服务器永远看不到对话内容,无法在消息到达模型之前拦截它们,也无法裁剪任何内容。LM Studio 在内部自行执行截断,不会就此事咨询任何服务器。

所以这不是自动滑动窗口,任何将其宣传为滑动窗口的产品都在误导你。它实际是:一个模型主动分页访问的存储区,将大部分材料保留在窗口之外,只取回所需的部分。对于 8k token 的本地模型来说,这确实非常强大——但它的生效是因为模型主动调用它,而不是因为它拦截了任何东西。

实际后果是:模型必须配合。 这里的工具描述写得具有指令性,context_guide 会返回预期的工作流程。如果你的模型忽略了这些,请在系统提示中明确说明。

一个相关说明:MCP Sampling——即允许服务器请求客户端 LLM 生成文本的机制——已在 2026-07-28 规范中弃用,官方建议"改为直接与 LLM 提供商 API 集成"。因此,本服务器自行调用 OpenAI 兼容端点。这也使其与宿主无关:同一套代码可适用于 LM Studio、Ollama、llama.cpp 或 vLLM。


Related MCP server: membot

两大部分

会话——长任务中的工作记忆

工具

用途

context_open

开始或恢复一个命名会话;显示已存储的内容

context_append

记录一个事实、决策或死胡同。固定绝不能丢失的内容

context_recall

取回最相关的条目,打包进 token 预算

context_compact

将旧条目折叠为摘要以释放预算

context_status

会话已满程度,以及是否需要压缩

context_update

固定、取消固定或删除一个条目

context_list_sessions

从之前的工作中查找会话 id

文档——太大而无法一次性阅读的材料

工具

用途

doc_ingest

加载文本或文件;分块存储,几乎不占用上下文

doc_outline

结构图:块索引、标题、大小、可选摘要

doc_search

通过关键词找到相关块并逐字返回

doc_window

按顺序读取块范围;游标自动前进

doc_summarize

总结一个范围,或整个文档

doc_list / doc_forget

管理已存储的内容

另有 context_guide,向模型解释工作流程。


快速开始

npm install
npm run build
npm test
node dist/index.js --ingest-root ./sources

或交互式探索:

npx @modelcontextprotocol/inspector node dist/index.js

LM Studio

通过 Program → Install → Edit mcp.json 编辑 ~/.lmstudio/mcp.json(Windows 上为 C:\Users\<you>\.lmstudio\mcp.json),然后重新加载 LM Studio。

{
  "mcpServers": {
    "context": {
      "command": "node",
      "args": [
        "/absolute/path/to/mcp-context-sliding/dist/index.js",
        "--ingest-root", "/absolute/path/to/your/project",
        "--budget", "4000"
      ]
    }
  }
}

这两个路径必须是绝对路径。 宿主以不可预测的工作目录将服务器作为子进程派生,因此相对路径无法解析。在命令行中,由于你控制工作目录,像 --ingest-root ./sources 这样的相对路径没有问题。

在 Windows 上,要么使用正斜杠(C:/Users/you/projects),要么将反斜杠加倍,因为单个 \ 在 JSON 字符串中是转义字符。

将 --budget 设置为模型上下文长度的大约一半。它是本服务器打包召回内容的目标值,不是 LM Studio 强制执行的限制。

--ingest-root 是让 doc_ingest 能够读取文件的配置。不设置它,服务器只接受内联文本——这是安全的默认值,因为一个仅凭模型一句话就打开任意路径的服务器是个隐患。

Docker

docker build -t mcp-context-window:latest .
{
  "mcpServers": {
    "context": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm", "--init",
        "-v", "mcp-context-data:/data",
        "-v", "/absolute/path/to/your/project:/ingest:ro",
        "-e", "CTX_INGEST_ROOTS=/ingest",
        "--add-host", "host.docker.internal:host-gateway",
        "mcp-context-window:latest", "--stdio"
      ]
    }
  }
}

这里有两个容易踩的坑:-i 是必需的,否则 JSON-RPC 握手永远不会发生;命名卷也是必需的,否则每次重启都会静默丢弃所有已存储的会话。从容器内部看,localhost 就是容器本身,因此 LLM 基础 URL 默认为 host.docker.internal。Docker 还要求 -v 绑定挂载的宿主机一侧必须是绝对路径。


会话的实际流程

context_open        session_id "refactor-auth"
context_append      "Goal: replace session cookies with JWT" (pinned)
context_append      "auth/middleware.ts:42 assumes a cookie is present"
context_append      "Decision: keep cookie support behind a flag for one release"
...
context_status      → 3200/4000 tokens — approaching budget
context_compact     → folds 14 old entries into one 380-token summary
context_recall      "cookie flag decision" → returns the pinned goal + the decision

以及一个文档:

doc_ingest      file_path "logs/build-failure.log"  → doc_kx91, 240 chunks
doc_search      "OutOfMemory"                       → 3 chunks, 1400 tokens
doc_window      from 118 to 121                     → the surrounding context

日志从未进入模型的上下文。三次有针对性的读取就完成了。


配置

标志

环境变量

默认值

含义

--data-dir <dir>

CTX_DATA_DIR

平台数据目录

状态存储位置

--ingest-root <dir>

CTX_INGEST_ROOTS

(无)

允许 doc_ingest 在此处读取文件。可重复。

--llm-base-url <url>

CTX_LLM_BASE_URL

http://localhost:1234/v1

OpenAI 兼容端点

--llm-model <id>

CTX_LLM_MODEL

(已加载的模型)

留空则使用当前已加载的模型

--llm-timeout <ms>

CTX_LLM_TIMEOUT_MS

120000

本地模型可能很慢

--no-llm

CTX_LLM_ENABLED=false

启用

仅使用抽取式摘要

--budget <n>

CTX_BUDGET

4000

默认召回/窗口预算

--chunk-tokens <n>

CTX_CHUNK_TOKENS

800

目标块大小

--chunk-overlap <n>

CTX_CHUNK_OVERLAP

80

块之间的重叠

--token-ratio <n>

CTX_TOKEN_RATIO

0.27

冷启动时每字符 token 数估算

--stdio / --http

CTX_TRANSPORT

stdio

传输方式

--host / --port

CTX_HTTP_HOST / CTX_HTTP_PORT

127.0.0.1 / 3001

HTTP 绑定

--audit / --no-audit

CTX_AUDIT

开启

每次调用在 stderr 输出 JSON 日志


设计说明

Token 计数针对你的实际模型进行校准。 不存在通用的分词器——Llama、Qwen 和 GPT 的分词方式各不相同——捆绑一个分词器会体积庞大且对你加载的模型不准确。因此服务器先进行低成本估算,再测量真实值:它向你的端点发送两个不同长度的样本,设置 max_tokens: 1,取两者报告的 usage.prompt_tokens 之间的斜率。斜率抵消了聊天模板的固定开销,得出每字符的真实边际成本。结果会被缓存,因此只有第一次运行是未校准的,而且它在后台运行,启动永远不会因模型可能尚未加载而阻塞。

估算值刻意偏高。低估会导致窗口溢出,截断这个服务器存在的意义就是要保护的上下文。

摘要功能降级而非失败。 如果端点不可达或没有加载模型,它会回退到抽取式摘要——TF-ISF 句子评分——这种方式即时、确定性,且在结构上不可能产生幻觉,因为它只能选择真实存在的句子。失去对已存储上下文的访问比得到更粗糙的摘要更糟糕。失败后客户端会短暂退避,因此 200 块的文档不会等待 200 次独立的 TCP 超时。

存储采用追加式 JSONL。 崩溃最多损坏最后一行,加载时会跳过该行而不是导致致命错误。用 tail 查看文件即可观察记忆的累积。压缩将原始条目标记为已取代而不是删除,因此即使压缩丢弃了重要内容,仍可从日志中恢复。

分块遵循文档结构,而非固定偏移——标题、段落和围栏代码块保持完整,每个块携带其所属的标题路径。只有真正大于整个块的块才会被硬切分。

检索采用 BM25 加时效性,不需要嵌入模型。这无需加载任何额外内容,不占用主模型旁边的 VRAM,而且是确定性的——当全部意义在于模型所见内容的可预测性时,这一点至关重要。标识符按整体和拆分两种方式索引,因此 getUserName 可以通过"user name"找到。

限制

  • 模型必须实际调用这些工具。没有任何自动机制。

  • 关键词搜索会漏掉嵌入模型能捕捉到的同义改写。

  • 在首次校准成功之前,token 计数只是估算值。

  • 两种传输方式均无认证;HTTP 因此绑定到回环地址。

  • doc_ingest 读取 UTF-8 文本。它不是 PDF 或 DOCX 提取器。

许可证

MIT

Available Tools

15 tools
context_appendA

Record something worth remembering into the session. Use this as you go — after discovering a fact, making a decision, or hitting a dead end — rather than trying to hold it all in your reply. Keep each entry self-contained: it may be read back much later without the surrounding conversation. Set pinned for facts that must never be dropped during compaction, such as the goal or a hard constraint.

Inputs: text (required), session_id (required), role, tags, +1 more.

context_compactA

Fold older entries into a single summary to free budget, keeping the most recent entries verbatim. Call this when context_status or context_append warns that the session is over budget. Pinned entries are never compacted. The originals are kept on disk and can be recovered, so this is safe to run. Use dry_run first to see what would happen.

Inputs: session_id (required), dry_run, keep_recent, target_tokens.

context_guideA

Explain how to use this server effectively — the intended workflow for sessions and documents. Call this once if you have not used these tools before.

Inputs: no named parameters.

context_list_sessionsA

List stored sessions, newest first. Use this to find a session id from earlier work when you do not remember it.

Inputs: no named parameters.

context_openA

Start or resume a named memory session. Call this ONCE at the beginning of any task that will run long enough to risk losing earlier details, then reuse the same session_id for every later call. Returns what is already stored, so resuming a session after a restart tells you what you previously knew.

Inputs: title, session_id.

context_recallA

Retrieve the most relevant stored entries for a query, packed to fit a token budget. This is the main way to get memory back into your working context: ask for what you need rather than reading the whole session. Pinned entries are always included. Omit the query to get the most recent entries instead.

Inputs: session_id (required), limit, query, budget_tokens.

context_statusA

Report how full a session is, what is pinned, and whether compaction is advisable. Cheap to call — use it to decide whether you need to compact before adding more.

Inputs: session_id (required).

context_updateA

Pin, unpin, or delete a single entry by its id. Pin what must survive compaction; delete what turned out to be wrong, so it stops polluting recall.

Inputs: entry_id (required), session_id (required), delete, pinned.

doc_forgetA

Permanently delete an ingested document and everything derived from it. Use when a document is stale or was ingested by mistake.

Inputs: doc_id (required).

doc_ingestA

Load a large text into the store and split it into addressable chunks. Use this INSTEAD OF reading a big file into your context: the content stays on disk and you page through it with doc_outline, doc_search and doc_window. Accepts inline text, or a file path if the server was started with an ingest root. Returns a document id.

Inputs: text, title, doc_id, file_path.

doc_listA

List ingested documents with their ids, sizes and read positions.

Inputs: no named parameters.

doc_outlineA

Show the structure of an ingested document: every chunk with its index, heading and size. Call this right after doc_ingest to decide what is worth reading. Set summarize to also generate a one-line summary per chunk — more useful, but it runs the summarizer once per chunk, so it is slow on large documents.

Inputs: doc_id (required), summarize, max_chunks.

doc_summarizeA

Summarize a whole document or a range of its chunks. Use this to get the gist of something too large to read, before deciding which parts to pull verbatim. The whole-document summary is cached, so asking again is free.

Inputs: doc_id (required), to, from, refresh, +1 more.

doc_windowA

Read a range of chunks verbatim. This is the sliding window: ask for chunks 0-2, then 3-5, and so on, keeping each read inside your budget. Omit from/to to continue from where the last window left off — the read cursor is stored server-side, so sequential paging works without you tracking position.

Inputs: doc_id (required), to, from, reset, +1 more.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.3/5.0

    Scored across 15 tools

    Disambiguation5/5

    The tools are cleanly divided into context/session memory tools and document ingestion tools, with each serving a distinct operation: append, recall, compact, status, update, ingest, outline, window, search, summarize, list, and forget. Even the two retrieval-style tools, context_recall and doc_search, are clearly scoped to different stores by their descriptions.

    Naming Consistency4/5

    All names are lowercase snake_case and consistently grouped with context_ and doc_ prefixes, mostly following a verb-action pattern. Minor deviations exist: context_status and doc_window use nouns as commands, but the overall convention is readable and predictable.

    Tool Count5/5

    At 15 tools, the server is at the upper edge of a well-scoped set, but every tool maps to a distinct and useful operation across two related subdomains. There are no redundant utilities, and the count feels justified for the stated context-window and document-management purpose.

    Completeness4/5

    The server covers the core session lifecycle (open/resume, append, recall, compact, status, update, list) and the document lifecycle (ingest, outline, read, search, summarize, list, forget). The main gap is the absence of an explicit session deletion or close tool, though agents can still work around this by leaving sessions unused.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Provides persistent session memory for AI assistants, enabling them to store, search, and retrieve conversation summaries across sessions via the Model Context Protocol.
      10
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Provides a persistent, versioned, and searchable context store for AI agents with local embedding and hybrid search.
      65 npm
      3
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides a unified context layer for Cursor's agent with lossless token savings and verifiable memory, enabling efficient code exploration and cross-session continuity.
      15 npm
      1
      MIT