HIVE

Agent Configuration

Agent Tools

Agent Tools

Tools transform AI agents from conversational assistants into powerful automation systems. They give your agents the ability to interact with the real world—searching for information, executing code, calling APIs, and performing actions that text generation alone cannot accomplish.

This comprehensive guide covers everything from using built-in tools to creating sophisticated custom integrations. By mastering tools, you'll unlock the full potential of your HIVE Protocol agents.

Understanding Tools

What Are Tools?

Tools are functions that agents can invoke during conversations to perform specific actions. When an agent determines it needs external information or capabilities, it generates a tool call with the appropriate parameters, the system executes the tool, and the results are returned to the agent.

┌─────────────────────────────────────────────────────────────┐
│                      TOOL EXECUTION FLOW                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. USER MESSAGE                                            │
│     "What's the weather in Tokyo today?"                    │
│            │                                                │
│            ▼                                                │
│  2. AGENT REASONING                                         │
│     "I need current weather data. I'll use get_weather."    │
│            │                                                │
│            ▼                                                │
│  3. TOOL CALL                                               │
│     get_weather({ location: "Tokyo", units: "celsius" })    │
│            │                                                │
│            ▼                                                │
│  4. TOOL EXECUTION                                          │
│     → API call to weather service                           │
│     ← Returns: { temp: 22, conditions: "Partly Cloudy" }    │
│            │                                                │
│            ▼                                                │
│  5. AGENT RESPONSE                                          │
│     "It's currently 22C and partly cloudy in Tokyo."        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Why Tools Matter

Without tools, agents are limited to their training data. Tools enable:

CapabilityWithout ToolsWith Tools
Current InformationOutdated training dataReal-time web search
CalculationsMay make errorsPrecise code execution
External ServicesCannot accessFull API integration
Data ProcessingManual handlingAutomated pipelines
ActionsSuggestions onlyExecute real changes

Tool Categories

HIVE Protocol tools fall into several categories:

CategoryPurposeExamples
InformationGather external dataWeb search, weather, news
ComputationProcess and calculateCode execution, math, analysis
IntegrationConnect to servicesHTTP requests, webhooks, APIs
StoragePersist and retrieveDatabase queries, file operations
CommunicationSend notificationsEmail, Slack, SMS

Built-in Tools

HIVE Protocol includes several pre-built tools ready to use immediately.

Search the internet for current information.

{
  "name": "web_search",
  "description": "Search the web for current information on any topic. Returns relevant search results including titles, URLs, and snippets.",
  "category": "Information",
  "parameters": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "The search query (be specific for better results)"
      },
      "num_results": {
        "type": "number",
        "description": "Number of results to return (1-10)",
        "default": 5
      },
      "recency": {
        "type": "string",
        "enum": ["any", "day", "week", "month", "year"],
        "description": "Filter by content recency",
        "default": "any"
      }
    },
    "required": ["query"]
  }
}

Use Cases:

  • Researching current events
  • Finding recent statistics or data
  • Checking facts against current sources
  • Discovering new information on topics

Example Interaction:

User: "What's the latest news about SpaceX launches?"

Agent: [Invokes web_search with query: "SpaceX launches 2024 news"]

Agent: "Based on recent news, SpaceX has had several significant
launches this month. Their latest Starship test flight on..."

Code Execution

Execute code in a secure sandboxed environment.

{
  "name": "execute_code",
  "description": "Execute code in a sandboxed environment. Supports Python, JavaScript, and Bash. Use for calculations, data processing, and algorithm implementation.",
  "category": "Computation",
  "parameters": {
    "type": "object",
    "properties": {
      "language": {
        "type": "string",
        "enum": ["python", "javascript", "bash"],
        "description": "Programming language to use"
      },
      "code": {
        "type": "string",
        "description": "The code to execute"
      },
      "timeout": {
        "type": "number",
        "description": "Maximum execution time in seconds",
        "default": 30
      }
    },
    "required": ["language", "code"]
  }
}

