How API Wrappers Connect AI Agents to Legacy Systems | Hokstad Consulting

How API Wrappers Connect AI Agents to Legacy Systems

How API Wrappers Connect AI Agents to Legacy Systems

An API wrapper lets an AI agent use selected legacy functions without replacing the system. Start with one read-only account lookup. Add writes only after access checks, human approval and duplicate prevention have been tested.

The path is simple: AI agent → tool schema → wrapper API → legacy application. The agent requests an action; application code and the wrapper decide whether it can run.

This guide covers how to:

  • Define narrow tools, data formats and safe error responses.
  • Choose immediate responses, queued jobs or batch processing.
  • Build an account lookup and an approved service-request flow.
  • Protect credentials, limit personal data and trace each request.
  • Test failures, measure results and pilot with a manual fallback.

A timeout does not mean a write failed. Check the legacy record before retrying, and remember that stopping the agent does not reverse completed changes.

::: @figure How API Wrappers Safely Connect AI Agents to Legacy Systems{How API Wrappers Safely Connect AI Agents to Legacy Systems} :::

Design the API Contract and Tool Schema

Define Requests, Responses and Errors

Use two contracts: an OpenAPI spec for software and a narrower tool schema for the model. Document methods, paths, authentication, fields, validation, status codes, errors, pagination, timeouts, versioning and audit fields. This keeps the legacy function stable and gives the agent access only to a controlled set of actions.

The wrapper exposes GET /v1/customer-accounts/{customer_id}; the agent receives the get_customer_account tool.

The adapter translates canonical JSON into the legacy format: SOAP/XML, fixed-width records, field codes or positional parameters. Normalise status codes into documented values, dates into ISO 8601 timestamps, and amounts into exact decimals with an explicit currency, such as GBP.

Use a new API version for breaking changes. You can add optional response fields without breaking existing clients. When deprecating a field, state its removal date.

Define consistent errors: 400 invalid_request, 401 unauthorised, 403 forbidden, 404 not_found, 409 duplicate_or_conflict, 429 rate_limited and 502 legacy_unavailable. Each error should include a user-safe message, correlation ID and retry guidance. Keep diagnostic details in protected logs, not in raw backend errors shown to users.

For list operations, enforce a maximum limit and use an opaque continuation token. Set wrapper timeouts below agent timeouts. Pass correlation IDs through every step and audit the requesting user, agent identity, authorised application or service account, action, target record and outcome. Store action times as ISO 8601 timestamps with explicit time zones.

Once the contract is fixed, choose the processing mode that fits the legacy function.

Choose Synchronous, Asynchronous or Batch Processing

Use the wrapper’s latency profile to decide whether an operation should return immediately, queue a job or run in batch.

Interface Suitable use Latency pattern Operational trade-off
Synchronous request Customer-account lookup Immediate response within a bounded timeout Holds connections and depends on legacy availability
Asynchronous job Longer service-request processing Acknowledgement followed by later completion Requires durable job status and duplicate handling
Batch interface Scheduled reconciliation Delayed until the scheduled run completes Efficient grouping but unsuitable for immediate answers

Measure actual latency, error rates and throughput against the legacy application before setting timeouts. For asynchronous work, return 202 Accepted, a job ID and a status endpoint backed by durable storage. Acceptance does not mean completion.

Write contracts need an approval reference bound to the exact payload and a durable idempotency key. Retrying with the same key must not create another request. Keep the states accepted, completed, rejected and outcome_uncertain separate. Reconcile uncertain writes using their key or business reference rather than retrying blindly.

Keep the tool schema as narrow as the chosen interface allows.

Define Narrow Tools and Validate Tool Calls

Describe get_customer_account as a read-only lookup for a trusted customer context. Require customer_id as its only argument. Return only account status, product type, currency and last-updated time. additionalProperties: false blocks undeclared arguments; it does not grant permission.

The model proposes the call. The application validates it. The wrapper executes only the approved legacy action.

{
  "type": "object",
  "properties": {
    "customer_id": {
      "type": "string",
      "description": "Exact customer identifier from trusted application context; never guess.",
      "minLength": 1,
      "maxLength": 32
    }
  },
  "required": ["customer_id"],
  "additionalProperties": false
}

