> ## Documentation Index
> Fetch the complete documentation index at: https://blackbox.dasha.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Add External API Integrations

> Enable agents to call external APIs, query databases, and perform actions during conversations using function calling.

Give your agent the ability to take action. Tools let the LLM call external APIs, query databases, book appointments, and check order status — anything your webhook can handle.

**What you'll learn:** How to define tools with JSON Schema, configure webhooks, handle responses, and test tool execution.

***

## Quick start: Add a tool

<Steps>
  <Step title="Navigate to Tools tab">
    When creating or editing an agent, select the **Tools** tab.
  </Step>

  <Step title="Add a new tool">
    Click **Add Tool** to create a new tool configuration.
  </Step>

  <Step title="Configure settings">
    * **Tool Name**: Unique identifier (e.g., `get_weather`)
    * **Description**: What the tool does and when to use it
    * **Schema**: Define parameters using JSON Schema
    * **Webhook URL**: Your endpoint
    * **Headers**: Authentication and custom headers
  </Step>

  <Step title="Test your tool">
    Click **Test Tool**, enter sample arguments, and verify the response.
  </Step>

  <Step title="Save and enable">
    Save the agent and toggle **Allow this agent to take calls**.
  </Step>
</Steps>

<Accordion title="How function calling works">
  When you configure tools, the LLM gains awareness of available functions and autonomously decides when to call them during conversation. Dasha BlackBox sends requests to your webhook, your webhook executes the function, and the LLM incorporates results into its response.

  **Key capabilities:** JSON Schema for tool definitions, call metadata (callId, agentId, orgId) in webhook requests, automatic retry with exponential backoff, and built-in testing.
</Accordion>

***

## Define a tool

<Accordion title="Tool structure">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "get_weather",
    "description": "Get current weather for a city",
    "schema": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "City name"
        },
        "units": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"]
        }
      },
      "required": ["city"]
    },
    "webhook": {
      "url": "https://api.example.com/tools/weather",
      "headers": {
        "Authorization": "Bearer your-api-key"
      }
    },
    "fallBackResult": {
      "temperature": "unknown",
      "conditions": "unavailable"
    }
  }
  ```
</Accordion>

### Required fields

| Field         | Type   | Description                                                               |
| ------------- | ------ | ------------------------------------------------------------------------- |
| `name`        | string | Unique identifier. Pattern: `^[a-zA-Z_][a-zA-Z0-9_]*$`. No hyphens.       |
| `description` | string | Clear explanation of what the tool does. Helps LLM decide when to use it. |
| `schema`      | object | JSON Schema defining parameters.                                          |
| `webhook`     | object | URL and headers for the endpoint.                                         |

### Optional fields

| Field            | Type    | Description                                                                  |
| ---------------- | ------- | ---------------------------------------------------------------------------- |
| `fallBackResult` | any     | Default result if webhook fails. Allows conversation to continue gracefully. |
| `timeoutSeconds` | integer | Max wait time (1–300). Note: Currently uses fixed 60s HTTP timeout.          |
| `retryCount`     | integer | Retry attempts (0–5). Uses global retry policy with exponential backoff.     |

***

## JSON Schema examples

<Accordion title="Simple parameters">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "send_sms",
    "description": "Send an SMS message",
    "schema": {
      "type": "object",
      "properties": {
        "phone_number": {
          "type": "string",
          "pattern": "^\\+[1-9]\\d{1,14}$",
          "description": "Phone in E.164 format"
        },
        "message": {
          "type": "string",
          "maxLength": 160,
          "description": "Message content"
        }
      },
      "required": ["phone_number", "message"]
    }
  }
  ```
</Accordion>

<Accordion title="Nested objects">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "book_appointment",
    "description": "Schedule an appointment",
    "schema": {
      "type": "object",
      "properties": {
        "customer": {
          "type": "object",
          "properties": {
            "name": { "type": "string" },
            "email": { "type": "string", "format": "email" },
            "phone": { "type": "string" }
          },
          "required": ["name", "email"]
        },
        "appointment": {
          "type": "object",
          "properties": {
            "datetime": { "type": "string", "format": "date-time" },
            "duration_minutes": { "type": "integer", "minimum": 15 },
            "service_type": {
              "type": "string",
              "enum": ["consultation", "follow-up", "emergency"]
            }
          },
          "required": ["datetime", "service_type"]
        }
      },
      "required": ["customer", "appointment"]
    }
  }
  ```
</Accordion>

<Accordion title="Arrays">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "search_products",
    "description": "Search product catalog",
    "schema": {
      "type": "object",
      "properties": {
        "keywords": {
          "type": "array",
          "items": { "type": "string" },
          "minItems": 1
        },
        "categories": {
          "type": "array",
          "items": {
            "type": "string",
            "enum": ["electronics", "clothing", "home", "books"]
          }
        },
        "in_stock_only": {
          "type": "boolean",
          "default": true
        }
      },
      "required": ["keywords"]
    }
  }
  ```
</Accordion>

<Accordion title="Enumerations">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "update_ticket_status",
    "description": "Update support ticket status",
    "schema": {
      "type": "object",
      "properties": {
        "ticket_id": {
          "type": "string",
          "pattern": "^TKT-[0-9]{6}$"
        },
        "status": {
          "type": "string",
          "enum": ["open", "in_progress", "waiting_customer", "resolved", "closed"]
        },
        "priority": {
          "type": "string",
          "enum": ["low", "medium", "high", "urgent"]
        }
      },
      "required": ["ticket_id", "status"]
    }
  }
  ```
</Accordion>

***

## Configure webhooks

<Accordion title="Request format">
  When your tool is invoked, Dasha BlackBox sends a POST request:

  ```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
  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"
    },
    "agentAdditionalData": {
      "department": "sales"
    }
  }
  ```
</Accordion>

<Note>
  Only headers configured in your tool definition are sent. The `callAdditionalData`, `agentAdditionalData`, `serverJobId`, and `sip` fields are optional.
</Note>

<Accordion title="Response format">
  Return a JSON response within the timeout period:

  **Success (200 OK):**

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "temperature": 68,
    "conditions": "sunny",
    "humidity": 65
  }
  ```
