Extend with Tools
Custom tools let agents call your code as naturally as they call built-in file or shell tools. Define the input schema, write the handler, and register it with the agent.
Why extend with tools
Built-in tools cover files, shells, and common reasoning patterns. Real applications often need domain-specific actions, such as querying an internal API, reading a feature flag, or updating a project management ticket. Custom tools expose those actions to the agent with the same interface as built-in tools.
Tool definition schema
A tool has three parts:
- Name - a unique identifier using snake_case.
- Description - a clear explanation that helps the model decide when to call the tool.
- Parameters - a JSON Schema object describing the arguments.
- Handler - the function that runs when the tool is invoked.
Define a tool
Tool shape is consistent across SDKs: name, description, JSON Schema parameters, and a handler. Use curl when the tool is only a thin wrapper around an HTTP endpoint.
import { defineTool } from '@autohandai/agent-sdk';
export const fetchCustomer = defineTool({
name: 'fetch_customer',
description: 'Fetch a customer record by ID',
parameters: {
type: 'object',
properties: { id: { type: 'string' } },
required: ['id']
},
handler: async ({ id }) => {
const res = await fetch(`${process.env.API_URL}/customers/${id}`, {
headers: { Authorization: `Bearer ${process.env.API_KEY}` }
});
return res.json();
}
});import { defineTool } from '@autohandai/agent-sdk';
export const fetchCustomer = defineTool<{ id: string }>({
name: 'fetch_customer',
description: 'Fetch a customer record by ID',
parameters: {
type: 'object',
properties: { id: { type: 'string', description: 'Customer ID' } },
required: ['id']
},
handler: async ({ id }) => {
const res = await fetch(`${process.env.API_URL}/customers/${id}`);
if (!res.ok) throw new Error(`Customer ${id} not found`);
return res.json();
}
});from autohand_sdk import define_tool
import httpx
import os
@define_tool(
name="fetch_customer",
description="Fetch a customer record by ID",
parameters={
"type": "object",
"properties": {"id": {"type": "string"}},
"required": ["id"],
},
)
async def fetch_customer(id: str):
async with httpx.AsyncClient() as client:
response = await client.get(
f"{os.environ['API_URL']}/customers/{id}",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
)
response.raise_for_status()
return response.json()fetchCustomer := autohand.Tool{
Name: "fetch_customer",
Description: "Fetch a customer record by ID",
Parameters: autohand.Schema{
Type: "object",
Properties: map[string]autohand.Schema{
"id": {Type: "string"},
},
Required: []string{"id"},
},
Handler: func(ctx context.Context, args map[string]any) (any, error) {
id := args["id"].(string)
return fetchCustomerRecord(ctx, id)
},
}Tool fetchCustomer = Tool.builder()
.name("fetch_customer")
.description("Fetch a customer record by ID")
.parameter("id", JsonSchema.string().description("Customer ID"))
.handler(args -> {
String id = args.getString("id");
return customersApi.fetchCustomer(id);
})
.build();let fetchCustomer = Tool(
name: "fetch_customer",
description: "Fetch a customer record by ID",
parameters: [
"id": .string(description: "Customer ID")
]
) { args in
let id = try args.requireString("id")
return try await customersAPI.fetchCustomer(id: id)
}curl -X POST "$API_URL/customers/CUST-1234" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"include":["plan","usage","owner"]}'The defineTool helper validates the parameter schema and serializes the result for the model.
Register the tool with an agent
import { Agent } from '@autohandai/agent-sdk';
import { fetchCustomer } from './tools/fetch-customer.js';
const agent = await Agent.create({
cwd: '.',
instructions: 'Use fetch_customer when users ask about customer data.',
tools: [fetchCustomer]
});
const result = await agent.run('What is the plan for customer CUST-1234?');
console.log(result.text);import { Agent } from '@autohandai/agent-sdk';
import { fetchCustomer } from './tools/fetch-customer';
const agent = await Agent.create({
cwd: '.',
instructions: 'Use fetch_customer when users ask about customer data.',
tools: [fetchCustomer]
});
const result = await agent.run('What is the plan for customer CUST-1234?');
console.log(result.text);from autohand_sdk import Agent
from tools import fetch_customer
agent = await Agent.create(
cwd=".",
instructions="Use fetch_customer when users ask about customer data.",
tools=[fetch_customer],
)
result = await agent.run("What is the plan for customer CUST-1234?")
print(result.text)agent, _ := autohand.NewAgent(ctx, autohand.AgentConfig{
Cwd: ".",
Instructions: "Use fetch_customer when users ask about customer data.",
Tools: []autohand.Tool{fetchCustomer},
})
result, _ := agent.Run(ctx, "What is the plan for customer CUST-1234?")
fmt.Println(result.Text)Agent agent = Agent.create(AgentConfig.builder()
.cwd(".")
.instructions("Use fetch_customer when users ask about customer data.")
.tools(List.of(fetchCustomer))
.build());
AgentResult result = agent.run("What is the plan for customer CUST-1234?");
System.out.println(result.text());let agent = try await Agent.create(
cwd: ".",
instructions: "Use fetch_customer when users ask about customer data.",
tools: [fetchCustomer]
)
let result = try await agent.run("What is the plan for customer CUST-1234?")
print(result.text)Connect external tools with MCP
If a tool already exists as a service, you can expose it through the Model Context Protocol instead of writing a handler. MCP lets Autohand discover and call tools hosted in a separate process.
See Connect to external tools with MCP for setup instructions.
Best practices
- Keep handlers focused on a single operation. The model composes multiple tool calls to solve larger tasks.
- Return structured data when possible. JSON results are easier for the model to reason about than free text.
- Validate and sanitize arguments inside the handler, even when JSON Schema is enforced.
- Throw or return errors with context so the model can retry or ask for clarification.
- Load secrets from environment variables, never from arguments or source code.