Gate execution with checks at each step. Application code validates the tool name, JSON arguments and documented identifier format, then checks the user’s access and rate limits. The wrapper authenticates, translates the request and invokes the permitted legacy function. The application returns a validated structured result or a controlled error. Keep credentials, approval decisions and unrestricted network access outside the model.

Before enabling execution, test both contracts against sanitised legacy responses. Cover valid accounts, missing records, missing optional fields, malformed dates, unknown status codes, permission failures, timeouts and large result sets. Confirm that invalid calls never reach the backend and that correlation IDs survive every step.

Build the Account Lookup and Service Request Workflow

Build this example against a hypothetical legacy test system. The wrapper must authorise requests, translate fields, log activity and return controlled results. Read first. Write only with approval.

Configure the base URL, timeout, retry limit, audit log and credentials through environment variables and a secret manager. Agree field mappings and allowed status values before coding. Apply that contract to the read path first, then to the approved write path.

Build and Verify the Account Lookup

Expose the lookup route under /v1 and register get_customer_account. Authorise access using the validated application token - not tool arguments.

Map customer_id to CustomerNumber, and translate AccountStatus=OPEN to account_status=active. Treat unknown codes as validation errors. Check that an authorised lookup returns the mapped fields and that access to another account is denied before any legacy call.

Tool: get_customer_account
Arguments: {"customer_id":"CUST-10482"}

Wrapper route: GET /customer-accounts/{customer_id}
Request: GET /v1/customer-accounts/CUST-10482

Legacy request:  CustomerNumber=CUST-10482
Legacy response: AccountStatus=OPEN

{"customer_id":"CUST-10482","account_status":"active",
 "correlation_id":"corr-7f21"}

Keep addresses, payment details and account history out of this response.

Once the read path passes these checks, reuse the same wrapper controls for the write flow.

Submit a Service Request With Approval

Register submit_service_request with four required fields: customer_id, request_type, details and idempotency_key. Block extra fields and accept only address_change or statement_copy as the request type.

Limit details to 500 characters and the key to 100 characters. The application should generate or validate the key. At submission, recheck account access and write permission.

Tool: submit_service_request
Arguments and POST /v1/service-requests body:
{"customer_id":"CUST-10482","request_type":"statement_copy",
 "details":"Provide a statement copy","idempotency_key":"req-7f3c"}

Wrapper route: POST /service-requests

Field mappings:
customer_id     → CustomerNumber
request_type    → ServiceCode, through an agreed code map
details         → RequestText
idempotency_key → ClientReference

Confirm that the resulting legacy record contains these approved values.

Store the approver, expiry and hashes of the requester, tool, customer and normalised payload in application-controlled storage. Check and consume approval atomically when reserving the operation. Changed details require new approval.

Persist the idempotency key and hash before dispatch, then attach the legacy reference when it becomes available. Verify that an identical repeat returns the stored result with only one legacy submission. Changed content sent under the same key must return 409. Use a separate business-duplicate check based on customer, service type and time window.

Use the same correlation and approval records to trace failures in the next section.

Handle Errors and Uncertain Writes

Test malformed identifiers, unavailable services and malformed legacy responses in both paths. Return safe messages and correlation IDs. For transient read failures, configure a finite retry limit with exponential back-off.

For writes, simulate an immediate timeout and a lost response after commit. Mark the operation outcome_uncertain, then reconcile using ClientReference before considering resubmission. Test rejection and partial completion too.

If reconciliation cannot establish the result, suspend automatic retries. Pass the correlation ID and idempotency key to the legacy support team, record the final disposition and notify the user without exposing account details.

Secure, Test and Roll Out the Integration

Protect Credentials, Data and Approvals

Once you’ve defined the workflow, secure credentials, approvals and logging before the pilot. The wrapper, not the model, controls credentials, approvals and permissions. Use separate, least-privilege service accounts for each environment and workflow. Store credentials in a secrets service, favour short-lived credentials and limit network access to required connections over TLS. Keep the wrapper separate from unrelated systems and, where possible, bind calls to the requesting user’s identity.[4][5] Treat external tool descriptions and legacy responses as untrusted data. They must not change application-controlled tools, permissions or approvals.[3][4]

