Connect Business Central (on-prem) to AI Agents: Automate ERP
Learn how to connect Microsoft Dynamics 365 Business Central (on-prem) to AI agents using Truto. Fetch ERP tools, manage ETags, and automate AP/AR workflows.
You want to connect Microsoft Dynamics 365 Business Central (on-premises) to an AI agent so your system can independently audit financial ledgers, generate purchase orders, reconcile vendor payments, and automate supply chain logistics. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the nightmare of building and maintaining a custom OData integration from scratch.
Giving a Large Language Model (LLM) read and write access to your on-premises ERP instance is an engineering minefield. You either spend months building, hosting, and maintaining a custom connector to handle OData v4 quirks, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Microsoft Dynamics 365 Business Central (on-premises) to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Microsoft Dynamics 365 Business Central (on-premises) 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 Microsoft Dynamics 365 Business Central, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex ERP operations. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.
Why a Unified Tool Layer Matters for Agent Safety
Before writing a line of integration code, decide what layer your agent talks to. Direct API tools (one tool per raw Business Central endpoint) look convenient in a prototype but push vendor-specific idiosyncrasies directly into the LLM's context window.
The model has to remember that Business Central requires explicit company IDs in the URL path, that dimension lines are heavily nested, and that updates require specific concurrency tokens. Every one of those quirks is a hallucination waiting to happen.
A unified tool layer collapses these complexities behind strict, LLM-optimized schemas. Your agent sees create_sales_order, get_purchase_order_by_id, and create_journal_line - not raw OData endpoints wrapped in AL table constraints. This provides three concrete safety wins:
- Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments are rejected before they hit your on-prem ERP, meaning a broken tool call fails fast instead of executing a malformed GL entry.
- Reduced attack surface for hallucination. The LLM only ever chooses from a stable set of function names. It never invents OData
$filtersyntax or guesses at internal C/AL table relationships. - Normalized error handling. When an agent makes a mistake, it gets a clean, standardized error message back, allowing it to reason about the failure and retry with corrected parameters.
The Engineering Reality of the Business Central (On-Prem) API
Giving an LLM access to external data sounds simple. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production against complex on-premises ERP systems, this approach collapses immediately.
Microsoft Dynamics 365 Business Central exposes its API via OData v4. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning capabilities. Here are the specific hurdles that make Business Central uniquely tricky for AI agents.
The Concurrency Trap: ETags and If-Match Headers
Business Central strictly enforces optimistic concurrency using ETags. When you update a record - say, patching a sales_invoice to change its status - you cannot simply send the updated fields. You must provide the exact @odata.etag value that corresponds to the current version of the record in the database.
If you expose the raw API to an LLM, the model will frequently forget to fetch the record first, guess the ETag, or attempt to update without the If-Match header entirely. The API rejects this with a 412 Precondition Failed error. Truto's proxy layer normalizes this by explicitly requiring the etag parameter in the tool schema for any update operation, forcing the LLM to execute a get_x_by_id tool first to retrieve the state.
Deeply Nested Navigational Properties
Standard LLMs are trained to expect flat, intuitive JSON objects. Business Central's data model is deeply relational. A Sales Order is not just an object; it contains salesOrderLines, which contain dimensionSetLines, which map to dimensionValues.
If an agent attempts to fetch a purchase order to summarize its contents, the raw API might only return the header information unless explicitly commanded to expand the navigational properties using $expand=purchaseOrderLines. An LLM will often assume the lines are missing and hallucinate the line items based on previous context. Truto's tools handle this by automatically expanding critical relational data (like line items and dimensions) out of the box, ensuring the agent always receives the complete picture in a single tool call.
Company ID and Environment Routing
Unlike modern SaaS applications where a bearer token implies a specific workspace, Business Central requires you to specify the environment and the company_id for almost every transaction. The typical endpoint looks like /v2.0/{environment}/api/v2.0/companies({company_id})/items.
If an LLM has to dynamically construct these URLs, it will inevitably corrupt the path syntax. Truto abstracts this away. The LLM simply passes the environment and company_id as standard JSON properties into the tool call, and the underlying proxy engine handles the path parameter injection and URL encoding securely.
AI-Ready Hero Tools for Business Central
To build autonomous ERP workflows, you need tools that map to high-leverage business operations. Instead of exposing hundreds of raw endpoints, Truto curates these into focused, descriptive tools with strict schemas.
Here are six high-leverage hero tools you can bind to your agent today.
get_purchase_order_by_id
Retrieves a specific purchase order by its ID. Crucially, this tool automatically expands the purchaseOrderLines and dimensionSetLines, giving the agent the full context of the order, including the vendor details, item costs, tax calculations, and shipping status without requiring secondary API calls.
Contextual usage notes: Agents should use this tool when asked to audit an incoming invoice against the original PO, or when tasked with summarizing spending for a specific vendor.
"Fetch purchase order 10450 from the Production environment for company ID 8b4a2... and summarize the line items. Check if the total amount exceeds $5,000 and confirm if it is fully received."
create_sales_order
Creates a new sales order in Business Central. This tool supports deep inserts, meaning the agent can create the top-level sales order and the associated salesOrderLines in a single, unified JSON payload.
Contextual usage notes: The LLM must be provided with the exact customerId and the itemId for the lines. It should typically call list_all_items or get_customer_by_id before invoking this tool to ensure foreign keys are accurate.
"Create a new sales order for customer ID 9a2b... include two line items: 5 units of item ID 11b3... and 10 units of item ID 44c1... Set the requested delivery date to next Friday."
update_sales_invoice_by_id
Updates an existing sales invoice. Because Business Central requires optimistic concurrency control, this tool mandates the inclusion of the etag property.
Contextual usage notes: The agent must be instructed to always call get_sales_invoice_by_id first to retrieve the current @odata.etag string, which it must then pass into this tool exactly as received.
"Retrieve sales invoice INV-1002, extract its current ETag, and update the external document number to 'PO-99411'. Use the ETag you retrieved to ensure the update succeeds."
list_all_vendor_payments
Fetches a paginated list of vendor payments from the ERP. It returns the journal details, posting dates, amounts, and applied invoice IDs for reconciliation purposes.
Contextual usage notes: Perfect for AP automation workflows. Agents can use this to cross-reference bank feed data against recorded ERP payments to detect discrepancies.
"List all vendor payments recorded in the last 7 days. Find any payments made to vendor ID 33a1... that exceed $10,000 and list the invoices they were applied to."
get_item_by_id
Retrieves the master record for a specific inventory item, including its unit cost, unit price, stock levels (inventory), tax grouping, and base unit of measure.
Contextual usage notes: This is a vital read tool for agents handling supply chain queries or quoting workflows. The agent can check real-time stock levels before attempting to draft a sales quote.
"Check the inventory level for item ID 55f9... If we have fewer than 20 units in stock, alert the supply chain team that we need to generate a new purchase order."
create_journal_line
Creates a general ledger entry within a specific journal. This allows the agent to handle custom accounting workflows, expense logging, and month-end adjustments.
Contextual usage notes: The agent needs the journal_id, accountId, and the amount (debit/credit). It must be strictly prompted to ensure debits and credits balance if it is orchestrating a multi-line entry.
"Create a journal line in the standard general journal (ID 77d2...) for account 40000. Post a debit of $500 for 'Software Subscriptions' and ensure the posting date is set to today."
For the complete tool inventory, required arguments, and JSON schema definitions, visit the Microsoft Dynamics 365 Business Central (on-premises) integration page.
Workflows in Action
Individual tools are useful, but chaining them together is where autonomous agents deliver ROI. Because Truto normalizes the inputs and outputs, your LLM can reliably execute multi-step workflows across your ERP. Here are two concrete examples of what this looks like in production.
Workflow 1: Autonomous AP Invoice Reconciliation
Finance teams waste hours manually checking vendor invoices against the purchase orders generated in the ERP. You can build an agent that handles this automatically when an invoice arrives in a shared inbox.
"An invoice just arrived from TechSupply Inc for $1,250 referencing PO-5501. Retrieve the PO from Business Central, verify the line items match the invoice totals, and if they do, list all current vendor payments for this vendor to see if it was already paid."
Step-by-step execution:
- The agent calls
get_purchase_order_by_id(using a previously mapped ID for PO-5501) to pull the full order, includingpurchaseOrderLines. - It analyzes the payload, calculating the
totalAmountIncludingTaxand comparing it to the $1,250 figure from the user's prompt. - The agent calls
get_vendor_by_idto retrieve the internal vendor ID for TechSupply Inc. - It executes
list_all_vendor_payments, filtering the results in memory to check if theappliesToInvoiceNumbermatches the incoming invoice.
Result: The agent replies confirming the PO matches the invoice exactly, and informs the user that no payment has been recorded yet, effectively clearing the invoice for AP approval.
Workflow 2: Intelligent Inventory Routing and Ordering
Supply chain agents need to constantly monitor stock levels and initiate purchasing workflows before inventory hits zero.
"Audit our stock for the 'Premium Widget' (Item ID: 88A4). If we have fewer than 50 units in stock, immediately draft a new purchase order to our primary supplier (Vendor ID: 99B2) for 100 units at the current unit cost."
Step-by-step execution:
- The agent executes
get_item_by_idusing the provided item ID. - It reads the
inventoryinteger from the response. It notes theunitCostis currently $14.50. - Seeing the inventory is at 32 (below the threshold of 50), it decides to initiate a purchase.
- It calls
create_purchase_order, passing thevendorId. In the same payload, it deep-inserts thepurchaseOrderLineswith theitemId, aquantityof 100, and thedirectUnitCostof $14.50.
Result: The agent successfully drafts the PO and returns the new number (e.g., PO-10045) to the user so a human manager can review and post it.
Building Multi-Step Workflows
To build these workflows, you need to connect your agent framework to Truto's Unified API. The architecture described below applies whether you are using LangChain, LangGraph, CrewAI, or the Vercel AI SDK. We will use the truto-langchainjs-toolset for this example.
Handling Rate Limits in Agent Loops
When your agent chains 15 tools together in a complex reasoning loop, it will eventually hit an ERP rate limit.
Truto does not absorb rate limit errors, apply backoff, or silently throttle your requests. When the upstream Business Central API returns an HTTP 429 Too Many Requests, Truto passes that 429 directly back to your agent framework. Truto normalizes the upstream rate limit information into standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset).
Your agent loop is responsible for catching these errors, reading the reset header, sleeping, and retrying the exact tool call. This is a deliberate architectural choice to prevent silent timeouts in long-running agent threads.
sequenceDiagram
participant Agent as Agent Framework (LangGraph)
participant SDK as Truto Tool Manager
participant BC as Dynamics 365 BC API
Agent->>SDK: Invokes create_sales_order
SDK->>BC: POST /companies({id})/salesOrders
BC-->>SDK: HTTP 429 Too Many Requests
SDK-->>Agent: Throws Error with ratelimit-reset
Agent->>Agent: Sleeps until reset time
Agent->>SDK: Retries create_sales_order
SDK->>BC: POST /companies({id})/salesOrders
BC-->>SDK: HTTP 201 Created
SDK-->>Agent: Returns nested order JSONImplementation with LangChain
Here is how you bind Microsoft Dynamics 365 Business Central tools to an OpenAI model and execute a multi-step workflow.
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 runBusinessCentralAgent() {
// 1. Initialize the Truto Tool Manager with your integrated account ID
const trutoManager = new TrutoToolManager({
apiKey: process.env.TRUTO_API_KEY,
accountId: "your_business_central_integrated_account_id"
});
// 2. Fetch the Business Central tools programmatically
// This queries GET /integrated-account/{id}/tools
const tools = await trutoManager.getTools();
// 3. Initialize your LLM
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0,
});
// 4. Create the agent prompt
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a financial operations agent with access to Microsoft Dynamics 365 Business Central. When updating records, you MUST fetch them first to retrieve the exact ETag. If you hit a rate limit, pause and retry."],
["placeholder", "{chat_history}"],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"],
]);
// 5. Bind tools to the agent
const agent = createToolCallingAgent({
llm,
tools,
prompt,
});
const agentExecutor = new AgentExecutor({
agent,
tools,
// In production, implement custom error handling here to catch 429s
// and parse Truto's ratelimit-reset header.
maxIterations: 10,
});
// 6. Execute a multi-step workflow
const result = await agentExecutor.invoke({
input: "Check the inventory level for item ID 55f9-2b... in the Production environment. If it is below 50, create a purchase order to vendor ID 99a1... for 100 units."
});
console.log(result.output);
}
runBusinessCentralAgent();In this execution, the agent evaluates the prompt, searches its injected tool schemas, realizes it needs to call get_item_by_id first, inspects the response to check the stock, and then uses that context to construct a valid JSON payload for create_purchase_order.
Strategic Wrap-up
Building autonomous AI agents requires shifting your engineering focus from writing integration boilerplate to optimizing agent reasoning. Microsoft Dynamics 365 Business Central (on-premises) is a massive, complex ERP. If you force your engineers to map OData v4 nested properties, manage ETags, and maintain custom C/AL logic just to give an LLM API access, your AI project will stall.
By leveraging a unified API layer to deliver pre-configured, schema-strict tools to your agent framework, you drastically shrink the attack surface for model hallucinations and give your agents a deterministic, reliable way to interact with enterprise data.
FAQ
- How do AI agents handle ETags when updating records in Business Central?
- Agents must first call a GET tool (like `get_sales_invoice_by_id`) to retrieve the record's current `@odata.etag`. They then pass this exact ETag string into the update tool's schema to satisfy Business Central's optimistic concurrency requirements.
- How does Truto handle API rate limits from Business Central?
- Truto does not absorb or retry on rate limit errors. When Business Central returns an HTTP 429, Truto passes the error to the caller, normalizing the upstream rate limit data into standard headers (`ratelimit-limit`, `ratelimit-reset`). The agent framework is responsible for handling the backoff.
- Can I use these Business Central tools with any AI framework?
- Yes. Truto's `/tools` endpoint returns standardized JSON schemas that can be bound to any modern framework, including LangChain, LangGraph, CrewAI, and the Vercel AI SDK.
- Do I need to build custom endpoints for Business Central line items?
- No. Truto's proxy tools automatically handle deeply nested navigational properties (like `purchaseOrderLines` and `dimensionSetLines`), allowing agents to read and write complex relational data in a single tool call.