Use Cases:

  • Mathematical calculations
  • Data transformations
  • Algorithm implementations
  • String processing
  • Statistical analysis

Example Interaction:

User: "Calculate the compound interest on $10,000 at 5% for 10 years"

Agent: [Invokes execute_code with Python code]

Code:
principal = 10000
rate = 0.05
years = 10
result = principal * (1 + rate) ** years
print(f"Final amount: ${result:,.2f}")
print(f"Interest earned: ${result - principal:,.2f}")

Output:
Final amount: $16,288.95
Interest earned: $6,288.95

Agent: "After 10 years at 5% compound interest, your $10,000
would grow to $16,288.95, earning $6,288.95 in interest."

HTTP Request

Make HTTP requests to external APIs.

{
  "name": "http_request",
  "description": "Make HTTP requests to external APIs. Useful for fetching data from REST APIs, webhooks, or any HTTP endpoint.",
  "category": "Integration",
  "parameters": {
    "type": "object",
    "properties": {
      "url": {
        "type": "string",
        "description": "The URL to request"
      },
      "method": {
        "type": "string",
        "enum": ["GET", "POST", "PUT", "PATCH", "DELETE"],
        "default": "GET"
      },
      "headers": {
        "type": "object",
        "description": "Request headers (key-value pairs)"
      },
      "body": {
        "type": "object",
        "description": "Request body for POST/PUT/PATCH"
      },
      "timeout": {
        "type": "number",
        "description": "Request timeout in milliseconds",
        "default": 30000
      }
    },
    "required": ["url"]
  }
}

Use Cases:

  • Fetching data from REST APIs
  • Sending data to external services
  • Triggering webhooks
  • Checking service status

Security Note: This tool respects allowed domain configurations. Only pre-approved domains can be accessed.

File Reader

Read and process file contents.

{
  "name": "read_file",
  "description": "Read contents of uploaded files. Supports text files, CSVs, JSON, and more.",
  "category": "Storage",
  "parameters": {
    "type": "object",
    "properties": {
      "file_id": {
        "type": "string",
        "description": "The ID of the uploaded file"
      },
      "encoding": {
        "type": "string",
        "default": "utf-8"
      },
      "parse_as": {
        "type": "string",
        "enum": ["text", "json", "csv"],
        "description": "How to parse the file contents"
      }
    },
    "required": ["file_id"]
  }
}

Database Query

Execute database queries (when configured).

{
  "name": "database_query",
  "description": "Execute SQL queries against configured database connections. Read-only by default for safety.",
  "category": "Storage",
  "parameters": {
    "type": "object",
    "properties": {
      "connection": {
        "type": "string",
        "description": "Database connection name"
      },
      "query": {
        "type": "string",
        "description": "SQL query to execute"
      },
      "parameters": {
        "type": "array",
        "description": "Query parameters for parameterized queries"
      }
    },
    "required": ["connection", "query"]
  }
}

Assigning Tools to Agents

Via the Dashboard

  1. Navigate to Agents in the sidebar
  2. Select the agent you want to configure
  3. Click the Tools tab
  4. You'll see a list of available tools with toggle switches
  5. Enable the tools you want the agent to use
  6. Configure any tool-specific settings
  7. Click Save Changes

Tool Availability

┌─────────────────────────────────────────────────────────────┐
│                    TOOL CONFIGURATION                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Agent: Research Analyst                                    │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ ENABLED TOOLS                                        │   │
│  │ ✓ web_search          Search the internet           │   │
│  │ ✓ execute_code        Run Python/JS code            │   │
│  │ ✗ http_request        Make API calls                │   │
│  │ ✓ read_file           Process uploaded files        │   │
│  │ ✗ database_query      Query databases               │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ TOOL SETTINGS                                        │   │
│  │                                                       │   │
│  │ web_search:                                          │   │
│  │   Max results: 5                                     │   │
│  │   Safe search: On                                    │   │
│  │                                                       │   │
│  │ execute_code:                                        │   │
│  │   Timeout: 30 seconds                                │   │
│  │   Languages: python, javascript                      │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│                                   [Save Changes]            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Tool Configuration Options

