---
title: 記憶工具
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool
description: 透過在您的應用程式中實作記憶工具的檔案操作，讓 Claude 能夠跨對話儲存和擷取資訊。
---

「memory tool」（記憶工具）讓 Claude 能夠在記憶檔案目錄中跨對話儲存和擷取資訊。Claude 可以建立、讀取、更新和刪除在工作階段之間持續保存的檔案，隨著時間累積知識，而不必將所有內容都保留在「context window」（上下文視窗）中。

記憶支援「just-in-time context retrieval」（即時上下文擷取）。代理不會預先載入所有相關資訊，而是將學到的內容記錄在記憶檔案中，並在需要時讀回。這能讓作用中的上下文專注於目前的任務，對於長時間執行、否則會塞滿上下文視窗的工作階段而言尤其重要。如需了解更廣泛的模式，請參閱[有效的上下文工程](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents)。

記憶工具在用戶端運作：Claude 請求檔案操作，由您的應用程式執行這些操作。您可以透過自己的基礎架構控制資料的儲存位置和方式。

<Note>
  請透過[意見回饋表單](https://forms.gle/YXC2EKGMhjN1c4L88)分享您對此功能的意見。
</Note>

<Note>
  若要了解「zero data retention」（零資料保留），即 ZDR 如何適用於此功能，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。
</Note>

## 使用案例

* 在多個代理工作階段之間維持專案上下文
* 將過去互動、決策和回饋中學到的經驗應用於新任務
* 隨著時間建立知識庫

## 運作方式

啟用記憶工具後，Claude 會在開始任務前自動檢查其記憶目錄。在工作過程中，Claude 會將學到的內容儲存在 `/memories` 下的檔案中，並在之後的對話中讀回這些檔案，以延續先前的工作。

由於記憶工具在用戶端運作，Claude 只會請求記憶操作。您的應用程式會針對您所控制的儲存空間執行每個請求，並在 `tool_result` 區塊中傳回結果（請參閱[處理工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls)）。`/memories` 路徑是一個前綴，由您的處理程式對應到實際的儲存空間，例如每位使用者專屬的目錄或資料庫中的鍵。記憶完全存在於您的應用程式中。當後續對話傳送相同的 `tools` 項目，且您的處理程式提供相同的儲存區時，該對話就會從相同的記憶繼續。為了安全起見，請將所有記憶操作限制在 `/memories` 目錄內（請參閱[路徑遍歷防護](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool#path-traversal-protection)）。

### 範例：記憶工具呼叫的運作方式

典型的互動如下所示：

**1. 使用者請求：**

```text wrap
"Help me respond to this customer service ticket."
```

**2. Claude 檢查記憶目錄：**

```text wrap
"I'll help you respond to the customer service ticket. Let me check my memory for any previous context."
```

Claude 呼叫記憶工具：

```json
{
  "type": "tool_use",
  "id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "name": "memory",
  "input": {
    "command": "view",
    "path": "/memories"
  }
}
```

**3. 您的應用程式傳回目錄內容：**

```json
{
  "type": "tool_result",
  "tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "content": "Here're the files and directories up to 2 levels deep in /memories, excluding hidden items and node_modules:\n4.0K\t/memories\n1.5K\t/memories/customer_service_guidelines.xml\n2.0K\t/memories/refund_policies.xml"
}
```

**4. Claude 讀取相關檔案：**

```json
{
  "type": "tool_use",
  "id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5",
  "name": "memory",
  "input": {
    "command": "view",
    "path": "/memories/customer_service_guidelines.xml"
  }
}
```

**5. 您的應用程式傳回檔案內容：**

```json
{
  "type": "tool_result",
  "tool_use_id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5",
  "content": "Here's the content of /memories/customer_service_guidelines.xml with line numbers:\n     1\t<guidelines>\n     2\t<addressing_customers>\n     3\t- Always address customers by their first name\n     4\t- Use empathetic language\n..."
}
```

**6. Claude 運用記憶提供協助：**

```text wrap
"Based on your customer service guidelines, I can help you craft a response. Please share the ticket details..."
```

記憶工具適用於所有 Claude 4 及更新的模型。如需 Anthropic 提供之工具的完整清單，請參閱[工具參考](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference)。

## 開始使用

使用記憶工具需要兩個步驟：

1. 將記憶工具加入您的請求中。`tools` 項目 `{"type": "memory_20250818", "name": "memory"}` 就是完整的設定：`name` 必須是 `memory`，而且您不需要為 Anthropic 提供的工具定義輸入結構描述。
2. 為每個記憶命令實作用戶端處理程式。您的處理程式必須拒絕 `/memories` 以外的路徑，因此在撰寫之前，請先閱讀[路徑遍歷防護](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool#path-traversal-protection)。

## 基本用法

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 2048,
      "messages": [
        {
          "role": "user",
          "content": "Help me respond to this customer service ticket."
        }
      ],
      "tools": [{
        "type": "memory_20250818",
        "name": "memory"
      }]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 2048
  tools:
    - type: memory_20250818
      name: memory
  messages:
    - role: user
      content: Help me respond to this customer service ticket.
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  message = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=2048,
      messages=[
          {
              "role": "user",
              "content": "Help me respond to this customer service ticket.",
          }
      ],
      tools=[{"type": "memory_20250818", "name": "memory"}],
  )

  print(message)
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic();

  const message = await anthropic.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 2048,
    messages: [
      {
        role: "user",
        content: "Help me respond to this customer service ticket."
      }
    ],
    tools: [{ type: "memory_20250818", name: "memory" }]
  });

  console.log(message);
  ```

  ```csharp C#
  var client = new AnthropicClient();

  var message = await client.Messages.Create(
      new()
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 2048,
          Messages =
          [
              new()
              {
                  Role = Role.User,
                  Content = "Help me respond to this customer service ticket.",
              },
          ],
          Tools = [new MemoryTool20250818()],
      }
  );

  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 2048,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Help me respond to this customer service ticket.")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfMemoryTool20250818: &anthropic.MemoryTool20250818Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(message)
  ```

  ```java Java
  import com.anthropic.models.messages.MemoryTool20250818;
  // ...
    AnthropicClient client = AnthropicOkHttpClient.fromEnv();

    MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(2048L)
      .addTool(MemoryTool20250818.builder().build())
      .addUserMessage("Help me respond to this customer service ticket.")
      .build();

    Message message = client.messages().create(params);
    IO.println(message);
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 2048,
      messages: [
          [
              'role' => 'user',
              'content' => 'Help me respond to this customer service ticket.',
          ],
      ],
      tools: [new MemoryTool20250818],
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 2048,
    messages: [
      {
        role: "user",
        content: "Help me respond to this customer service ticket."
      }
    ],
    tools: [
      {
        type: "memory_20250818",
        name: "memory"
      }
    ]
  )
  puts message
  ```
</CodeGroup>

## 實作記憶處理程式

Claude 對類似上述請求的回覆，會以一個請求記憶操作（例如 `view /memories`）的 `tool_use` 區塊結尾。您的應用程式執行該操作，並在 `tool_result` 區塊中傳回結果，然後將對話送回，讓 Claude 繼續進行：這就是標準的[工具使用迴圈](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls)。

有四個 SDK 提供記憶工具輔助程式，可處理工具介面和迴圈。您可以繼承 `BetaAbstractMemoryTool`（Python 和 C#）、使用 `betaMemoryTool`（TypeScript），或實作 `BetaMemoryToolHandler`（Java），以您自己的儲存空間作為記憶的後端，例如磁碟上的檔案、資料庫、雲端儲存空間或加密檔案。Python 和 TypeScript 也提供現成的本機檔案系統實作 `BetaLocalFilesystemMemoryTool`。即使記憶工具本身不需要 beta 標頭，輔助程式和工具執行器介面仍位於您 SDK 的 beta 命名空間中。Go 和 Ruby SDK 沒有記憶輔助程式，因此這些範例會自行執行工具使用迴圈，而 PHP 則將您的處理程式閉包包裝在其通用的 `BetaRunnableTool` 中。這三者都使用記憶體內儲存區，您可以將其替換為自己的儲存空間。

<CodeGroup exclude="shell">
  ```python 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-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)
  ```

  ```typescript TypeScript
  import Anthropic from "@anthropic-ai/sdk";
  import { betaMemoryTool } from "@anthropic-ai/sdk/helpers/beta/memory";
  import { BetaLocalFilesystemMemoryTool } from "@anthropic-ai/sdk/tools/memory/node";

  const client = new Anthropic();

  const backend = await BetaLocalFilesystemMemoryTool.init("./memory");
  const memory = betaMemoryTool(backend); // or pass your own handlers object

  const runner = client.beta.messages.toolRunner({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: "Remember that customer Acme Corp prefers email follow-ups."
      }
    ],
    tools: [memory],
    max_iterations: 10
  });

  const finalMessage = await runner;
  console.log(finalMessage.content);
  ```

  ```csharp C#
  using Anthropic;
  using Anthropic.Helpers.Beta;
  using Anthropic.Models.Beta.Messages;

  var client = new AnthropicClient();

  // 您的 BetaAbstractMemoryTool 子類別
  var memory = new FilesystemMemoryTool("./memories");

  var runner = client.Beta.Messages.ToolRunner(
      new MessageCreateParams
      {
          Model = Anthropic.Models.Messages.Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Messages =
          [
              new()
              {
                  Role = Role.User,
                  Content = "Remember that customer Acme Corp prefers email follow-ups.",
              },
          ],
      },
      [memory],
      maxIterations: 10
  );

  var finalMessage = await runner.RunUntilDoneAsync();
  Console.WriteLine(finalMessage);
  ```

  ```go Go
  package main

  import (
  	"context"
  	"encoding/json"
  	"fmt"
  	"log"
  	"slices"
  	"sort"
  	"strings"

  	"github.com/anthropics/anthropic-sdk-go"
  )

  // 一個記憶體內的儲存區，將記憶檔案路徑對應至其內容。
  // 在正式環境中，請使用您自己的儲存機制。
  var store = map[string]string{}

  type memoryCommand struct {
  	Command    string `json:"command"`
  	Path       string `json:"path"`
  	FileText   string `json:"file_text"`
  	OldStr     string `json:"old_str"`
  	NewStr     string `json:"new_str"`
  	InsertLine int    `json:"insert_line"`
  	InsertText string `json:"insert_text"`
  	OldPath    string `json:"old_path"`
  	NewPath    string `json:"new_path"`
  }

  func executeMemory(raw json.RawMessage) string {
  	var cmd memoryCommand
  	if err := json.Unmarshal(raw, &cmd); err != nil {
  		return "Error: invalid memory command"
  	}
  	switch cmd.Command {
  	case "view":
  		if content, ok := store[cmd.Path]; ok {
  			lines := strings.Split(strings.TrimSuffix(content, "\n"), "\n")
  			for i, line := range lines {
  				lines[i] = fmt.Sprintf("%6d\t%s", i+1, line)
  			}
  			return fmt.Sprintf("Here's the content of %s with line numbers:\n%s", cmd.Path, strings.Join(lines, "\n"))
  		}
  		if cmd.Path == "/memories" {
  			listing := []string{"1.0K\t/memories"}
  			for path := range store {
  				listing = append(listing, "1.0K\t"+path)
  			}
  			sort.Strings(listing[1:])
  			return fmt.Sprintf("Here're the files and directories up to 2 levels deep in %s, excluding hidden items and node_modules:\n%s", cmd.Path, strings.Join(listing, "\n"))
  		}
  		return fmt.Sprintf("The path %s does not exist. Please provide a valid path.", cmd.Path)
  	case "create":
  		store[cmd.Path] = cmd.FileText
  		return "File created successfully at: " + cmd.Path
  	case "str_replace":
  		content, ok := store[cmd.Path]
  		if !ok || !strings.Contains(content, cmd.OldStr) {
  			return fmt.Sprintf("No replacement was performed, old_str `%s` did not appear verbatim in %s.", cmd.OldStr, cmd.Path)
  		}
  		store[cmd.Path] = strings.Replace(content, cmd.OldStr, cmd.NewStr, 1)
  		return "The memory file has been edited."
  	case "insert":
  		content, ok := store[cmd.Path]
  		if !ok {
  			return fmt.Sprintf("Error: The path %s does not exist", cmd.Path)
  		}
  		lines := strings.Split(content, "\n")
  		if cmd.InsertLine < 0 || cmd.InsertLine > len(lines) {
  			return fmt.Sprintf("Error: Invalid `insert_line` parameter: %d. It should be within the range of lines of the file: [0, %d]", cmd.InsertLine, len(lines))
  		}
  		lines = slices.Insert(lines, cmd.InsertLine, strings.TrimSuffix(cmd.InsertText, "\n"))
  		store[cmd.Path] = strings.Join(lines, "\n")
  		return fmt.Sprintf("The file %s has been edited.", cmd.Path)
  	case "delete":
  		if _, ok := store[cmd.Path]; !ok {
  			return fmt.Sprintf("Error: The path %s does not exist", cmd.Path)
  		}
  		delete(store, cmd.Path)
  		return "Successfully deleted " + cmd.Path
  	case "rename":
  		if _, ok := store[cmd.OldPath]; !ok {
  			return fmt.Sprintf("Error: The path %s does not exist", cmd.OldPath)
  		}
  		if _, ok := store[cmd.NewPath]; ok {
  			return fmt.Sprintf("Error: The destination %s already exists", cmd.NewPath)
  		}
  		store[cmd.NewPath] = store[cmd.OldPath]
  		delete(store, cmd.OldPath)
  		return fmt.Sprintf("Successfully renamed %s to %s", cmd.OldPath, cmd.NewPath)
  	default:
  		return "Error: unknown command " + cmd.Command
  	}
  }

  func main() {
  	client := anthropic.NewClient()
  	tools := []anthropic.ToolUnionParam{{OfMemoryTool20250818: &anthropic.MemoryTool20250818Param{}}}
  	messages := []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Remember that customer Acme Corp prefers email follow-ups.")),
  	}

  	for {
  		message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  			Model:     anthropic.ModelClaudeOpus5_5,
  			MaxTokens: 1024,
  			Messages:  messages,
  			Tools:     tools,
  		})
  		if err != nil {
  			log.Fatal(err)
  		}
  		if message.StopReason != anthropic.StopReasonToolUse {
  			for _, block := range message.Content {
  				if block.Type == "text" {
  					fmt.Println(block.Text)
  				}
  			}
  			break
  		}
  		results := []anthropic.ContentBlockParamUnion{}
  		for _, block := range message.Content {
  			if block.Type == "tool_use" {
  				results = append(results, anthropic.NewToolResultBlock(block.ID, executeMemory(block.Input), false))
  			}
  		}
  		messages = append(messages, message.ToParam(), anthropic.NewUserMessage(results...))
  	}
  }
  ```

  ```java Java
  import com.anthropic.client.AnthropicClient;
  import com.anthropic.client.okhttp.AnthropicOkHttpClient;
  import com.anthropic.helpers.BetaMemoryToolHandler;
  import com.anthropic.helpers.BetaToolRunner;
  import com.anthropic.models.beta.messages.BetaMemoryTool20250818;
  import com.anthropic.models.beta.messages.BetaMessage;
  import com.anthropic.models.beta.messages.MessageCreateParams; // beta package, not models.messages
  import com.anthropic.models.beta.messages.ToolRunnerCreateParams;
  import com.anthropic.models.messages.Model;
  import java.nio.file.Path;

  void main() {
    AnthropicClient client = AnthropicOkHttpClient.fromEnv();

    // 您的 BetaMemoryToolHandler 實作，涵蓋六個記憶體指令
    BetaMemoryToolHandler handler = new FileSystemMemoryToolHandler(Path.of("memories"));

    MessageCreateParams createParams = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(1024L)
      .addTool(BetaMemoryTool20250818.builder().build())
      .addUserMessage("Remember that customer Acme Corp prefers email follow-ups.")
      .build();

    ToolRunnerCreateParams runnerParams = ToolRunnerCreateParams.builder()
      .betaMemoryToolHandler(handler)
      .initialMessageParams(createParams)
      .maxIterations(10)
      .build();

    BetaToolRunner runner = client.beta().messages().toolRunner(runnerParams);
    for (BetaMessage message : runner) {
      IO.println(message);
    }
  }
  ```

  ```php PHP
  <?php

  use Anthropic\Beta\Messages\BetaMemoryTool20250818;
  use Anthropic\Client;
  use Anthropic\Lib\Tools\BetaRunnableTool;
  use Anthropic\Messages\Model;

  $client = new Client();

  // 一個記憶體內的儲存區，將記憶檔案路徑對應至其內容。
  // 在正式環境中，請使用您自己的儲存機制。
  $store = [];

  $memory = new BetaRunnableTool(
      definition: new BetaMemoryTool20250818,
      run: function (array $input) use (&$store): string {
          $path = $input['path'] ?? '';
          switch ($input['command']) {
              case 'view':
                  if (isset($store[$path])) {
                      $numbered = [];
                      foreach (explode("\n", preg_replace('/\n\z/', '', $store[$path])) as $i => $line) {
                          $numbered[] = sprintf("%6d\t%s", $i + 1, $line);
                      }
                      return "Here's the content of {$path} with line numbers:\n" . implode("\n", $numbered);
                  }
                  if ($path === '/memories') {
                      $listing = ["1.0K\t/memories"];
                      foreach (array_keys($store) as $stored) {
                          $listing[] = "1.0K\t{$stored}";
                      }
                      return "Here're the files and directories up to 2 levels deep in {$path}, excluding hidden items and node_modules:\n" . implode("\n", $listing);
                  }
                  return "The path {$path} does not exist. Please provide a valid path.";
              case 'create':
                  $store[$path] = $input['file_text'];
                  return "File created successfully at: {$path}";
              case 'str_replace':
                  $position = strpos($store[$path] ?? '', $input['old_str']);
                  if ($position === false) {
                      return "No replacement was performed, old_str `{$input['old_str']}` did not appear verbatim in {$path}.";
                  }
                  $store[$path] = substr_replace($store[$path], $input['new_str'] ?? '', $position, strlen($input['old_str']));
                  return 'The memory file has been edited.';
              case 'insert':
                  if (!isset($store[$path])) {
                      return "Error: The path {$path} does not exist";
                  }
                  $lines = explode("\n", $store[$path]);
                  if ($input['insert_line'] < 0 || $input['insert_line'] > count($lines)) {
                      return "Error: Invalid `insert_line` parameter: {$input['insert_line']}. It should be within the range of lines of the file: [0, " . count($lines) . "]";
                  }
                  array_splice($lines, $input['insert_line'], 0, [preg_replace('/\n\z/', '', $input['insert_text'])]);
                  $store[$path] = implode("\n", $lines);
                  return "The file {$path} has been edited.";
              case 'delete':
                  if (!isset($store[$path])) {
                      return "Error: The path {$path} does not exist";
                  }
                  unset($store[$path]);
                  return "Successfully deleted {$path}";
              case 'rename':
                  if (!isset($store[$input['old_path']])) {
                      return "Error: The path {$input['old_path']} does not exist";
                  }
                  if (isset($store[$input['new_path']])) {
                      return "Error: The destination {$input['new_path']} already exists";
                  }
                  $store[$input['new_path']] = $store[$input['old_path']];
                  unset($store[$input['old_path']]);
                  return "Successfully renamed {$input['old_path']} to {$input['new_path']}";
              default:
                  return "Error: unknown command {$input['command']}";
          }
      },
  );

  $runner = $client->beta->messages->toolRunner(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Remember that customer Acme Corp prefers email follow-ups.']],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [$memory],
      maxIterations: 10,
  );

  $finalMessage = $runner->runUntilDone();
  print_r($finalMessage->content);
  ```

  ```ruby Ruby
  require "anthropic"

  client = Anthropic::Client.new
  TOOLS = [{type: "memory_20250818", name: "memory"}].freeze

  # 記憶體內的儲存區，將記憶檔案路徑對應至其內容。
  # 在正式環境中，請使用您自己的儲存機制。
  STORE = {}

  def execute_memory(input)
    path = input[:path]
    case input[:command]
    when "view"
      if STORE.key?(path)
        lines = STORE[path].chomp.split("\n", -1)
        lines = [""] if lines.empty?
        numbered = lines.each_with_index.map { |line, i| format("%6d\t%s", i + 1, line) }
        "Here's the content of #{path} with line numbers:\n#{numbered.join("\n")}"
      elsif path == "/memories"
        listing = ["1.0K\t/memories"] + STORE.keys.map { |stored| "1.0K\t#{stored}" }
        "Here're the files and directories up to 2 levels deep in #{path}, excluding hidden items and node_modules:\n#{listing.join("\n")}"
      else
        "The path #{path} does not exist. Please provide a valid path."
      end
    when "create"
      STORE[path] = input[:file_text]
      "File created successfully at: #{path}"
    when "str_replace"
      unless STORE.key?(path) && STORE[path].include?(input[:old_str])
        return "No replacement was performed, old_str `#{input[:old_str]}` did not appear verbatim in #{path}."
      end
      STORE[path] = STORE[path].sub(input[:old_str]) { input[:new_str].to_s }
      "The memory file has been edited."
    when "insert"
      return "Error: The path #{path} does not exist" unless STORE.key?(path)
      lines = STORE[path].split("\n", -1)
      lines = [""] if lines.empty?
      if input[:insert_line] < 0 || input[:insert_line] > lines.length
        return "Error: Invalid `insert_line` parameter: #{input[:insert_line]}. It should be within the range of lines of the file: [0, #{lines.length}]"
      end
      lines.insert(input[:insert_line], input[:insert_text].chomp)
      STORE[path] = lines.join("\n")
      "The file #{path} has been edited."
    when "delete"
      return "Error: The path #{path} does not exist" unless STORE.key?(path)
      STORE.delete(path)
      "Successfully deleted #{path}"
    when "rename"
      return "Error: The path #{input[:old_path]} does not exist" unless STORE.key?(input[:old_path])
      return "Error: The destination #{input[:new_path]} already exists" if STORE.key?(input[:new_path])
      STORE[input[:new_path]] = STORE.delete(input[:old_path])
      "Successfully renamed #{input[:old_path]} to #{input[:new_path]}"
    else
      "Error: unknown command #{input[:command]}"
    end
  end

  messages = [{role: "user", content: "Remember that customer Acme Corp prefers email follow-ups."}]
  loop do
    message = client.messages.create(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 1024,
      messages: messages,
      tools: TOOLS
    )
    unless message.stop_reason == :tool_use
      puts message.content
      break
    end
    tool_results = message.content.filter_map do |block|
      next unless block.type == :tool_use
      {type: "tool_result", tool_use_id: block.id, content: execute_memory(block.input)}
    end
    messages << {role: "assistant", content: message.content} << {role: "user", content: tool_results}
  end
  ```
</CodeGroup>

Go、PHP 和 Ruby 範例中的記憶體內儲存區讓這些範例能夠自成一體：每個儲存區都會根據 `tool_use` 區塊 `input` 中的 `command` 欄位進行分派，並傳回[工具命令](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool#tool-commands)中所述的字串。正式環境的處理程式還需要這些示範儲存區所省略的[路徑驗證](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool#path-traversal-protection)。如需各 SDK 本身的完整範例，請參閱：

* Python：[examples/memory/basic.py](https://github.com/anthropics/anthropic-sdk-python/blob/main/examples/memory/basic.py)
* TypeScript：[examples/tools-helpers-memory.ts](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/examples/tools-helpers-memory.ts)
* C#：[MemoryToolExample](https://github.com/anthropics/anthropic-sdk-csharp/tree/main/examples/MemoryToolExample)
* Java：[BetaMemoryToolExample.java](https://github.com/anthropics/anthropic-sdk-java/blob/main/anthropic-java-example/src/main/java/com/anthropic/example/BetaMemoryToolExample.java)

## 工具命令

您的用戶端實作必須處理下列命令。這些規格描述了建議的行為和傳回字串：Claude 會讀取您的工具結果中包含的任何文字，因此如果您的應用程式有需要，也可以傳回不同的字串。

### view

顯示目錄內容或檔案內容，並可選擇指定行範圍：

```json
{
  "command": "view",
  "path": "/memories/notes.txt",
  "view_range": [1, 10]
}
```

`view_range` 為選用參數，適用於文字檔案的檢視：`[start_line, end_line]` 會傳回這些行，而 `[start_line, -1]` 會傳回從 `start_line` 到檔案結尾的所有內容。

#### 傳回值

**對於目錄：** 傳回顯示檔案和目錄及其大小的清單：

```text
Here're the files and directories up to 2 levels deep in {path}, excluding hidden items and node_modules:
{size}\t{path}
{size}\t{path}/{filename1}
{size}\t{path}/{filename2}
```

* 列出最多 2 層深的檔案
* 顯示人類可讀的大小（例如 `5.5K`、`1.2M`）
* 排除隱藏項目（以 `.` 開頭的檔案）和 `node_modules`
* 在大小和路徑之間使用 Tab 字元

在空的儲存區上首次對 `/memories` 執行 `view` 並不是錯誤。若您的 SDK 提供本機檔案系統記憶工具 `BetaLocalFilesystemMemoryTool`，它會在 Claude 首次呼叫之前建立記憶根目錄，並傳回清單標頭，後面接著一行代表該空目錄本身的大小與路徑。

**對於檔案：** 傳回帶有標頭和行號的檔案內容：

```text wrap
Here's the content of {path} with line numbers:
{line_numbers}{tab}{content}
```

行號格式：

* **寬度：** 6 個字元，靠右對齊並以空格填補
* **分隔符號：** 行號與內容之間使用 Tab 字元
* **索引：** 從 1 開始（第一行為第 1 行）
* **行數限制：** 超過 999,999 行的檔案應傳回錯誤：`"File {path} exceeds maximum line limit of 999,999 lines."`

**輸出範例：**

```text
Here'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
```

Claude 的工具描述也說明 `view` 會顯示圖片檔案（`.jpg`、`.jpeg` 和 `.png`），並會截斷超過 16,000 個字元之檔案的文字檢視。請預期會有針對圖片路徑的 `view` 呼叫，以及針對長檔案的後續範圍檢視。

#### 錯誤處理

* **檔案或目錄不存在：** `"The path {path} does not exist. Please provide a valid path."`

### create

建立新檔案：

```json
{
  "command": "create",
  "path": "/memories/notes.txt",
  "file_text": "Meeting notes:\n- Discussed project timeline\n- Next steps defined\n"
}
```

#### 傳回值

* **成功：** `"File created successfully at: {path}"`

#### 錯誤處理

* **檔案已存在：** `"Error: File {path} already exists"`

Claude 的工具描述指出 `create` 會「建立或覆寫」檔案，因此請預期會有針對已存在路徑的 `create` 呼叫。傳回錯誤是參考行為，而改為覆寫也是有效的實作選擇。

### str\_replace

取代檔案中的文字：

```json
{
  "command": "str_replace",
  "path": "/memories/preferences.txt",
  "old_str": "Favorite color: blue",
  "new_str": "Favorite color: green"
}
```

對於 `str_replace`，`new_str` 為選用參數：省略時，`old_str` 會被刪除而不進行取代。

#### 傳回值

* **成功：** `"The memory file has been edited."`，後面接著帶有行號的已編輯檔案片段

#### 錯誤處理

* **檔案不存在：** `"Error: The path {path} does not exist. Please provide a valid path."`
* **找不到文字：** ``"No replacement was performed, old_str `\{old_str}` did not appear verbatim in {path}."``
* **重複的文字：** 當 `old_str` 出現多次時，傳回：``"No replacement was performed. Multiple occurrences of old_str `\{old_str}` in lines: {line_numbers}. Please ensure it is unique"``

#### 目錄處理

如果路徑是目錄，請傳回「檔案不存在」錯誤。

### insert

在特定行插入文字：

```json
{
  "command": "insert",
  "path": "/memories/todo.txt",
  "insert_line": 2,
  "insert_text": "- Review memory tool documentation\n"
}
```

`insert_text` 會插入在第 `insert_line` 行之後，而 `0` 表示插入在檔案開頭。

#### 傳回值

* **成功：** `"The file {path} has been edited."`

#### 錯誤處理

* **檔案不存在：** `"Error: The path {path} does not exist"`
* **無效的行號：** ``"Error: Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: [0, {n_lines}]"``

#### 目錄處理

如果路徑是目錄，請傳回「檔案不存在」錯誤。

### delete

刪除檔案或目錄：

```json
{
  "command": "delete",
  "path": "/memories/old_file.txt"
}
```

#### 傳回值

* **成功：** `"Successfully deleted {path}"`

#### 錯誤處理

* **檔案或目錄不存在：** `"Error: The path {path} does not exist"`

#### 目錄處理

以遞迴方式刪除目錄及其所有內容。工具描述告知 Claude 不能刪除 `/memories` 目錄本身，因此請拒絕路徑為記憶根目錄的 `delete`。

### rename

重新命名或移動檔案或目錄：

```json
{
  "command": "rename",
  "old_path": "/memories/draft.txt",
  "new_path": "/memories/final.txt"
}
```

#### 傳回值

* **成功：** `"Successfully renamed {old_path} to {new_path}"`

#### 錯誤處理

* **來源不存在：** `"Error: The path {old_path} does not exist"`
* **目的地已存在：** 傳回錯誤（不要覆寫）：`"Error: The destination {new_path} already exists"`

#### 目錄處理

重新命名目錄。工具描述告知 Claude 不能重新命名 `/memories` 目錄本身，因此請拒絕 `old_path` 為記憶根目錄的 `rename`。

## 提示指引

當您請求的 `tools` 中包含記憶工具時，API 會自動將以下指示加入系統提示中。您不需要自行傳送：

```text wrap
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.
```

Claude 的工具描述已經告知它要保持記憶目錄井然有序，因此您不需要重複該指示。如果 Claude 仍然建立雜亂的記憶檔案，您可以在提示中加以強調：

```text wrap
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.
```

您也可以引導 Claude 寫入記憶的內容。例如：「Only write down information relevant to \<topic> in your memory system.」

## 安全性考量

您的應用程式會執行 Claude 請求的每一項檔案操作，因此以下防護措施是您的責任：

### 敏感資訊

Claude 通常會拒絕將敏感資訊寫入記憶檔案。若要獲得更強的保證，請加入驗證機制，在您的處理程式寫入檔案之前移除敏感資料。

### 檔案儲存大小

追蹤記憶檔案的大小，並限制檔案可成長的上限。請考慮限制 `view` 命令傳回的字元數，並讓 Claude 使用 `view_range` 分頁瀏覽其餘內容。

### 記憶過期

定期刪除長時間未被存取的記憶檔案。

### 路徑遍歷防護

<Warning>
  惡意路徑（例如 `/memories/../../secrets.env`）可能會存取到 `/memories` 目錄以外的檔案。您的實作必須驗證每個命令中的每個路徑，以防止「directory traversal」（目錄遍歷）攻擊。
</Warning>

請考慮以下防護措施：

* 驗證所有路徑都以 `/memories` 開頭
* 將路徑解析為其標準形式，並確認它們仍位於記憶目錄內
* 拒絕包含 `../`、`..\\` 等序列或其他遍歷模式的路徑
* 留意經過 URL 編碼的遍歷序列（`%2e%2e%2f`）
* 使用您程式語言內建的路徑安全工具（例如 Python 的 `pathlib.Path.resolve()` 和 `relative_to()`）

## 錯誤處理

記憶工具使用與[文字編輯器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/text-editor-tool#handle-errors)類似的錯誤處理模式。各命令的錯誤訊息列於[工具命令](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool#tool-commands)中。若要將錯誤傳回給 Claude，請在工具結果上將 `is_error` 設為 `true`，並將訊息放在 `content` 中：

```json
{
  "type": "tool_result",
  "tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "content": "Error: The path /memories/notes.txt does not exist",
  "is_error": true
}
```

## 上下文編輯整合

記憶工具可與「context editing」（上下文編輯）搭配使用，以管理長時間執行的對話。如需詳細資訊，請參閱[上下文編輯](https://platform.claude.com/docs/zh-TW/build-with-claude/context-editing)。

## 搭配壓縮使用

記憶工具也可以與「[compaction](https://platform.claude.com/docs/zh-TW/build-with-claude/compaction)」（壓縮）搭配使用，壓縮會在伺服器端摘要較舊的對話上下文。上下文編輯會在用戶端清除特定的工具結果。壓縮則會在對話接近上下文視窗上限時，自動在伺服器上摘要整個對話。

對於長時間執行的代理，請考慮同時使用兩者：壓縮可讓作用中的上下文保持精簡，而無需在用戶端進行記錄管理；記憶則會保存必須在摘要後仍然保留的資訊。

## 多工作階段軟體開發模式

對於跨越多個代理工作階段的軟體專案，請刻意規劃記憶檔案，而不是在工作進行時臨時寫入。以下模式將記憶轉變為一種復原機制：每個新的工作階段都會從上一個工作階段所記錄的狀態繼續。

### 模式的運作方式

1. **初始化工作階段：** 第一個工作階段會在任何實質工作開始之前設定記憶檔案。這包括進度日誌（追蹤已完成的工作和接下來的工作）、功能檢查清單（定義工作範圍），以及專案所需的任何啟動或初始化指令碼的參考。

2. **後續工作階段：** 每個新的工作階段一開始都會讀取這些記憶檔案。這樣可以還原專案狀態，而無需重新探索程式碼庫或重新追溯先前的決策。

3. **工作階段結束時的更新：** 在工作階段結束之前，會以已完成和尚待完成的工作更新進度日誌。這可確保下一個工作階段有準確的起點。

### 關鍵原則

一次只處理一項功能。只有在端對端驗證確認功能正常運作後，才將該功能標記為完成，而不是在程式碼寫完時就標記。這能讓進度日誌在各工作階段之間保持準確。

<Tip>
  如需此模式實際應用的詳細案例研究，包括初始化指令碼、進度檔案結構和以 git 為基礎的復原，請參閱[長時間執行代理的有效框架](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)。
</Tip>

## 後續步驟

<CardGroup cols={2}>
  <Card title="Bash 工具" icon="terminal" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/bash-tool">
    在持續性的 bash 工作階段中執行 shell 命令。
  </Card>

  <Card title="上下文編輯" icon="edit" href="https://platform.claude.com/docs/zh-TW/build-with-claude/context-editing">
    透過上下文編輯，在對話上下文成長時自動加以管理。
  </Card>

  <Card title="壓縮" icon="stack" href="https://platform.claude.com/docs/zh-TW/build-with-claude/compaction">
    伺服器端上下文壓縮，用於管理接近上下文視窗上限的長對話。
  </Card>

  <Card title="工具參考" icon="book" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference">
    Anthropic 提供之工具的目錄，以及選用工具定義屬性的參考資料。
  </Card>
</CardGroup>
