AI · Automation · Engineering

Custom AI Agents in Business Central: A Playbook

By Lazar MilicevicAugust 22, 202611 min read
Developer workstation with code for custom AI agents in Business Central

The dangerous version of an AI agent in an ERP is not the one that gives a bad answer. It is the one that posts a journal, changes a vendor record, or creates a purchase document with incomplete context and no clean way to reverse it.

I have built autonomous systems that run without a person watching every step, from multi-agent content pipelines to serverless operational integrations. The same lesson applies when I translate those patterns into Microsoft Dynamics 365 Business Central: the model should help interpret work, but the ERP must remain the system of record and policy enforcement point.

Start With a Bounded Decision, Not a General Chatbot

A useful Business Central agent should own one narrow operational decision, have a defined data boundary, and produce an auditable outcome. “Help finance with AI” is not an implementation scope. “Review overdue invoices daily, classify likely collection blockers, and create approval-ready follow-up tasks” is.

This distinction matters because finance and operations workflows contain state, permissions, financial controls, and downstream consequences. A conversational agent that can “do anything in Business Central” is difficult to test and almost impossible to govern.

I start by separating work into three classes:

Workflow type Example Agent autonomy level
Read and summarize Explain why a customer balance increased this month Read-only
Prepare a recommendation Draft a vendor follow-up based on blocked invoices Draft plus human approval
Execute a controlled action Create a replenishment suggestion under preset rules Limited execution with validation

For most teams, the first production release should sit in the second row. The agent can retrieve relevant records, identify a pattern, prepare a structured recommendation, and hand it to the accountable person.

That sounds conservative. It is also how I avoid a common AI proof of concept failure: a convincing demo that cannot survive real operational inputs.

A good first agent might do this:

  1. Run each morning against a defined company and date range.
  2. Retrieve overdue customer ledger entries and recent interaction notes.
  3. Group items by customer and materiality threshold.
  4. Explain the likely issue using linked evidence.
  5. Create a draft collection task or case.
  6. Require approval before any message, payment action, or document posting.

The agent has a job. It does not have open-ended access to the ledger.

Use Copilot Studio for Interaction, APIs for Data, and AL for Rules

The cleanest Business Central architecture puts Copilot Studio at the interaction and orchestration layer, Business Central APIs at the data boundary, and AL extensions at the business-rule boundary. This keeps language-model behavior separate from the financial logic that needs deterministic execution.

I think of the stack as three layers:

User or scheduled trigger
        |
Copilot Studio agent
        |
Custom connector or API service
        |
Business Central standard API / custom API page
        |
AL validation, approval workflow, posting logic
        |
Business Central data and audit trail

Copilot Studio is useful when the agent needs a user-facing conversational interface, workflow orchestration, approvals, and connections to Microsoft 365 tools. Business Central provides standard REST APIs for common business entities, while custom API pages let me expose only the business objects and fields a custom AI agent actually needs.

Microsoft documents its Business Central API surface in the Business Central API reference. I use standard APIs where they match the use case. I build a custom API when the agent needs a deliberately constrained operational view rather than broad access to raw entities.

For example, I would not give an invoice-resolution agent unrestricted write access to sales invoices. I would create an AI Exception table and custom API endpoint that accepts a small, validated recommendation:

  • Document reference
  • Exception category
  • Confidence level
  • Evidence links
  • Proposed next action
  • Assigned approver
  • Agent run ID

That object becomes the handoff between probabilistic AI output and deterministic ERP workflow.

A simplified custom API page in AL can expose a controlled entity:

page 50120 "AI Exception API"
{
    PageType = API;
    APIPublisher = 'bizflowai';
    APIGroup = 'operations';
    APIVersion = 'v1.0';
    EntityName = 'aiException';
    EntitySetName = 'aiExceptions';
    SourceTable = "AI Exception";
    ODataKeyFields = SystemId;
    DelayedInsert = true;

    layout
    {
        area(content)
        {
            repeater(Group)
            {
                field(id; SystemId) { }
                field(documentNo; "Document No.") { }
                field(category; Category) { }
                field(recommendation; Recommendation) { }
                field(status; Status) { }
                field(agentRunId; "Agent Run ID") { }
            }
        }
    }
}

The code is not the hard part. The contract is. Every field should answer a governance question: what did the agent observe, what did it recommend, who approved it, and what happened next?

If I need to create or modify an operational record, I do not let the agent call posting code directly. I pass the request into an AL codeunit that applies the same checks a human-operated page or established workflow would apply.

Treat the Agent Workflow as a State Machine

An autonomous workflow in Business Central should move through explicit states, not jump from an LLM response to a posted financial transaction. I use state transitions because they make retries, approvals, error handling, and audit evidence manageable.

A practical state model looks like this:

