Skip to content

Connect Textmagic to AI Agents: Buy Numbers, Manage Lists & Audit Stats

Learn how to connect Textmagic to AI agents using Truto's unified tool layer. Buy dedicated numbers, manage contact lists, and execute complex SMS workflows autonomously.

Sidharth Verma Sidharth Verma · · 8 min read
Connect Textmagic to AI Agents: Buy Numbers, Manage Lists & Audit Stats

You want to connect Textmagic to an AI agent so your system can independently research and purchase dedicated numbers, sync contact lists, execute outbound SMS campaigns, and audit delivery statistics. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to manually code dozens of endpoints or maintain complex API wrappers.

Giving a Large Language Model (LLM) read and write access to your SMS infrastructure is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector that understands the nuances of telecommunications APIs, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Textmagic to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Textmagic to Claude. 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 Textmagic, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex messaging operations. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.

The Engineering Reality of Custom Textmagic Connectors

Building AI agents is easy. Connecting them to external SaaS APIs is hard. Giving an LLM access to external data sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production, this approach collapses entirely, especially with a telecommunications provider like Textmagic.

If you decide to build this integration yourself, you own the entire API lifecycle. Textmagic's API introduces several highly specific integration challenges that break standard LLM assumptions.

The Asynchronous Number Purchasing Trap

Buying a phone number programmatically is not a single atomic operation. To purchase a dedicated number, an agent must first query the available inventory for a specific region. In Textmagic, this means calling the available numbers endpoint, parsing a list of strings, extracting exactly one valid E.164 formatted string, and then feeding that string into a completely different endpoint alongside the account's userId. If you expose raw HTTP endpoints to an LLM, the model will inevitably try to skip the inventory search and invent a random phone number to pass to the purchase endpoint, resulting in immediate failure.

E.164 Formatting and One-by-One Lookups

Telecommunications APIs are notoriously strict about data formatting. Textmagic requires strict E.164 formatting for all phone numbers across its contact, messaging, and lookup endpoints. When an agent attempts to clean a list of contacts before a campaign, it might try to validate 500 numbers at once. However, Textmagic requires numbers to be checked one by one via its lookup endpoint. If you do not map this correctly, the LLM will pass an array of numbers to an endpoint that only accepts a single string, crashing the agent loop.

The Pagination Quirk: last_id vs Pages

Most APIs use simple page-based or cursor-based pagination. Textmagic uses standard page numbering for some resources (like contacts), but relies on a last_id parameter for others, such as outbound messages. If an agent wants to audit all messages sent in the last week, it must recursively fetch pages by supplying the lowest ID from the previous batch as the new last_id. Teaching an LLM this specific quirk via system prompts wastes valuable context tokens and dramatically increases the likelihood of hallucination.

Architecting the Proxy Layer for AI Safety

Direct API tools - exposing one tool per raw Textmagic endpoint - look convenient but push provider quirks directly into the LLM's context. The model has to remember that message history requires last_id while contact lists require page.

A structured proxy layer abstracts these inconsistencies. Truto operates by mapping any API into a REST-based CRUD concept called Resources. Every Resource has Methods defined on them (List, Get, Create, Update, Delete). Truto handles all the pagination, authentication, and query parameter processing automatically.

When your agent queries Truto's /tools endpoint, it receives a normalized, AI-ready JSON schema for every supported method. Your agent sees create_a_textmagic_number and list_all_textmagic_stats_messagings with strict property types. Invalid arguments are rejected locally against the schema before they ever hit the wire, meaning a broken tool call fails fast and allows the LLM to self-correct immediately.

Fetching and Binding Tools to Your Agent

Truto provides all the resources defined on an Integration as tools for your LLM frameworks to use. For Node.js and TypeScript developers, the easiest way to inject these tools is using the @trutohq/truto-langchainjs-toolset SDK.

Here is how you initialize the tool manager, fetch the Textmagic proxy endpoints, and bind them to an OpenAI model.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "@trutohq/truto-langchainjs-toolset";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";
 
