RLM MCP服务器
Claude代码的递归语言模型模式——通过将大量上下文(10M+令牌)视为外部变量来处理它们。
基于:https://arxiv.org/html/2512.24601v1
用户如何互动
您不直接调用RLM工具。你让克劳德分析大文件,克劳德在幕后使用了RLM。
例子:
- 你说:“分析这个2MB的日志文件是否有错误”
- Claude在内部使用RLM工具
- 您会得到:“我发现了3种错误模式:数据库超时(47)、身份验证失败(23)……”
核心理念
与其将大量上下文直接输入LLM:
- 负载 上下文作为外部变量(不显示提示)
- 检查 程序化结构
- 块 策略性(行、字符或段落)
- 子查询 递归块
- 聚合 最终合成结果
快速开始
安装
git clone https://github.com/richardwhiteii/rlm.git
cd rlm
uv sync或者使用pip:
python -m venv .venv
source .venv/bin/activate
pip install -e .配置Claude代码
选项1:快速设置(推荐)
# From the rlm directory
claude mcp add rlm -s user -- uv run --directory "$(pwd)" python -m src.rlm_mcp_server这在全球范围内增加了RLM(-s user)因此,它在您的所有Claude Code会话中都可用。
选项2:使用Ollama(自由局部推理)
首先设置环境变量,然后添加:
export RLM_DATA_DIR="$HOME/.rlm-data"
export OLLAMA_URL="http://localhost:11434"
claude mcp add rlm -s user -- uv run --directory "$(pwd)" python -m src.rlm_mcp_server选项3:手动JSON配置
增添 ~/.claude/.mcp.json 为了实现完全控制:
{
"mcpServers": {
"rlm": {
"command": "uv",
"args": ["run", "--directory", "/path/to/rlm", "python", "-m", "src.rlm_mcp_server"],
"env": {
"RLM_DATA_DIR": "/path/to/.rlm-data",
"OLLAMA_URL": "http://localhost:11434"
}
}
}
}备注:替换/path/to/rlm使用您的实际安装路径(运行pwd在rlm目录中)。
启用自动检测
使Claude能够自动使用RLM工具,而无需手动调用:
1.CLAUDE.md集成 复制 CLAUDE.md.example 内容到您的项目 CLAUDE.md (或 ~/.claude/CLAUDE.md 用于全局)教Claude何时自动使用RLM工具。
2.吊钩安装 复制 .claude/hooks/ 在读取大于25KB的文件时,将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,而不是直接将大文件读入上下文。
工具
Claude在处理大型上下文时在内部使用这些工具。你不直接给他们打电话,你只需要让克劳德分析大文件。
| 工具 | 目的 |
|---|---|
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
对于大多数用例,Claude使用 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
对于确定性模式匹配和数据提取,Claude可以使用 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 用于过滤结果的语义分析。
提供商
默认情况下,子查询使用 克劳德·海库4.5 通过Claude Agent SDK。如果您配置了一个Claude API密钥,那么这是开箱即用的。
| 提供者 | 默认模型 | 成本 | 用例 |
|---|---|---|---|
claude-sdk | claude-haiku-4-5 | ~0.80/1M输入 | 默认,适用于所有地方 |
ollama | olmo-3.13.22b | $0 | 局部推理,需要Ollama |
递归子查询
这 rlm_sub_query 和 rlm_sub_query_batch 工具通过以下方式支持分层分解 max_depth 参数:
max_depth=0(默认):平面调用,无递归max_depth=1-5:Sub-LLM可以使用RLM工具(块、过滤器、Sub_query等)
示例:使用2级递归分析大量代码库:
rlm_sub_query(
query="Find all security vulnerabilities",
context_name="codebase",
chunk_index=0,
max_depth=2 # Allow sub-queries to further decompose
)它是如何工作的:
- 当
max_depth > 0,子LLM在其函数调用上下文中接收RLM工具 - 如果子LLM决定使用工具(例如。,
rlm_chunk_context),代理循环会处理它 - 每次递归调用都会递减深度限制,直到
max_depth达到 - 响应包括递归元数据:
depth_reached和call_trace
建议用于递归调用:使用本地模型,如 gemma3:27b 通过Ollama避免深度递归导致的成本上升。
使用Ollama(自由局部推理)
随着 奥拉玛 在本地安装后,您可以零成本运行子查询:
- 安装Ollama 并拉取一个模型:
ollama pull gemma3:27b- 添加Ollama URL 到您的MCP配置:
{
"mcpServers": {
"rlm": {
"command": "uv",
"args": ["run", "--directory", "/Users/your_username/projects/rlm", "python", "-m", "src.rlm_mcp_server"],
"env": {
"RLM_DATA_DIR": "/Users/your_username/.rlm-data",
"OLLAMA_URL": "http://localhost:11434"
}
}
}
}- 指定提供者 在子查询中:
rlm_sub_query(
query="Summarize this section",
context_name="my_doc",
chunk_index=0,
provider="ollama" # Use local Ollama instead of default claude-sdk
)或用于批量处理:
rlm_sub_query_batch(
query="Extract key points",
context_name="my_doc",
chunk_indices=[0, 1, 2, 3],
provider="ollama", # Use local Ollama instead of default claude-sdk
concurrency=4
)用法示例
基本模式
# 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
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 # uses claude-sdk by default
)
# 5. Store results for aggregation
rlm_store_result(name="topics", result=)
# 6. Retrieve all results
rlm_get_results(name="topics")分析大英百科全书(11MB)
RLM能力的旗舰示例——处理古腾堡项目的《大英百科全书》第11版:
# Load the full encyclopedia (11MB, ~2M tokens)
content = open("docs/encyclopedia/merged_encyclopedia.txt").read()
rlm_load_context(name="encyclopedia", content=content)
# Inspect
rlm_inspect_context(name="encyclopedia")
# → 11MB, 184K lines, ~2M tokens
# Chunk for processing
rlm_chunk_context(name="encyclopedia", strategy="paragraphs", size=30)
# Query across the corpus
rlm_sub_query_batch(
query="Summarize the main topics in this section",
context_name="encyclopedia",
chunk_indices=[0, 50, 100, 150],
provider="claude-sdk" # or "ollama" for free local inference
)提取主题目录:
# Filter for specific subject
rlm_filter_context(
name="encyclopedia",
output_name="botany",
pattern="(?i)(botan|plant|flora|flower|genus)",
mode="keep"
)
# Analyze filtered content
rlm_auto_analyze(
name="botany_analysis",
content=filtered_content,
goal="answer:List all botanical articles with brief descriptions"
)| 度量 | 值 |
|---|---|
| 文件大小 | 11 MB |
| 线路 | 184000 |
| 代币 | ~2M |
| 加工成本 | 0美元(奥利玛)或~1.60美元(俳句) |
数据存储
$RLM_DATA_DIR/
├── contexts/ # Raw contexts (.txt + .meta.json)
├── chunks/ # Chunked versions (by context name)
└── results/ # Stored sub-call results (.jsonl)上下文在会话中持续存在。分块上下文被缓存以供重用。
建筑
Claude Code
│
▼
RLM MCP Server
│
├─► claude-sdk (Haiku 4.5) ─► Anthropic API
│
└─► ollama ─► Local LLM (gemma3:27b, llama3, etc.)关键见解: 上下文保持在外部,而不是提示中克劳德负责编排;子模型分析。
对于贡献者:学习代码库
使用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?测试语料库:大英百科全书
该存储库包括以下内容的摘录 大英百科全书,第11版 (1910-1911)来自古腾堡项目,用于在大型参考文档上测试RLM能力。
包含的文件
| 文件 | 大小 | 描述 |
|---|---|---|
docs/encyclopedia/merged_encyclopedia.txt | 11MB | 所有切片已合并(约2M个令牌) |
用于测试
# Load the full encyclopedia
content = open("docs/encyclopedia/merged_encyclopedia.txt").read()
rlm_load_context(name="encyclopedia", content=content)
# Inspect
rlm_inspect_context(name="encyclopedia")
# → 11MB, 184K lines, ~2M tokens
# Chunk for processing
rlm_chunk_context(name="encyclopedia", strategy="paragraphs", size=30)
# Query across the corpus
rlm_sub_query_batch(
query="Summarize the main topics in this section",
context_name="encyclopedia",
chunk_indices=[0, 50, 100, 150],
provider="claude-sdk" # or "ollama" for free local inference
)示例:提取主题目录
# Filter for specific subject
rlm_filter_context(
name="encyclopedia",
output_name="botany",
pattern="(?i)(botan|plant|flora|flower|genus)",
mode="keep"
)
# Analyze filtered content
rlm_auto_analyze(
name="botany_analysis",
content=filtered_content,
goal="answer:List all botanical articles with brief descriptions"
)下载更多切片
古腾堡项目提供的其他百科全书卷:
- 搜索:https://www.gutenberg.org/ebooks/search/?query=encyclopaedia+大不列颠+11
- 约130片,覆盖A-Z
归因
大英百科全书,第11版(1910-1911)来源于 古登堡计划.公共领域。
许可证
麻省理工学院