Different tools have different configuration requirements:

web_search Configuration:

max_results: 5          # Maximum search results (1-10)
safe_search: true       # Filter explicit content
region: "us"            # Regional search preference

execute_code Configuration:

timeout: 30             # Max execution time (seconds)
memory_limit: 256       # Memory limit (MB)
allowed_languages:      # Which languages to enable
  - python
  - javascript

http_request Configuration:

timeout: 30000          # Request timeout (ms)
max_retries: 3          # Retry failed requests
allowed_domains:        # Whitelist of allowed domains
  - api.example.com
  - data.company.org
blocked_domains:        # Domains to never access
  - internal.corp

Creating Custom Tools

Custom tools let you extend agent capabilities to match your specific needs. You can create tools that integrate with your internal systems, proprietary APIs, or unique workflows.

Tool Definition Structure

Every tool requires a complete definition:

interface ToolDefinition {
  name: string;                    // Unique identifier (snake_case)
  description: string;             // What the tool does
  category: string;                // For organization
  input_schema: {                  // Parameters the tool accepts
    type: "object";
    properties: {
      [paramName: string]: {
        type: string;              // "string", "number", "boolean", etc.
        description: string;       // Help the agent use it correctly
        enum?: string[];           // Optional: allowed values
        default?: any;             // Optional: default value
      };
    };
    required: string[];            // Required parameters
  };
  output_schema?: {                // Optional: document what's returned
    type: "object";
    properties: {
      [fieldName: string]: {
        type: string;
        description: string;
      };
    };
  };
  config_schema?: {                // Optional: configuration options
    type: "object";
    properties: {
      [configName: string]: {
        type: string;
        description: string;
        secret?: boolean;          // Mark sensitive values
      };
    };
  };
}

Complete Custom Tool Examples

CRM Lookup Tool

{
  "name": "crm_lookup",
  "description": "Look up customer information from the CRM system. Returns customer details, recent interactions, and account status.",
  "category": "Integration",
  "input_schema": {
    "type": "object",
    "properties": {
      "search_type": {
        "type": "string",
        "enum": ["email", "phone", "company", "id"],
        "description": "Type of search to perform"
      },
      "search_value": {
        "type": "string",
        "description": "Value to search for"
      },
      "include_history": {
        "type": "boolean",
        "description": "Include interaction history",
        "default": false
      }
    },
    "required": ["search_type", "search_value"]
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "customer_id": { "type": "string" },
      "name": { "type": "string" },
      "company": { "type": "string" },
      "email": { "type": "string" },
      "status": { "type": "string" },
      "lifetime_value": { "type": "number" },
      "recent_interactions": { "type": "array" }
    }
  },
  "config_schema": {
    "type": "object",
    "properties": {
      "api_key": {
        "type": "string",
        "description": "CRM API key",
        "secret": true
      },
      "instance_url": {
        "type": "string",
        "description": "CRM instance URL"
      }
    }
  }
}

Inventory Checker Tool

{
  "name": "check_inventory",
  "description": "Check product inventory levels across warehouses. Use when customers ask about product availability or stock status.",
  "category": "Integration",
  "input_schema": {
    "type": "object",
    "properties": {
      "product_id": {
        "type": "string",
        "description": "Product SKU or ID"
      },
      "warehouse": {
        "type": "string",
        "enum": ["all", "east", "west", "central"],
        "description": "Warehouse to check (or 'all')",
        "default": "all"
      },
      "include_incoming": {
        "type": "boolean",
        "description": "Include incoming shipments in count",
        "default": true
      }
    },
    "required": ["product_id"]
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "product_id": { "type": "string" },
      "product_name": { "type": "string" },
      "available": { "type": "number" },
      "reserved": { "type": "number" },
      "incoming": { "type": "number" },
      "by_warehouse": { "type": "object" },
      "last_updated": { "type": "string" }
    }
  }
}

Notification Sender Tool

