Articles

Reverse engineering an undocumented API with mitmproxy and an AI agent

Capture an API's traffic with mitmproxy, filter and replay flows, have an AI agent infer the schema from real requests, and turn the captures into an OpenAPI spec and a typed client. Only for APIs you're authorized to inspect.

· 7 min read

An old-master oil painting of a hand holding a letter with a broken red wax seal over a candle, its edge catching fire.

Plenty of APIs have no documentation worth the name: your company's legacy backend, the internal service the original team never wrote up, the API behind a device you own, the backend of an app you've been engaged to test. Reverse engineering one means watching real traffic, working out the endpoints and payloads, and writing it all down as something you can code against. The watching is a proxy's job. The working out and writing down is where an AI agent saves the most time — it's good at reading a hundred JSON bodies and producing the schema they share.

Authorization comes first, and it's specific here. Capture and replay traffic only for APIs you own, operate, have written permission to test, or that a bug-bounty program puts in scope. Replaying requests against someone else's production API, scraping past its terms, or using captured tokens that aren't yours is not reverse engineering, whatever tool does it. Use your own accounts and test data, and keep captures private — they hold credentials.

From captured traffic to a typed clientCapture the client's traffic with mitmproxy, using your own account. Filter the flows down to the API's host. Replay a few to learn which headers and parameters matter. Have the agent infer the schema from the real requests and responses. Turn that into an OpenAPI spec, check it against fresh traffic, and generate a typed client from it.Capture with mitmproxyyour own accountFilter tothe API's hostReplay to learnwhat mattersThe agentinfers the schemaAn OpenAPI spec,checked on new trafficA typed client
From captured traffic to a typed client

Step 1: capture with mitmproxy

mitmproxy is an intercepting HTTP(S) proxy with three faces: mitmproxy (an interactive terminal UI), mitmweb (the same in a browser) and mitmdump (headless, for scripts). For an agent, mitmdump writing to a file is the useful one:

mitmdump -w flows.mitm

It listens on 127.0.0.1:8080. Point the client at it:

  • A CLI tool or script: most honour the proxy environment variables, e.g. HTTPS_PROXY=http://127.0.0.1:8080.
  • A browser: set the proxy in the browser or the OS, or run a separate browser profile for it.
  • A device you own: set the Wi-Fi proxy to your machine's address and port 8080.

To read HTTPS, the client has to trust mitmproxy's certificate authority, which it generates on first run in ~/.mitmproxy/. Visit http://mitm.it through the proxy for install instructions per platform, or pass the CA file directly where a tool allows it (curl --cacert ~/.mitmproxy/mitmproxy-ca-cert.pem). Install that CA only on machines and profiles you use for testing, and remove it when you're done: anyone holding its key can intercept that device's traffic.

If you control the client's configuration and just need to sit in front of one backend, reverse-proxy mode is simpler — the client talks to mitmproxy as if it were the server:

mitmdump --mode reverse:https://api.example.internal -w flows.mitm

Then exercise the client deliberately. Log in, do each action once, and note what you did and when — a list like "12:04 created an order, 12:05 cancelled it" turns a pile of flows into labelled examples. That list is the single most useful thing you can give the agent.

Step 2: filter and inspect

A capture is noisy: analytics, fonts, CDNs, telemetry. Keep only the API with mitmproxy's filter expressions — ~d matches a domain, ~m a method, ~u a URL regex — and write the result to a new file:

mitmdump -nr flows.mitm --set save_stream_filter='~d api.example.internal' -w api.mitm

-r reads a saved capture and -n stops mitmproxy from starting a proxy server. To browse what's left by hand, open it in the UI with mitmproxy -r api.mitm (or mitmweb -r api.mitm); in the flow view you can export a single request as a curl command, which is the quickest way to hand one exact request to the agent.

For the agent, a plain-text dump is easier than the binary capture format. A short mitmproxy addon writes one JSON object per flow:

# dump_jsonl.py — mitmdump -nr api.mitm -s dump_jsonl.py
import json
from mitmproxy import http

out = open("api.jsonl", "w")

def response(flow: http.HTTPFlow) -> None:
    req, res = flow.request, flow.response
    out.write(json.dumps({
        "method": req.method,
        "url": req.pretty_url,
        "req_headers": dict(req.headers),
        "req_body": req.get_text(strict=False),
        "status": res.status_code,
        "res_headers": dict(res.headers),
        "res_body": res.get_text(strict=False),
    }) + "\n")

