CCDV-F Domain 2: Tool Use (Function Calling) Implementation
How to define JSON Schema tools, parse `tool_use` blocks, execute deterministic code in your application, and return `tool_result` responses to Claude.
1. Defining Tools in the Request Payload
Tools are declared in the top-level tools array of your API request. Each tool requires:
name: Unique alphanumeric identifier (e.g.,get_weather,query_database).description: Detailed instructions explaining when and how Claude should invoke the tool.input_schema: A standard JSON Schema object defining required properties and data types.
{
"name": "get_stock_quote",
"description": "Retrieves the real-time share price and trading volume for a given equity ticker.",
"input_schema": {
"type": "object",
"properties": {
"ticker": { "type": "string", "description": "The stock ticker symbol (e.g. AAPL, GOOGL)" }
},
"required": ["ticker"]
}
}
2. The Complete 5-Step Tool Execution Loop
Execution Flow
1. User Prompt: User asks: "What is Apple's current share price?"
2. Tool Request: Claude returns stop_reason: "tool_use" with a content block of type: "tool_use" containing id: "toolu_01X", name: "get_stock_quote", and input: {"ticker": "AAPL"}.
3. Local Execution: Your backend application intercepts this block and calls your real stock market API.
4. Tool Result Return: Your code appends Claude's assistant message to the message history, followed by a new user turn containing a type: "tool_result" content block with matching tool_use_id: "toolu_01X" and the returned data.
5. Final Synthesis: Claude inspects the returned data and delivers the final natural language answer to the user.
3. Handling Tool Errors Gracefully
If your local tool execution fails (e.g., database timeout or invalid symbol), pass is_error: true in the tool_result block:
{
"type": "tool_result",
"tool_use_id": "toolu_01X",
"is_error": true,
"content": "DatabaseConnectionTimeout: Server failed to respond after 5000ms."
}
This allows Claude to understand what went wrong, explain the issue to the user, or attempt an alternative recovery strategy.