// 1. Initialize the Truto Tool Manager with your integrated account ID
const toolManager = new TrutoToolManager({
  trutoApiKey: process.env.TRUTO_API_KEY,
  integratedAccountId: "textmagic-account-id-123",
});
 
async function runAgent() {
  // 2. Fetch all available Textmagic tools for this specific account
  const tools = await toolManager.getTools();
  
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // 3. Bind the Truto proxy tools to the LLM
  const llmWithTools = llm.bindTools(tools);
 
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are an elite revenue operations and SMS automation agent. You execute telecommunications tasks flawlessly."],
    ["human", "{input}"],
    new MessagesPlaceholder("agent_scratchpad"),
  ]);
 
  const agent = await createOpenAIToolsAgent({
    llm: llmWithTools,
    tools,
    prompt,
  });
 
  const agentExecutor = new AgentExecutor({
    agent,
    tools,
    maxIterations: 10,
  });
 
  // Execute a workflow
  const result = await agentExecutor.invoke({
    input: "Find an available US phone number and buy it for our account.",
  });
 
  console.log(result.output);
}

By calling .getTools(), the SDK reaches out to GET https://api.truto.one/integrated-account/<id>/tools. This returns an array of proxy APIs complete with descriptions and JSON schemas automatically generated from your Truto integration UI settings.

Core Textmagic Agent Tools

Rather than forcing your model to memorize REST paths, Truto translates the Textmagic API into distinct, isolated tools. Here are the highest-leverage operations you can expose to your agent.

list_all_textmagic_numbers_availables

Before purchasing a dedicated number, the agent must query available inventory. This tool requires a country parameter (2-letter ISO code) and returns an array of available strings.

"I need to run a local campaign in Canada. Query Textmagic for available numbers in the CA region and return the first three options."

create_a_textmagic_number

Once the agent has identified an available phone string, it uses this tool to execute the purchase. It requires the phone string, country, and the userId belonging to the account. Upon success, it returns an empty 201 response.

"Purchase the dedicated number +14165550198 for the CA region under user ID 88912."

create_a_textmagic_contacts_normalized

Building audience lists requires creating contact entities. This tool creates a new Textmagic contact and assigns it directly to one or more lists. It requires a strictly formatted phone parameter and a lists array containing list IDs.

"Create a new contact for John Doe with the number +15550198234 and add him to the VIP distribution list (ID: 9912)."

Agents need to cross-reference existing records to prevent duplicate sends. This tool searches Textmagic contacts by query strings, specific list IDs, or precise phone numbers, returning the full entity including custom fields, tags, and notes.

"Search our Textmagic database to see if we already have a contact record associated with the number +14155550199."

create_a_textmagic_message

This is the core execution tool for sending SMS or MMS messages. It accepts a text string and an array of phones, contact IDs, or list IDs. It supports advanced scheduling via rrule syntax and bulk sending for large recipient pools.

"Draft a welcome message reading 'Thanks for joining our loyalty program!' and send it to the contact ID 44512."

list_all_textmagic_stats_messagings

For auditing and observability, agents use this tool to fetch messaging statistics grouped by day, month, or overall totals. It returns critical deliverability data including replyRate, deliveryRate, messagesSentDelivered, and messagesSentFailed.

"Pull the messaging delivery statistics for the last 7 days and calculate our overall failure rate."

For the complete tool inventory and schema definitions - including sub-account management, custom fields, and invoice fetching - visit the Textmagic integration page.

Building Multi-Step Workflows and Handling Rate Limits

When executing multi-step loops, you must anticipate API rate limiting. This is a critical architectural consideration: Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Textmagic API returns an HTTP 429 (Too Many Requests), Truto immediately passes that exact error back to the caller.

However, Truto normalizes the upstream rate limit information into standardized headers per the IETF specification. Regardless of how Textmagic formats its headers natively, your agent framework will always receive ratelimit-limit, ratelimit-remaining, and ratelimit-reset.

