Skip to main content

Tools & Functions

Tools enable your AI agents to perform actions beyond conversation by calling external APIs, querying databases, checking calendars, updating CRMs, and more. BlackBox implements function calling using industry-standard JSON schemas, compatible with supported LLM providers (OpenAI, Groq, Grok, DeepSeek, and custom-compatible models).

Overview

When you configure tools for an agent, the LLM gains awareness of available functions it can invoke during conversations. The agent autonomously decides when to call a tool based on context, executes the function via webhook, receives the result, and incorporates it into the conversation. Key capabilities:
  • Industry-standard JSON Schema for tool definitions
  • Webhook calls include call metadata (callId, agentId, orgId, additionalData) so your service has full context
  • Automatic retry policy with exponential backoff handles transient webhook failures (initial attempt plus up to three retries)
  • Integrated tooling to exercise webhooks from the dashboard and the /api/v1/webhooks/test endpoint

How Function Calling Works

The function calling workflow follows this sequence:

Execution Flow

  1. User Input: User asks a question or makes a request
  2. LLM Analysis: The language model analyzes the request with tool schemas in context
  3. Tool Selection: LLM autonomously decides if a tool call is needed and which tool to invoke
  4. Argument Generation: LLM generates properly formatted arguments matching the tool schema
  5. Webhook Invocation: BlackBox sends a POST request to your webhook URL with the tool call payload
  6. External Execution: Your webhook handler processes the request and calls external systems
  7. Result Return: Webhook returns the result in JSON format
  8. Response Generation: LLM incorporates the result into its response to the user

Defining Tools

Tools are defined using JSON Schema, which describes the function name, description, and expected parameters.

Basic Tool Structure

{
  "name": "get_weather",
  "description": "Get current weather information for a specific city",
  "schema": {
    "type": "object",
    "properties": {
      "city": {
        "type": "string",
        "description": "City name"
      },
      "units": {
        "type": "string",
        "enum": ["celsius", "fahrenheit"],
        "description": "Temperature units"
      }
    },
    "required": ["city"]
  },
  "webhook": {
    "url": "https://api.example.com/tools/weather",
    "headers": {
      "Authorization": "Bearer your-api-key",
      "Content-Type": "application/json"
    }
  },
  "fallBackResult": {
    "temperature": "unknown",
    "conditions": "unavailable"
  }
}

Tool Properties

Required Fields

name (string, required)
  • Unique identifier for the tool
  • Must match pattern: ^[a-zA-Z_][a-zA-Z0-9_]*$
  • Must start with a letter or underscore; hyphens are not allowed
  • Used by LLM to reference the function
  • Example: "get_weather", "book_appointment", "search_database"
description (string, required)
  • Clear explanation of what the tool does
  • Helps the LLM decide when to use this tool
  • Should describe inputs, outputs, and side effects
  • Example: "Get current weather information for a specific city. Returns temperature, conditions, and forecast."
schema (object, required)
  • JSON Schema defining the tool’s parameters
  • Must be a valid JSON Schema object
  • Describes expected arguments and their types
  • Supports complex nested structures
webhook (object, required)
  • Configuration for the webhook endpoint that executes the tool
  • Contains URL and optional headers
  • See Webhook Configuration below

Optional Fields

fallBackResult (any, optional)
  • Default result returned if webhook fails or times out
  • Can be any JSON-serializable value
  • Allows conversation to continue gracefully on errors
  • Example: {"error": "Service temporarily unavailable"}
timeoutSeconds (integer, optional)
  • Maximum time to wait for webhook response
  • Validated range: 1-300 seconds
  • Note: Webhook calls currently use a fixed 60-second HTTP timeout regardless of this setting
  • After timeout, fallback result is used
retryCount (integer, optional)
  • Number of retry attempts on webhook failure
  • Validated range: 0-5
  • Note: Webhook retries already use a global retry policy (initial attempt plus up to three retries with exponential backoff), so per-tool overrides are not yet applied
  • Useful for handling transient network errors

JSON Schema Examples

Simple Parameter Tool

A basic tool with primitive parameters:
{
  "name": "send_sms",
  "description": "Send an SMS message to a phone number",
  "schema": {
    "type": "object",
    "properties": {
      "phone_number": {
        "type": "string",
        "pattern": "^\\+[1-9]\\d{1,14}$",
        "description": "Recipient's phone number in E.164 format"
      },
      "message": {
        "type": "string",
        "maxLength": 160,
        "description": "Message content (max 160 characters)"
      }
    },
    "required": ["phone_number", "message"]
  }
}

Complex Nested Parameters