{
  "name": "send_notification",
  "description": "Send notifications through various channels (email, Slack, SMS). Use when the user needs to be notified about something or wants to alert others.",
  "category": "Communication",
  "input_schema": {
    "type": "object",
    "properties": {
      "channel": {
        "type": "string",
        "enum": ["email", "slack", "sms"],
        "description": "Notification channel"
      },
      "recipient": {
        "type": "string",
        "description": "Email address, Slack channel, or phone number"
      },
      "subject": {
        "type": "string",
        "description": "Message subject (for email)"
      },
      "message": {
        "type": "string",
        "description": "Message content"
      },
      "priority": {
        "type": "string",
        "enum": ["low", "normal", "high", "urgent"],
        "default": "normal"
      }
    },
    "required": ["channel", "recipient", "message"]
  }
}

Tool Implementation

Tools are implemented as serverless functions. Here's a complete example:

// tools/crm_lookup/index.ts

interface CRMLookupInput {
  search_type: "email" | "phone" | "company" | "id";
  search_value: string;
  include_history?: boolean;
}

interface CRMLookupConfig {
  api_key: string;
  instance_url: string;
}

interface CRMLookupResult {
  success: boolean;
  customer?: {
    customer_id: string;
    name: string;
    company: string;
    email: string;
    status: string;
    lifetime_value: number;
    recent_interactions?: Array<{
      date: string;
      type: string;
      summary: string;
    }>;
  };
  error?: string;
}

export async function execute(
  input: CRMLookupInput,
  config: CRMLookupConfig
): Promise<CRMLookupResult> {

  // Validate input
  if (!input.search_value || input.search_value.trim() === "") {
    return {
      success: false,
      error: "Search value is required"
    };
  }

  // Build API request
  const searchEndpoint = `${config.instance_url}/api/v2/customers/search`;

  try {
    const response = await fetch(searchEndpoint, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${config.api_key}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        type: input.search_type,
        value: input.search_value,
        include_history: input.include_history ?? false
      })
    });

    if (!response.ok) {
      if (response.status === 404) {
        return {
          success: true,
          customer: undefined,
          error: "No customer found matching your search"
        };
      }
      throw new Error(`CRM API error: ${response.status}`);
    }

    const customer = await response.json();

    return {
      success: true,
      customer: {
        customer_id: customer.id,
        name: customer.full_name,
        company: customer.company_name,
        email: customer.primary_email,
        status: customer.account_status,
        lifetime_value: customer.ltv,
        recent_interactions: input.include_history
          ? customer.interactions
          : undefined
      }
    };

  } catch (error) {
    return {
      success: false,
      error: `Failed to search CRM: ${error.message}`
    };
  }
}

Tool Best Practices

1. Write Descriptive Tool Descriptions

The description is how the agent decides whether to use your tool. Be specific about:

  • What the tool does
  • When to use it
  • What kind of input it expects
  • What it returns
GOOD Description:
"Search the CRM for customer information using email, phone, company
name, or customer ID. Use when you need to look up customer details,
check account status, or review interaction history. Returns customer
profile, status, lifetime value, and optionally recent interactions."

BAD Description:
"CRM search tool"

2. Design Clear Parameter Schemas

Parameters should be self-documenting:

GOOD:
{
  "date_range": {
    "type": "string",
    "enum": ["today", "week", "month", "quarter", "year", "custom"],
    "description": "Time period for the report. Use 'custom' with start_date and end_date for specific ranges."
  }
}

BAD:
{
  "range": {
    "type": "string"
  }
}

3. Handle Errors Gracefully

Always return structured error responses that help the agent (and ultimately the user) understand what went wrong:

// Good error handling
try {
  const result = await apiCall();
  return { success: true, data: result };
} catch (error) {
  if (error.status === 401) {
    return {
      success: false,
      error: "Authentication failed. The API credentials may be invalid.",
      suggestion: "Please check your API key in tool settings."
    };
  }
  if (error.status === 429) {
    return {
      success: false,
      error: "Rate limit exceeded. Too many requests.",
      suggestion: "Please wait a moment before trying again."
    };
  }
  return {
    success: false,
    error: `Unexpected error: ${error.message}`
  };
}

