Connect HubSpot to AI Agents: Sync invoices, orders, and workflows
A definitive engineering guide to connecting HubSpot to AI agents. Learn how to fetch AI-ready tools, handle HubSpot's strict associations, and automate CRM workflows using Truto.
You want to connect HubSpot to an AI agent so your system can independently read deals, sync invoices, generate orders, and trigger marketing workflows based on historical context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to connect AI agents to read and write data in HubSpot manually.
Giving a Large Language Model (LLM) read and write access to your HubSpot instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting HubSpot to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting HubSpot 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 HubSpot, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex revenue operations workflows. 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 HubSpot 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.
If you decide to build a custom integration for HubSpot, you own the entire API lifecycle. HubSpot's CRM API introduces several specific integration challenges that break standard LLM assumptions.
The Object Association Maze
Unlike legacy CRMs that use standard foreign keys for relationships, HubSpot relies heavily on an independent Associations API. A Contact is not just a child of a Company. A Deal is not inherently tied to a specific Line Item or Invoice. They are distinct objects linked by specific associationTypeId values.
When an AI agent wants to find the billing contact for a specific invoice, it cannot simply query the invoice and read a contact_id field. It must first query the Invoice object, then query the Associations API targeting from_object_type=invoices and to_object_type=contacts to retrieve the association labels, and finally fetch the Contact record. LLMs consistently fail at this multi-step relational logic unless you provide them with strictly defined, purpose-built proxy tools that handle the association graph.
Search API Pagination and Filter Groups
When an LLM needs to find a specific set of orders or deals, it typically attempts to pass a simple query string. HubSpot's Search API requires a complex JSON payload structuring criteria into filterGroups containing filters with specific operators (EQ, GTE, CONTAINS_TOKEN).
Furthermore, when the search returns a list, the response is paginated using an after cursor. LLMs do not inherently understand cursor-based pagination. If you do not explicitly write logic to handle the filterGroup schema and feed pagination cursors back into the model's context window, your agent will hallucinate data, construct invalid API requests, or simply assume the first 100 records represent the entire database.
Hard Rate Limits and 429 Exhaustion
HubSpot enforces strict API rate limits. Depending on the tier, standard limits are typically 100 requests per 10 seconds or 150 requests per 10 seconds. AI agents, especially those utilizing MapReduce patterns or parallel tool calling to summarize dozens of tickets or invoices, will hit these limits almost immediately.
It is critical to understand that Truto does not retry, throttle, or apply backoff on rate limit errors. When HubSpot returns an HTTP 429 Too Many Requests error, Truto passes that error directly back to the caller.
To help your execution loop handle this gracefully, Truto normalizes the upstream rate limit information into standardized headers per the IETF specification:
ratelimit-limit: The maximum number of requests permitted in the current time window.ratelimit-remaining: The number of requests remaining in the current window.ratelimit-reset: The time at which the current window resets.
Your agent's execution loop is fully responsible for catching the 429, reading the ratelimit-reset header, pausing execution, and retrying. Failing to implement backoff will cause your agent workflow to crash mid-execution.
HubSpot AI Agent Tools
Truto provides a set of tools for your LLM frameworks—frequently highlighted among the best unified APIs for LLM function calling—by offering a description and schema for all the Methods defined on the Resources for an integration. We call the /integrated-account/:id/tools endpoint on the Truto API to return these Proxy APIs as pre-formatted tools.
Here are the most critical, high-leverage tools available for orchestrating HubSpot revenue operations.
Search Invoices
list_all_hub_spot_invoices_search
This tool allows the agent to query HubSpot invoices using specific filter groups. It is essential for workflows that require the agent to audit unpaid balances, find invoices associated with specific deals, or retrieve historical billing data based on dates or amounts.
"Find all invoices created in the last 30 days that have a status of 'Overdue' and an amount greater than 5000."
Create an Order
create_a_hub_spot_order
Agents use this tool to autonomously generate sales orders within HubSpot. You pass in the specified properties like amount, order status, and dates. This is the primary write tool for e-commerce or B2B SaaS workflows where an external event triggers order creation.
"Generate a new order record for 12,000 with a status of 'Pending Fulfillment' and set the expected delivery date to next Friday."
Update a Deal
update_a_hub_spot_deal_by_id
This tool performs a partial update of a deal identified by its exact ID. Agents use this to move deals across pipeline stages, update the forecasted amount, or append closing notes. The agent must provide a properties object with values to overwrite existing deal properties.
"Update the deal with ID 98273645. Change the dealstage to 'closedwon' and update the amount to 45000."
Create an Association
create_a_hub_spot_association
Because HubSpot relies heavily on strict relational mapping, this tool is mandatory for complex workflows. It sets association labels between two records using objectType, objectId, toObjectType, and toObjectId.
"Link the newly created Order ID 112233 to Contact ID 445566 using the standard order-to-contact association type."
List Workflows
list_all_hub_spot_workflows
Agents use this tool to retrieve a list of all automated workflows configured in the HubSpot instance. This is highly useful for auditing system state, checking if specific marketing automations are active, or mapping workflow IDs before attempting to enroll a contact.
"Retrieve a list of all workflows in the system and find the ID for the 'Enterprise Onboarding Drip' workflow."
Create an Internal Note
create_a_hub_spot_note
When AI agents execute consequential actions - like modifying an invoice or updating a deal stage - they should leave an audit trail. This tool creates a note record that can then be associated with a contact, company, or deal, explaining exactly why the agent took the action.
"Create a note stating: 'AI Agent escalated this deal due to 3 consecutive days of unresponsiveness from the billing contact'."
To view the complete inventory of available HubSpot tools and their required schemas, check out the HubSpot integration page.
Workflows in Action
Connecting these tools transforms an LLM from a passive text generator into an autonomous revenue operations engineer. Here are two real-world examples of how these tools chain together.
Scenario 1: RevOps Invoice Escalation
Revenue Operations teams spend hours manually cross-referencing overdue invoices with active deals. An AI agent can automate this completely.
"Find any overdue invoices over $10,000. If you find any, locate the associated deal, change the deal stage to 'At Risk', and add an internal note explaining the escalation."
Step-by-step execution:
- Search Invoices: The agent calls
list_all_hub_spot_invoices_searchwith a filter group targetingstatus = overdueandamount >= 10000. - Fetch Associations: For each returned invoice ID, the agent queries the associations to find the related
deal_id. - Update Deal: The agent calls
update_a_hub_spot_deal_by_idon the target deal, changing thedealstageproperty to the internal ID representing "At Risk". - Create Note: The agent calls
create_a_hub_spot_notegenerating the audit text. - Create Association: Finally, the agent calls
create_a_hub_spot_associationto attach the newly created note directly to the Deal record.
Outcome: The system autonomously flags high-value churn risks and leaves a clear paper trail for human account executives to follow up on, requiring zero manual reporting.
Scenario 2: Post-Sale Order Processing
When a B2B contract is signed via an external platform, you need to reflect that reality in your CRM immediately to trigger downstream fulfillment.
"A contract was just signed for Acme Corp. Find the primary contact for the Acme Corp company, create a new order for $5,000, and link the order to both the company and the contact."
Step-by-step execution:
- Search Companies: The agent searches for "Acme Corp" to obtain the
company_id. - Fetch Associations: The agent retrieves the associated contacts for that company to find the primary stakeholder's
contact_id. - Create Order: The agent calls
create_a_hub_spot_orderpassing the$5,000amount and default status properties. It receives the neworder_idin the response. - Create Associations: The agent calls
create_a_hub_spot_associationtwice. First linking theorder_idto thecompany_id, then linking theorder_idto thecontact_id.
Outcome: The CRM accurately reflects the new financial reality, properly linked across the entire customer graph, ensuring marketing and support teams have full context.
Building Multi-Step Workflows
To build these workflows, you need an agentic framework. Truto provides a LangChain.js SDK (truto-langchainjs-toolset) that makes binding these tools trivial.
Every integration on Truto maps the underlying product's API into a REST-based CRUD API using Resources and Methods. We expose these Proxy APIs with full schemas so the LLM knows exactly what arguments to pass.
The code block below demonstrates how to fetch HubSpot tools, bind them to an OpenAI model, and execute a loop. Crucially, it highlights how to handle the 429 Too Many Requests scenario by inspecting Truto's standardized rate limit headers.
import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { TrutoToolManager } from "@trutohq/truto-langchainjs-toolset";
async function runHubSpotAgent(prompt: string, integratedAccountId: string) {
// 1. Initialize the LLM
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0,
});
// 2. Initialize Truto Tool Manager using your Truto Developer Token
const toolManager = new TrutoToolManager({
token: process.env.TRUTO_API_KEY,
});
// 3. Fetch dynamically generated tools for the specific HubSpot account
// This hits GET /integrated-account/<id>/tools behind the scenes
const tools = await toolManager.getTools(integratedAccountId);
// 4. Bind the tools to the LLM
const promptTemplate = ChatPromptTemplate.fromMessages([
["system", "You are a Revenue Operations AI assistant. You have full access to the user's HubSpot instance. Follow instructions carefully."],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
const agent = createToolCallingAgent({
llm,
tools,
prompt: promptTemplate,
});
const agentExecutor = new AgentExecutor({
agent,
tools,
maxIterations: 10,
});
// 5. Execute the workflow with custom 429 backoff logic
let success = false;
let attempts = 0;
const maxAttempts = 3;
while (!success && attempts < maxAttempts) {
try {
attempts++;
console.log(`Starting execution attempt ${attempts}...`);
const result = await agentExecutor.invoke({
input: prompt,
});
console.log("Workflow completed successfully:", result.output);
success = true;
} catch (error: any) {
// Truto passes the exact 429 error from HubSpot back to the caller.
// You must handle the retry logic based on the normalized headers.
if (error.response && error.response.status === 429) {
console.warn("Rate limit hit. Inspecting Truto normalized headers...");
const resetTimeStr = error.response.headers['ratelimit-reset'];
const resetTime = parseInt(resetTimeStr, 10);
if (!isNaN(resetTime)) {
// Calculate how long to sleep (adding a small buffer)
const sleepSeconds = Math.max(0, resetTime - Math.floor(Date.now() / 1000)) + 1;
console.log(`Sleeping for ${sleepSeconds} seconds before retrying...`);
await new Promise(resolve => setTimeout(resolve, sleepSeconds * 1000));
} else {
// Fallback exponential backoff if header is missing or malformed
const fallbackSleep = Math.pow(2, attempts) * 1000;
console.log(`Sleeping for ${fallbackSleep}ms (fallback backoff)...`);
await new Promise(resolve => setTimeout(resolve, fallbackSleep));
}
} else {
// Re-throw if it's not a rate limit issue
console.error("Execution failed with a non-recoverable error:", error);
throw error;
}
}
}
if (!success) {
console.error("Workflow failed after maximum retry attempts due to rate limiting.");
}
}
// Example execution
runHubSpotAgent(
"Find all overdue invoices and update the related deal to 'At Risk'.",
"hubspot_integrated_account_12345"
);By leveraging the /tools endpoint, your code remains entirely framework-agnostic. You do not maintain custom schemas, manage OAuth token lifecycles, or hardcode query parameter logic. When you make changes to a tool description in the Truto integration UI, the tool definitions update automatically in your next API call.
Ship Autonomous Revenue Workflows Today
Building an AI agent is only half the battle. If your agent cannot interact with the system of record where actual business data lives, it is just an expensive toy.
Writing bespoke API wrappers for HubSpot forces your engineering team to spend their cycles reading CRM API documentation, battling complex association schemas, and debugging pagination cursors. By utilizing Truto's proxy architecture and dynamically generated tool schemas, you can connect your agent framework directly to HubSpot in minutes, ensuring zero drift as APIs evolve.
FAQ
- Does Truto automatically handle HubSpot API rate limits?
- No. Truto does not retry, throttle, or apply backoff on rate limit errors. When HubSpot returns an HTTP 429, Truto passes that error to the caller, normalizing the rate limit information into standard headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). The caller's execution loop is responsible for retry and backoff logic.
- Can I use Truto's tools with agent frameworks other than LangChain?
- Yes. Truto's /tools endpoint dynamically returns standard JSON schemas for all available proxy APIs. These can easily be parsed and bound to any major agent framework, including LangGraph, CrewAI, AutoGen, and the Vercel AI SDK.
- How do AI agents handle relationships between HubSpot records?
- HubSpot uses a dedicated Associations API to link records (like Contacts to Deals). Truto exposes specific association tools (e.g., create_a_hub_spot_association) that you must provide to the LLM so it can properly map relational connections during a workflow execution.
- Do I have to write custom JSON schemas for HubSpot endpoints?
- No. The Truto /tools endpoint automatically generates and supplies the necessary API descriptions and parameters as tools. Truto handles the pagination, authentication, and query parameter processing in the background.