A tool with nested objects and arrays:
{
  "name": "book_appointment",
  "description": "Schedule an appointment with availability checking",
  "schema": {
    "type": "object",
    "properties": {
      "customer": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "Customer's full name"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Customer's email address"
          },
          "phone": {
            "type": "string",
            "description": "Customer's phone number"
          }
        },
        "required": ["name", "email"]
      },
      "appointment": {
        "type": "object",
        "properties": {
          "datetime": {
            "type": "string",
            "format": "date-time",
            "description": "Requested appointment time (ISO 8601)"
          },
          "duration_minutes": {
            "type": "integer",
            "minimum": 15,
            "maximum": 480,
            "description": "Appointment duration in minutes"
          },
          "service_type": {
            "type": "string",
            "enum": ["consultation", "follow-up", "emergency"],
            "description": "Type of appointment"
          }
        },
        "required": ["datetime", "service_type"]
      },
      "notes": {
        "type": "string",
        "description": "Optional notes or special requests"
      }
    },
    "required": ["customer", "appointment"]
  }
}

Enumerated Options

A tool with predefined choices:
{
  "name": "update_ticket_status",
  "description": "Update the status of a support ticket",
  "schema": {
    "type": "object",
    "properties": {
      "ticket_id": {
        "type": "string",
        "pattern": "^TKT-[0-9]{6}$",
        "description": "Ticket ID (format: TKT-123456)"
      },
      "status": {
        "type": "string",
        "enum": ["open", "in_progress", "waiting_customer", "resolved", "closed"],
        "description": "New status for the ticket"
      },
      "priority": {
        "type": "string",
        "enum": ["low", "medium", "high", "urgent"],
        "description": "Ticket priority level"
      },
      "assigned_to": {
        "type": "string",
        "description": "Email of agent to assign ticket to"
      }
    },
    "required": ["ticket_id", "status"]
  }
}

Array Parameters

A tool that accepts arrays:
{
  "name": "search_products",
  "description": "Search product catalog with filters",
  "schema": {
    "type": "object",
    "properties": {
      "keywords": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "minItems": 1,
        "description": "Search keywords"
      },
      "categories": {
        "type": "array",
        "items": {
          "type": "string",
          "enum": ["electronics", "clothing", "home", "books"]
        },
        "description": "Filter by product categories"
      },
      "price_range": {
        "type": "object",
        "properties": {
          "min": {
            "type": "number",
            "minimum": 0
          },
          "max": {
            "type": "number",
            "minimum": 0
          }
        }
      },
      "in_stock_only": {
        "type": "boolean",
        "default": true,
        "description": "Only show products in stock"
      }
    },
    "required": ["keywords"]
  }
}

Webhook Configuration

Webhooks are HTTP endpoints that receive tool call requests and return results.

Webhook Object Structure

{
  "url": "https://api.example.com/webhooks/tools",
  "headers": {
    "Authorization": "Bearer sk-abc123...",
    "X-Custom-Header": "value"
  },
  "customSettings": {
    // Provider-specific settings (optional)
  }
}

Request Format

When your tool is invoked, BlackBox sends a POST request to your webhook URL with the following JSON payload. Only headers configured in your tool definition are sent; no automatic X-BlackBox-* headers are injected.
POST https://api.example.com/webhooks/tools
Content-Type: application/json
Authorization: Bearer sk-abc123...

{
  "type": "ToolWebHookPayload",
  "status": "Running",
  "callId": "67890abcdef123456789",
  "agentId": "12345abcdef67890",
  "orgId": "org_abc123xyz",
  "toolName": "get_weather",
  "arguments": {
    "city": "San Francisco",
    "units": "fahrenheit"
  },
  "callAdditionalData": {
    "campaign_id": "summer_outreach",
    "region": "west_coast"
  },
  "agentAdditionalData": {
    "department": "sales",
    "tier": "premium"
  },
  "serverJobId": "job_xyz789abc",
  "sip": {
    "from": "sip:+14155551234@sip.example.com",
    "to": "sip:+14085559876@sip.example.com"
  }
}
Note: The callAdditionalData, agentAdditionalData, serverJobId, and sip fields are optional and only included when available.

Response Format

Your webhook must return a JSON response within the timeout period: Success Response (200 OK)
{
  "temperature": 68,
  "conditions": "sunny",
  "humidity": 65,
  "forecast": "Clear skies throughout the day"
}
Error Response (4xx or 5xx)
{
  "error": "Invalid city name",
  "errorCode": "INVALID_CITY",
  "details": "City 'Atlantis' not found in database"
}
If your webhook returns an error status code, the fallBackResult will be used (if configured), or the agent will inform the user that the tool failed.