</Accordion>

<Accordion title="Error Response (4xx/5xx)">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "error": "Invalid city name",
    "errorCode": "INVALID_CITY"
  }
  ```
</Accordion>

If your webhook returns an error, the `fallBackResult` is used (if configured).

### Response best practices

* **Return structured data** with clear field names
* **Include context** for the LLM to formulate complete responses
* **Handle errors gracefully** — return error objects instead of crashing
* **Be concise** — avoid massive datasets, summarize when possible
* **Respond quickly** — aim for sub-second responses

***

## Test webhooks

### 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

<Accordion title="Via API">
  ```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = 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 response.json();
  console.log(result);
  // Output:
  // {
  //   "success": true,
  //   "httpStatus": 200,
  //   "httpStatusText": "OK",
  //   "responseData": { "temperature": 68, "conditions": "sunny" },
  //   "validationResult": { "isValid": true, "errors": [] },
  //   "timeTaken": 145
  // }
  ```
</Accordion>

***

## Tool webhooks vs event webhooks

| Feature          | Tool webhooks                         | Event webhooks                                |
| ---------------- | ------------------------------------- | --------------------------------------------- |
| **Purpose**      | Execute functions during conversation | Receive call lifecycle notifications          |
| **Trigger**      | LLM decides to invoke a tool          | Specific events (call start, result, failure) |
| **Response**     | Returns result to LLM                 | Acknowledgment only                           |
| **Timeout**      | 60 seconds                            | 30 seconds                                    |
| **Configure in** | Tools tab                             | Webhooks tab                                  |

See [Webhook Events](/docs/webhooks-and-events/webhook-events) for event webhook details.

***

## MCP tools

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

### MCP vs custom webhooks

| Feature        | Custom webhooks       | MCP servers                    |
| -------------- | --------------------- | ------------------------------ |
| Setup          | Write webhook handler | Connect to existing server     |
| Tool discovery | Manual definition     | Automatic from server          |
| Hosting        | Self-hosted or cloud  | MCP server provider            |
| Customization  | Full control          | Limited to server capabilities |

**Use custom webhooks** for full control or proprietary system integration.

**Use MCP connections** for standard integrations like databases, calendars, or public APIs.

See [MCP Connections](/docs/create/mcp-connections) for setup instructions.

***

## Common use cases

<Accordion title="CRM integration">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "lookup_customer",
    "description": "Retrieve customer information by email or phone",
    "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"
      }
    }
  }
  ```
</Accordion>

<Accordion title="Calendar booking">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "check_availability",
    "description": "Check available appointment slots",
    "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"
        }
      },
      "required": ["start_date", "end_date"]
    }
  }
  ```
</Accordion>

<Accordion title="Knowledge base search">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "name": "search_knowledge_base",
    "description": "Search company knowledge base",
    "schema": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "Search query"
        },
        "category": {
          "type": "string",
          "enum": ["products", "policies", "troubleshooting"]
        },
        "max_results": {
          "type": "integer",
          "minimum": 1,
          "maximum": 10,
          "default": 5
        }
      },
      "required": ["query"]
    }
  }
  ```
</Accordion>

***

## Best practices

### Tool design

* **Keep tools focused** — one tool, one purpose
* **Write clear descriptions** — explain when the LLM should use the tool
* **Use strong typing** — precise schemas with proper types, enums, formats
* **Provide defaults** — sensible fallback results for error handling

<Accordion title="Schema guidelines">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // ✅ Good: Descriptive with constraints
  {
    "customer_email": {
      "type": "string",
      "format": "email",
      "description": "Customer's email for order confirmation"
    }
  }

  // ❌ Avoid: Vague and unconstrained
  {
    "email": {
      "type": "string",
      "description": "Email"
    }
  }
  ```
</Accordion>

### Webhook implementation

**Security:**

* Always use HTTPS endpoints
* Implement authentication via headers
* Validate incoming requests
* Rate limit to prevent abuse

**Performance:**

* Respond within timeout (aim for \< 1 second)
* Use async processing for slow operations
* Implement caching where appropriate

**Reliability:**

* Use idempotent operations when possible
* Monitor webhook uptime
* Set up alerting for failures

***

## Troubleshooting

<Accordion title="Tool not being called">
  * 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
</Accordion>

<Accordion title="Webhook timeouts">
  * Optimize webhook processing time
  * Use async processing and return immediately
  * Configure appropriate `fallBackResult`
</Accordion>

<Accordion title="Schema validation errors">
  * Review LLM-generated arguments in call logs
  * Simplify complex nested schemas
  * Add clear descriptions to all properties
  * Use enums to constrain values
</Accordion>

<Accordion title="Authentication failures">
  * 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
</Accordion>

***

## Next steps

<CardGroup cols={2}>
  <Card title="MCP connections" icon="plug" href="/docs/create/mcp-connections">
    Connect to MCP servers for pre-built tools
  </Card>

  <Card title="Webhook events" icon="bell" href="/docs/webhooks-and-events/webhook-events">
    Configure call lifecycle notifications
  </Card>

  <Card title="Test webhooks" icon="flask" href="/docs/webhooks-and-events/testing-webhooks">
    Validate webhook implementations
  </Card>

  <Card title="Dashboard testing" icon="desktop" href="/docs/test/dashboard-testing">
    Test tools in real conversations
  </Card>
</CardGroup>
