Connect Dub to AI Agents: Automate Link Creation and Lead Tracking
Learn how to connect Dub to AI agents using Truto's /tools endpoint. Fetch native tools, handle Dub API quirks, and build autonomous link tracking workflows.
You want to connect Dub to an AI agent so your system can autonomously provision short links, analyze click metrics, attribute revenue events, and manage partner programs. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to write and maintain a custom Dub API integration from scratch.
If your team uses ChatGPT, check out our guide on connecting Dub to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Dub 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 covers how to do exactly that using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK.
Marketing operations and affiliate management require massive scale. Manually generating UTM-tagged links, tracking lead conversions across platforms, and verifying partner payouts is slow and error-prone. Industry teams are shifting from manual link management to agentic AI - systems that execute multi-step workflows across your SaaS stack autonomously.
Giving a Large Language Model (LLM) read and write access to your Dub workspace is an engineering challenge. You either spend weeks building a custom connector, managing authentication lifecycles, and formatting API responses, or you use a managed infrastructure layer that handles the boilerplate for you.
The Engineering Reality of Dub's API
Giving an LLM access to external data sounds simple during a proof-of-concept. You write a Node.js script that makes a standard fetch request to the Dub API and wrap it in an @tool decorator. In a production environment, this approach collapses. If you build a custom integration for Dub, you own the entire API lifecycle, from schema maintenance to authentication state.
Dub's API introduces several domain-specific integration challenges that break standard CRUD assumptions and will easily confuse an LLM if not handled properly.
The Analytics Aggregation Black Hole
When an LLM tries to pull performance data, it typically assumes a flat list of records. Dub's list_all_dub_analytics endpoint does not work this way. It relies heavily on strict combinations of event (e.g., clicks, leads, sales) and groupBy parameters (e.g., timeseries, countries, devices, browsers). If your agent fails to pass a valid groupBy dimension, or requests conflicting intervals, the API will reject the request. You must ensure your tool schemas enforce strict enums so the LLM does not hallucinate arbitrary SQL-like grouping parameters.
Silent Failures in Bulk Operations
Dub provides excellent bulk endpoints like dub_links_bulk_create and dub_links_bulk_update to handle up to 100 links simultaneously. However, these bulk operations explicitly do not trigger webhook events. If your AI agent architecture relies on a downstream system catching a webhook to confirm a link was created, the workflow will silently stall. Your agent execution loop must proactively read the HTTP response array to verify success rather than waiting for an asynchronous event.
Strict Customer External ID Mapping
When tracking a sale or a lead via the create_a_dub_track_sale endpoint, the API requires a customerExternalId. LLMs are notorious for extracting an email address from context and trying to force it into an ID field, or hallucinating a database ID format. You must explicitly define your agent's system prompt and tool descriptions to ensure it queries your CRM or internal database for the exact, canonical externalId before attempting to track a conversion event in Dub.
Rate Limits and Exhaustion Handling
Like any high-volume platform, Dub enforces rate limits. If your agent enters an aggressive loop - checking analytics for hundreds of links individually instead of using bulk filters - it will hit a wall.
A critical architectural note: Truto does not retry, throttle, or apply backoff on rate limit errors. When Dub returns an HTTP 429 Too Many Requests error, Truto passes that error directly back to the caller. What Truto does provide is normalization. Truto intercepts the upstream rate limit data and normalizes it into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification. It is entirely the responsibility of your agent framework's execution loop to catch the 429, read the ratelimit-reset header, and implement exponential backoff.
Fetching Dub Tools via Truto
Every integration on Truto operates as a comprehensive JSON object mapping a product's API behavior. Truto abstracts the underlying API into a standardized REST-based CRUD interface. These are exposed as Proxy APIs.
To equip your AI agent, Truto provides the /integrated-account/<id>/tools endpoint. Calling this endpoint returns a complete array of Proxy APIs formatted specifically as LLM-ready tools. Truto handles the OAuth credential injection, pagination formatting, and query parameter serialization behind the scenes.
Instead of manually writing JSON schemas for Dub's endpoints, you initialize the Truto SDK, pass your integrated account ID, and receive fully typed, heavily described tools ready to be passed into .bindTools().
Hero Tools for Dub AI Agents
We provide a comprehensive set of predefined tools for Dub. Here are the high-leverage "hero" tools that enable complex autonomous workflows, rather than standard read-only operations.
create_a_dub_link
This is the fundamental primitive of the integration. It allows the agent to provision a new short link on your workspace's domain. It supports extensive configuration, including expiration dates, password protection, and UTM parameter injection.
"Generate a new tracking link for the Q3 Product Launch webinar URL. Tag it as 'webinar-q3' and inject UTM source 'linkedin', medium 'social', and campaign 'q3-launch'."
dub_links_bulk_create
When an agent needs to process a massive spreadsheet of affiliates or spin up regional campaigns, creating links one-by-one is inefficient and consumes too many API calls. This tool accepts an array of up to 100 link configurations and processes them in a single batch.
"I have a list of 50 new regional sales managers. Take their LinkedIn profile URLs and bulk create personalized Dub tracking links for each of them under the 'sales-team' folder."
list_all_dub_analytics
This tool is the engine for AI-driven reporting. It retrieves aggregate data based on specific dimensions. You can instruct the agent to pivot the data by country, device, or timeseries to generate comprehensive performance summaries without exporting CSVs.
"Pull the timeseries analytics for the last 30 days for the 'summer-promo' link. Group the clicks by country and tell me which region had the highest engagement rate."
create_a_dub_track_sale
Essential for revenue attribution. This tool allows the agent to listen to a CRM update or payment gateway event and push that financial data back into Dub, completing the loop from initial link click to closed-won revenue.
"The customer with external ID 'ext_99482' just upgraded to the Pro plan for $1,200. Log this as a tracked sale in Dub associated with their profile."
create_a_dub_partner
For teams running affiliate or referral programs, this tool automates onboarding. The agent can take an approved application, create the partner profile in Dub, and automatically provision their unique sharing assets.
"Approve Jane Doe's affiliate application. Create a new Dub partner profile using jane.doe@example.com and enroll her in the 'Global Ambassadors' program."
update_a_dub_link_by_id
Link lifecycles require maintenance. Instead of deleting old links, an agent can use this tool to dynamically redirect traffic, update UTM parameters, or append tags based on how a campaign is performing.
"The flash sale has ended. Find the link ID for 'black-friday-special' and update its destination URL to point to our standard pricing page instead."
To view the complete inventory of available methods, schemas, and resource definitions, visit the Dub integration page.
Workflows in Action
Connecting these tools to an LLM unlocks autonomous execution. Here is how specific engineering and marketing personas use these capabilities in production.
Workflow 1: Autonomous Campaign Deployment
Marketing teams often spend hours manually generating UTM matrices and short links for cross-channel campaigns. An AI agent can orchestrate this instantly.
"We are launching the new 'Enterprise Security Report'. Generate 10 distinct Dub links for our upcoming email, LinkedIn, and Twitter campaigns. Organize them into a new folder called 'Security-Report-2026', apply the tag 'Q1-Content', and output a markdown table of the generated shortlinks."
- The agent calls
create_a_dub_folderto provision 'Security-Report-2026' and retrieves the new Folder ID. - The agent calls
create_a_dub_tagto provision 'Q1-Content' and retrieves the Tag ID. - The agent formats an array of 10 link objects, injecting the necessary UTM parameters, the Folder ID, and the Tag ID.
- The agent calls
dub_links_bulk_createto generate all 10 links in a single API transaction. - The agent parses the response array and formats the final markdown table for the user.
Workflow 2: Revenue Attribution Auditing
Revenue operations teams need to ensure that sales logged in Stripe or Salesforce are accurately reflected in Dub for affiliate payouts.
"Audit yesterday's closed-won deals in the CRM. For any deal associated with a Dub customer, verify if the sale was tracked in Dub. If it is missing, track the sale retroactively."
- The agent queries the internal CRM (via another tool) to get yesterday's closed deals.
- For each deal, the agent calls
get_single_dub_customer_by_idusing the CRM's external ID (prefixing withext_) to check if the user exists in Dub. - The agent calls
list_all_dub_eventsfiltering for thesalesevent type for that specific customer. - If the sale event is missing, the agent calls
create_a_dub_track_sale, passing thecustomerExternalIdand theamountto reconcile the data.
Workflow 3: Automated Partner Offboarding
When an affiliate violates terms of service, security teams must revoke their access and invalidate their links immediately.
"Partner ID 'prt_773' was flagged for spam. Deactivate their partner account, and bulk update all their associated partner links to point to our compliance warning page."
- The agent calls
dub_partners_deactivatepassing the target Partner ID. - The agent calls
list_all_dub_partner_linksfiltering by the specific Partner ID to retrieve all active URLs. - The agent extracts the IDs of the returned links.
- The agent calls
dub_links_bulk_update, passing the array of link IDs and overriding theurlparameter to the compliance page destination.
Building Multi-Step Workflows
To build these workflows, you need to architect an execution loop. We strongly recommend reading our foundational guide on Architecting AI Agents: LangGraph, LangChain, and the SaaS Integration Bottleneck for a deep dive into state management.
Because Truto acts as a pass-through for rate limits, your code must be resilient. If your agent decides to update 500 links iteratively instead of using the bulk endpoint, Dub will return an HTTP 429. Your execution loop must catch this, inspect the normalized ratelimit-reset header Truto provides, and pause execution.
Below is a conceptual TypeScript implementation using LangChain and the @trutohq/truto-langchainjs-toolset package. This demonstrates fetching the tools, binding them, and handling the execution state.
import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "@trutohq/truto-langchainjs-toolset";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
async function executeDubAgentWorkflow() {
// 1. Initialize the Truto SDK with your environment token
const trutoManager = new TrutoToolManager({
apiKey: process.env.TRUTO_API_KEY,
});
// 2. Fetch the Dub tools for the specific authenticated tenant
const dubAccountId = "acc_dub_production_991";
const tools = await trutoManager.getTools(dubAccountId);
// 3. Initialize the LLM and bind the dynamically generated schemas
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0
});
const llmWithTools = llm.bindTools(tools);
// 4. Define strict systemic instructions to prevent hallucination
const prompt = ChatPromptTemplate.fromMessages([
["system", `You are an elite marketing operations AI.
You manage the company's Dub workspace.
Always prioritize bulk endpoints (like dub_links_bulk_create) when handling multiple items.
If you encounter an API error, summarize the failure instead of guessing data.
Never hallucinate customerExternalIds; always ask the user if they are missing.`],
["placeholder", "{chat_history}"],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
// 5. Construct the execution agent
const agent = createToolCallingAgent({
llm: llmWithTools,
tools,
prompt,
});
const executor = new AgentExecutor({
agent,
tools,
// Custom error handling strategy is critical here
handleParsingErrors: true,
maxIterations: 15,
});
try {
// 6. Execute the workflow
const result = await executor.invoke({
input: "Generate a new tracking link for our Q4 recap blog post. Give me the shortLink back."
});
console.log("Workflow Complete:", result.output);
} catch (error: any) {
// 7. Explicit Rate Limit (429) Handling
// Truto normalizes standard headers but leaves retry logic to you.
if (error.response && error.response.status === 429) {
const resetTime = error.response.headers['ratelimit-reset'];
console.warn(`Dub Rate Limit Exceeded. Agent paused. Resume after Unix Epoch: ${resetTime}`);
// Implement your framework-specific backoff or suspend the LangGraph state here
} else {
console.error("Agent execution failed:", error);
}
}
}
executeDubAgentWorkflow();This architecture guarantees that your LLM always has the most up-to-date schema. If Dub releases a new configuration parameter for link creation, Truto updates the JSON integration definition, and your agent inherits the new capability on its next execution cycle - without any code deployments on your end.
Moving Past Hardcoded API Wrappers
Building autonomous systems requires a high volume of tools. Hardcoding schemas, managing OAuth token refreshes, and mapping complex pagination logic for Dub diverts engineering resources away from building your core agent architecture.
By routing your integrations through Truto, you treat external SaaS platforms as dynamic tool registries. You fetch the schemas, bind them to your model, handle the 429 backoff gracefully, and let the agent orchestrate the complex logic of link management and analytics attribution.
FAQ
- Does Truto automatically retry requests when Dub rate limits are exceeded?
- No. Truto passes HTTP 429 (Too Many Requests) errors directly back to the caller. However, Truto does normalize the upstream rate limit data into standard headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your agent framework must implement the retry and backoff logic.
- Can I use these Dub tools with frameworks other than LangChain?
- Yes. Truto's /tools endpoint returns standard JSON schemas that can be parsed and bound to any modern AI framework, including LangGraph, CrewAI, Vercel AI SDK, and AutoGen.
- How does an AI agent handle bulk link creation in Dub?
- Agents should use the dub_links_bulk_create tool to process up to 100 links in a single batch. Note that bulk endpoints in Dub do not trigger webhook events, so the agent must rely on the immediate HTTP response to verify success.
- How are tools kept up to date when the Dub API changes?
- Truto maintains the integration definitions. When you call the /tools endpoint, it dynamically returns the latest schema. Your agent inherits any new parameters or updated descriptions on its next execution cycle without requiring code redeployments.