Logo di API Agent

API Agent

Organizzazione
agoda-com

Universal MCP server for GraphQL/REST APIs

Autoreagoda-com
Repositoryapi-agent
LinguaPython
Fork
43
Stelle
291
Strumenti disponibili
0
Tipo di trasportostdio, streamable-http
Categorie
LicenzaMIT
Link
  • Collega gli strumenti ai flussi di lavoro IA

    API Agent mette a disposizione funzionalità MCP utilizzabili da client e agenti IA compatibili.

  • 0 strumenti disponibili

    Esplora le azioni richiamabili qui sotto, con nomi e descrizioni quando forniti dal server.

  • Configurazione pronta da copiare

    Usa gli esempi di installazione per configurare questo server nel tuo client MCP preferito.

  • Indicatori di interesse open source

    291 stelle e 43 fork nel repository collegato.

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.

Installazione

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

Usa MCP API Agent con più modelli IA

TypingMind collega gli strumenti MCP a livello di area di lavoro: una volta connesso API Agent, puoi usarlo con diversi modelli IA in TypingMind, senza configurarlo separatamente per ogni modello. Puoi eseguire MCP localmente sul tuo dispositivo o connetterti all'URL di un server MCP remoto.

Opzione 1: usa il connettore locale

Usa questo metodo quando il server MCP deve accedere a file locali, app o risorse private sul tuo computer.

1

Apri le impostazioni MCP

In TypingMind, vai su Impostazioni, Impostazioni avanzate, poi su Model Context Protocol e scegli Configura MCP.

  1. Apri TypingMind nel tuo browser.
  2. Fai clic sull'icona Impostazioni.
  3. Vai a Impostazioni avanzate.
  4. Apri la sezione Model Context Protocol.
  5. Fai clic su Configura MCP e scegli Questo dispositivo.
Schermata di configurazione del connettore MCP di TypingMind con Questo dispositivo selezionato
2

Esegui il comando del connettore

Scegli Questo dispositivo, copia il comando da TypingMind ed eseguilo nel terminale. Lascia il processo in esecuzione mentre usi MCP.

  1. Copia il comando di configurazione mostrato da TypingMind.
  2. Apri Terminale su macOS o Windows Terminal su Windows.
  3. Incolla ed esegui il comando.
  4. Conferma l'installazione del pacchetto se il terminale ti chiede di procedere.
  5. Tieni aperta la finestra del terminale con il processo in esecuzione mentre usi gli strumenti MCP.
3

Aggiungi API Agent come server

Quando lo stato del connettore è Pronto, fai clic su Modifica server e incolla la configurazione del server MCP.

  1. Attendi che lo stato del connettore sia Pronto.
  2. Fai clic su Modifica server.
  3. Incolla la configurazione del server MCP di API Agent.
  4. Salva l'elenco dei server.
  5. Aggiorna per verificare che il connettore sia ancora pronto.
