From fa8ba27b1068b34660f9fcce867bd6538edcff46 Mon Sep 17 00:00:00 2001 From: rajashidattapy Date: Thu, 20 Aug 2026 00:52:58 +0530 Subject: [PATCH] refactor(tools): narrow memory tool input with a type guard Replace the bare `block.input as MemoryCommand` assertions in the Anthropic example with an isMemoryCommand type guard, so unexpected tool input is skipped instead of silently mistyped. --- packages/tools/test/anthropic-example.ts | 33 ++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/packages/tools/test/anthropic-example.ts b/packages/tools/test/anthropic-example.ts index a9855eb7..a4d1d9fe 100644 --- a/packages/tools/test/anthropic-example.ts +++ b/packages/tools/test/anthropic-example.ts @@ -11,6 +11,27 @@ import { } from "../src/claude-memory" import "dotenv/config" +const MEMORY_COMMANDS: readonly string[] = [ + "view", + "create", + "str_replace", + "insert", + "delete", + "rename", +] + +function isMemoryCommand(input: unknown): input is MemoryCommand { + return ( + typeof input === "object" && + input !== null && + "command" in input && + "path" in input && + typeof input.command === "string" && + MEMORY_COMMANDS.includes(input.command) && + typeof input.path === "string" + ) +} + /** * Handle Claude's memory tool calls using the Anthropic SDK */ @@ -75,7 +96,11 @@ async function chatWithMemoryTool() { if (block.type === "text") { console.log("💭", block.text) } else if (block.type === "tool_use" && block.name === "memory") { - const command = block.input as MemoryCommand + const command = block.input + if (!isMemoryCommand(command)) { + console.log("Skipping unrecognized memory tool input:", command) + continue + } console.log("🔧 Claude is using memory tool:") console.log(" Command:", command.command) console.log(" Path:", command.path) @@ -142,7 +167,11 @@ async function chatWithMemoryTool() { if (block.type === "text") { console.log("💭", block.text) } else if (block.type === "tool_use" && block.name === "memory") { - const command = block.input as MemoryCommand + const command = block.input + if (!isMemoryCommand(command)) { + console.log("Skipping unrecognized memory tool input:", command) + continue + } console.log("🔧 Claude is using memory tool again:") console.log(" Command:", command.command) console.log(" Path:", command.path)