Before the agent reads it, redact secrets — session cookies, bearer tokens, API keys — or replace them with placeholders. The model doesn't need your real token to infer a schema, and transcripts and logs outlive the session.

Step 3: replay to learn what matters

Captured requests carry far more than the server needs: browser headers, tracking parameters, cache-busters. Replay is how you find the minimum. mitmproxy can replay a whole capture (mitmdump -C api.mitm sends its requests again), but for learning, single requests are clearer — have the agent turn one flow into a curl command or a small script, then strip headers and parameters one at a time:

Replaying one request to find what the server needsTake one captured request and replay it unchanged to confirm it still works. Remove one header or parameter and replay again. If the response is unchanged, it wasn't needed, so leave it out. If the response changes, it matters, so record what it does. Repeat until only the parts that matter are left, against your own account at a gentle rate.NoYesOne captured request,replayed unchangedRemove one headeror parameterResponsechanged?Not needed,leave it outIt matters:record what it does
Replaying one request to find what the server needs

This is where you learn how authentication works (a cookie, a bearer token, a signed header with a timestamp), which IDs are yours, and which parameters change the response. Keep the rate gentle, use your own account and your own records, and don't replay requests that change state — payments, deletes, messages to other people — unless you're on a test environment where that's expected.

If a request carries a signature you can't reproduce — a header that's clearly a hash over the body and a timestamp — the signing code is in the client. That's a reversing job on the client itself: the JavaScript deobfuscation guide for a web app, the Ghidra/IDA guide for a native one.

Step 4: have the agent infer the schema

Now give the agent the redacted api.jsonl and your list of actions:

api.jsonl is redacted traffic from our internal orders service, which I'm authorized to document. actions.txt says what I did when. Group the requests by endpoint, treating IDs in paths as parameters (/orders/{orderId}). For each endpoint, give the method, path parameters, query parameters, request body schema and response schema, with types inferred from every example you have, not just the first. Mark fields that are sometimes missing or null as optional, and list anything you're unsure of.

The agent is good at this because it's tedious pattern work across many examples: noticing that status is always one of four strings (an enum), that price is sometimes an integer and sometimes a string (worth a note), that /orders/8812 and /orders/9034 are the same route. The things to check:

  • Coverage. A schema inferred from three examples is a guess about the fourth. Exercise each action more than once, with different inputs, before trusting optional/required calls.
  • Types from one example. "count": 0 looks like an integer until a capture shows 0.5. Have the agent cite how many examples each type is based on.
  • Invented endpoints. The model should describe only routes that appear in the capture. Ask it to cite the flow for each.

There are also tools for a first draft. mitmproxy2swagger reads a capture and writes an OpenAPI skeleton for one API prefix:

mitmproxy2swagger -i api.mitm -o spec.yml -p https://api.example.internal

Its README explains the two-pass workflow (it first lists the paths it found for you to keep or ignore, then fills in the schemas). A good split: let mitmproxy2swagger draft the structure, then have the agent refine types, enums, descriptions and optional fields from the JSONL.

Step 5: from schema to a typed client

Once the spec is right, the client is generated, not written. For TypeScript, openapi-typescript turns the spec into types:

bunx openapi-typescript spec.yml -o api.d.ts

Pair it with a small fetch wrapper (openapi-fetch, from the same project, is built for this), or have the agent write a thin client over fetch that uses those types. For Python, an OpenAPI generator or a set of pydantic models the agent writes from the spec works the same way.

Then close the loop: capture fresh traffic, run it through the same JSONL dump, and have the agent validate every response against the spec. Mismatches are either spec bugs or behaviour you haven't seen yet. Both are worth knowing, and a validation step catches the API changing under you later.

Which AI to use

The model doesn't need anything security-specific for most of this — schema inference from JSON is ordinary work, and any capable agent with a shell does it well. What helps is a long context (captures are big) and an agent that runs the tools itself rather than asking you to paste output. Mainstream assistants occasionally balk at "replay this captured request" or anything near authentication, even on your own service; this guide covers getting legitimate work through.

caveira has one thing built for this workflow: its optional Docker box runs a headless Chromium behind mitmproxy, and the agent's browser tool drives it — navigating, clicking, filling forms, listing the requests it captured, showing one in full, and replaying it with a new method, URL, headers or body. For a web client, that means the agent can exercise the app and read the traffic itself, inside a container rather than your own browser. For practice, point it at the /lab start targets (Juice Shop, DVWA, WebGoat), which exist to be poked at. For anything real, the same rule holds as everywhere in this guide: only APIs you're authorized to inspect, your own accounts, and a gentle rate.