Logo vun API Agent

API Agent

Organisatioun
agoda-com

Universal MCP server for GraphQL/REST APIs

Editeuragoda-com
Repositoryapi-agent
SproochPython
Forks
43
Stären
291
Disponibel Tools
0
Transporttypstdio, streamable-http
Kategorien
LizenzMIT
Linken
  • Tools mat KI-Workflows verbannen

    API Agent stellt MCP-Funktioune bereit, déi vu kompatibele KI-Clienten a KI-Agente kënne benotzt ginn.

  • 0 disponibel Tools

    Kuckt Iech déi opruffbar Aktiounen hei drënner un, mat Nimm a Beschreiwungen, wa se vum Server geliwwert ginn.

  • Konfiguratioun fir ze kopéieren

    Benotzt d'Installatiounsbeispiller, fir dëse Server an Ärem bevorzugte MCP-Client ze konfiguréieren.

  • Indicateure fir Open Source

    291 Stären an 43 Forks aus dem verlinkte Repository.

API Agent

Turn any API into an MCP server. Query in English. Get results even when the API can't.

Point at any GraphQL or REST API. Ask questions in natural language. The agent fetches data, stores it in DuckDB, and runs SQL post-processing. Rankings, filters, and joins over returned data work even if the API doesn't support them.

What Makes It Different

🎯 Zero config. No custom MCP code per API. Point at a GraphQL endpoint, OpenAPI 3.x spec, or Swagger 2.0 spec. The agent introspects/loads schema automatically.

✨ SQL post-processing. API returns 10,000 unsorted rows? Agent ranks top 10. No GROUP BY? Agent aggregates. Need to join returned tables? Agent combines. The API doesn't need to support it—the agent does.

🔒 Safe by default. Read-only. Mutations blocked unless explicitly allowed.

🧠 Recipe learning. Agent samples successful queries into reusable workflows. Ask once, reuse cached pipelines that execute without LLM reasoning. Learned recipes are exposed as tools named r_<tool_name>.

Quick Start

1. Run:

bash
# Direct run (no clone needed)
OPENAI_API_KEY=your_key uvx --from git+https://github.com/agoda-com/api-agent api-agent

# Or clone
git clone https://github.com/agoda-com/api-agent.git && cd api-agent
uv sync --group dev

Set the OpenAI secret in env:

bash
export OPENAI_API_KEY=your_key

Direct uvx runs use built-in defaults unless API_AGENT_CONFIG points to a TOML file. A cloned checkout uses api-agent.toml from the repository root by default.

2. Start local clone:

bash
uv run api-agent

# Or Docker
docker build -t api-agent .
docker run -p 3000:3000 -e OPENAI_API_KEY=your_key api-agent

3. Add to any MCP client:

json
{
  "mcpServers": {
    "rickandmorty": {
      "url": "http://localhost:3000/mcp",
      "headers": {
        "X-Target-URL": "https://rickandmortyapi.com/graphql",
        "X-API-Type": "graphql"
      }
    }
  }
}

4. Ask questions:

  • "Show characters from Earth, only alive ones, group by species"
  • "Top 10 characters by episode count"
  • "Compare alive vs dead by species, only species with 10+ characters"

That's it. Agent introspects schema, generates calls, runs SQL post-processing.

More Examples

REST API (Petstore):

json
{
  "mcpServers": {
    "petstore": {
      "url": "http://localhost:3000/mcp",
      "headers": {
        "X-Target-URL": "https://petstore3.swagger.io/api/v3/openapi.json",
        "X-API-Type": "rest"
      }
    }
  }
}

Your own API with auth:

json
{
  "mcpServers": {
    "myapi": {
      "url": "http://localhost:3000/mcp",
      "headers": {
        "X-Target-URL": "https://api.example.com/graphql",
        "X-API-Type": "graphql",
        "X-Target-Headers": "{\"Authorization\": \"Bearer YOUR_TOKEN\"}"
      }
    }
  }
}

Reference

Headers