Impostazioni MCP di TypingMind con un server attivo e il pulsante Modifica server
{
  "mcpServers": {
    "api-agent": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Usa la connessione con diversi modelli

Salva l'elenco dei server, apri Plugin, abilita gli strumenti MCP di API Agent, poi seleziona un modello IA supportato in TypingMind e usa gli strumenti in chat o assegnali a un agente IA.

  1. Apri la pagina Plugin in TypingMind.
  2. Abilita gli strumenti MCP di API Agent.
  3. Avvia una chat e scegli il modello IA che vuoi usare.
  4. Usa gli strumenti MCP in chat o assegnali a un agente IA.
  5. Passa a un altro modello IA quando serve, senza riconnettere MCP.
Chat di TypingMind che usa gli strumenti MCP abilitati con un modello IA selezionato
Puoi usare API Agent per aiutarmi con questa attività?
API Agent
Certo. Ho letto.
Ecco cosa ho trovato con API Agent.

Opzione 2: aggiungi l'URL di un server MCP

Usa questo metodo se API Agent è già ospitato in remoto o se il tuo team vuole un unico connettore condiviso accessibile a più utenti.

1

Apri Connettori MCP

In TypingMind, vai su Plugin, apri Connettori MCP e scegli Aggiungi URL.

  1. Apri TypingMind nel tuo browser.
  2. Vai a Plugin.
  3. Apri Connettori MCP.
  4. Fai clic su Aggiungi URL.
Modulo di TypingMind per aggiungere l'URL di un server MCP personalizzato
2

Incolla l'URL del server

Inserisci l'URL del server MCP fornito dal provider nel campo URL del server. Aggiungi un nome per la connessione, una descrizione, un'icona, header HTTP personalizzati o le impostazioni del client OAuth se richiesti dal server.

  1. Incolla l'URL del server MCP fornito dal provider nel campo URL del server.
  2. Inserisci un nome per la connessione a API Agent.
  3. Aggiungi una descrizione e un'icona per riconoscere più facilmente la connessione.
  4. Aggiungi header HTTP personalizzati o i dati del client OAuth se il server richiede l'autenticazione.
3

Crea la connessione

Fai clic su Crea connessione, poi torna all'elenco dei plugin e verifica che la nuova connessione MCP sia attiva.

  1. Fai clic su Crea connessione.
  2. Torna all'elenco dei connettori MCP.
  3. Verifica che la connessione API Agent risulti attiva.
  4. Aggiorna l'elenco dei plugin se la connessione non appare subito.
4

Cambia modello senza riconnetterti

Avvia una chat con il tuo modello preferito, abilita gli strumenti di API Agent dalla sezione Plugin e passa a un altro modello quando serve. La connessione MCP rimane disponibile nell'area di lavoro di TypingMind.

  1. Avvia una nuova chat in TypingMind.
  2. Seleziona il modello IA che vuoi usare.
  3. Abilita gli strumenti di API Agent dalla sezione Plugin.
  4. Chiedi al modello di usare lo strumento quando serve.
  5. Passa a un altro modello IA e riutilizza la stessa connessione MCP.
Chat di TypingMind che usa gli strumenti MCP abilitati con un modello IA selezionato
Puoi usare API Agent per aiutarmi con questa attività?
API Agent
Certo. Ho letto.
Ecco cosa ho trovato con API Agent.

Domande frequenti

A cosa serve il server MCP API Agent?

API Agent è un server MCP che consente ai client IA compatibili di accedere a strumenti e informazioni di contesto esterni. In TypingMind puoi aggiungere questo server MCP una sola volta e rendere disponibili i suoi strumenti nella tua area di lavoro IA.

Posso usare API Agent MCP con più modelli IA in TypingMind?

Sì. TypingMind collega gli strumenti MCP a livello di area di lavoro, quindi puoi usare API Agent con diversi modelli IA come Claude, ChatGPT, Gemini o altri modelli che hai configurato in TypingMind, senza dover configurare il server MCP separatamente per ogni modello.

Perché usare il connettore MCP API Agent con TypingMind?

TypingMind è una delle migliori interfacce per chattare con gli LLM perché riunisce più modelli IA, prompt, plugin, agenti IA, chiavi API e strumenti MCP in un'unica area di lavoro. Collegando API Agent, puoi usare i suoi strumenti MCP con i tuoi modelli preferiti e mantenere organizzato il tuo flusso di lavoro in chat su TypingMind.

Come collego API Agent MCP a TypingMind?

Puoi collegare API Agent a TypingMind con il connettore MCP locale oppure aggiungendo l'URL di un server MCP remoto. Usa il connettore locale quando il server deve accedere a file, app o risorse private sul tuo dispositivo; usa invece l'URL del server quando il server MCP è ospitato in remoto.

Quali strumenti offre API Agent MCP in TypingMind?

API Agent mette a disposizione funzionalità MCP che puoi attivare dalla pagina Plugin di TypingMind e usare in chat o assegnare agli agenti IA.

Devo condividere le mie chiavi API con TypingMind per usare API Agent MCP?

No. TypingMind privilegia il funzionamento in locale e ti permette di mantenere il controllo su fornitori di modelli, chiavi API, prompt e configurazione MCP. Se API Agent richiede l'autenticazione, aggiungi le intestazioni, le impostazioni OAuth o la configurazione locale necessarie per quel server MCP quando crei la connessione.

Server MCP correlati

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