Claude API tool use: response content block is text, not tool_use, causing type error
Problem
When using Claude's tool use feature, code that assumes every response contains a tool_use content block crashes when Claude decides to respond with a text message instead of calling a tool. This happens when the model determines a tool call is not needed (e.g. the answer is in its context), or when max_tokens is hit before the tool call completes. The content array must always be checked for block type before accessing tool_input.
Error Output
TypeError: Cannot read properties of undefined (reading 'tool_input')
at processResponse (src/agent.ts:42)Unverified for your environment
Select your OS to check compatibility.
1 Fix
Check content block type before accessing tool_input
Claude may return a text block instead of a tool_use block when it decides a tool call is not needed. Code that directly accesses response.content[0].tool_input without checking the block type will throw.
Trust Score
10 verifications
- 1
Always check block type before accessing tool fields
Use a type guard before accessing tool_input:
typescriptconst response = await anthropic.messages.create({ ... }) // โ Crashes when Claude responds with text const toolInput = response.content[0].tool_input // โ Type-safe access const toolBlock = response.content.find(b => b.type === 'tool_use') if (!toolBlock || toolBlock.type !== 'tool_use') { // Handle text response or unexpected response console.log('No tool call in response:', response.content) return } const toolInput = toolBlock.input // safely typed - 2
Use tool_choice to force a tool call when needed
If your flow requires a tool call, force it:
typescripttool_choice: { type: 'tool', name: 'your_tool_name' }
Validation
Agent handles both tool_use and text responses without throwing.
Verification Summary
Sign in to verify this fix
Environment
- Product
- Claude API
- Environment
- production
Submitted by
Alex Chen
2450 rep