匠人学院 JR Academy
Skip to article
Learning guide
FDE Guide

How to become a Forward Deployed Engineer and how the work is done: who hires FDEs, how the role differs from AI Engineer and Solutions Engineer, whether juniors can get in, certifications, and paths from engineering or business.

6 chapters·27 guides·Access varies by chapter
Integrating AI with Enterprise Systems: Legacy APIs, MCP, Idempotency and Long-running Workflows
On this page

Integrating AI with Enterprise Systems: Legacy APIs, MCP, Idempotency and Long-running Workflows

#Quick answer: what has to be solid before an AI feature touches a client's systems?

The model call is the easy part of the integration. Production incidents come from four other places: a legacy API whose responses drift, the same event delivered twice, an MCP tool running with far too much permission, and a long workflow that fails halfway with nobody told. A Forward Deployed Engineer (FDE) is expected to close those four gaps first, then tune model quality.

  • Legacy APIs: never let the model or agent call them directly. Put an adapter layer you own in between, with fixed field names, timeouts, retries and error codes.
  • MCP (Model Context Protocol): tool permissions follow the real user, and every call is written to an audit log. The current MCP specification is version 2026-07-28, and authorization is OPTIONAL for HTTP transports, so enterprise permissions are your design work, not something the protocol guarantees (MCP specification↗, authorization↗).
  • Idempotency: any handler with side effects must be safe to trigger twice by the same event.
  • Long-running workflows: persist state at every step, resume from the last good step, hand off to a person when stuck, and continue after the person decides.

Last checked: 2026-12-04. The code below was run on Python 3.14 using only the standard library (sqlite3, json, dataclasses).


#Why do legacy APIs cause the most trouble, and how do you wrap them?

ERP, CRM and ticketing systems at Australian banks, councils, insurers and retailers are often SOAP services or custom HTTP endpoints that are ten years old or more. Typical problems and the adapter-layer response:

ProblemConsequenceWhat the adapter does
No stable event ID, only "last modified"Cannot tell duplicates apartBuild an idempotency key from source system plus business fields
Field meaning changes between versions, mixed date formatsThe model reads wrong dataConvert to a fixed internal schema and validate on the way in and out
Strict rate limits, slow responses, occasional 5xxAgent retries overload the client's systemOne place for timeouts, exponential backoff and a concurrency cap
Write endpoints cannot be undone and have no dry-runOne bad call is a real incidentSplit writes into "create change request" and "apply change request", with approval in between
Only a shared service account existsNobody can tell who did whatRecord the real user in the adapter; keep the service account for the connection only

The rule is simple: the model only ever sees the adapter's interface, never the legacy API itself. When the legacy system changes, you edit the adapter; the eval set and prompts stay put. The matching task in the FDE Tech program is Working with Legacy APIs (FDE Tech).


#How do you process a duplicate event only once?

Webhooks and message queues in enterprise systems are almost always at-least-once delivery, so duplicates are normal. Claim an idempotency key before doing anything; only the caller that wins the claim runs the side effect. Put the business write and the key record in the same transaction.

python
# Python 3.14, standard library only import hashlib import json import sqlite3 db = sqlite3.connect(":memory:") db.execute(""" CREATE TABLE processed_events ( idem_key TEXT PRIMARY KEY, -- source system + event ID, or a hash of business fields status TEXT NOT NULL, -- 'in_progress' | 'done' result TEXT )""") db.execute("CREATE TABLE tickets (id INTEGER PRIMARY KEY, order_ref TEXT, note TEXT)") def idem_key(event: dict) -> str: # Use the source's event_id when it is stable; otherwise hash the business fields if event.get("event_id"): return f"{event['source']}:{event['event_id']}" body = json.dumps( {k: event[k] for k in ("source", "order_ref", "type")}, sort_keys=True ) return "h:" + hashlib.sha256(body.encode()).hexdigest() def handle(event: dict) -> str: key = idem_key(event) with db: # one transaction: claim the key + write business data, all or nothing claimed = db.execute( "INSERT INTO processed_events (idem_key, status) VALUES (?, 'in_progress') " "ON CONFLICT(idem_key) DO NOTHING", (key,), ).rowcount if claimed == 0: # key seen before: skip the side effect row = db.execute( "SELECT status, result FROM processed_events WHERE idem_key = ?", (key,) ).fetchone() return f"duplicate ({row[0]})" cur = db.execute( "INSERT INTO tickets (order_ref, note) VALUES (?, ?)", (event["order_ref"], event["type"]), ) db.execute( "UPDATE processed_events SET status = 'done', result = ? WHERE idem_key = ?", (str(cur.lastrowid), key), ) return "created" e = {"source": "erp", "event_id": "evt-1001", "order_ref": "SO-77", "type": "refund_requested"} print(handle(e)) # created print(handle(e)) # duplicate (done) print(db.execute("SELECT COUNT(*) FROM tickets").fetchone()[0]) # 1

Common mistakes:

  • Key scope: the same event_id can collide across source systems, so the key includes the source.
  • Side effects in someone else's system (for example writing an order into the client's ERP) are outside your transaction. Pass your idempotency key to that system if it accepts one. If it does not, write a local "pending" record first, mark it done after the call, and on restart check whether the other side already applied it.
  • Claim inside the transaction. A check-then-write pattern lets two concurrent workers both pass.
  • Replay test: send a batch of real events twice and assert the business table row count is unchanged. That is the acceptance check for the Events, Idempotency and Duplicates task in the course.

