# Tool Use Concepts This file covers the conceptual foundations of tool use with the Claude API. For language-specific code examples, see the \`python/\`, \`typescript/\`, or other language folders. ## User-Defined Tools ### Tool Definition Structure > **Note:** When using the Tool Runner (beta), tool schemas are generated automatically from your function signatures (Python) or Zod schemas (TypeScript). The raw JSON schema format below is for the manual approach or SDKs without tool runner support. Each tool requires a name, description, and JSON Schema for its inputs: \`\`\`json { "name": "get_weather", "description": "Get current weather for a location", "input_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "City and state, e.g., San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } \`\`\` **Best practices for tool definitions:** - Use clear, descriptive names (e.g., \`get_weather\`, \`search_database\`, \`send_email\`) - Write detailed descriptions — Claude uses these to decide when to use the tool - Include descriptions for each property - Use \`enum\` for parameters with a fixed set of values - Mark truly required parameters in \`required\`; make others optional with defaults --- ### Tool Choice Options Control when Claude uses tools: | Value | Behavior | | --------------------------------- | --------------------------------------------- | | \`{"type": "auto"}\` | Claude decides whether to use tools (default) | | \`{"type": "any"}\` | Claude must use at least one tool | | \`{"type": "tool", "name": "..."}\` | Claude must use the specified tool | | \`{"type": "none"}\` | Claude cannot use tools | --- ### Tool Runner vs Manual Loop **Tool Runner (Recommended):** The SDK's tool runner handles the agentic loop automatically — it calls the API, detects tool use requests, executes your tool functions, feeds results back to Claude, and repeats until Claude stops calling tools. Available in Python and TypeScript SDKs (beta). **Manual Agentic Loop:** Use when you need fine-grained control over the loop (e.g., custom logging, conditional tool execution, human-in-the-loop approval). Loop until \`stop_reason == "end_turn"\`, always append the full \`response.content\` to preserve tool_use blocks, and ensure each \`tool_result\` includes the matching \`tool_use_id\`. > **Security:** The tool runner executes your tool functions automatically whenever Claude requests them. For tools with side effects (sending emails, modifying databases, financial transactions), validate inputs within your tool functions and consider requiring confirmation for destructive operations. Use the manual agentic loop if you need human-in-the-loop approval before each tool execution. --- ### Handling Tool Results When Claude uses a tool, the response contains a \`tool_use\` block. You must: 1. Execute the tool with the provided input 2. Send the result back in a \`tool_result\` message 3. Continue the conversation **Error handling in tool results:** When a tool execution fails, set \`"is_error": true\` and provide an informative error message. Claude will typically acknowledge the error and either try a different approach or ask for clarification. **Multiple tool calls:** Claude can request multiple tools in a single response. Handle them all before continuing — send all results back in a single \`user\` message. --- ## Server-Side Tools: Code Execution The code execution tool lets Claude run code in a secure, sandboxed container. Unlike user-defined tools, server-side tools run on Anthropic's infrastructure — you don't execute anything client-side. Just include the tool definition and Claude handles the rest. **Beta:** Pass \`betas=["code-execution-2025-08-25"]\` in your API calls (the SDK sets the required header automatically). ### Key Facts - Runs in an isolated container (1 CPU, 5 GiB RAM, 5 GiB disk) - No internet access (fully sandboxed) - Python 3.11 with data science libraries pre-installed - Containers persist for 30 days and can be reused across requests - 1,550 free hours/month per organization, then $0.05/hour ### Tool Definition The tool requires no schema — just declare it in the \`tools\` array: \`\`\`json { "type": "code_execution_20250825", "name": "code_execution" } \`\`\` Claude automatically gains access to \`bash_code_execution\` (run shell commands) and \`text_editor_code_execution\` (create/view/edit files). ### Pre-installed Python Libraries - **Data science**: pandas, numpy, scipy, scikit-learn, statsmodels - **Visualization**: matplotlib, seaborn - **File processing**: openpyxl, xlsxwriter, pillow, pypdf, pdfplumber, python-docx, python-pptx - **Math**: sympy, mpmath - **Utilities**: tqdm, python-dateutil, pytz, sqlite3 Additional packages can be installed at runtime via \`pip install\`. ### Supported File Types for Upload | Type | Extensions | | ------ | ---------------------------------- | | Data | CSV, Excel (.xlsx/.xls), JSON, XML | | Images | JPEG, PNG, GIF, WebP | | Text | .txt, .md, .py, .js, etc. | ### Container Reuse Reuse containers across requests to maintain state (files, installed packages, variables). Extract the \`container_id\` from the first response and pass it to subsequent requests. ### Response Structure The response contains interleaved text and tool result blocks: - \`text\` — Claude's explanation - \`server_tool_use\` — What Claude is doing - \`bash_code_execution_tool_result\` — Code execution output (check \`return_code\` for success/failure) - \`text_editor_code_execution_tool_result\` — File operation results > **Security:** Always sanitize filenames with \`os.path.basename()\` / \`path.basename()\` before writing downloaded files to disk to prevent path traversal attacks. Write files to a dedicated output directory. --- ## Server-Side Tools: Computer Use Computer use lets Claude interact with a desktop environment (screenshots, mouse, keyboard). It can be Anthropic-hosted (server-side, like code execution) or self-hosted (you provide the environment and execute actions client-side). For full documentation, use WebFetch: - URL: \`https://platform.claude.com/docs/en/agents-and-tools/computer-use/overview\` --- ## Client-Side Tools: Memory The memory tool enables Claude to store and retrieve information across conversations through a memory file directory. Claude can create, read, update, and delete files that persist between sessions. **Beta:** Use the SDK's beta namespace with \`betas: ["context-management-2025-06-27"]\`. ### Key Facts - Client-side tool — you control storage via your implementation - Supports commands: \`view\`, \`create\`, \`str_replace\`, \`insert\`, \`delete\`, \`rename\` - Operates on files in a \`/memories\` directory - The SDKs provide helper classes/functions for implementing the memory backend > **Security:** Never store API keys, passwords, tokens, or other secrets in memory files. Be cautious with personally identifiable information (PII) — check data privacy regulations (GDPR, CCPA) before persisting user data. The reference implementations have no built-in access control; in multi-user systems, implement per-user memory directories and authentication in your tool handlers. For full implementation examples, use WebFetch: - Docs: \`https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool.md\` --- ## Structured Outputs Structured outputs constrain Claude's responses to follow a specific JSON schema, guaranteeing valid, parseable output. This is not a separate tool — it enhances the Messages API response format and/or tool parameter validation. Two features are available: - **JSON outputs** (\`output_config.format\`): Control Claude's response format - **Strict tool use** (\`strict: true\`): Guarantee valid tool parameter schemas **Supported models:** Claude Opus 4.6, Claude Sonnet 4.6, and Claude Haiku 4.5. Legacy models (Claude Opus 4.5, Claude Opus 4.1) also support structured outputs. > **Recommended:** Use \`client.messages.parse()\` which automatically validates responses against your schema. When using \`messages.create()\` directly, use \`output_config: {format: {...}}\`. The old \`output_format\` parameter is deprecated (SDK helpers like \`.parse()\` still accept it as a convenience). ### JSON Schema Limitations **Supported:** - Basic types: object, array, string, integer, number, boolean, null - \`enum\`, \`const\`, \`anyOf\`, \`allOf\`, \`$ref\`/\`$def\` - String formats: \`date-time\`, \`time\`, \`date\`, \`duration\`, \`email\`, \`hostname\`, \`uri\`, \`ipv4\`, \`ipv6\`, \`uuid\` - \`additionalProperties: false\` (required for all objects) **Not supported:** - Recursive schemas - Numerical constraints (\`minimum\`, \`maximum\`, \`multipleOf\`) - String constraints (\`minLength\`, \`maxLength\`) - Complex array constraints - \`additionalProperties\` set to anything other than \`false\` The Python and TypeScript SDKs automatically handle unsupported constraints by removing them from the schema sent to the API and validating them client-side. ### Important Notes - **First request latency**: New schemas incur a one-time compilation cost. Subsequent requests with the same schema use a 24-hour cache. - **Refusals**: If Claude refuses for safety reasons (\`stop_reason: "refusal"\`), the output may not match your schema. - **Token limits**: If \`stop_reason: "max_tokens"\`, output may be incomplete. Increase \`max_tokens\`. - **Incompatible with**: Citations (returns 400 error), message prefilling. - **Works with**: Batches API, streaming, token counting, extended thinking. --- ## Tips for Effective Tool Use 1. **Provide detailed descriptions**: Claude relies heavily on descriptions to understand when and how to use tools 2. **Use specific tool names**: \`get_current_weather\` is better than \`weather\` 3. **Validate inputs**: Always validate tool inputs before execution 4. **Handle errors gracefully**: Return informative error messages so Claude can adapt 5. **Limit tool count**: Too many tools can confuse the model — keep the set focused 6. **Test tool interactions**: Verify Claude uses tools correctly in various scenarios For detailed tool use documentation, use WebFetch: - URL: \`https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview\`