sequenceDiagram
    participant Agent as AI Agent
    participant Truto as Truto Tool Manager
    participant Upstream as Textmagic API

    Agent->>Truto: call create_a_textmagic_message
    Truto->>Upstream: POST /api/v2/messages
    Upstream-->>Truto: HTTP 429 Too Many Requests
    Truto-->>Agent: Error 429 with IETF headers
    Note over Agent: Agent parses ratelimit-reset<br>Agent sleeps for X seconds
    Agent->>Truto: Retry call create_a_textmagic_message
    Truto->>Upstream: POST /api/v2/messages
    Upstream-->>Truto: HTTP 201 Created
    Truto-->>Agent: Success Response

Because the caller is entirely responsible for retry and backoff logic, you must implement a robust interceptor or instruct your agent framework on how to handle failures. If you are using LangChain, you can inject retry logic directly into the tool execution layer, reading the ratelimit-reset header to pause execution until the window clears.

Workflows in Action

Connecting Textmagic proxy tools to an agent transforms passive scripts into autonomous revenue operations engines. Here is how specific personas utilize these multi-step workflows in production.

Scenario 1: New Market Campaign Expansion

A growth marketer wants to spin up a localized SMS campaign for a new geographical region without touching the UI.

"We are launching in the UK next week. Find an available UK phone number, buy it, create a new contact list named 'UK Early Access', and give me the new list ID."

Agent Execution Sequence:

  1. Tool Call 1: list_all_textmagic_users to retrieve the current account's userId (required for purchasing).
  2. Tool Call 2: list_all_textmagic_numbers_availables with country: "GB" to fetch inventory.
  3. Tool Call 3: create_a_textmagic_number using the chosen number, GB country code, and the retrieved userId.
  4. Tool Call 4: create_a_textmagic_list passing name: "UK Early Access".

The agent successfully provisions telecommunications infrastructure entirely via API tools, returning the newly minted List ID to the human operator.

Scenario 2: Campaign Deliverability Audit

A DevOps engineer needs to monitor account health and clean up failing numbers after a massive broadcast.

"Audit our messaging statistics for the last 30 days. If the failure rate is above 2%, find the last 50 failed outbound messages and list the recipient phone numbers that bounced."

Agent Execution Sequence:

  1. Tool Call 1: list_all_textmagic_stats_messagings (passing interval parameters for 30 days).
  2. Internal Logic: The agent reads the JSON response, summing messagesSentFailed against messagesSentDelivered. It determines the failure rate is 3.1%.
  3. Tool Call 2: textmagic_messages_search applying a filter for status: "failed" or status: "rejected".
  4. Internal Logic: The agent compiles the list of offending receiver phone numbers.

The agent provides a concise markdown list of failed E.164 phone numbers, bypassing the need for an engineer to manually export and pivot CSV files from the dashboard.

If you want to build durable, production-grade AI agents, you cannot rely on bespoke API wrappers that push unnormalized schemas into your LLM's context window. By standardizing the integration layer into reliable, declarative proxy tools, you shrink the surface area for hallucinations and guarantee deterministic execution across complex, multi-step SaaS workflows.

FAQ

How do AI agents format phone numbers for Textmagic?
Textmagic requires strict E.164 formatting for all phone numbers. Truto's proxy tool schemas enforce these data types, ensuring the LLM validates the format before dispatching the request to the upstream API.
How are rate limits handled when an agent sends bulk Textmagic messages?
Truto does not retry or apply backoff. When Textmagic returns an HTTP 429, Truto passes the error back to the caller while normalizing the upstream data into standard IETF headers (ratelimit-remaining, ratelimit-reset). The caller is responsible for retry logic.
Can an AI agent buy a dedicated Textmagic number autonomously?
Yes. The agent first calls the `list_all_textmagic_numbers_availables` tool to check regional inventory, then passes the selected number and account user ID to the `create_a_textmagic_number` tool to finalize the purchase.

More from our Blog