Connect Mercury to AI Agents: Automate Treasury and Operations
Learn how to connect Mercury to AI Agents using Truto's /tools endpoint. Automate treasury workflows, card issuance, and payments without custom code.
You want to connect Mercury to an AI agent so your internal systems can independently monitor balances, generate virtual cards, reconcile transactions, and draft send-money requests based on operational context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to manually code dozens of endpoints, maintain complex API wrappers, or handle changing financial schemas.
Giving a Large Language Model (LLM) read and write access to your Mercury instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector that understands the rigid requirements of FinTech 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 Mercury to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Mercury to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them directly to your agent framework.
This guide breaks down exactly how to fetch AI-ready tools for Mercury, bind them natively to an LLM using LangChain (or any framework like LangGraph, CrewAI, or Vercel AI SDK), and execute complex treasury 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 Mercury Connectors
Building AI agents is easy. Connecting them to external FinTech 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 banking and treasury ecosystem as strict as Mercury.
If you decide to build a custom Mercury API integration yourself, you own the entire API lifecycle. Mercury's API introduces several highly specific integration challenges that break standard LLM assumptions.
The Idempotency and Financial State Trap
When an AI agent interacts with standard CRM records, a duplicate POST request might result in a redundant contact. Annoying, but harmless. When an agent interacts with Mercury, a duplicate POST request results in sending real money twice. Mercury mandates strict idempotency keys for operations like create_a_mercury_internal_transfer and create_a_mercury_send_money_request.
If you hand-code this integration, you have to write explicit system prompts to teach the LLM how to generate and persist unique idempotency keys per discrete operation. Furthermore, the LLM must understand that creating a send-money request does not immediately transfer funds. It creates a request that enters a specific approval state machine based on the organization's Mercury rules. The agent must understand the difference between querying a completed transaction and querying a pending approval request.
Segmented Account Architectures
Unlike a generic unified ledger, Mercury segments assets across distinct account primitives. An organization has standard depository accounts, treasury accounts, and credit accounts. The API treats these differently. If an agent tries to pull a statement using the standard list_all_mercury_account_statements endpoint but passes a treasury_id, the request will fail.
The agent must understand how to map specific tool executions to the correct account primitives. Teaching an LLM to navigate the graph of a Mercury organization - finding the right accountId, locating a specific recipientId, verifying the paymentMethod metadata, and finally executing the transfer - requires hundreds of lines of complex tool definitions and schema validation if built from scratch.
Unforgiving Rate Limits and Error Handling
Mercury enforces rate limits to protect financial infrastructure. When an AI agent runs a recursive loop attempting to reconcile 500 transactions against accounting software by firing off parallel requests, it will rapidly hit HTTP 429 Too Many Requests errors.
Standard AI frameworks handle API errors poorly. If the agent receives a raw 429, it might hallucinate a success state or crash the run. When integrating Mercury through Truto, it is critical to understand how rate limits are passed. Truto does not retry, throttle, or apply backoff on rate limit errors. Instead, when the upstream Mercury API returns an HTTP 429, Truto passes that exact error to the caller, normalizing the upstream rate limit information into standardized IETF headers: ratelimit-limit, ratelimit-remaining, and ratelimit-reset.
The caller (your agent orchestration layer) is responsible for reading the ratelimit-reset header, pausing execution, and applying appropriate retry or backoff logic. Truto does not automatically absorb these errors - it provides a clean, predictable interface so your engineering team can handle backpressure deterministically.
Providing Mercury Tools to AI Agents via Truto
To solve these engineering bottlenecks, Truto provides a GET /tools endpoint. Instead of writing custom API wrappers for Mercury's endpoints, Truto maps Mercury's underlying API resources into standardized REST-based CRUD Proxy APIs.
Every integration on Truto acts as a comprehensive schema representing how the underlying product's API behaves. Resources map to endpoints, and Methods (List, Get, Create, Update, Delete) are defined on those resources. Truto handles the authentication lifecycle, standardizes query parameter processing, and provides these Methods as a clean JSON schema.
When you call the /tools endpoint for a connected Mercury account, Truto returns a framework-agnostic array of tools containing the exact descriptions, expected query parameters, and required body schemas. These tools can be injected directly into LangChain, Vercel AI SDK, or passed raw to OpenAI's tool-calling API.
flowchart TD
A["AI Agent Framework"] -->|"1. Fetch Tools"| B["Truto /tools API"]
B -->|"2. Return JSON Schemas"| A
A -->|"3. Execute Selected Tool"| C["Truto Proxy Layer"]
C -->|"4. Normalized Request"| D["Mercury API"]
D -->|"5. Standardized Response"| C
C -->|"6. Tool Output"| AHero Tools for Mercury AI Agents
Truto exposes dozens of endpoints for Mercury. When building autonomous treasury and operations workflows, you should restrict the agent to the highest-leverage operations to conserve token context limits. Here are the core hero tools to bind to your agent.
list_all_mercury_account
This tool allows the agent to fetch all standard depository accounts for the organization. It returns the current balance, available balance, routing numbers, and account IDs. This is the foundational read operation required before an agent can initiate any funds transfer.
"Check the available balance in our primary operating account. If it is below $50,000, alert the finance channel immediately."
create_a_mercury_send_money_request
This is the most critical write tool for accounts payable workflows. It allows the agent to create a send money request that requires approval. The agent must supply the source account_id, the amount, a unique idempotencyKey, the recipientId, and the paymentMethod.
"Draft a send money request to pay Acme Corp $2,500 for the Q3 hosting invoice. Pull the funds from the Marketing checking account. Do not finalize the payment, just queue it for approval."
create_a_mercury_card
This tool allows the agent to issue virtual or physical cards to existing users in the organization. It requires specifying the card type, kind, and the userId of the recipient. It returns the issued card details including spending limits and expiration dates.
"Issue a new virtual software subscription card for Jane Doe. Set a monthly spend limit of $500 and name it 'AWS Subscriptions'."
update_a_mercury_card_by_id
Financial control requires dynamic limit management. This tool allows the agent to update a card's nickname or modify its spending controls. You must supply the specific card id and the new spendLimit parameters.
"Find the travel card assigned to John Smith and temporarily increase the spend limit to $5,000 for his upcoming conference in London."
list_all_mercury_transaction
This tool is essential for reconciliation and audit workflows. It allows the agent to list transactions across Mercury accounts, returning records complete with account references, amounts, status, timing, counterparty details, and attachment metadata.
"Pull all outbound transactions over $10,000 from the past 7 days and format them into a markdown table grouped by category."
create_a_mercury_invoice
For Accounts Receivable operations, this tool allows the agent to generate native Mercury AR invoices. The agent must provide due dates, customer IDs, line items, and payment enablement flags (like ACH or Credit Card).
"Generate an invoice for Client XYZ for 40 hours of consulting work at $150 per hour. Enable ACH payments and set the due date to Net-30."
For the complete inventory of available tools and exact schema definitions, visit the Mercury integration page.
Building Multi-Step Workflows
Fetching a tool is only the first step. To execute complex operations, you must bind these tools to your agent framework and implement a robust execution loop that handles the reality of network operations, including Mercury's rate limits.
Because Truto normalizes API specifications, integrating Mercury requires zero custom HTTP clients. Using the TrutoToolManager from our truto-langchainjs-toolset, you can initialize the tools dynamically.
import { ChatAnthropic } from "@langchain/anthropic";
import { TrutoToolManager } from "@trutohq/truto-langchainjs-toolset";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
async function buildMercuryAgent(integratedAccountId: string) {
// 1. Initialize the Tool Manager for the Mercury account
const toolManager = new TrutoToolManager({
trutoApiKey: process.env.TRUTO_API_KEY,
integratedAccountId: integratedAccountId,
});
// 2. Fetch specific write and read tools
const tools = await toolManager.getTools({
methods: ["read", "write"],
});
// 3. Initialize the LLM (e.g., Claude 3.5 Sonnet)
const llm = new ChatAnthropic({
modelName: "claude-3-5-sonnet-20241022",
temperature: 0,
});
// 4. Bind the Mercury tools to the model
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a senior treasury operations AI. You execute financial tasks in Mercury. Always verify balances before initiating payments."],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
const agent = createToolCallingAgent({
llm,
tools,
prompt,
});
return new AgentExecutor({
agent,
tools,
maxIterations: 10,
});
}Handling Rate Limits in Agent Loops
When your agent chains multiple operations - for example, iterating over 50 past transactions to analyze vendor spend - it may hit Mercury's rate limits. As noted earlier, Truto passes HTTP 429 errors directly back to the caller alongside standardized IETF headers.
Your agent execution loop or the underlying HTTP client invoking the tool must inspect the response headers. If a 429 occurs, extract the ratelimit-reset header, which indicates the number of seconds (or a specific timestamp) until the quota replenishes. The orchestration layer must then await sleep(resetTime) before allowing the agent to retry the tool execution. Never configure your agent to blindly retry on failure without inspecting the reset header, as this will trigger extended lockouts.
sequenceDiagram
participant Agent as AI Agent Framework
participant Truto as Truto API
participant Upstream as Mercury API
Agent->>Truto: Execute list_all_mercury_transaction
Truto->>Upstream: Forward Proxy Request
Upstream-->>Truto: HTTP 429 Too Many Requests
Truto-->>Agent: HTTP 429 (Pass-through)
Note over Agent: Extract ratelimit-reset header
Note over Agent: Wait for reset window
Agent->>Truto: Retry Request
Truto->>Upstream: Forward Proxy Request
Upstream-->>Truto: HTTP 200 OK
Truto-->>Agent: Tool Execution SuccessWorkflows in Action
Once connected, AI agents can transform static treasury data into autonomous workflows. Here are concrete examples of how an agent uses the Mercury toolset in production.
1. Autonomous Vendor Payment Preparation
Accounts payable is historically a manual process of matching invoices to internal vendors and queuing transfers. An AI agent can handle the entire preparation phase.
"We just received an invoice from Vercel for $1,200. Check if we have enough funds in the primary operating account. If we do, find Vercel in our recipients list and draft a send money request for approval."
Step-by-step Execution:
- The agent calls
list_all_mercury_accountto identify the primary operating account and verify theavailableBalanceis greater than $1,200. - It calls
list_all_mercury_recipientfiltering for names matching "Vercel" to retrieve the correctrecipientIdand activepaymentMethod. - It generates a unique GUID to use as the
idempotencyKey. - It calls
create_a_mercury_send_money_requestpassing the account ID, recipient ID, amount, and idempotency key. - The agent returns a success message confirming the request is sitting in Mercury awaiting human approval.
2. Dynamic Employee Card Issuance and Control
Managing corporate cards for a growing team requires constant administrative overhead. An AI agent connected to Slack or Microsoft Teams can manage card lifecycles conversationally.
"Sarah in marketing needs a new virtual card for digital ad spend. Issue her one with a $5,000 limit. Also, she lost her physical travel card, so cancel that immediately."
Step-by-step Execution:
- The agent calls
list_all_mercury_userto find Sarah'suserId. - It calls
create_a_mercury_cardpassingkind=virtual, the target user ID, and aspendLimitof $5000. - It calls
list_all_mercury_cardfiltered by Sarah's user ID to identify her physical travel card. - It calls
delete_a_mercury_card_by_idpassing the physical card ID to permanently cancel it. - The agent returns a summary confirming the new card issuance and the successful cancellation of the compromised asset.
3. Automated Accounts Receivable Generation
For B2B service businesses, generating invoices often involves copying data from a CRM or project management tool into the banking layer. An agent can bridge this gap autonomously.
"The implementation project for GlobalTech is complete. Generate an invoice for them for $15,000 for 'Enterprise Implementation Services' due in 30 days. Make sure they can pay by credit card."
Step-by-step Execution:
- The agent calls
list_all_mercury_customerto retrieve the internal customer ID for GlobalTech. - It calculates the
dueDateby adding 30 days to the current timestamp. - It formats the
lineItemsarray containing the $15,000 charge and description. - It calls
create_a_mercury_invoicepassing the customer ID, line items, due date, and setscreditCardEnabled=true. - The agent returns the generated
invoiceNumberand theslugURL so the user can send it to the client.
Integrating Mercury Without the Maintenance Burden
Connecting AI agents to Mercury unlocks massive operational leverage for finance, operations, and IT teams. But attempting to build this connectivity in-house forces your engineering team to become experts in financial API schemas, strict idempotency enforcement, and managing volatile rate limits.
By leveraging Truto's /tools endpoint, you abstract away the underlying infrastructure completely. Truto provides clean, typed, and normalized proxy tools that plug directly into LangChain, CrewAI, or any modern agent orchestration layer. Your developers focus on designing robust agent prompts and business logic, while Truto handles the integration surface area.
FAQ
- How does Truto handle Mercury API rate limits?
- Truto does not automatically retry or apply backoff on rate limit errors. It passes the HTTP 429 error directly to the caller, normalizing the upstream data into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) so your agent framework can execute proper retry logic.
- Can AI agents safely send money using the Mercury integration?
- Yes. Agents can use tools like create_a_mercury_send_money_request. This requires strict idempotency keys and typically generates an approval request in Mercury rather than instantly moving funds, ensuring human-in-the-loop oversight.
- Which agent frameworks are supported by Truto's Mercury tools?
- Truto's proxy APIs are framework-agnostic. You can bind them to any modern framework including LangChain, LangGraph, CrewAI, Vercel AI SDK, or use them directly with OpenAI's raw tool-calling API.
- Do I need to manage OAuth tokens for Mercury manually?
- No. Truto handles the entire authentication lifecycle and OAuth token management. You simply call the proxy API endpoints using your Truto API key and the specific integrated account ID.