# Agent Tools

Extend your AI agents' capabilities with custom tools and function calling for advanced agentic workflows.

## What are Agent Tools?

**Agent Tools** are functions that AI agents can call to:

* Perform calculations
* Query databases
* Make API calls
* Execute actions
* Retrieve real-time data
* Interact with external systems

Tools enable agents to go beyond text generation and take actions.

## Tool vs. Standard Response

**Standard Agent (Text Only):**

```
User: "What's 15% of $2,450?"
Agent: "15% of $2,450 is approximately $367.50"
(May be slightly inaccurate)
```

**Agent with Calculator Tool:**

```
User: "What's 15% of $2,450?"
Agent: [Calls calculate tool]
Tool Result: 367.50
Agent: "15% of $2,450 is exactly $367.50"
(Precise, using actual calculation)
```

## Built-in Tools

### 1. Web Search

Search the web for real-time information.

**Configuration:**

```typescript
{
  "name": "web_search",
  "description": "Search the web for current information",
  "enabled": true,
  "parameters": {
    "query": "string",
    "maxResults": "number"
  }
}
```

**Use Cases:**

* Current events
* Real-time data (stock prices, weather)
* Information not in knowledge base

### 2. Calculator

Perform precise mathematical calculations.

**Configuration:**

```typescript
{
  "name": "calculator",
  "description": "Perform mathematical calculations",
  "enabled": true,
  "parameters": {
    "expression": "string"
  }
}
```

**Use Cases:**

* Pricing calculations
* Unit conversions
* Financial math
* Data analysis

### 3. Database Query

Query your database directly.

**Configuration:**

```typescript
{
  "name": "database_query",
  "description": "Query customer database",
  "enabled": true,
  "parameters": {
    "table": "string",
    "query": "string",
    "filters": "object"
  },
  "permissions": ["read"],
  "allowedTables": ["customers", "orders"]
}
```

**Use Cases:**

* Customer lookup
* Order status
* Account information
* Inventory checks

## Creating Custom Tools

### Tool Definition

```typescript
{
  "name": "check_inventory",
  "description": "Check product inventory levels",
  "parameters": {
    "type": "object",
    "properties": {
      "productId": {
        "type": "string",
        "description": "Product SKU or ID"
      },
      "location": {
        "type": "string",
        "description": "Warehouse location",
        "enum": ["US-EAST", "US-WEST", "EU", "ASIA"]
      }
    },
    "required": ["productId"]
  },
  "endpoint": "https://api.company.com/inventory/check",
  "method": "GET",
  "authentication": {
    "type": "bearer",
    "token": "${API_KEY}"
  }
}
```

### Tool Implementation

**Option 1: API Endpoint**

```typescript
{
  "name": "get_weather",
  "endpoint": "https://api.weather.com/v1/current",
  "method": "GET",
  "headers": {
    "Authorization": "Bearer ${WEATHER_API_KEY}"
  },
  "queryParams": {
    "location": "${location}",
    "units": "metric"
  }
}
```

**Option 2: Custom Function**

```python
# Hosted function
def calculate_discount(price, percentage, coupon_code=None):
    """Calculate discounted price"""
    discount = price * (percentage / 100)
    
    if coupon_code:
        # Check coupon validity
        additional_discount = check_coupon(coupon_code)
        discount += additional_discount
    
    return {
        "original_price": price,
        "discount_amount": discount,
        "final_price": price - discount
    }
```

**Option 3: Webhook**

```typescript
{
  "name": "send_notification",
  "type": "webhook",
  "url": "https://hooks.company.com/notify",
  "method": "POST",
  "timeout": 5000
}
```

## Tool Execution Flow

```
User Query: "What's the inventory for SKU-12345?"
     ↓
[1] Agent analyzes query
    → Determines tool is needed
     ↓
[2] Agent decides to call check_inventory tool
    → Parameters: {productId: "SKU-12345"}
     ↓
[3] Tool is executed
    → API call made
    → Response: {stock: 245, location: "US-EAST"}
     ↓
[4] Agent receives tool result
    → Incorporates into response
     ↓
[5] Final Response Generated
    "We currently have 245 units of SKU-12345
     in stock at our US-EAST warehouse."
```