Where UK GDPR applies, document the processing purpose, lawful basis, data flows and retention schedule. Send only the personal data the model needs. Audit records should include the authenticated principal, tool, validated arguments, approval decision, outcome, error category and correlation ID. Mask secrets and sensitive fields, restrict log access and name the people responsible for reviews and incident escalation.[6][7][9]

Test Behaviour and Measure Results

With access controls in place, test how the wrapper handles misuse, failures and prompt injection. Run contract, tool-schema, integration, security and agent-scenario tests. Cover incorrect tool selection, refusal, cross-account access, approval bypass, duplicate submissions and prompt injection in legacy responses. Repeat regression tests when prompts, models, tools, policies or memory change, not just when wrapper code changes.[3][4]

During the pilot, measure manual handling time, completion rate and cost per completed request. Compare equivalent cases, and report costs in pounds sterling only when you’ve measured them. Monitor p50 and p95 latency, timeouts, error categories, retries, write anomalies and legacy CPU or queue pressure. Set rate limits, concurrency caps and circuit breakers within the capacity agreed with the legacy owner. Name the teams responsible for responding to alerts.

Check Readiness and Test Rollback

Once tests pass, begin a limited pilot with manual oversight. Start with a small, monitored read-only cohort for a defined observation period before enabling any writes.[8] Expand only when access checks, latency and capacity meet the agreed thresholds.

Before enabling one approved write operation, confirm that contracts are stable, validation is strict and approvals are bound to the operation. Check idempotency, complete audit records, negative-test coverage and documented recovery procedures. Review every write during the pilot.

Rehearse disabling tool execution and restoring the manual workflow, including queue ownership and customer communications. If the pilot exposes a failure, stop tool execution and switch to the manual process. Rollback stops deployment, not completed transactions; cancellation or reversal needs a separate authorised, audited action.[5]

Conclusion: Start With a Verified, Read-Only Pilot

Keep the model advisory. The wrapper validates inputs, controls credentials and decides whether an action runs.[3]

Use get_customer_account for the pilot. Check its results against source records, set acceptance criteria, and assign one owner, one user group and one documented fallback. Enable writes only when the read-only workflow meets those criteria.

Once the read-only pilot is stable, Hokstad Consulting can help with AI strategy and custom agent implementation for legacy integrations.

FAQs

Can I wrap a legacy system that has no API?

Yes. With the Strangler Pattern, you can build an API layer or middleware around a legacy application without changing the underlying system.

This wrapper gives AI agents a single entry point and handles protocol translation, security and traffic management. It exposes selected legacy functions as tools, with schema contracts setting out the authorised, read-only operations agents can perform.

How can I prevent duplicates if my legacy system lacks idempotency?

Track requests at the application level. Generate a unique idempotency key for each operation and store it alongside the actor, a hash of the arguments and the execution status.

Check the external status before retrying any state-changing operation that times out or fails. Use a business reference or operation ID to confirm what happened. Resolve uncertain outcomes first. If that isn’t possible, quarantine the task for human review rather than retrying it.

Test repeated requests with the same key to confirm that retries don’t create duplicate resources.

How do I detect legacy changes that could break my wrapper?

Treat each tool wrapper as a versioned contract. Store immutable snapshots of tool definitions, validators, adapters/transforms and backend contracts, along with schema versions/hashes. Compare every change with the production baseline to spot request and response drift.

When a call fails, replay a sanitised request in an isolated staging environment. Validate each boundary to find the first mismatch. Block incompatible deployments, then add regression tests and consumer-driven contract tests to stop the same drift recurring. [1][2]

Need help with your DevOps, cloud or AI plans?

Hokstad Consulting helps companies with DevOps transformation, cloud architecture and hands-on AI development — pragmatic consulting with measurable results.

Our services: DevOps on Retainer · Hosting & Cloud · AI Development & Strategy