海量上下文MCP
     
通过Ollama使用分块、子查询和自由局部推理处理大量上下文(1000多万个令牌)。
flowchart TD
A[Claude Code] --> B[RLM MCP Server]
B --> C{rlm_ollama_status}
C -->|cached 60s| D{provider = auto}
D -->|Ollama running| E[🦙 Ollama
gemma3:12b]
D -->|Ollama unavailable| F[☁️ Claude SDK
claude-haiku-4-5]
E --> G[["💰 $0
Free local inference"]]
F --> H[["💰 ~$0.80/1M
Cloud inference"]]
style A fill:#ff922b,color:#fff
style B fill:#339af0,color:#fff
style E fill:#51cf66,color:#fff
style F fill:#748ffc,color:#fff
style G fill:#51cf66,color:#fff
style H fill:#748ffc,color:#fff📸 Screenshots
核心理念
与其将大量上下文直接输入LLM:
- 负载 上下文作为外部变量(不显示提示)
- 检查 程序化结构
- 块 策略性(行、字符或段落)
- 子查询 递归块
- 聚合 最终合成结果
快速开始
安装
选项1:PyPI(推荐)
uvx massive-context-mcp
# or
pip install massive-context-mcp带可选附加功能:
# With Code Firewall integration (security filter for rlm_exec)
pip install massive-context-mcp[firewall]
# With Claude Agent SDK (for programmatic Claude API access)
pip install massive-context-mcp[claude]
# With all extras
pip install massive-context-mcp[firewall,claude]选项2:克劳德桌面一键
下载 .mcpb 从 发布 然后双击进行安装。
选项3:来源
git clone https://github.com/egoughnour/massive-context-mcp.git
cd massive-context-mcp
uv sync连接到克劳德代码/克劳德桌面
添加到 ~/.claude/.mcp.json (克劳德代码)或 claude_desktop_config.json (克劳德桌面):
{
"mcpServers": {
"massive-context": {
"command": "uvx",
"args": ["massive-context-mcp"],
"env": {
"RLM_DATA_DIR": "~/.rlm-data",
"OLLAMA_URL": "http://localhost:11434"
}
}
}
}工具
设置和状态工具
| 工具 | 目的 |
|---|---|
rlm_system_check | 检查系统要求 --验证macOS、苹果Silicon、16GB+RAM、Homebrew |
rlm_setup_ollama | 通过Homebrew安装 --托管服务,自动更新,需要Homebrew |
rlm_setup_ollama_direct | 直接下载安装 --没有sudo,完全无头,在锁定的机器上工作 |
rlm_ollama_status | 查看Ollama的可用性 --检测是否有可用的自由局部推理 |
分析工具
| 工具 | 目的 |
|---|---|
rlm_auto_analyze | 一步分析 --自动检测类型、块和查询 |
rlm_load_context | 将上下文作为外部变量加载 |
rlm_inspect_context | 无需加载到提示符中即可获取结构信息 |
rlm_chunk_context | 按行/字符/段落分组 |
rlm_get_chunk | 检索特定块 |
rlm_filter_context | 使用正则表达式过滤(保留/删除匹配行) |
rlm_exec | 在加载的上下文中执行Python代码(沙盒) |
rlm_sub_query | 对chunk进行子LLM调用 |
rlm_sub_query_batch | 并行处理多个块 |
rlm_store_result | 存储子调用结果以进行聚合 |
rlm_get_results | 检索存储的结果 |
rlm_list_contexts | 列出所有加载的上下文 |
快速分析 rlm_auto_analyze
对于大多数用例,只需使用 rlm_auto_analyze --它自动处理一切:
rlm_auto_analyze(
name="my_file",
content=file_content,
goal="find_bugs" # or: summarize, extract_structure, security_audit, answer:
)它自动执行的操作:
- 检测内容类型(Python、JSON、Markdown、日志、散文、代码)
- 选择最佳组块策略
- 根据内容类型调整查询
- 运行并行子查询
- 返回聚合结果
支持的目标:
| 目标 | 描述 |
|---|---|
summarize | 总结内容目的和要点 |
find_bugs | 识别错误、问题、潜在问题 |
extract_structure | 列出函数、类、模式、标题 |
security_audit | 查找漏洞和安全问题 |
answer: | 回答有关内容的自定义问题 |
程序化分析 rlm_exec
对于确定性模式匹配和数据提取,请使用 rlm_exec 直接在加载的上下文中运行Python代码。这更接近于本文的REPL方法,并提供了对分析逻辑的完全控制。
工具: rlm_exec
目的:在沙盒子进程中对加载的上下文执行任意Python代码。
参数:
code(必填):要执行的Python代码。设置result变量以捕获输出。context_name(必填):以前加载的上下文的名称。timeout(可选,默认值为30):最大执行时间(秒)。
特性:
- 上下文可用作只读
context变量 - 预导入模块:
re,json,collections - 子进程隔离(不会使服务器崩溃)
- 超时执行
- 适用于任何使用Python的系统(无需Docker)
示例——在加载的上下文中查找模式:
# After loading a context
rlm_exec(
code="""
import re
amounts = re.findall(r'\$[\d,]+', context)
result = {'count': len(amounts), 'sample': amounts[:5]}
""",
context_name="bill"
)示例响应:
{
"result": {
"count": 1247,
"sample": ["$500", "$1,000", "$250,000", "$100,000", "$50"]
},
"stdout": "",
"stderr": "",
"return_code": 0,
"timed_out": false
}示例——提取结构化数据:
rlm_exec(
code="""
import re
import json
# Find all email addresses
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', context)
# Count by domain
from collections import Counter
domains = [e.split('@')[1] for e in emails]
domain_counts = Counter(domains)
result = {
'total_emails': len(emails),
'unique_domains': len(domain_counts),
'top_domains': domain_counts.most_common(5)
}
""",
context_name="dataset",
timeout=60
)何时使用 rlm_exec 对比 rlm_sub_query:
| 用例 | 工具 | 为什么 |
|---|---|---|
| 提取所有日期、ID、金额 | rlm_exec | 正则表达式具有确定性和快速性 |
| 查找安全漏洞 | rlm_sub_query | 需要推理和上下文 |
| 解析JSON/XML结构 | rlm_exec | 标准库完美运行 |
| 总结主题或基调 | rlm_sub_query | 需要自然语言理解 |
| 统计单词频率 | rlm_exec | 计算简单,无需人工智能 |
| 回答“X为什么会发生?” | rlm_sub_query | 需要推理和推理 |
小贴士:对于大型上下文,将两者结合使用 rlm_exec 过滤/提取,然后 rlm_sub_query 用于过滤结果的语义分析。
代码防火墙集成(可选)
为了增强安全性,请集成 代码防火墙mcp 在执行之前过滤危险的代码模式:
pip install massive-context-mcp[firewall]当安装时, rlm_exec 可以根据已知危险模式的黑名单自动检查代码(例如。, os.system(), eval(), subprocess 随着 shell=True).防火墙使用结构相似性匹配——将代码规范化为骨架,并通过嵌入与黑名单模式进行比较。
它是如何工作的:
- 代码被解析为语法树并规范化(标识符→
_,字符串→"S") - 通过Ollama嵌入标准化结构
- 根据ChromaDB中的黑名单模式检查相似性
- 如果相似性超过阈值(默认值:0.85),代码将被阻止
配置 (环境变量):
RLM_FIREWALL_ENABLED=true--启用防火墙检查(安装软件包时自动启用)RLM_FIREWALL_MODE=warn|block--在匹配时发出警告或阻止(默认值:warn)
阻塞模式示例:
os.system(user_input)--命令注入eval(untrusted_data)--代码注入subprocess.Popen(..., shell=True)--壳体注射
使用 rlm_firewall_status 检查防火墙的可用性和配置。
供应商和自动检测
RLM会自动检测并使用最佳可用提供商:
| 提供者 | 默认模型 | 成本 | 用例 |
|---|---|---|---|
auto | (最佳可用) | 0美元或约0.80/100万美元 | 默认 --如果有机会,更喜欢Ollama |
ollama | gemma3:12b | $0 | 局部推理,需要Ollama |
claude-sdk | claude-haiku-4-5 | ~0.80/1M输入 | 云推理,始终可用 |
自动检测的工作原理
当你使用 provider="auto" (默认),RLM:
- 检查Ollama是否正在运行 在
OLLAMA_URL(默认值:http://localhost:11434) - 检查gemma3:12b是否可用 (或任何gemma3变体)
- 如果可用,使用Olama,否则退回到Claude SDK
状态将缓存60秒,以避免重复的网络检查。
检查Ollama状态
使用 rlm_ollama_status 查看可用内容:
rlm_ollama_status()Ollama准备就绪时的响应:
{
"running": true,
"models": ["gemma3:12b", "llama3:8b"],
"default_model_available": true,
"best_provider": "ollama",
"recommendation": "Ollama is ready! Sub-queries will use free local inference by default."
}Ollama不可用时的响应:
{
"running": false,
"error": "connection_refused",
"best_provider": "claude-sdk",
"recommendation": "Ollama not available. Sub-queries will use Claude API. To enable free local inference, install Ollama and run: ollama serve"
}透明提供商选择
所有子查询响应都包括实际使用的提供程序:
{
"provider": "ollama",
"model": "gemma3:12b",
"requested_provider": "auto",
"response": "..."
}自主使用
使Claude能够自动使用RLM工具,而无需手动调用:
1.CLAUDE.md集成 复制 CLAUDE.md.example 内容到您的项目 CLAUDE.md (或 ~/.claude/CLAUDE.md 用于全局)教Claude何时自动使用RLM工具。
2.吊钩安装 复制 .claude/hooks/ 在读取大于10KB的文件时,将RLM自动建议到项目的目录:
cp -r .claude/hooks/ /Users/your_username/your-project/.claude/hooks/钩子提供指导,但不会阻止读取。
3.技能参考 复制 .claude/skills/ RLM综合指南目录:
cp -r .claude/skills/ /Users/your_username/your-project/.claude/skills/有了这些,Claude将自动检测何时使用RLM,而不是直接将大文件读入上下文。
设置Ollama(自由局部推理)
RLM可以使用Apple Silicon在macOS上自动安装和配置Ollama。有 两种安装方法 有不同的权衡:
选择安装方法
| 方面 | rlm_setup_ollama (自制) | rlm_setup_ollama_direct (直接下载) |
|---|---|---|
| Sudo必填 | 仅当未安装Homebrew时 | ❌ 从来没有 |
| 需要自制 | ✅ 是 | ❌ 没有 |
| 自动更新 | ✅ 是的(brew upgrade) | ❌ 手册 |
| 服务管理 | ✅ brew services (launchd) | ⚠️ ollama serve (前景) |
| 安装位置 | /opt/homebrew/ | ~/Applications/ |
| 锁定机器 | ⚠️ 可能失败 | ✅ 作品 |
| 完全无头 | ⚠️ 可能会提示使用sudo | ✅ 是的 |
建议:
- 使用 自制法 如果您有Homebrew并希望进行托管更新
- 使用 直接下载 用于自动化、锁定机器或当您没有管理员权限时
方法1:Homebrew安装(如果您有Homebrew,建议使用)
# 1. Check if your system meets requirements
rlm_system_check()
# 2. Install via Homebrew
rlm_setup_ollama(install=True, start_service=True, pull_model=True)这有什么作用:
- 通过Homebrew安装Ollama(
brew install ollama) - 启动Ollama作为托管后台服务(
brew services start ollama) - 拉动gemma3:12b型号(约8GB下载)
要求:
- 带苹果硅(M1/M2/M3/M4)的macOS
- 16GB+内存(gemma3:12b需要~8GB才能运行)
- Homebrew已安装
方法2:直接下载(完全无头,无Sudo)
# 1. Check system (Homebrew NOT required for this method)
rlm_system_check()
# 2. Install via direct download - no sudo, no Homebrew
rlm_setup_ollama_direct(install=True, start_service=True, pull_model=True)这有什么作用:
- 下载Ollamahttps://ollama.com/download/Ollama-darwin.zip
- 摘录至
~/Applications/Ollama.app(用户目录,无需管理员) - 从奥拉玛出发
ollama serve(后台进程) - 拉宝石3:12b模型
要求:
- 带苹果硅(M1/M2/M3/M4)的macOS
- 16GB+内存
- 无需特殊权限!
关于PATH的注释: 直接安装后,CLI位于:
~/Applications/Ollama.app/Contents/Resources/ollama如果需要,添加到shell配置中:
export PATH="$HOME/Applications/Ollama.app/Contents/Resources:$PATH"适用于RAM较少的系统
在以下任一安装方法上使用较小的型号:
rlm_setup_ollama(install=True, start_service=True, pull_model=True, model="gemma3:4b")
# or
rlm_setup_ollama_direct(install=True, start_service=True, pull_model=True, model="gemma3:4b")手动设置
如果您更喜欢手动安装或使用其他平台:
- 安装Ollama 从https://ollama.ai或通过Homebrew:
brew install ollama- 启动服务:
brew services start ollama
# or: ollama serve- 拉动模型:
ollama pull gemma3:12b- 验证它是否正常工作:
rlm_ollama_status()提供者选择
RLM在可用时自动使用Ollama。您还可以强制特定的提供者:
# Auto-detection (default) - uses Ollama if available
rlm_sub_query(query="Summarize", context_name="doc")
# Explicitly use Ollama
rlm_sub_query(query="Summarize", context_name="doc", provider="ollama")
# Explicitly use Claude SDK
rlm_sub_query(query="Summarize", context_name="doc", provider="claude-sdk")用法示例
基本模式
# 0. (Optional) First-time setup on macOS - choose ONE method:
# Option A: Homebrew (if you have it)
rlm_system_check()
rlm_setup_ollama(install=True, start_service=True, pull_model=True)
# Option B: Direct download (no sudo, fully headless)
rlm_system_check()
rlm_setup_ollama_direct(install=True, start_service=True, pull_model=True)
# 0b. (Optional) Check if Ollama is available for free inference
rlm_ollama_status()
# 1. Load a large document
rlm_load_context(name="report", content=)
# 2. Inspect structure
rlm_inspect_context(name="report", preview_chars=500)
# 3. Chunk into manageable pieces
rlm_chunk_context(name="report", strategy="paragraphs", size=1)
# 4. Sub-query chunks in parallel (auto-uses Ollama if available)
rlm_sub_query_batch(
query="What is the main topic? Reply in one sentence.",
context_name="report",
chunk_indices=[0, 1, 2, 3],
concurrency=4
)
# 5. Store results for aggregation
rlm_store_result(name="topics", result=)
# 6. Retrieve all results
rlm_get_results(name="topics")处理2MB文档
使用H.R.1 Bill(2MB)进行测试:
# Load
rlm_load_context(name="bill", content=)
# Chunk into 40 pieces (50K chars each)
rlm_chunk_context(name="bill", strategy="chars", size=50000)
# Sample 8 chunks (20%) with parallel queries
# (auto-uses Ollama if running, otherwise Claude SDK)
rlm_sub_query_batch(
query="What topics does this section cover?",
context_name="bill",
chunk_indices=[0, 5, 10, 15, 20, 25, 30, 35],
concurrency=4
)结果:综合主题提取成本为0美元(使用Ollama)或约0.02美元(使用Claude)。
战争与和平分析(3.3MB)
从古腾堡计划看托尔斯泰史诗小说的文学分析:
# Download the text
curl -o war_and_peace.txt https://www.gutenberg.org/files/2600/2600-0.txt# Load into RLM (3.3MB, 66K lines)
rlm_load_context(name="war_and_peace", content=open("war_and_peace.txt").read())
# Chunk by lines (1000 lines per chunk = 67 chunks)
rlm_chunk_context(name="war_and_peace", strategy="lines", size=1000)
# Sample 10 chunks evenly across the book (15% coverage)
sample_indices = [0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
# Extract characters from each sampled section
rlm_sub_query_batch(
query="List major characters in this section with brief descriptions.",
context_name="war_and_peace",
chunk_indices=sample_indices,
provider="claude-sdk", # Haiku 4.5
concurrency=8
)结果:小说中完整的人物弧线——皮埃尔从理想主义者到囚犯再到丈夫的旅程,娜塔莎的成长,尼科拉·罗斯托夫从士兵到地主的旅程——全部花费约0.03美元。
| 度量 | 值 |
|---|---|
| 文件大小 | 3.35 MB |
| 线路 | 66033 |
| 大块 | 67 |
| 采样 | 10(15%) |
| 成本 | ~0.03美元 |
数据存储
graph TD
A[("$RLM_DATA_DIR")] --> B["📁 contexts/"]
A --> C["📁 chunks/"]
A --> D["📁 results/"]
B --> B1[".txt files"]
B --> B2[".meta.json"]
C --> C1["by context name"]
D --> D1[".jsonl files"]
style A fill:#339af0,color:#fff
style B fill:#51cf66,color:#fff
style C fill:#51cf66,color:#fff
style D fill:#51cf66,color:#fff上下文在会话中持续存在。分块上下文被缓存以供重用。
学习提示
使用Claude Code的这些提示来探索代码库并学习RLM模式。代码是唯一的真理来源。
了解工具
Read src/rlm_mcp_server.py and list all RLM tools with their parameters and purpose.Explain the chunking strategies available in rlm_chunk_context.
When would I use each one?What's the difference between rlm_sub_query and rlm_sub_query_batch?
Show me the implementation.理解架构
Read src/rlm_mcp_server.py and explain how contexts are stored and persisted.
Where does the data live?How does the claude-sdk provider extract text from responses?
Walk me through _call_claude_sdk.What happens when I call rlm_load_context? Trace the full flow.动手学习
Load the README as a context, chunk it by paragraphs,
and run a sub-query on the first chunk to summarize it.Show me how to process a large file in parallel using rlm_sub_query_batch.
Use a real example.I have a 1MB log file. Walk me through the RLM pattern to extract all errors.扩展RLM
Read the test file and explain what scenarios are covered.
What edge cases should I be aware of?How would I add a new chunking strategy (e.g., by regex delimiter)?
Show me where to modify the code.How would I add a new provider (e.g., OpenAI)?
What functions need to change?许可证
麻省理工学院