HeaderRequiredDescription
X-Target-URLYesGraphQL endpoint OR OpenAPI/Swagger spec URL
X-API-TypeYesgraphql or rest
X-Target-HeadersNoJSON auth headers, e.g. {"Authorization": "Bearer xxx"}
X-Passthrough-HeadersNoJSON array of header names to copy from this MCP request onto outbound API calls (merged after X-Target-Headers)
X-API-NameNoOverride tool name prefix (default: auto-generated)
X-Base-URLNoOverride base URL for REST API calls
X-Allow-Unsafe-PathsNoJSON array of glob patterns for POST/PUT/DELETE/PATCH
X-Poll-PathsNoJSON array of REST paths requiring polling
X-Include-ResultNoTruthy values include full result in wrapped output
X-Recipe-Learn-RateNoOverride recipe sample rate for this request, 0 to 1
X-DebugNoTruthy values include debug metadata with calls and trace id when available

X-Passthrough-Headers is a JSON array of header names, for example ["Authorization", "X-Request-Id"]. For each name that appears on the MCP request (matching is case-insensitive), the value is copied into the headers sent to the target API. Use this when the client already sends auth or tracing headers on the MCP connection and you want those same values forwarded without duplicating them in X-Target-Headers. Entries missing from the request are skipped.

Truthy header values are true, 1, and yes (case-insensitive). X-Recipe-Learn-Rate: 1 always samples successful queries for recipe extraction; 0 disables learning for the request. Invalid optional JSON headers are ignored and default to empty values.

MCP Tools

Core tool (prefix auto-generated from URL or X-API-Name):

ToolInputOutput
{prefix}_queryNatural language question + optional return_directly{ok, data, error, result?} or CSV

X-API-Name preserves hyphens in the prefix; the tool suffix separator remains _ (for example, weather-alerts exposes weather-alerts_query).

If a tool call used return_directly, the MCP response is raw CSV instead of the wrapper. Otherwise data contains the agent summary and result contains retrieved rows when available.

Set X-Debug: true to force wrapped JSON and include a debug object:

json
{
  "ok": true,
  "data": "...",
  "debug": {
    "api_calls": [{"method": "GET", "path": "/users/{id}", "success": true}],
    "trace_id": "62ee6f56fc839a7291d09935a0974727"
  },
  "error": null
}

For GraphQL debug responses, calls are returned under debug.queries. For REST debug responses, calls are returned under debug.api_calls.

debug.trace_id is included only when OTEL tracing is enabled and a trace is active.

Recipe tools (dynamically added as the agent learns):

ToolInputOutput
r_{slug}Intent argsCSV
  • Slug derived from LLM-suggested recipe name, max 49 chars total including r_.
  • All declared tool args are required top-level fields.
  • Recipe tools always return directly as CSV.

Schema tools (agent-internal):

During query planning, agents also have search_schema(pattern, context?, before?, after?, offset?) for grep-like regex search over raw GraphQL introspection or OpenAPI JSON. This is used when compact schema context is truncated.

Configuration

App configuration lives in api-agent.toml. Environment variables do not override app settings except listed overrides. API_AGENT_CONFIG selects a TOML file path; Docker defaults it to /app/api-agent.toml. A cloned checkout reads api-agent.toml by default. Direct installed runs, including uvx, use built-in defaults unless API_AGENT_CONFIG points to a TOML file. OPENAI_API_KEY is env-only; OPENAI_BASE_URL and PORT can be set in TOML and overridden by env.