Detected -> Enriched -> Recommended -> Awaiting Approval
         -> Approved -> Executed -> Verified
         -> Rejected / Failed / Expired

Each transition should be owned by a specific component:

  • Detected: a scheduled job, webhook, Power Automate flow, or external worker finds a relevant event.
  • Enriched: the agent retrieves only the records needed for this case.
  • Recommended: the LLM produces structured output, not free-form prose.
  • Awaiting Approval: Business Central, Teams, or a defined workflow routes the action to a human.
  • Executed: AL code or an approved API operation performs the allowed change.
  • Verified: a deterministic check confirms the intended record state exists.

The verification stage is routinely skipped in AI prototypes. It should not be. A successful HTTP response does not prove a successful business outcome.

For a purchase-order exception agent, verification might check:

  1. The purchase order still exists and is open.
  2. The expected vendor and amount match the approved payload.
  3. The agent action has not already been applied.
  4. The final status is written back to the exception record.
  5. The approver, timestamp, and source run ID are recorded.

That third check is critical. Scheduled agents retry. APIs timeout. A user can click Approve twice. Without idempotency, an agent that appears reliable in testing can create duplicate tasks, duplicate records, or repeated notifications in production.

I use a stable idempotency key such as:

{companyId}:{sourceDocumentSystemId}:{actionType}:{businessDate}

I store that key with the proposed and executed action. Before execution, the workflow checks whether that exact action has already completed. If it has, the operation returns the existing result instead of doing the work again.

This is one of the patterns I carried from event-driven AWS integrations into AI workflow automation. Reliability comes from making retries safe, not from pretending retries will never happen.

Give the Model Structured Outputs and a Small Evidence Window

LLMs are useful at classification, extraction, prioritization, and explanation. They are not a substitute for Business Central validation rules, approval limits, dimensions, posting groups, or financial controls.

I make the model return a structured schema. For example, an invoice exception agent might return:

{
  "classification": "missing_purchase_order",
  "confidence": 0.86,
  "recommended_action": "request_po_reference",
  "risk_level": "medium",
  "evidence": [
    {
      "record_type": "purchaseInvoice",
      "record_id": "8a31...",
      "reason": "No matching PO reference found"
    }
  ],
  "requires_human_approval": true
}

The application validates this output before writing anything to Business Central:

  • Is classification one of the allowed values?
  • Is the document ID in scope for this agent?
  • Does the evidence refer to records the agent was allowed to retrieve?
  • Does the action match the configured risk level?
  • Is human approval required for this company, amount, or document type?

I also keep the context window intentionally small. Dumping every ledger entry, vendor note, and transaction history into a prompt is expensive, slow, and unsafe. It also makes the answer less reliable because the model has too much loosely related information.

For retrieval-heavy use cases, I prefer a two-step pattern:

  1. Query Business Central for canonical transactional data using deterministic filters.
  2. Retrieve supplementary unstructured context, such as policy documents or case notes, from a separate RAG index.

That allows the agent to say, “This invoice is blocked because it lacks a purchase order reference, and the applicable AP policy requires one,” while preserving the distinction between source-of-truth ERP data and supporting documentation.

For RAG, I would store document chunks with metadata such as company, department, policy version, document status, and access scope. Hybrid retrieval, combining keyword search and vector similarity, is generally more dependable than embeddings alone when users reference document numbers, vendor names, or accounting terms.

Put Identity, Permissions, and Approval Boundaries First

The safest custom AI agent uses a dedicated application identity with the minimum Business Central permissions necessary for one workflow. It should not impersonate an administrator, share a service account across unrelated agents, or receive broad write permissions because that is convenient during a demo.

This is where an AI implementation becomes an enterprise AI automation project rather than a chatbot experiment.

I would create a separate identity for each production agent or tightly related workflow. For example:

  • ai-ar-exceptions-prod
  • ai-ap-invoice-review-prod
  • ai-inventory-replenishment-prod

Each identity gets a narrowly scoped permission set and access only to the relevant Business Central company or environment. Production and sandbox credentials stay separate. Logs must avoid storing full financial records, secrets, or personal data unless there is a defined retention and access policy.

For service-to-service integrations, Business Central supports Microsoft Entra application registrations and application permissions. Microsoft’s documentation on Microsoft Entra applications in Business Central is the right starting point for configuring that access model.

I also apply a simple rule:

The agent can recommend beyond its authority, but it cannot execute beyond its authority.

A model may identify that a payment hold should be reconsidered. It should not remove the hold unless a deterministic policy check and the responsible approval path allow it.

Microsoft’s own responsible AI guidance describes six principles: “fairness, reliability and safety, privacy and security, inclusiveness, transparency, and accountability.” Those are not abstract policy words when an agent sits near financial operations. Microsoft’s Responsible AI Standard is a useful reference point, but I translate those principles into concrete controls: access boundaries, evidence records, approval gates, reversal paths, and run-level logging.