#How do you run an MCP server inside an enterprise: permissions and audit?

An MCP server hands the model a way to act. The specification's own security principles say tools represent arbitrary code execution, hosts must obtain explicit user consent before invoking any tool, and tool descriptions and annotations should be treated as untrusted unless they come from a trusted server (MCP specification↗, version 2026-07-28). The authorization points that matter most in an enterprise:

  • Authorization is optional for HTTP transports. When used, the MCP server acts as an OAuth 2.1 resource server and must implement Protected Resource Metadata (RFC 9728).
  • Clients must send the resource parameter (RFC 8707) when requesting tokens; the server must validate that a token was issued for it and must not accept or pass through other tokens.
  • Insufficient permission returns 403 with insufficient_scope, and the WWW-Authenticate header names the scope needed (authorization↗).

On top of that, add three things:

  1. Permissions follow the real user, not the agent. Carry the user identity from the token into each tool, and check that user's scopes. Avoid one all-powerful service account.
  2. Declare read and write separately. Each tool states its required scope and whether it writes; writes go through approval (the Approval-aware Tool Use task).
  3. Audit every call, including successes, failures and denials: who, when, which tool, which arguments, what outcome.

The snippet below does not depend on any MCP SDK. It shows the wrapper logic that belongs at the entry of each tool handler; with an official SDK, call it from the handler.

python
# Python 3.14, standard library only import json import time from dataclasses import dataclass, field from typing import Callable # Each tool declares the scope it needs and whether it writes TOOLS: dict[str, dict] = { "get_invoice": {"scope": "invoices:read", "write": False}, "approve_refund": {"scope": "refunds:write", "write": True}, } @dataclass class Principal: user_id: str # the real user, not a shared service account scopes: set[str] = field(default_factory=set) class PermissionDenied(Exception): pass def call_tool(principal: Principal, name: str, args: dict, handlers: dict[str, Callable[..., dict]], audit_sink) -> dict: spec = TOOLS[name] record = {"ts": time.time(), "user": principal.user_id, "tool": name, "args": args, "write": spec["write"]} if spec["scope"] not in principal.scopes: record["outcome"] = "denied" audit_sink(json.dumps(record)) raise PermissionDenied(f"{principal.user_id} lacks {spec['scope']}") try: result = handlers[name](**args) record["outcome"] = "ok" return result except Exception as exc: record["outcome"] = f"error:{type(exc).__name__}" raise finally: audit_sink(json.dumps(record)) # one record for success, failure and denial log: list[str] = [] handlers = {"get_invoice": lambda invoice_id: {"id": invoice_id, "total_aud": 1280.0}, "approve_refund": lambda invoice_id, amount_aud: {"ok": True}} reader = Principal("amy@client.example", {"invoices:read"}) print(call_tool(reader, "get_invoice", {"invoice_id": "INV-9"}, handlers, log.append)) try: call_tool(reader, "approve_refund", {"invoice_id": "INV-9", "amount_aud": 50}, handlers, log.append) except PermissionDenied as e: print("denied:", e) print(len(log), json.loads(log[1])["outcome"]) # 2 denied

Audit arguments can contain personal information, so decide with the client's data classification whether to log raw values, redacted values or only a hash. For tool design and debugging see MCP development best practices; for the attack surface (tool-description poisoning, token misuse) see security and threat modeling; for MCP basics see the MCP chapter of the Agent guide.


#How do you resume a long workflow after a failure, and when does a person take over?

Expense approval, account opening and bulk reconciliation can run for minutes or days, waiting on external systems and on people. Do not keep progress in memory or in the chat context. Keep it in a table, updated before and after every step. MCP also has a matching extension: Tasks, for asynchronous execution of long-running operations with polling and durable handles (Tasks extension↗).

A minimal state table:

StateMeaningWho moves it forwardAllowed next states
pendingCreated, not startedSchedulerrunning
runningExecuting a step; records step name and start timeWorkerstep_done, failed
step_doneOne step finished, output persistedWorkerrunning (next step), completed
waiting_humanNeeds approval or missing informationA person on the client siderunning (with their decision), cancelled
failedA step failed; records error and retry countWorker or a personrunning (retry), waiting_human
completed / cancelledTerminaln/an/a

Design points:

  • Make every step idempotent, so "restart after the last step_done" is safe. Steps that cannot be idempotent (sending an email, taking a payment) get flagged, and before resuming you check whether the other system already did it.
  • Cap retries. For example, move to waiting_human after 3 failures of the same step instead of retrying forever; set the number from what the client's system tolerates.
  • Hand over with full context: completed steps, the failing step and its error, the model's suggestion, and the decision the person needs to make. Write the decision back to the same row and continue from that step.
  • Plan for partial failure. If step 2 of 3 succeeded and step 3 failed, you need a compensating action or an explicit manual-rollback list. The course tasks for this are Long-running Workflows, Human Handover and Resume, and Recovery after Partial Failure.

#Next steps

  • Main: FDE Tech career program. The enterprise-integration and agent-control groups (10 tasks) are done against real enterprise situations, and the deliverables include a replayable idempotency test and an approval-aware long workflow.
  • Secondary: MCP chapter of the Agent guide. Read it first if you still need MCP basics and how a server is written, then come back for enterprise permissions and audit.
Published by
JR Academy
Learning resources

Individual authors and reviewers are credited where recorded.

Related Roadmaps

Done reading? Next steps