TOML keyDefaultNotes
[mcp].nameAPI AgentMCP display name
[server].host0.0.0.0bind host
[server].port3000bind port; env PORT may override
[server].transportstreamable-httphttp, streamable-http, or sse
[server].stateless_httptruestateless MCP HTTP mode
[server].cors_allowed_origins*comma-separated origins
[server].debugfalsedebug logging
[model].apiresponsesresponses or chat_completions
[model].namegpt-5.5model name
[model].openai_base_urlhttps://api.openai.com/v1env OPENAI_BASE_URL may override
[model].reasoning_effortlowmodel reasoning effort
[description].model_namegpt-5.4-minioptional tool description model; empty uses [model].name
[description].timeout_seconds15tool description generation timeout
[agent].max_turns30max agent turns per query
[agent].max_response_chars50000max final response chars
[agent].max_schema_chars32000compact schema cap
[agent].max_preview_rows10result preview rows
[agent].max_tool_response_chars32000tool response context cap
[polling].max_polls20max REST poll attempts
[polling].default_delay_ms3000default REST poll delay
[polling].max_delay_ms3000max REST poll delay
[recipes].enabledtrueenable learned recipes
[recipes].max_size1000max stored recipes
[recipes].learn_rate0.2deterministic sample rate
[storage].backendmemorymemory or redis
[storage].namespaceapi-agentRedis key namespace
[redis].urlemptyrequired only for Redis storage

Docker copies this TOML to /app/api-agent.toml, and start.sh sets API_AGENT_CONFIG=/app/api-agent.toml by default. Keep app settings in TOML, set OPENAI_API_KEY in env, and leave proxy/OTEL to env.

[storage] backs learned recipes and generated downstream tool descriptions. Generated descriptions are cached by API id and schema hash. If description generation fails or times out, API Agent returns a deterministic fallback and caches that fallback for 5 minutes before retrying generation.


How It Works

Architecture

Stack: FastMCP • OpenAI Agents SDK • DuckDB

Agents use the OpenAI Responses API model path by default. Set [model].api = "chat_completions" only for models/endpoints that support Chat Completions.

Current target scope: each query runs against one configured API target. Multi-endpoint support should expose multiple named targets, but cross-target joins are intentionally out of scope for now.

REST specs can be JSON or YAML. OpenAPI 3.x is used directly; Swagger 2.0 is normalized into an OpenAPI 3.0-compatible shape. For REST base URLs, the agent uses X-Base-URL first, then servers[0].url, then derives the origin from the spec URL.


REST Polling

Set X-Poll-Paths to enable the poll_until_done agent tool for async REST endpoints:

json
["/jobs", "/search"]

The agent must use poll_until_done for matching paths. It polls until done_field equals done_value, supports dot paths like status or trips.0.isCompleted, waits [polling].default_delay_ms by default, caps waits at [polling].max_delay_ms, stops after [polling].max_polls, and increments body.polling.count when present.


Recipe Learning

Agent samples successful queries into reusable MCP tools. Recipe capture is best-effort after the user-facing query succeeds; recipe extraction/store failures are logged and do not fail the query response.

  1. Captures - Records successful API and SQL tool calls into one ordered steps list.
  2. Samples - Uses X-Recipe-Learn-Rate when present, otherwise [recipes].learn_rate.
  3. Extracts - Structured extractor proposes a public MCP tool contract plus private optimized execution plan.
  4. Validates - Runs the candidate once with fixture tool args and compares final rows to the original result. Extractor prompts receive bounded result samples; deterministic replay keeps the full local result.
  5. Caches - Stores by API id + schema hash with fingerprint deduplication.
  6. Reuses - Similar {prefix}_query requests get recipe tools injected for the agent to choose.
  7. Exposes - Learned recipes are also published as direct MCP tools named r_<tool_name>.

Recipe structure:

  • public_contract contains MCP tool_name, description, and public tool_args.
  • execution_plan.steps is a dataflow graph. Each step has id, kind, input, and output.name.
  • input.mode="single" uses public args via input.with; map and batch read one prior rowset via input.from + input.bind.
  • Multiple dependencies must first be joined by SQL into one ordered binding rowset; there is no implicit Cartesian product.
  • GraphQL: call.query_template with {{param}} placeholders.
  • REST: call.path_params, call.query_params, call.body with {"$var": "name"} refs. List query params are encoded as repeated keys.
  • SQL: query_template inside the same ordered steps list.

Mapped REST dependency shape:

