一行要約
memory tool は client-side — Claude はファイル操作を「要求する」だけで、実際に実行するのは自分のアプリケーション。したがってパストラバーサル対策は自分の責任であり、これが最も重要な実装上の注意。
要点
The memory tool operates client-side: Claude requests file operations, and your application executes them. You control where and how the data is stored. memory tool はクライアント側で動く。Claude がファイル操作を要求し、それを実行するのはあなたのアプリケーションである。データをどこにどう保存するかはあなたが決める。
/memories はプレフィックスであって実際のパスではない — 自分のハンドラが実ストレージ(ユーザーごとのディレクトリ、DB のキーなど)にマップする。
全 Claude 4 以降のモデルで利用可能。beta header は不要。
導入は2ステップ
toolsに{"type": "memory_20250818", "name": "memory"}を追加する。これが設定のすべて —nameはmemoryでなければならず、input schema は定義しない- 各コマンドの client-side ハンドラを実装する(パス検証込みで)
API が自動的に system prompt に注入する指示(自分で送る必要はない):
IMPORTANT: ALWAYS VIEW YOUR MEMORY DIRECTORY BEFORE DOING ANYTHING ELSE.
MEMORY PROTOCOL:
1. Use the `view` command of your `memory` tool to check for earlier progress.
2. ... (work on the task) ...
- As you make progress, record status / progress / thoughts etc in your memory.
ASSUME INTERRUPTION: Your context window might be reset at any moment, so you risk losing any progress that is not recorded in your memory directory.6つのコマンド
| コマンド | 引数 | 成功時の返り値 |
|---|---|---|
view | path、view_range(任意。[start, end] / [start, -1]) | ディレクトリなら一覧、ファイルなら行番号付きの内容 |
create | path, file_text | File created successfully at: {path} |
str_replace | path, old_str, new_str(任意 — 省くと削除) | The memory file has been edited. + 編集箇所の抜粋 |
insert | path, insert_line, insert_text | The file {path} has been edited. |
delete | path | Successfully deleted {path} |
rename | old_path, new_path | Successfully renamed {old_path} to {new_path} |
view の返り値の書式(守るべき仕様):
- ディレクトリ: 2階層まで、人間可読なサイズ(
5.5K)、隠しファイルとnode_modulesを除外、サイズとパスの間はタブ - ファイル: 行番号は6文字幅・右寄せ・空白パディング・タブ区切り・1始まり
- 999,999行を超えるファイルはエラーを返す
実装時に気をつける挙動:
viewは画像ファイル(.jpg/.jpeg/.png)も表示すると Claude のツール説明に書かれているので、画像パスへのview呼び出しを想定する。16,000文字を超えるファイルはテキスト表示が切り詰められるとも書かれている- Claude のツール説明では
createは「作成または上書き」なので、既存パスへのcreate呼び出しが来る。 エラーを返すのがリファレンス実装だが、上書きも妥当な選択 str_replaceでold_strが複数回出現したらエラーにする(行番号を挙げて一意にするよう促す)/memories自体のdeleteとrenameは拒否する- 空のストアへの最初の
view /memoriesはエラーではない
セキュリティ(自分の責任)
A malicious path such as
/memories/../../secrets.envcan reach files outside the/memoriesdirectory. Your implementation must validate every path in every command./memories/../../secrets.envのような悪意あるパスは、/memoriesディレクトリの外のファイルに届きうる。実装は、すべてのコマンドのすべてのパスを検証しなければならない。
対策:
- 全パスが
/memoriesで始まることを検証する - 正規形に解決して、memory ディレクトリ内に留まることを検証する
../、..\\などのシーケンスを拒否する- URL エンコードされたトラバーサル(
%2e%2e%2f)にも注意する - 言語組み込みのパス安全ユーティリティを使う(Python の
pathlib.Path.resolve()とrelative_to())
他の3点:
- 機微情報 — Claude は通常書き込みを拒否するが、より強い保証が要るなら書き込み前に除去する検証を足す
- ファイルサイズ — 上限を設ける。
viewが返す文字数にも上限をかけ、残りはview_rangeでページングさせる - 有効期限 — 長期間アクセスされていない memory ファイルを定期的に削除する
SDK のヘルパ
| 言語 | ヘルパ |
|---|---|
| Python / C# | BetaAbstractMemoryTool を継承 |
| TypeScript | betaMemoryTool |
| Java | BetaMemoryToolHandler を実装 |
| Python / TypeScript | BetaLocalFilesystemMemoryTool(ローカルファイルシステムの既製実装) |
| Go / Ruby | ヘルパなし。tool-use ループを自分で回す |
| PHP | BetaRunnableTool でクロージャをラップ |
ヘルパと tool-runner は各 SDK の beta 名前空間にある(memory tool 自体は GA だが)。
複数セッションにわたるソフトウェア開発パターン
set up memory files deliberately instead of writing them ad hoc as work progresses. The following pattern turns memory into a recovery mechanism. 作業の進行に合わせて場当たり的に書くのではなく、意図をもって memory ファイルを構成せよ。次のパターンは、memory を復旧の仕組みに変える。
- initializer セッション — 実質的な作業の前に memory ファイルを用意する。進捗ログ(何をやったか / 次に何をするか)、機能チェックリスト(作業範囲の定義)、起動 / 初期化スクリプトへの参照
- 以降のセッション — それらを読んで始める。コードベースの再探索や過去の判断の再導出をしなくて済む
- セッション終了前 — 進捗ログを更新する
Key principle: Work on one feature at a time. Mark a feature complete only after end-to-end verification confirms it works, not when the code is written. 要点: 一度に1機能ずつ取り組め。機能を完了と印すのは、コードを書いたときではなく、エンドツーエンドの検証で動作が確認できた後だけにせよ。
そのまま使える具体例
有効化(これだけ):
message = client.messages.create(
model="claude-opus-5",
max_tokens=2048,
messages=[{"role": "user", "content": "Help me respond to this customer service ticket."}],
tools=[{"type": "memory_20250818", "name": "memory"}],
)SDK ヘルパを使う(Python):
import anthropic
from anthropic.tools import BetaLocalFilesystemMemoryTool
client = anthropic.Anthropic()
memory = BetaLocalFilesystemMemoryTool(base_path="./memory")
runner = client.beta.messages.tool_runner(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Remember that customer Acme Corp prefers email follow-ups."}],
tools=[memory],
)
final_message = runner.until_done()
print(final_message.content)view が返すべき書式:
Here're the files and directories up to 2 levels deep in /memories, excluding hidden items and node_modules:
4.0K /memories
1.5K /memories/customer_service_guidelines.xml
2.0K /memories/refund_policies.xmlHere's the content of /memories/notes.txt with line numbers:
1 Hello World
2 This is line two
10 Line ten
100 Line one hundredエラーを返す:
{
"type": "tool_result",
"tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
"content": "Error: The path /memories/notes.txt does not exist",
"is_error": true
}memory が散らかるときの追加プロンプト:
Note: when editing your memory folder, always try to keep its content up-to-date, coherent and organized. You can rename or delete files that are no longer relevant. Do not create new files unless necessary.書く内容を絞る:
Only write down information relevant to <topic> in your memory system.パス検証の骨格(Python):
from pathlib import Path
MEMORY_ROOT = Path("/memories").resolve()
def safe_path(requested: str) -> Path:
p = (MEMORY_ROOT / requested.removeprefix("/memories").lstrip("/")).resolve()
p.relative_to(MEMORY_ROOT) # ValueError if outside
return p原典で言及されている関連文書
- effective-harnesses-for-long-running-agents — multisession パターンの詳細な事例(原典が明示的に参照)
- effective-context-engineering-for-ai-agents — just-in-time retrieval
- context-editing — 消える情報を memory に退避する
- compaction — 長時間エージェントでは両方使うことが推奨されている
- memory — Claude Code 側の auto memory(同じ発想の製品実装)