session-migrator
session-migrator
クロスエージェントセッション記憶移行レイヤー:ターゲットモデルのコンテキストウィンドウ容量に基づいて、会話を自動的に移行または圧縮します。
解決する問題
エージェント1で進行中の会話をエージェント2に引き継ぐ必要があるが、2つのエージェントは異なるコンテキストウィンドウを持つ異なるモデルを使用しています。ルールはシンプルです:
ターゲットモデルが会話全体を収まる場合 → そのまま移行、圧縮なし;
収まらない場合 → 最も価値のあるコンテキストのみを保持(最新メッセージ優先)。
Related MCP server: @yavdaanalytics/context-optimiser
ディレクトリ構造
session-migrator/
├── session_migrator/
│ ├── context_windows.py # model capacity mapping table (the soul)
│ ├── exporter.py # session export/serialization + token estimation
│ ├── decision.py # decision engine: compare capacity → direct/compress
│ ├── compressors.py # compressor: budget truncation, keeps latest
│ ├── storage.py # shared storage: JSON files, per-workspace isolation
│ ├── codex_adapter.py # Codex session → Session adapter
│ ├── llm_summarizer.py # LLM topic summarization (deepseek/OpenAI-compatible)
│ ├── server.py # MCP server entry (exposes migration tools)
│ └── __init__.py
├── examples/
│ ├── demo.py # full demo, zero dependencies
│ ├── codex_to_workbuddy_demo.py # Codex → memory (truncation)
│ └── llm_summarize_demo.py # Codex → memory (LLM topic summarization)
├── tests/test_core.py # core logic tests
├── pyproject.toml
├── requirements.txt
└── LICENSEクイックスタート
1. まずコアロジックを実行(依存関係ゼロ)
python examples/demo.py
python tests/test_core.pyどちらも標準ライブラリのみを使用します。インストール不要 — 「決定+圧縮+保存」がエンドツーエンドで動作するのをすぐに確認できます。
2. MCPサーバーとして実行
pip install mcp
python -m session_migrator.server3. 任意のMCPクライアントに接続
例としてClaude Codeを使用する場合、これをプロジェクトの.mcp.json(またはグローバル設定)に追加します:
{
"mcpServers": {
"session-migrator": {
"command": "python",
"args": ["-m", "session_migrator.server"]
}
}
}Cursor / Codex / WorkBuddy、またはMCP stdioをサポートする任意のクライアントでも同様に動作します。接続後、エージェントはmodel_context_window、list_known_models、migrate_sessionを呼び出すことができます。
4. LLM APIを設定(「トピック要約」にのみ必要)
Codexセッションを構造化メモリに圧縮するには、OpenAI互換のLLMが必要です。deepseek / OpenAI、または/chat/completionsと互換性のある任意のサービスで動作します — 環境変数を設定するだけです:
export DEEPSEEK_API_KEY="sk-xxx" # or OPENAI_API_KEY3つのコアMCPツールには不要です(決定/切り詰め圧縮のみを行い、LLM呼び出しはありません)。
MCPツール
ツール | 目的 |
| モデルのコンテキストウィンドウ容量を照会 |
| 組み込みモデルとその容量を一覧表示 |
| 移行を実行、決定+移行済みメッセージ+トークン前後を返す |
migrate_sessionのmessages_jsonは次のようになります:
[{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]コアコンセプト
決定エンジン decide(session, target_model)
基準は「ターゲット容量がセッションの実際のトークン数を収容できるか」であり、単に2つのモデルの容量を比較するのではありません — ターゲット容量がソースモデルより小さくても、小さなセッションはそのまま移行されます。
コンプレッサー TruncationCompressor
デフォルト実装は外部依存ゼロ:最新から遡ってメッセージ全体を保持し、収まらない以前のメッセージは省略し、先頭にプレースホルダーノート(省略数+最古メッセージのプレビュー)を挿入します。
トピック要約(Codex → メモリ)
Codexセッションを構造化メモリに移行するための完全なパイプライン(アダプター+LLM):
from session_migrator.codex_adapter import get_thread_meta, extract_rollout
from session_migrator.llm_summarizer import summarize_session
meta = get_thread_meta("your-codex-thread-id")
session = extract_rollout(meta["rollout_path"], meta["id"], meta["model"])
markdown = summarize_session(session, meta, target_chars=5000) # needs LLM key set firstLLMを使用しない切り詰め版:codex_adapter.to_memory_markdown(session, meta)。
モデル容量テーブル
session_migrator/context_windows.pyには静的マッピングテーブル(OpenAI / Anthropic / Google / 中国モデル)が同梱されています。注意:これらは静的フォールバック値であり、プロバイダーの更新に応じて変更される可能性があります。
ロードマップ
LLMトピック要約(
llm_summarizer.py、「トピック要約」を参照)動的容量取得(各プロバイダーの
/modelsAPIを呼び出し)ヘッドルーム可逆圧縮(元のテキストを復元可能)
ベクターストア検索インジェクション(オンデマンド検索)
tiktokenによる正確なトークンカウント
ライセンス
MIT
Available Tools
3 toolslist_known_modelsB
列出内置映射表里已知的模型及其容量。
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of disclosing behavior. '列出' clearly indicates a read-only listing operation with no mutation, but the description does not mention return format, whether the list is sorted, or what '容量' precisely refers to. This is acceptable for a simple list tool but not rich.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single short sentence that directly states the tool's purpose with no filler. For a zero-parameter tool, this is appropriately sized and immediately informative.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple and has no parameters, so the description covers the core purpose. However, with no output schema, no annotations, and no mention of the exact meaning of '容量' (e.g., context window size vs. model size), the description is only minimally complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has zero parameters, so the baseline is 4. The description adds no parameter details because none exist, and it appropriately focuses on what the tool returns.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific action ('列出') and a specific resource ('内置映射表里已知的模型及其容量'), so the purpose is clear. However, it does not explicitly distinguish itself from siblings like model_context_window, which may also relate to model properties.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no guidance on when to use this tool versus the sibling tools. The description implies a simple enumeration use case, but it never states conditions or alternatives, so the agent must infer when this is the right choice.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
migrate_sessionA
把一个会话从源模型迁移到目标模型。
messages_json: JSON 数组字符串,形如 [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]
返回:决策(action / reason / 容量对比)+ 迁移后的消息数组 + token 前后对比。
| Name | Required | Description | Default |
|---|---|---|---|
| session_id | No | migrated | |
| source_model | Yes | ||
| target_model | Yes | ||
| messages_json | Yes | ||
| force_compress | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the behavioral burden. It does disclose the return contract: a decision with action/reason/capacity comparison, a migrated message array, and token comparison. However, it does not state whether the original session is mutated, whether the operation is safe to re-run, or what side effects it has, which is important for a tool named 'migrate'.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact, front-loads the core purpose, and efficiently contains the message format example plus the return summary. There is no filler, repetition, or unnecessary dependency on structured fields.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With 5 parameters, 0% schema coverage, no annotations, and no output schema, the tool description is not complete enough for reliable invocation. It omits force_compress semantics, model identifier constraints, session_id purpose, and any error or edge-case behavior. The return description helps but does not fill these gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It documents messages_json with a concrete format example, but it does not explain source_model, target_model, session_id, or force_compress. In particular, force_compress is a boolean that could significantly change behavior, and the agent is given no clue about its effect.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The opening phrase '把一个会话从源模型迁移到目标模型' clearly names the verb (migrate), the resource (session/conversation), and the source-to-target relationship. It is obviously distinct from siblings model_context_window and list_known_models, so an agent can identify the tool without inspecting the schema.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The intended use is implied by the purpose: use it when a session needs to be migrated to another model. However, there is no explicit when-to-use/when-not-to-use guidance, no prerequisites or constraints (e.g., target model compatibility), and no discussion of how it relates to the sibling tools.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
model_context_windowB
查询某个模型的上下文窗口容量(token 数)。
| Name | Required | Description | Default |
|---|---|---|---|
| model | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The description indicates a read-only query operation and clarifies that the result is a token count. However, with no annotations, it does not disclose behavior for unknown models, accepted model identifier formats, or whether any special permissions are needed.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, front-loaded sentence that directly states the tool's purpose without redundancy or filler. Every word contributes to understanding.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple with one parameter and no output schema, so the description covers the core operation adequately. Still, it omits how to source valid model names and lacks any usage guidance, which are meaningful gaps for an agent deciding how to invoke it.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has no description coverage for the required 'model' parameter, and the tool description only says '某个模型' (a certain model), adding no meaningful information about valid values, format, or how to obtain model identifiers. The description fails to compensate for the missing parameter documentation.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb ('查询' / query) and a clear resource ('某个模型的上下文窗口容量' / a model's context window capacity). It is clearly distinct from sibling tools like list_known_models and migrate_session.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is given about when to use this tool versus alternatives. In particular, it does not mention that valid model names could come from list_known_models, nor does it explain when migration or listing would be more appropriate.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v0.1.0- First observed
list_known_models - First observed
migrate_session - First observed
model_context_window
TDQS
Scored across 3 tools
每个工具职责明确:一个查询具体模型容量,一个列出所有已知模型,一个执行会话迁移。三者之间没有功能重叠或模糊边界。
list_known_models和migrate_session遵循动词_名词模式,但model_context_window是名词短语,缺少动词前缀,构成轻微偏差。整体命名仍可读且可预测。
3个工具对于会话迁移这一窄领域非常合适,每个工具都服务于核心流程,没有冗余或缺失。
覆盖了迁移会话所需的全部关键操作:查看模型容量、列出已知模型、执行迁移并返回结果对比。没有明显的功能缺口。
Maintenance
Related MCP Connectors
Use AI models for chat, image, and video generation from Claude Code and other MCP hosts.
Multiple MCP tools, persistent graph memory, token-saving data pointers, and more.
Your org's AI agents, tasks, runs, search, and brain files as MCP tools and resources.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides context compression via the tokenslim engine, enabling MCP hosts to reduce token usage while preserving key information. Offers compress, retrieve, and stats tools for managing compressed content.Apache 2.0
- AlicenseNot gradedqualityBmaintenanceA context window optimizer and session rotator MCP server for agentic workflows that prevents LLMs from running out of context by compacting chat history and rotating sessions.3 npmMIT
- AlicenseAqualityDmaintenanceLets Claude Desktop, Cursor, Cline, Windsurf, Zed, or any other MCP client estimate token counts and fit a chat history into a model's context budget on demand.337 npm1MIT
- AlicenseNot gradedqualityAmaintenanceProvides MCP tools to profile and optimize LLM conversation context, identifying token waste and applying deterministic fixes to reduce context window usage.931 npm1MIT