Response Best Practices

  1. Return Structured Data: Use JSON objects with clear field names
  2. Include Context: Return enough information for the LLM to formulate a complete response
  3. Handle Errors Gracefully: Return error objects instead of crashing
  4. Be Concise: Avoid returning massive datasets; summarize when possible
  5. Fast Response: Aim for sub-second responses to maintain conversation flow

Configuring Tools in the Dashboard

Step 1: Navigate to Tools Tab

When creating or editing an agent, navigate to the Tools tab: Tools tab in agent creation interface Configure function calling tools for your agent

Step 2: Add a New Tool

Click Add Tool to create a new tool configuration:
  1. Tool Name: Enter a unique identifier (e.g., get_weather)
  2. Description: Describe what the tool does and when to use it
  3. Schema Editor: Define parameters using JSON Schema
  4. Webhook URL: Enter your webhook endpoint
  5. Headers: Add authentication and custom headers
  6. Advanced Options:
    • Set timeout (1-60 seconds)
    • Configure retry count (0-3)
    • Define fallback result

Step 3: Test Your Tool

Use the built-in testing interface:
  1. Click Test Tool
  2. Enter sample arguments
  3. Review the webhook request
  4. Verify the response
  5. Check that the LLM can interpret the result

Step 4: Save and Enable

After configuring your tools:
  1. Click Save Agent
  2. Toggle Allow this agent to take calls
  3. Test with the dashboard test widget

Tool Webhooks vs Event Webhooks

BlackBox supports two types of webhooks:

Tool Webhooks

  • Purpose: Execute specific functions called by the agent
  • Trigger: LLM decides to invoke a tool during conversation
  • Request: Contains tool name and arguments
  • Response: Returns function result to LLM
  • Timeout: Tool webhooks use a fixed 60-second HTTP timeout; the timeoutSeconds field is validated (1-300 seconds) but not yet applied
  • Configured: Per tool in the Tools tab

Event Webhooks

  • Purpose: Receive notifications about call lifecycle events
  • Trigger: Specific events (call start, result, failure, deadline)
  • Request: Contains event data and call metadata
  • Response: Acknowledgment only (not used in conversation)
  • Timeout: Fixed at 30 seconds
  • Configured: In the Webhooks tab
See Webhook Events for event webhook details.

Testing Webhooks

BlackBox provides a testing endpoint to validate your webhook implementations:

Via Dashboard

  1. Navigate to agent’s Tools tab
  2. Click Test Tool on any configured tool
  3. Enter sample arguments
  4. Review request/response in real-time

Via API

Use the webhook testing endpoint:
const testPayload = await fetch('https://blackbox.dasha.ai/api/v1/webhooks/test', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    webHook: {
      url: 'https://api.example.com/webhooks/tools',
      headers: {
        'Authorization': 'Bearer your-webhook-key'
      }
    },
    webhookType: 'ToolWebHookPayload',
    toolName: 'get_weather',
    toolArguments: {
      city: 'San Francisco',
      units: 'fahrenheit'
    }
  })
});

const result = await testPayload.json();
console.log('Webhook test result:', result);
The testing endpoint simulates a real tool call and validates:
  • HTTP response status and timing
  • Response payload structure
  • Error handling behavior
  • Authentication and headers

MCP Tools

BlackBox integrates with Model Context Protocol (MCP) servers to provide pre-built tools without custom webhook development.

What is MCP?

Model Context Protocol is an open standard for connecting AI agents to external data sources and tools. MCP servers expose tools that your agent can use automatically.

Configuring MCP Connections

  1. Navigate to the MCP Connections tab
  2. Click Add Connection
  3. Enter the MCP server URL
  4. Click Test Connection to verify
  5. Review available tools from the server
  6. Save agent to enable MCP tools
See MCP Connections for detailed setup instructions.

MCP vs Custom Webhooks

FeatureCustom WebhooksMCP Servers
Setup ComplexityMedium (write webhook handler)Low (connect to existing server)
Tool DiscoveryManual definitionAutomatic from server
Schema FormatJSON SchemaMCP tool schema
HostingSelf-hosted or cloudMCP server provider
CustomizationFull controlLimited to server capabilities
Use custom webhooks when you need full control or integration with proprietary systems. Use MCP connections for standard integrations like databases, calendars, or public APIs.

Best Practices

Tool Design

Keep Tools Focused
  • Each tool should do one thing well
  • Avoid multi-purpose tools with too many parameters
  • Split complex operations into multiple simple tools
