ClaudeAgentSDK.Tool (claude_agent_sdk v0.6.9)
View SourceTool definition macro for creating in-process MCP tools.
Provides the deftool macro for defining tools that can be used with
create_sdk_mcp_server/2 to create SDK-based MCP servers without subprocess overhead.
Usage
defmodule MyTools do
use ClaudeAgentSDK.Tool
deftool :calculator,
"Performs basic calculations",
%{
type: "object",
properties: %{
expression: %{type: "string"}
},
required: ["expression"]
} do
def execute(%{"expression" => expr}) do
result = eval_expression(expr)
{:ok, %{"content" => [%{"type" => "text", "text" => "Result: #{result}"}]}}
end
defp eval_expression(expr) do
# Implementation
end
end
endTool Metadata
Each tool defined with deftool creates a module with:
__tool_metadata__/0- Returns tool metadataexecute/1- Executes the tool with given input
Input/Output Format
Tools receive input as a map matching the input_schema and return:
{:ok, result}- Success with result map{:error, reason}- Error with reason string
Result map should contain:
"content"- List of content blocks (text, image, etc.)- Optional:
"isError"- Boolean indicating error state
Summary
Functions
Collects all defined tools and makes them discoverable.
When used, defines the deftool macro in the calling module.
Shorthand for deftool with minimal schema (just type: object).
Defines a tool with name, description, and input schema.
Lists all tools defined in a module.
Validates a JSON schema map.
Functions
Collects all defined tools and makes them discoverable.
When used, defines the deftool macro in the calling module.
Shorthand for deftool with minimal schema (just type: object).
Defines a tool with name, description, and input schema.
Parameters
name- Atom tool name (e.g.,:calculator)description- String description of what the tool doesinput_schema- JSON Schema map defining expected inputdo_block- Block containingexecute/1function definition
Examples
deftool :add, "Add two numbers", %{
type: "object",
properties: %{a: %{type: "number"}, b: %{type: "number"}},
required: ["a", "b"]
} do
def execute(%{"a" => a, "b" => b}) do
{:ok, %{"content" => [%{"type" => "text", "text" => "Result: #{a + b}"}]}}
end
end
Lists all tools defined in a module.
Parameters
module- The module that usedClaudeAgentSDK.Tool
Returns
List of tool metadata maps.
Examples
iex> ClaudeAgentSDK.Tool.list_tools(MyTools)
[%{name: :calculator, description: "Performs calculations", ...}]
Validates a JSON schema map.
Parameters
schema- JSON Schema map
Returns
Boolean indicating if schema is valid.
Examples
iex> ClaudeAgentSDK.Tool.valid_schema?(%{type: "object"})
true
iex> ClaudeAgentSDK.Tool.valid_schema?(%{})
false