4. Validate All Inputs

Never trust input data. Validate before processing:

function validateInput(input: any): { valid: boolean; error?: string } {
  if (!input.product_id || typeof input.product_id !== "string") {
    return { valid: false, error: "Product ID is required" };
  }

  if (input.product_id.length > 50) {
    return { valid: false, error: "Product ID is too long" };
  }

  if (!/^[A-Z0-9-]+$/.test(input.product_id)) {
    return { valid: false, error: "Invalid product ID format" };
  }

  return { valid: true };
}

5. Implement Rate Limiting

Protect external services and control costs:

const rateLimiter = new Map<string, { count: number; resetAt: number }>();

function checkRateLimit(userId: string): boolean {
  const now = Date.now();
  const userLimit = rateLimiter.get(userId);

  if (!userLimit || now > userLimit.resetAt) {
    rateLimiter.set(userId, { count: 1, resetAt: now + 60000 });
    return true;
  }

  if (userLimit.count >= 10) {
    return false; // Rate limited
  }

  userLimit.count++;
  return true;
}

6. Log Tool Usage

Maintain audit trails for debugging and compliance:

async function executeWithLogging(
  toolName: string,
  input: any,
  execute: () => Promise<any>
) {
  const startTime = Date.now();

  try {
    const result = await execute();
    await logToolUsage({
      tool: toolName,
      input: sanitize(input),
      success: true,
      duration: Date.now() - startTime
    });
    return result;
  } catch (error) {
    await logToolUsage({
      tool: toolName,
      input: sanitize(input),
      success: false,
      error: error.message,
      duration: Date.now() - startTime
    });
    throw error;
  }
}

Configuring Tools in System Prompts

Help your agent use tools effectively through system prompt instructions:

## Tool Usage Guidelines

### When to Use Tools
- Use web_search for ANY question about current events, recent news,
  or information that might have changed since your training
- Use execute_code for precise calculations, data processing, or
  when accuracy is critical
- Use crm_lookup whenever the user mentions a customer name, email,
  or asks about account status

### Tool Usage Principles
1. Explain what you're going to do before invoking a tool
2. If a tool fails, explain the error and offer alternatives
3. Don't make up data—if you need information, use a tool
4. Combine tool results with your analysis, don't just dump raw output

### Example Flow
User: "What's the status of John Smith's account?"

You: "Let me look up John Smith in our CRM system."
[Use crm_lookup tool]

"I found John Smith's account. He's a Premium customer since 2022
with a lifetime value of $45,000. His account is in good standing,
and the last interaction was a support call on March 15th about
billing questions, which was resolved."

Security Considerations

Protect Sensitive Configuration

Never expose API keys or credentials:

  • Store secrets using the secret: true flag in config schema
  • Secrets are encrypted at rest
  • Never log or return secrets in responses

Domain Whitelisting

For HTTP tools, always configure allowed domains:

allowed_domains:
  - api.company.com
  - data.trusted-service.com

blocked_domains:
  - internal.corp
  - localhost

Input Sanitization

Always sanitize user-provided input before using in queries or commands:

// SQL injection prevention
const safeQuery = sql`SELECT * FROM customers WHERE id = ${userId}`;

// Command injection prevention
const safeFilename = filename.replace(/[^a-zA-Z0-9.-]/g, "_");

Next Steps

Now that you understand agent tools:

  • [Creating Swarms](/docs/swarms/creating-swarms): Build multi-agent systems with tool-equipped agents
  • [Webhooks](/docs/integrations/webhooks): Trigger external systems based on swarm events
  • [API Reference](/docs/api/tools-api): Programmatically manage tools

Cookie Preferences

We use cookies to enhance your experience, analyze site traffic, and for marketing purposes. By clicking "Accept All", you consent to our use of cookies. Read our Privacy Policy for more information.