Write Clear Descriptions
  • Explain what the tool does in natural language
  • Describe when the LLM should use this tool
  • Include examples of valid inputs
  • Mention side effects or limitations
Use Strong Typing
  • Define precise JSON schemas with proper types
  • Use enums for fixed choices
  • Add format hints (email, uri, date-time)
  • Set reasonable min/max constraints
Provide Good Defaults
  • Use schema defaults for optional parameters
  • Configure sensible fallback results
  • Set appropriate timeouts based on operation complexity

Webhook Implementation

Security
  • Always use HTTPS endpoints
  • Implement authentication via headers
  • Validate incoming requests
  • Rate limit to prevent abuse
  • Log all requests for debugging
Performance
  • Respond within timeout (aim for under 1 second)
  • Use async processing for slow operations
  • Implement caching where appropriate
  • Return concise responses
Error Handling
  • Return structured error objects
  • Use appropriate HTTP status codes
  • Log errors for troubleshooting
  • Configure fallback results for critical tools
Reliability
  • Implement retry logic in webhook handler
  • Use idempotent operations when possible
  • Monitor webhook uptime
  • Set up alerting for failures

Schema Guidelines

Property Descriptions
// ✅ Good
{
  "customer_email": {
    "type": "string",
    "format": "email",
    "description": "Customer's email address for order confirmation"
  }
}

// ❌ Avoid
{
  "email": {
    "type": "string",
    "description": "Email"
  }
}
Enums for Limited Choices
// ✅ Good - Fixed set of values
{
  "priority": {
    "type": "string",
    "enum": ["low", "medium", "high", "urgent"]
  }
}

// ❌ Avoid - Free text when choices are limited
{
  "priority": {
    "type": "string",
    "description": "Priority level"
  }
}
Required vs Optional
// ✅ Good - Clear requirements
{
  "properties": {
    "customer_id": { "type": "string" },
    "notes": { "type": "string", "default": "" }
  },
  "required": ["customer_id"]
}

Common Use Cases

CRM Integration

Enable your agent to query and update customer records:
{
  "name": "lookup_customer",
  "description": "Retrieve customer information by email or phone number",
  "schema": {
    "type": "object",
    "properties": {
      "identifier": {
        "type": "string",
        "description": "Customer email or phone number"
      }
    },
    "required": ["identifier"]
  },
  "webhook": {
    "url": "https://crm.example.com/api/webhooks/lookup",
    "headers": {
      "Authorization": "Bearer crm-api-key"
    }
  }
}

Calendar Booking

Allow agents to check availability and book appointments:
{
  "name": "check_availability",
  "description": "Check available appointment slots for a given date range",
  "schema": {
    "type": "object",
    "properties": {
      "start_date": {
        "type": "string",
        "format": "date",
        "description": "Start date (YYYY-MM-DD)"
      },
      "end_date": {
        "type": "string",
        "format": "date",
        "description": "End date (YYYY-MM-DD)"
      },
      "service_type": {
        "type": "string",
        "description": "Type of service requested"
      }
    },
    "required": ["start_date", "end_date"]
  }
}
Let agents search internal documentation:
{
  "name": "search_knowledge_base",
  "description": "Search company knowledge base for relevant information",
  "schema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Search query"
      },
      "category": {
        "type": "string",
        "enum": ["products", "policies", "troubleshooting"],
        "description": "Knowledge base category to search"
      },
      "max_results": {
        "type": "integer",
        "minimum": 1,
        "maximum": 10,
        "default": 5,
        "description": "Maximum number of results to return"
      }
    },
    "required": ["query"]
  }
}

Troubleshooting

Tool Not Being Called

LLM not invoking the tool:
  • Improve the tool description to be more specific
  • Mention the tool in system prompt if critical
  • Test with explicit user requests that should trigger the tool
  • Check that the tool name is clear and descriptive

Webhook Timeouts

Webhook exceeding timeout:
  • Increase timeoutSeconds for slow operations
  • Optimize webhook processing time
  • Use async processing and return immediately
  • Configure appropriate fallBackResult

Schema Validation Errors

Arguments not matching schema:
  • Review LLM-generated arguments in call logs
  • Simplify complex nested schemas
  • Add clear descriptions to all properties
  • Use enums to constrain values
  • Test schema with webhook testing endpoint

Authentication Failures

Webhook returning 401/403:
  • Verify header configuration in tool setup
  • Check that API keys are valid and not expired
  • Ensure webhook URL is correct and accessible
  • Test webhook independently with curl/Postman

Next Steps

API Cross-Refs