---
title: "Connect CallHub to AI Agents: Automate Phonebooks and Rent Numbers"
slug: connect-callhub-to-ai-agents-automate-phonebooks-and-rent-numbers
date: 2026-10-04
author: Nachi Raman
categories: ["AI & Agents"]
excerpt: "Learn how to connect CallHub to AI agents using Truto's /tools endpoint. Build autonomous workflows for phonebook management, campaign orchestration, and number renting."
tldr: "Connect CallHub to AI agents safely using Truto's proxy tool layer. We cover bypassing API quirks, managing asynchronous bulk imports, handling rate limits, and wiring CallHub into LangChain."
canonical: https://truto.one/blog/connect-callhub-to-ai-agents-automate-phonebooks-and-rent-numbers/
---

# Connect CallHub to AI Agents: Automate Phonebooks and Rent Numbers


You want to connect CallHub to an AI agent so your system can autonomously rent calling numbers, provision phonebooks, update campaign statuses, and enforce Do-Not-Call (DNC) lists. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to write custom integration boilerplate for the CallHub REST API.

Giving a Large Language Model (LLM) read and write access to your communications infrastructure requires a strict security and validation layer. If your team uses ChatGPT, check out our guide on [connecting CallHub to ChatGPT](https://truto.one/connect-callhub-to-chatgpt-manage-contacts-and-campaign-workflows/), or if you are building on Anthropic's models, read our guide on [connecting CallHub to Claude](https://truto.one/connect-callhub-to-claude-manage-teams-agents-and-script-templates/). For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for CallHub, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex campaign automation workflows. For a broader look at the architecture behind this tool-calling pattern, refer to our research on [architecting AI agents and the SaaS integration bottleneck](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/).

## Why a Proxy Tool Layer Matters for Agent Safety

Before writing a single fetch request to the CallHub API, you must decide how your agent interacts with external systems. This architectural choice determines the reliability and safety of your production environment.

Building direct API tools - where you manually wrap individual CallHub endpoints into function definitions - seems straightforward for a prototype. In production, it pushes vendor-specific API quirks directly into the LLM's context window. The model has to remember exact endpoint paths, unique ID formatting, and undocumented query parameter structures. Every edge case is an opportunity for the model to hallucinate a broken payload.

Truto solves this by providing a Proxy API layer. Truto reads the comprehensive JSON object representing the integration and maps every CallHub endpoint to a standardized `Resource` and `Method`. The `/tools` endpoint dynamically exposes these methods as strictly typed JSON schemas that an LLM can natively consume.

This approach yields significant safety advantages:

1. **Deterministic input validation.** Every tool has a strict JSON schema. If an agent hallucinates a parameter type, the tool call fails validation locally before a malformed request is ever sent to CallHub.
2. **Reduced context overhead.** The LLM sees clean, semantic function names like `create_a_call_hub_rent_number` rather than raw REST URLs. 
3. **Centralized authentication.** Your agent code never touches OAuth tokens, API keys, or refresh logic. The tool execution layer handles all session state via the integrated account ID.

```mermaid
flowchart TD
    Agent["AI Agent Core<br>(LangChain, CrewAI)"]
    ToolManager["Tool Manager<br>(SDK binding)"]
    Truto["Truto Unified<br>Tool Layer"]
    CallHub["CallHub API"]

    Agent -->|"Tool execution request"| ToolManager
    ToolManager -->|"Validates Schema"| Truto
    Truto -->|"Injects Auth & Proxies"| CallHub
    CallHub -->|"Raw JSON Response"| Truto
    Truto -->|"Standardized Output"| ToolManager
    ToolManager -->|"Agent Observation"| Agent
```

## The Engineering Reality of the CallHub API

Connecting AI agents to external systems is rarely as simple as sending a JSON payload. Telephony and campaign management APIs like CallHub introduce specific constraints that break standard CRUD assumptions. If you do not account for these behaviors, your agent will enter failure loops.

### Asynchronous Bulk Operations

Standard REST APIs typically return the created object immediately after a POST request. CallHub's bulk import endpoints deviate from this pattern. When using `create_a_call_hub_contacts_bulk_create`, the API accepts a CSV upload or a hosted `csv_url` and processes the import asynchronously. 

The agent does not receive an array of created contact IDs back. Instead, it receives an acceptance message indicating the job has started. You must explicitly prompt your agent to understand that this operation is asynchronous; otherwise, the agent will immediately attempt to query a contact that has not yet been processed by CallHub's background workers.

### Campaign State Machine Locking

Updating a Peer-to-Peer (P2P) campaign via `update_a_call_hub_p_2_p_campaign_by_id` requires strict adherence to CallHub's internal state machine. The endpoint uses strict PATCH semantics.

CallHub enforces a rule: you cannot change the name of a campaign while it is actively running (status `1 = START`). To rename an active campaign, the request must simultaneously transition the status out of START (e.g., to `2 = PAUSE`). If an autonomous agent attempts to rename a running campaign without changing its status, CallHub will reject the request. The tool schemas enforce the data types, but your system prompt must provide the agent with the operational logic regarding campaign states.

### Rate Limits and Header Normalization

When building autonomous agents, rate limits are not just an operational annoyance - they are application-breaking events. An overly aggressive agent loop can quickly exhaust API quotas.

**Fact:** Truto does not retry, throttle, or apply backoff on rate limit errors. 

When the upstream CallHub API returns an HTTP 429 Too Many Requests error, Truto intentionally passes that error directly back to the caller. Truto normalizes the upstream rate limit information into standardized HTTP headers per the IETF specification:

- `ratelimit-limit`: The total allowed requests in the current window.
- `ratelimit-remaining`: The number of requests left.
- `ratelimit-reset`: The time at which the window resets.

It is the caller's explicit responsibility to implement retry and backoff logic. Your agent framework must catch the 429 response, read the `ratelimit-reset` header, pause execution, and retry. Do not assume the proxy layer will automatically absorb or queue these errors.

## Hero Tools for CallHub Automation

Truto exposes the entire CallHub API surface area through the `/tools` endpoint. However, when orchestrating agents, you should restrict the agent's context to the highest-leverage operations. Here are the core "hero tools" for CallHub automation.

### List All Rented Calling Numbers

**Tool:** `list_all_call_hub_calling_numbers`

Before an agent can spin up a voice broadcast, it needs to know what phone numbers are currently available in the organization's inventory. This tool returns a list of rented numbers, including their `country`, `region`, `is_active` status, and whether they are currently assigned to a campaign. It supports filtering by country and region.

> "Check our CallHub account and list all active calling numbers located in the United States (US) that are not currently used in a campaign."

### Rent a Phone Number

**Tool:** `create_a_call_hub_rent_number`

This is a highly autonomous action. If an agent determines that a new campaign requires a local presence in a specific region, it can dynamically rent a number. The tool requires a `country_iso` code. If no numbers are available in the specifically requested area code, CallHub will automatically rent a random number from that country. It returns the rented number's ID, capabilities (voice/sms/mms), and rental charges.

> "We need a new local presence for our upcoming UK campaign. Rent a new phone number in the GB region that supports both Voice and SMS."

### Bulk Create Contacts in Phonebook

**Tool:** `create_a_call_hub_contacts_bulk_create`

Instead of inserting contacts one by one (which is slow and expensive on API limits), this tool allows the agent to trigger a bulk import into a specific phonebook. You provide the `phonebook_id` and a `csv_url` hosted externally. Remember that this operation returns asynchronously.

> "Take the voter registration CSV hosted at [URL] and trigger a bulk import into the 'Q3 Rally Attendees' phonebook. Acknowledge when the import job has been successfully queued."

### Add Contacts to Phonebook

**Tool:** `call_hub_phonebook_contacts_bulk_add`

For managing existing contacts, this tool allows the agent to associate an array of `contact_ids` with a specific `phonebook_id`. It returns the updated phonebook object, including the new contact count.

> "Take the contact IDs for John Doe and Jane Smith and add them in bulk to the 'High Value Donors' phonebook. Verify the new total contact count."

### Create a DNC Contact

**Tool:** `create_a_call_hub_dnc_contact`

Compliance is critical in telephony. This tool adds a phone number to the Do-Not-Call (DNC) list. The agent must pass the `phone_number` and the `dnc` boolean. It can also specify the `category` (1 for voice only, 2 for text only, 3 for both). 

> "A user explicitly requested to stop receiving communications. Add +15550198372 to the CallHub DNC list for both calling and texting immediately."

### Update a P2P Campaign

**Tool:** `update_a_call_hub_p_2_p_campaign_by_id`

This tool controls the lifecycle of a Peer-to-Peer campaign. The agent can pause, start, or end a campaign by passing the appropriate status integer (1 = START, 2 = PAUSE, 4 = END). 

> "The weekend outreach window has closed. Target the 'Voter GOTV' campaign by its ID and update its status to PAUSE (2)."

To view the complete inventory of available CallHub tools, their exact JSON schema definitions, and required parameters, visit the [CallHub integration page](https://truto.one/integrations/detail/callhub).

## Workflows in Action

Autonomous agents deliver value by chaining multiple discrete API calls into a unified business outcome. Here are two concrete, real-world examples of how an AI agent uses the tools defined above.

### Workflow 1: Autonomous Campaign Provisioning

An operations manager needs to spin up a localized outreach campaign for a specific geographic region without clicking through the CallHub UI.

> "We need to launch a new outreach initiative for our Texas constituents. Check if we have an active US number. If we don't, rent one. Then, create a new phonebook called 'TX Outreach', and assign the resulting phonebook ID to me so I can upload the contact list."

**Step-by-step Execution:**
1. The agent calls `list_all_call_hub_calling_numbers` filtered by US to check inventory.
2. Discovering no available numbers for the specific region, the agent calls `create_a_call_hub_rent_number` passing the US ISO code to acquire a new asset.
3. The agent calls a custom create phonebook proxy tool (or utilizes the standard REST API tool) to instantiate 'TX Outreach'.
4. The agent returns a synthesized summary containing the new phone number string, its monthly cost, and the destination Phonebook ID.

### Workflow 2: Automated Compliance Enforcement

A compliance monitor detects that a running campaign is generating a high volume of opt-out replies across multiple channels.

> "User +15550199999 reported our current P2P campaign as spam. Immediately add their number to the global DNC list. Because this is the 50th complaint today, locate the running campaign associated with this list and pause it pending human review."

**Step-by-step Execution:**
1. The agent calls `create_a_call_hub_dnc_contact`, setting the category to 3 (blocking both voice and SMS) for the flagged number.
2. The agent utilizes a search tool (or queries an internal database) to find the ID of the currently active P2P campaign.
3. The agent calls `update_a_call_hub_p_2_p_campaign_by_id`, targeting that ID and passing status `2` (PAUSE).
4. The agent reports back that compliance measures were enforced and the campaign is halted.

## Building Multi-Step Workflows

To actually execute these workflows, you need to bind the Truto tools to an agent framework. The following example demonstrates how to implement this pattern using LangChain.js, though the underlying architecture works seamlessly with LangGraph, CrewAI, or the Vercel AI SDK.

The critical engineering challenge here is handling tool failures - specifically rate limits. Because Truto passes HTTP 429s directly back to the caller, your execution loop must intercept these errors and apply backoff logic based on the `ratelimit-reset` header.

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { TrutoToolManager } from "truto-langchainjs-toolset";

async function buildCallHubAgent(integratedAccountId: string) {
  // 1. Initialize the Truto Tool Manager for the specific CallHub account
  const toolManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
    accountId: integratedAccountId,
  });

  // 2. Fetch the tools dynamically from the Truto API
  // You can filter to specific methods to save context space
  const callhubTools = await toolManager.getTools({
    methods: ["read", "write", "custom"]
  });

  // 3. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4-turbo",
    temperature: 0,
  });

  // 4. Bind the fetched JSON schemas directly to the LLM
  const llmWithTools = llm.bindTools(callhubTools);

  // 5. Define the Agent Prompt
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are a CallHub telecommunications administrator. You manage campaigns, rent numbers, and enforce DNC compliance. Remember that bulk imports are asynchronous."],
    ["human", "{input}"],
    ["placeholder", "{agent_scratchpad}"],
  ]);

  const agent = createToolCallingAgent({
    llm: llmWithTools,
    tools: callhubTools,
    prompt,
  });

  // 6. Create the executor
  const executor = new AgentExecutor({
    agent,
    tools: callhubTools,
    maxIterations: 5,
  });

  return executor;
}
```

### Handling CallHub Rate Limits in the Agent Loop

If the agent iterates too quickly through a list of DNC updates, it will trigger an HTTP 429. Your system needs a resilient wrapper around the agent execution to inspect the standardized headers.

```mermaid
sequenceDiagram
    participant Agent as Agent Executor
    participant Truto as Truto Tool Proxy
    participant Upstream as CallHub API

    Agent->>Truto: Call update_a_call_hub_contact_by_id
    Truto->>Upstream: Proxied PATCH Request
    Upstream-->>Truto: 429 Too Many Requests
    Truto-->>Agent: 429 Error + ratelimit-reset Header
    Note over Agent: Agent parses header<br>Calculates wait time
    Agent->>Agent: Sleep (Reset duration)
    Agent->>Truto: Retry update_a_call_hub_contact_by_id
    Truto->>Upstream: Proxied PATCH Request
    Upstream-->>Truto: 200 OK
    Truto-->>Agent: Success JSON
```

When a tool call fails, LangChain typically returns the error string to the model, allowing the LLM to decide what to do next. However, for 429s, it is often better to handle the retry at the transport layer (inside the tool implementation or a wrapper) before returning control to the LLM, preventing the LLM from wasting tokens trying to "reason" about rate limits.

> Stop spending engineering sprints maintaining CallHub API connections. Use Truto to instantly give your AI agents safe, structured tool access to over 200+ SaaS platforms.
>
> [Talk to us](https://truto.one/book-a-demo/)

Connecting external telecommunications platforms to autonomous workflows is an exercise in schema validation and state management. By utilizing a proxy tool layer, you remove the burden of auth management and endpoint mapping from your LLM prompts. The model relies on strict, normalized JSON interfaces, dramatically reducing hallucination risk and allowing your engineering team to focus on agent reasoning instead of integration boilerplate.