json
{
  "id": "key_results",
  "kind": "rest",
  "input": {
    "mode": "map",
    "from": "filtered_objectives",
    "bind": {"objective_id": "id"},
    "with": {}
  },
  "call": {
    "method": "GET",
    "path": "/objectives/{objective_id}/key-results",
    "path_params": {"objective_id": {"$var": "objective_id"}}
  },
  "output": {
    "name": "key_results",
    "attach_binding": ["objective_id"]
  }
}

input.from must name one prior output.name. For two upstream datasets, add a SQL step that joins them into one rowset first, then map from that SQL output.

Recipe tools:

  • Each cached recipe is surfaced as an MCP tool named r_{slug} (slugified from LLM-suggested name, max 49 chars).
  • Recipe names use concise snake_case action-resource slugs. Descriptions are outcome-focused and do not inject API labels or implementation step counts.
  • If multiple recipes share the same slug, the most recently used one is exposed.
  • Tool args are flat top-level fields (not nested under params), all required, and must be user-intent inputs.
  • Clients call these tools directly — no LLM reasoning, just cached API+SQL pipeline.

For normal {prefix}_query calls, recipe reuse is still agent-mediated: matching recipes are exposed as tools and prompt hints, then the agent decides whether to call one. If the agent uses a recipe tool, that run is not learned again, and the recipe tool returns directly by default. Direct r_{slug} calls bypass the agent entirely and always return directly as CSV.

Recipes are hidden when schema changes (hash mismatch). Storage is memory by default or Redis when configured. Recipe eviction is FIFO by recipes.max_size; recipes have no TTL.


Development

bash
git clone https://github.com/agoda-com/api-agent.git
cd api-agent
uv sync --group dev
uv lock --check
uv run ruff check api_agent/ tests/
uv run ruff format --check api_agent/ tests/
uv run ty check
uv run pytest tests/ -q

Agent guidance lives in AGENTS.md. See CONTRIBUTING.md for contribution guidelines and CHANGELOG.md for service history.

Observability

OpenTelemetry tracing is opt-in. For local tracing, run through opentelemetry-instrument and set either:

bash
OTEL_SERVICE_NAME=api-agent OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
  uv run --no-sync opentelemetry-instrument api-agent
# or
OTEL_SERVICE_NAME=api-agent OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces \
  uv run --no-sync opentelemetry-instrument api-agent

start.sh uses opentelemetry-instrument automatically when an OTEL endpoint is configured, so Docker can use the same env vars without changing the entrypoint. API Agent exports OpenAI Agents SDK spans over OTLP HTTP. Works with Jaeger, Grafana Tempo, Arize Phoenix, and other OTLP collectors. When not configured, tracing setup is skipped; queries still run and X-Debug still returns calls, but debug.trace_id is omitted.

Installatioun

TypingMind
{
  "mcpServers": {
    "api-agent": {
      "command": "uv",
      "args": [
        "run",
        "python",
        "-m",
        "api_agent"
      ],
      "env": {
        "OPENAI_API_KEY": "<OPENAI_API_KEY>"
      }
    }
  }
}

API Agent MCP mat verschiddene KI-Modeller benotzen

TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Soubal API Agent verbonnen ass, kënnt Dir et mat verschiddene KI-Modeller an TypingMind benotzen, amplaz et fir all Modell separat anzeriichten. Dir kënnt MCP lokal op Ärem Apparat ausféieren oder Iech mat enger Remote-MCP-Server-URL verbannen.

Optioun 1: De lokale Connector benotzen

Benotzt dës Optioun, wann den MCP-Server Zougrëff op lokal Fichieren, Appen oder privat Ressourcen op Ärem Computer brauch.

1

D'MCP-Astellungen opmaachen

Gitt an TypingMind op „Astellungen“, „Erweidert Astellungen“, dann op „Model Context Protocol“ a wielt „Connector ariichten“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Klickt op d'Astellungssymbol.
  3. Gitt op „Erweidert Astellungen“.
  4. Maacht d'Sektioun „Model Context Protocol“ op.
  5. Klickt op „Connector ariichten“ a wielt „Dësen Apparat“.