## Multi-Step Tool Usage

Agents can chain multiple tools:

```
User: "I want to buy product ABC. Check if it's available and calculate shipping."

Step 1: check_inventory("ABC")
→ Result: In stock, 50 units

Step 2: get_user_location()
→ Result: ZIP 94102

Step 3: calculate_shipping({product: "ABC", zip: "94102"})
→ Result: $12.50, 2-3 days

Final Response:
"Product ABC is in stock! Shipping to 94102 will cost
$12.50 and take 2-3 business days. Would you like to proceed?"
```

## Tool Configuration

### Basic Tool Setup

```typescript
{
  "tools": [
    {
      "name": "search_docs",
      "description": "Search technical documentation",
      "enabled": true,
      "required": false,        // Agent can choose
      "maxRetries": 3,
      "timeout": 5000,          // 5 seconds
      "cacheTTL": 300           // Cache for 5 minutes
    }
  ]
}
```

### Advanced Settings

```typescript
{
  "tools": [
    {
      "name": "database_query",
      "enabled": true,
      
      // Security
      "permissions": ["read"],
      "allowedTables": ["customers"],
      "rateLimit": 100,         // Calls per minute
      
      // Performance
      "timeout": 3000,
      "maxRetries": 2,
      "retryDelay": 1000,
      "cache": {
        "enabled": true,
        "ttl": 300,
        "keyBy": ["query", "filters"]
      },
      
      // Monitoring
      "logging": true,
      "trackMetrics": true,
      "alertOnFailure": true
    }
  ],
  
  // Global settings
  "maxConcurrentTools": 5,
  "maxToolCallsPerQuery": 10,
  "toolTimeout": 10000
}
```

## Tool Examples

### Customer Lookup Tool

```typescript
{
  "name": "lookup_customer",
  "description": "Look up customer information by email or ID",
  "parameters": {
    "type": "object",
    "properties": {
      "identifier": {
        "type": "string",
        "description": "Customer email or ID"
      },
      "fields": {
        "type": "array",
        "items": {"type": "string"},
        "description": "Fields to return",
        "default": ["name", "email", "plan"]
      }
    },
    "required": ["identifier"]
  },
  "endpoint": "https://api.company.com/customers/lookup",
  "method": "POST",
  "authentication": {
    "type": "bearer",
    "token": "${CUSTOMER_API_KEY}"
  }
}
```

**Usage:**

```
User: "What plan is customer john@example.com on?"
→ Agent calls: lookup_customer({identifier: "john@example.com"})
→ Result: {name: "John Doe", plan: "Enterprise"}
→ Response: "John Doe is on our Enterprise plan."
```

### Order Status Tool

```typescript
{
  "name": "check_order_status",
  "description": "Check the status of an order",
  "parameters": {
    "type": "object",
    "properties": {
      "orderId": {
        "type": "string",
        "description": "Order number"
      }
    },
    "required": ["orderId"]
  },
  "endpoint": "https://api.company.com/orders/${orderId}",
  "method": "GET"
}
```

### Email Notification Tool

```typescript
{
  "name": "send_email",
  "description": "Send email notification",
  "parameters": {
    "type": "object",
    "properties": {
      "to": {"type": "string"},
      "subject": {"type": "string"},
      "body": {"type": "string"},
      "priority": {
        "type": "string",
        "enum": ["low", "normal", "high"]
      }
    },
    "required": ["to", "subject", "body"]
  },
  "endpoint": "https://api.company.com/email/send",
  "method": "POST"
}
```

## Security Considerations

### 1. Authentication

```typescript
{
  "authentication": {
    "type": "bearer",           // bearer, basic, or api_key
    "token": "${API_KEY}",      // Use environment variable
    "header": "Authorization"   // Header name
  }
}
```

### 2. Permissions

```typescript
{
  "permissions": {
    "read": true,
    "write": false,
    "delete": false
  },
  "allowedOperations": ["GET", "POST"],
  "deniedOperations": ["DELETE", "PUT"]
}
```

### 3. Rate Limiting

