ERP, CRM, API and Event Integration
Systems of record deserve a careful visitor, not an improvising one.
Connect agents through narrow, supported interfaces that enforce identity and business rules on the server side. Make every write idempotent and version-checked, publish changes as events, expect partial failure, respect vendor terms and limits and keep a record that links each change to a user, an agent and a run.
What you will learn: integration styles, how to turn business operations into safe tools, how to handle identity, retries, conflicts and events, what to check in vendor terms and how to test integrations before real data is touched.
Prerequisites: Agent Tools, Function Calling and Tool Registries and Reliable Tool Execution and Error Recovery.
The example runs in November 2026 with Python 3.13 and only the standard library. Its "ERP" is a small in-memory simulation, not any vendor's product. Vendor interfaces and terms change, so check current documentation and your contract.
What agents need to connect to
ERP (enterprise resource planning) systems hold orders, stock, finance and purchasing. CRM (customer relationship management) systems hold accounts, contacts, opportunities and service cases. Around them sit HR, ticketing, document and data systems. These are systems of record: other people rely on what they say, and a wrong change can spread to invoices, shipments, payroll or reports.
Integration styles
| Style | Good for | Watch for |
|---|---|---|
| Business API | Reading and changing records with rules enforced | Rate limits, versioning |
| Events and messages | Reacting to changes without polling | Duplicates, ordering, replay |
| Integration platform | Mapping, routing and central policy | Another layer to own |
| MCP server or gateway | Describing tools to many agents in one way | Trust, permissions and sprawl |
| Data platform copy | Analysis and search without loading the source | Staleness; copied permissions |
| Screen automation | Systems with no usable interface | Brittle, hard to constrain |
| Direct database writes | Almost never | Bypasses business rules and audit |
Prefer the interface the vendor supports for the purpose. A direct database update may look quick and can silently skip validation, totals, postings and logs.
From API to tool
Do not hand a model hundreds of raw endpoints. Offer a few tools shaped around business tasks.
| Weak tool | Better tool | Why |
|---|---|---|
call_api(method, url, body) | get_order_status(order_id) | Reach is limited and testable |
update_customer(any_fields) | propose_address_change(customer_id, address) | One field set, one approval path |
search(sql) | list_open_invoices(supplier_id, since) | No query injection, bounded results |
send(email) | draft_reply(case_id, text) | A person sends |
Return compact results with stable identifiers and clear errors. A verbose record with two hundred fields wastes context, raises cost and invites mistakes. Describe units, currencies, time zones and allowed values. Designing Tool Schemas and Contracts goes further.
Whose permissions apply
| Model | Use | Risk |
|---|---|---|
| Acts for the signed-in user | Interactive help | Agent can do all the user can unless further limited |
| Own service identity | Background processing | Can become a powerful shared account |
| Both combined | Allowed only where user and agent are both permitted | More setup, usually the safest |
Use short-lived, scoped credentials, keep them out of prompts and logs and enforce permissions in the target system or gateway. Instructions to a model are not access control (Agent Identity, Authorization and Secrets). Keep separation of duties: an agent that creates a supplier should not also approve payment to it.
Safe writes
Networks fail after a change succeeds but before the answer arrives. Agents and workflow engines then retry. Without protection, the order is placed twice.
- Idempotency key: a stable identifier for the intended action. The server returns the first result when it sees the key again.
- Bind the key to content: reject a reused key with different values.
- Version check: change a record only if it is still the version that was read.
- Preview: where supported, validate without saving and show the difference to an approver.
- Approve the exact change: if values change after approval, ask again.
- Verify: read back and compare before reporting success.
A write gateway in miniature
The program shows a retry, a reused key, a stale read and a role limit. It also records an event together with each successful change.
"""Idempotent, version-checked writes to a simulated system of record."""
import hashlib
import json
class ERP:
def __init__(self):
self.orders = {"PO-7": {"version": 3, "ship_to": "Dock A", "total": 900}}
self.seen = {} # idempotency key -> (request hash, result)
self.outbox = [] # events saved together with the change
def update(self, user, order_id, expected_version, changes, key):
body = json.dumps([order_id, expected_version, changes], sort_keys=True)
digest = hashlib.sha256(body.encode()).hexdigest()
if key in self.seen:
old_digest, result = self.seen[key]
if old_digest != digest:
return "rejected: key reused with different content"
return result + " (replayed, no second change)"
if "total" in changes and user != "buyer":
return "rejected: this role may not change amounts"
order = self.orders[order_id]
if order["version"] != expected_version:
return f"conflict: record is now version {order['version']}, read it again"
order.update(changes)
order["version"] += 1
self.outbox.append({"id": key, "type": "order.changed", "order": order_id,
"version": order["version"]})
result = f"updated to version {order['version']}"
self.seen[key] = (digest, result)
return result
erp = ERP()
steps = [
("agent writes", ("logistics", "PO-7", 3, {"ship_to": "Dock B"}, "run42-step1")),
("network retry", ("logistics", "PO-7", 3, {"ship_to": "Dock B"}, "run42-step1")),
("changed content", ("logistics", "PO-7", 3, {"ship_to": "Dock C"}, "run42-step1")),
("stale read", ("logistics", "PO-7", 3, {"ship_to": "Dock C"}, "run43-step1")),
("beyond role", ("logistics", "PO-7", 4, {"total": 9000}, "run43-step2")),
]
for label, args in steps:
print(f"{label:16} {erp.update(*args)}")
print("record:", erp.orders["PO-7"])
print("events waiting to be published:", len(erp.outbox))
Output:
agent writes updated to version 4
network retry updated to version 4 (replayed, no second change)
changed content rejected: key reused with different content
stale read conflict: record is now version 4, read it again
beyond role rejected: this role may not change amounts
record: {'version': 4, 'ship_to': 'Dock B', 'total': 900}
events waiting to be published: 1
Five attempts produced one change and one event. The retry returned the earlier result, the altered request was refused, the stale write was told to read again and the role limit held even though the request was otherwise valid. In a real service, the key table, record update and event must be saved in one transaction, keys need an expiry policy, concurrent requests need locking or unique constraints and a replayed result should be returned only to a caller entitled to see it.
Events and the outbox pattern
Agents often start from events: a case opened, a delivery delayed, a document uploaded. Two rules prevent much trouble. First, assume an event can arrive more than once, so consumers must deduplicate by identifier. Second, do not assume order unless your platform guarantees it for that key; compare record versions.
When one action must both change a database and publish a message, doing them separately can leave one done and the other lost. The transactional outbox saves the change and a pending message together; a publisher sends pending messages afterward, possibly more than once. A shared event format such as CloudEvents gives each message a type, source, identifier and time. Event-Driven and Background Agents covers queues, retries and dead letters.
Actions across several systems
There is rarely one transaction across ERP, CRM and a payment provider. Use a workflow that records each step and can compensate: cancel the reservation, reverse the entry, notify a person. Some actions, such as a sent email or a released payment, cannot be undone, so place approval before them and order steps so that irreversible ones come last (Durable Execution, Checkpoints and Approvals).
| Step | If a later step fails |
|---|---|
| Reserve stock | Release reservation |
| Create draft order | Cancel draft |
| Hold credit | Remove hold |
| Confirm to customer | Cannot unsend; correct and apologize |
Protecting the source system
An agent can call far more often than a person. Set per-agent rate and concurrency limits, cache stable reference data, use bulk or analytical interfaces for large reads, page through results and back off when asked. Cap calls per run so a loop cannot flood a system. Schedule heavy work outside critical windows such as period close (Scaling, Hardware, Quotas and Caching).
Vendor terms are part of the design
A technically possible call may not be permitted. Software vendors have begun writing rules specifically about AI agents. In April 2026 SAP revised its API policy to limit use of its interfaces by autonomous AI systems outside architectures it endorses, which drew discussion among customers, and interpretations and details may continue to change.
For every system, ask:
- Are automated and AI-driven calls allowed under our license and API terms?
- Which interfaces are supported, and which are internal?
- Do machine users or documents created by agents affect licensing cost?
- May data be copied elsewhere, indexed or sent to a model provider?
- What notice do we get before an interface changes?
Involve procurement and legal staff, record the answers in the register and recheck at renewal.
MCP and gateways in the enterprise
The Model Context Protocol (MCP) standardizes how agents discover and call tools (What Is MCP? Hosts, Clients, Servers and Capabilities). It does not decide whether a call is allowed or wise. In larger settings, route tool servers through a gateway or registry that authenticates callers, limits which tools each agent sees, applies policy, logs calls and lets you disable a server quickly. Review third-party servers like any software dependency, pin versions and treat tool descriptions and results as untrusted input (MCP Gateways, Catalogs and Governance).
Data movement and freshness
Decide for each source whether the agent reads live, from a replica or from a search index. Live reads are current and carry load; copies are fast and can be stale or lose permissions. Show the time of the data in answers that matter, propagate deletions and access changes to indexes and never let a copy become an unofficial second source of truth (Knowledge Ingestion and Real-Time Pipelines).
Handling change
Interfaces evolve. Define the contract each tool relies on, test it automatically against a sandbox, alert on unknown fields or error codes and fail closed when a response no longer parses. Keep a mapping layer so a vendor change affects one place. Releases of the agent and of its connectors should be recorded together (Versioning, Registries and Evaluation-Driven Development).
Testing without hurting anyone
| Stage | Checks |
|---|---|
| Contract tests | Fields, types, errors, permissions |
| Simulator | Timeouts, duplicates, conflicts, partial failure |
| Vendor sandbox | Real behavior with synthetic data |
| Read-only production | Retrieval quality and load |
| Draft mode | Proposed changes compared with human choices |
| Limited writes | Small group, low limits, quick reversal |
Sandboxes often differ from production in data, configuration and limits, so note what was not tested. Never copy real personal data into test systems without permission and protection.
Observability and audit
For every change record the person or event that started it, the agent and release, the tool and arguments, the approval, the idempotency key, the system's response and the resulting record version. Reconcile regularly: compare what the agent says it did with what the system recorded. Redact secrets and sensitive values (Safe Logging, Sampling and Retention).
An agent updates delivery dates after reading supplier emails. A timeout makes the workflow retry, and without keys two change records and two customer notices appear. With a key per supplier message and line, plus a version check, the retry would return the first result and send one notice. This scenario is invented.
Errors an agent can act on
A vague "request failed" invites guessing and blind retries. Return a small, documented set of outcomes with the next permitted step.
| Outcome | Meaning | Next step |
|---|---|---|
| Invalid input | A field is wrong or missing | Correct from source data, or ask |
| Not permitted | Identity lacks the right | Do not retry; hand off |
| Conflict | Record changed | Read again and reconsider the change |
| Busy or rate limited | Try later | Wait with backoff, within a limit |
| Unknown result | Timeout after sending | Query by key before any retry |
The last row matters most. Treating a timeout as a failure is the classic source of duplicates.
Owning the connector
Every connector needs a named team that watches errors, rotates credentials, tracks vendor notices and removes unused tools. Publish what each tool may change, its limits and its contact. Review usage from time to time: a write permission that no run has used in months is a candidate for removal.
A decision shortcut
When unsure which route to take, ask three questions in order: does the vendor support and permit it, can the server enforce who may do what, and can we prove afterward what happened? A route that fails any one of these needs redesign, however quickly it could be demonstrated.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Generic "call any API" tool | Unbounded reach | Narrow business tools |
| Retrying writes without keys | Duplicate transactions | Idempotency and read-back |
| One administrator account | No least privilege or attribution | Scoped identity per agent |
| Writing to tables directly | Rules and audit skipped | Supported interfaces |
| Ignoring API terms | Blocked access or contract dispute | Check before building |
| Treating returned text as instructions | Prompt injection through records | Treat all content as data |
Checklist
- Each integration uses a supported interface permitted by contract.
- Tools are narrow, typed and return compact results.
- Permissions are enforced outside the model.
- Writes use keys, version checks and read-back.
- Events are deduplicated and ordering is not assumed.
- Multi-system steps have compensation or approval.
- Limits protect source systems.
- Changes are traceable from request to record.
Frequently asked questions
Should every system be exposed through MCP?
Only where reuse across agents or clients justifies it. A direct, well-controlled function is fine for a single narrow integration.
Can an agent use screen automation for a legacy system?
Sometimes, with an isolated session, limited account and verification after each action. Plan to replace it with a supported interface.
Where should business rules live?
In the system of record or a deterministic service in front of it. Prompts may explain rules but should not be the only enforcement.
How do we undo a wrong change?
Use the system's own reversal or correction process, keeping history. Design and rehearse that route before allowing writes.
References
- CloudEvents specification project
- Model Context Protocol documentation
- ASUG overview of the 2026 SAP API policy
- OWASP API Security Project
Where to go next
Tool Permissions, Approvals and Abuse Risks
Control what tools may do.
Enterprise Agent and Platform Reference Architectures
See the surrounding platform.
Finance, Tax and Audit Agents
Apply integration in finance work.