Ariichtungsbildschierm vum TypingMind-MCP-Connector mat „Dësen Apparat“ ausgewielt
2

De Connector-Befeel ausféieren

Wielt „Dësen Apparat“, kopéiert de Befeel aus TypingMind a féiert en am Terminal aus. Loosst de Prozess lafen, wärend Dir MCP benotzt.

  1. Kopéiert den Ariichtungsbefeel, deen TypingMind uweist.
  2. Maacht Terminal op macOS oder Windows Terminal op Windows op.
  3. Pescht de Befeel an a féiert en aus.
  4. Bestätegt d'Installatioun vum Package, wann den Terminal Iech freet, ob Dir weiderfuere wëllt.
  5. Loosst den Terminal an de Prozess doranner lafen, wärend Dir MCP-Tools benotzt.
3

API Agent als Server derbäisetzen

Wann de Connector-Status „Prett“ ass, klickt op „Serveren änneren“ a pescht d'MCP-Serverkonfiguratioun an.

  1. Waart, bis de Connector-Status „Prett“ weist.
  2. Klickt op „Serveren änneren“.
  3. Pescht d'MCP-Serverkonfiguratioun vu API Agent an.
  4. Späichert d'Serverlëscht.
  5. Aktualiséiert, wann Dir kontrolléiere wëllt, ob de Connector nach ëmmer prett ass.