```typescript
{
  "rateLimits": {
    "requestsPerMinute": 60,
    "requestsPerHour": 1000,
    "concurrentCalls": 5
  }
}
```

### 4. Input Validation

```typescript
{
  "validation": {
    "sanitizeInputs": true,
    "allowedDomains": ["api.company.com"],
    "blockSensitiveData": true,
    "maxPayloadSize": 10000
  }
}
```

### 5. Audit Logging

```typescript
{
  "auditLog": {
    "enabled": true,
    "logInputs": true,
    "logOutputs": true,
    "retentionDays": 90
  }
}
```

## Best Practices

### 1. Clear Tool Descriptions

✅ **Good:**

```
"Search customer database by email or ID. Returns customer
name, plan, and account status. Use for customer inquiries."
```

❌ **Bad:**

```
"Customer search"
```

### 2. Validate Tool Responses

✅ Check tool results before using ✅ Handle errors gracefully ✅ Provide fallback behavior ❌ Don't assume tool always succeeds

### 3. Limit Tool Scope

✅ Single, focused purpose per tool ✅ Clear input/output contract ✅ Appropriate permissions ❌ Don't create "do everything" tools

### 4. Monitor Tool Usage

✅ Track success/failure rates ✅ Monitor response times ✅ Alert on anomalies ✅ Review logs regularly ❌ Don't deploy without monitoring

### 5. Test Thoroughly

✅ Test with various inputs ✅ Test error scenarios ✅ Test timeouts ✅ Test rate limits ❌ Don't test only happy path

## Monitoring & Analytics

### Tool Metrics

Track these metrics:

* **Call count**: Number of times called
* **Success rate**: % successful calls
* **Response time**: Average latency
* **Error rate**: % failed calls
* **Cache hit rate**: % cached responses

### Example Dashboard

```
Tool: check_inventory
├─ Calls (24h):      1,234
├─ Success Rate:     98.5% ✅
├─ Avg Response:     245ms
├─ Error Rate:       1.5%
├─ Cache Hit Rate:   45%
└─ Cost (24h):       $2.45
```

## Troubleshooting

### Tool Not Being Called

**Symptoms:**

* Agent gives generic answer
* Tool should be used but isn't
* Agent says "I can't do that"

**Solutions:**

1. Improve tool description
2. Make tool more discoverable
3. Add usage examples to agent instructions
4. Check tool is enabled

### Tool Timeout

**Symptoms:**

* Tool takes too long
* Request times out
* Incomplete responses

**Solutions:**

```typescript
{
  "timeout": 10000,      // Increase from 5000
  "maxRetries": 3,       // Retry on timeout
  "retryDelay": 2000     // Wait between retries
}
```

### Tool Errors

**Symptoms:**

* Tool returns errors
* Agent can't complete task
* Error messages to user

**Solutions:**

1. Add error handling in agent instructions
2. Provide fallback tools
3. Improve error messages
4. Add retry logic

## Advanced Topics

### Conditional Tool Use

```typescript
// Only use tool if conditions met
{
  "name": "premium_feature",
  "enabled": true,
  "conditions": {
    "user.plan": "enterprise",
    "user.permissions": ["premium_access"]
  }
}
```

### Tool Chaining

```typescript
// Define tool dependencies
{
  "name": "complete_order",
  "dependsOn": [
    "check_inventory",
    "calculate_shipping",
    "process_payment"
  ],
  "executeSequentially": true
}
```

### Dynamic Tool Selection

```python
# Agent dynamically chooses tools
def select_tools(query, context):
    tools = []
    
    if "price" in query or "cost" in query:
        tools.append("calculator")
    
    if "customer" in query or "account" in query:
        tools.append("lookup_customer")
    
    if "order" in query:
        tools.append("check_order_status")
    
    return tools
```

## Next Steps

* [Agentic Workflows](/product/advanced/agentic-workflows.md) - Build complex workflows
* [Agent Configuration](/product/overview/configuration.md) - Configure tool usage
* [Prompt Engineering](/product/overview/prompt-engineering.md) - Guide tool selection
* [Security Best Practices](/product/security/best-practices.md) - Secure tool access


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.twig.so/product/advanced/agent-tools.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