Test With Replays Before You Trust Live Autonomy

The first production test for a Business Central AI agent should use historical or synthetic cases replayed through the full workflow. I do not start by pointing an agent at live operational records and hoping its confidence score means something.

I build a small evaluation set that includes ordinary cases, edge cases, and failure cases. For an accounts payable agent, that might include:

  • A valid invoice with a matching purchase order.
  • An invoice with a missing purchase order.
  • A duplicate invoice number from the same vendor.
  • A partial receipt that requires human review.
  • A vendor name with a near match to another vendor.
  • A malformed attachment or missing supporting record.

Then I measure the parts separately:

Check What I verify
Retrieval accuracy Did the agent retrieve the correct documents and policies?
Classification accuracy Did it assign the right exception type?
Action safety Did it avoid proposing prohibited actions?
Workflow correctness Did approvals, retries, and state changes behave correctly?
ERP verification Did the final record state match the intended result?

I want a trace for every run: input event, retrieved records, prompt version, model version, structured response, validation outcome, approver decision, execution result, and final verification result.

That trace makes troubleshooting possible when the agent gets something wrong. It also gives finance and operations teams a real basis for trust. “The model said so” is not an audit trail.

What I’d Do First

If I were asked to build custom AI agents for a Business Central environment, I would start with one high-volume, low-to-medium-risk exception workflow. I would choose a process with a measurable manual burden, clear data ownership, and a known human escalation path.

My first 30 days would look like this:

  1. Map the current workflow, including systems, owners, approvals, and failure modes.
  2. Define one measurable outcome, such as review time per invoice exception or overdue-account follow-up coverage.
  3. Build a read-only agent that produces recommendations with evidence.
  4. Add a controlled custom API and an AL-backed approval state.
  5. Run historical replay tests and correct retrieval or classification failures.
  6. Enable limited execution only after the verification and audit paths are working.

I would not begin with autonomous posting. I would earn that capability one bounded action at a time.

The most valuable AI agent development work in ERP systems is rarely about making the chat interface more impressive. It is about designing the controls around the model so the workflow remains correct when inputs are incomplete, permissions are constrained, and the agent runs at 2 a.m. without anyone watching.

If you are planning a Business Central AI proof of concept or need to turn an existing Copilot idea into a governed operational workflow, I write more about production AI automation on this blog. You can also reach me through lazar-milicevic.com/#contact.

Frequently asked questions

What is the safest first use case for a custom AI agent in Microsoft Dynamics 365 Business Central?

I recommend starting with a narrow, approval-based workflow rather than an agent that can perform open-ended ERP actions. A strong first use case is reviewing overdue invoices, identifying likely collection blockers, and creating draft follow-up tasks for a finance user to approve. This gives the agent a defined data scope and useful operational role while keeping posting, payments, and customer communications under human control.

Can an AI agent post journals or create purchase documents in Business Central?

An AI agent can support those processes, but I would not allow an LLM to post journals or create financial documents directly without controlled validation. The agent should prepare a structured recommendation, route it through an approval workflow, and pass the approved request to AL business logic. Business Central should remain the system of record and the place where permissions, validation rules, posting controls, and audit trails are enforced.

How should I connect Copilot Studio to Business Central for a custom AI agent?

I use Copilot Studio as the interaction and orchestration layer, Business Central APIs as the data boundary, and AL extensions as the business-rule boundary. Copilot Studio can handle conversational interactions, scheduled workflows, approvals, and Microsoft 365 connections, while standard or custom Business Central REST APIs provide controlled access to ERP data. I keep deterministic financial logic in AL codeunits rather than relying on model-generated actions.

When should I use a custom Business Central API instead of a standard API?

I use a standard Business Central API when it exposes exactly the entity and fields required for the workflow. I create a custom API page when an agent needs a deliberately limited operational view instead of broad access to raw ERP records. For example, an invoice-resolution agent can submit an AI Exception record containing a document reference, recommendation, evidence, confidence level, approver, and agent run ID instead of receiving write access to sales invoices.

Why should a Business Central AI agent use workflow states and approvals?

I treat an AI workflow as a state machine because explicit states make approvals, retries, failures, reversals, and auditing manageable. The workflow should move from detection and evidence gathering to recommendation, approval, controlled execution, and recorded outcome rather than jumping directly from an LLM response to a financial transaction. This creates a clear record of what the agent observed, what it proposed, who approved it, and what Business Central ultimately did.

Lazar Milicevic

Lazar Milićević

Senior Technical Engineer. I build AI automation, GenAI/LLM systems and cloud architecture — autonomous systems that run while you sleep. Founder of BizFlowAI.

Building something hard with AI or automation? I am open to talk.

Get in touch

← All posts