MCP-Astellunge vun TypingMind mat aktivem Server an dem Knäppchen „Serveren änneren“
{
  "mcpServers": {
    "api-agent": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

D'Verbindung mat verschiddene Modeller benotzen

Späichert d'Serverlëscht, maacht „Plugins“ op an aktivéiert d'MCP-Tools vu API Agent. Wielt dann e belibegen ënnerstëtzte KI-Modell an TypingMind a benotzt d'Tools am Chat oder weist se engem KI-Agent zou.

  1. Maacht d'Säit „Plugins“ an TypingMind op.
  2. Aktivéiert d'MCP-Tools vu API Agent.
  3. Start e Chat a wielt de KI-Modell, deen Dir benotze wëllt.
  4. Benotzt d'MCP-Tools am Chat oder weist se engem KI-Agent zou.
  5. Wiesselt bei Bedarf op en anere KI-Modell, ouni MCP nei ze verbannen.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat API Agent?
API Agent
Jo. Ech hunn et gelies.
Dat hunn ech mat API Agent fonnt.

Optioun 2: Eng MCP-Server-URL derbäisetzen

Benotzt dës Optioun, wann API Agent scho remote gehost gëtt oder Är Ekipp ee gemeinsame Connector wëllt, op dee méi Benotzer kënnen zougräifen.

1

MCP-Connectoren opmaachen

Gitt an TypingMind op „Plugins“, maacht „MCP-Connectoren“ op a wielt dann „URL derbäisetzen“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Gitt op „Plugins“.
  3. Maacht „MCP-Connectoren“ op.
  4. Klickt op „URL derbäisetzen“.
TypingMind-Formulaire fir eng benotzerdefinéiert MCP-Server-URL derbäizesetzen
2

D'Server-URL apeschen

Gitt d'MCP-Server-URL vum Ubidder am Feld „Server-URL“ an. Setzt e Verbindungsnumm, eng Beschreiwung, e Symbol, benotzerdefinéiert HTTP-Headeren oder OAuth-Clientastellungen derbäi, wann de Server se erfuerdert.

  1. Pescht d'MCP-Server-URL vum Ubidder an d'Feld „Server-URL“.
  2. Gitt en Numm fir d'Verbindung mat API Agent an.
  3. Setzt eng Beschreiwung an e Symbol derbäi, fir d'Verbindung méi einfach erëmzeerkennen.
  4. Setzt benotzerdefinéiert HTTP-Headeren oder OAuth-Clientdetailer derbäi, wann de Server eng Authentifizéierung erfuerdert.
3

D'Verbindung erstellen

Klickt op „Verbindung erstellen“, gitt dann zeréck op d'Plugin-Lëscht a kontrolléiert, ob déi nei MCP-Verbindung aktiv ass.

  1. Klickt op „Verbindung erstellen“.
  2. Gitt zeréck op d'Lëscht vun de MCP-Connectoren.
  3. Kontrolléiert, ob d'Verbindung mat API Agent als aktiv ugewise gëtt.
  4. Aktualiséiert d'Plugin-Lëscht, wann d'Verbindung net direkt ugewise gëtt.
4

Modeller wiesselen ouni nei ze verbannen

Start e Chat mat Ärem bevorzugte Modell, aktivéiert d'Tools vu API Agent ënner „Plugins“ a wiesselt bei Bedarf op en anere Modell. D'MCP-Verbindung bleift am TypingMind-Aarbechtsberäich disponibel.

  1. Start en neie Chat an TypingMind.
  2. Wielt de KI-Modell, deen Dir benotze wëllt.
  3. Aktivéiert d'Tools vu API Agent ënner „Plugins“.
  4. Biet de Modell, den Tool ze benotzen, wann néideg.
  5. Wiesselt op en anere KI-Modell a benotzt déiselwecht MCP-Verbindung weider.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat API Agent?
API Agent
Jo. Ech hunn et gelies.
Dat hunn ech mat API Agent fonnt.

Heefeg gestallte Froen

Fir wat gëtt de MCP-Server API Agent benotzt?

API Agent ass e MCP-Server, deen et kompatibele KI-Clienten erlaabt, sech mat externen Tools a Kontext ze verbannen. An TypingMind kënnt Dir dëse MCP-Server eemol derbäisetzen a seng Tools an Ärem KI-Aarbechtsberäich zur Verfügung stellen.

Kann ech API Agent MCP mat méi KI-Modeller an TypingMind benotzen?

Jo. TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Sou kënnt Dir API Agent mat verschiddene KI-Modeller wéi Claude, ChatGPT, Gemini oder anere Modeller benotzen, déi Dir an TypingMind konfiguréiert hutt, ouni de MCP-Server fir all Modell separat anzeriichten.

Firwat API Agent MCP mat TypingMind benotzen?

TypingMind ass eng vun de beschte Benotzeruewerfläche fir LLM-Chat, well et méi KI-Modeller, Prompts, Plugins, KI-Agenten, API-Schlësselen a MCP-Tools an engem Aarbechtsberäich zesummebréngt. Wann API Agent verbonnen ass, kënnt Dir seng MCP-Tools mat Äre bevorzugte Modeller benotzen a gläichzäiteg Är Chataarbecht an TypingMind organiséieren.

Wéi verbannen ech API Agent MCP mat TypingMind?

Dir kënnt API Agent iwwer de lokale MCP-Connector oder iwwer d'URL vun engem Remote-MCP-Server mat TypingMind verbannen. Benotzt de lokale Connector, wann de Server Zougrëff op Fichieren, Apps oder privat Ressourcen op Ärem Apparat brauch, an eng Server-URL, wann de MCP-Server op Distanz gehost gëtt.

Wéi eng Tools stellt API Agent MCP an TypingMind zur Verfügung?

API Agent stellt MCP-Funktiounen zur Verfügung, déi Dir op der Plugins-Säit vun TypingMind aktivéiere kënnt, fir se am Chat ze benotzen oder KI-Agenten zouzeweisen.

Muss ech meng API-Schlëssele mat TypingMind deelen, fir API Agent MCP ze benotzen?

Nee. TypingMind setzt op lokal Veraarbechtung a léisst Iech d'Kontroll iwwer Är Modellubidder, API-Schlësselen, Prompts a MCP-Konfiguratioun. Wann API Agent eng Authentifizéierung verlaangt, setzt déi néideg Headeren, OAuth-Astellungen oder lokal Konfiguratioun fir dee MCP-Server derbäi, wann Dir d'Verbindung erstallt.

Änlech MCP-Serveren

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