Skip to content
Back to search

api-agent

Universal MCP server for GraphQL/REST APIs

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/agoda-com--api-agent/badge.svg)](/listings/agoda-com--api-agent)

HTML

<a href="/listings/agoda-com--api-agent"><img src="/api/listings/agoda-com--api-agent/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**1. Run:**

# 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:

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:**

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:**

{
  "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.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 403 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # API Agent
  2. **Turn any API into an MCP server. Query in English. Get results even when the API can't.**
  3. 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**.
  4. ## What Makes It Different
  5. **🎯 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.
  6. **✨ 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.
  7. **🔒 Safe by default.** Read-only. Mutations blocked unless explicitly allowed.
  8. SQL runs sandboxed: no file, network, or extension access. REST calls stay under the API base URL; GraphQL allows only query operations. Recipes are scoped per target and credentials. Report vulnerabilities via [SECURITY.md](SECURITY.md).
  9. **🧠 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>`.
  10. ## Quick Start
  11. **1. Run:**
  12. ```bash
  13. # Direct run (no clone needed)
  14. OPENAI_API_KEY=your_key uvx --from git+https://github.com/agoda-com/api-agent api-agent
  15. # Or clone
  16. git clone https://github.com/agoda-com/api-agent.git && cd api-agent
  17. uv sync --group dev
  18. ```
  19. Set the OpenAI secret in env:
  20. ```bash
  21. export OPENAI_API_KEY=your_key
  22. ```
  23. Direct `uvx` runs use built-in defaults unless `API_AGENT_CONFIG` points to a
  24. TOML file. A cloned checkout uses `api-agent.toml` from the repository root by
  25. default.
  26. **2. Start local clone:**
  27. ```bash
  28. uv run api-agent
  29. # Or Docker
  30. docker build -t api-agent .
  31. docker run -p 3000:3000 -e OPENAI_API_KEY=your_key api-agent
  32. ```
  33. **3. Add to any MCP client:**
  34. ```json
  35. {
  36. "mcpServers": {
  37. "rickandmorty": {
  38. "url": "http://localhost:3000/mcp",
  39. "headers": {
  40. "X-Target-URL": "https://rickandmortyapi.com/graphql",
  41. "X-API-Type": "graphql"
  42. }
  43. }
  44. }
  45. }
  46. ```
  47. **4. Ask questions:**
  48. - *"Show characters from Earth, only alive ones, group by species"*
  49. - *"Top 10 characters by episode count"*
  50. - *"Compare alive vs dead by species, only species with 10+ characters"*
  51. That's it. Agent introspects schema, generates calls, runs SQL post-processing.
  52. ## More Examples
  53. **REST API (Petstore):**
  54. ```json
  55. {
  56. "mcpServers": {
  57. "petstore": {
  58. "url": "http://localhost:3000/mcp",
  59. "headers": {
  60. "X-Target-URL": "https://petstore3.swagger.io/api/v3/openapi.json",
  61. "X-API-Type": "rest"
  62. }
  63. }
  64. }
  65. }
  66. ```
  67. **Your own API with auth:**
  68. ```json
  69. {
  70. "mcpServers": {
  71. "myapi": {
  72. "url": "http://localhost:3000/mcp",
  73. "headers": {
  74. "X-Target-URL": "https://api.example.com/graphql",
  75. "X-API-Type": "graphql",
  76. "X-Target-Headers": "{\"Authorization\": \"Bearer YOUR_TOKEN\"}"
  77. }
  78. }
  79. }
  80. }
  81. ```
  82. ---
  83. ## Reference
  84. ### Headers
  85. | Header | Required | Description |
  86. | ---------------------- | -------- | ---------------------------------------------------------- |
  87. | `X-Target-URL` | Yes | GraphQL endpoint OR OpenAPI/Swagger spec URL |
  88. | `X-API-Type` | Yes | `graphql` or `rest` |
  89. | `X-Target-Headers` | No | JSON auth headers, e.g. `{"Authorization": "Bearer xxx"}` |
  90. | `X-Passthrough-Headers`| No | JSON array of header names to copy from this MCP request onto outbound API calls (merged after `X-Target-Headers`) |
  91. | `X-API-Name` | No | Override tool name prefix (default: auto-generated) |
  92. | `X-Base-URL` | No | Override base URL for REST API calls |
  93. | `X-Allow-Unsafe-Paths` | No | JSON array of glob patterns for POST/PUT/DELETE/PATCH |
  94. | `X-Poll-Paths` | No | JSON array of REST paths requiring polling |
  95. | `X-Include-Result` | No | Truthy values include full `result` in wrapped output |
  96. | `X-Recipe-Learn-Rate` | No | Override recipe sample rate for this request, `0` to `1` |
  97. | `X-Debug` | No | Truthy values include `debug` metadata with calls and trace id when available |
  98. `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.
  99. 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.
  100. ### MCP Tools
  101. **Core tool** (prefix auto-generated from URL or `X-API-Name`):
  102. | Tool | Input | Output |
  103. | ------------------ | -------------------------------------------------------------- | ------------------------------- |
  104. | `{prefix}_query` | Natural language question + optional `return_directly` | `{ok, data, error, result?}` or CSV |
  105. `X-API-Name` preserves hyphens in the prefix; the tool suffix separator remains `_`
  106. (for example, `weather-alerts` exposes `weather-alerts_query`).
  107. 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.
  108. Set `X-Debug: true` to force wrapped JSON and include a `debug` object:
  109. ```json
  110. {
  111. "ok": true,
  112. "data": "...",
  113. "debug": {
  114. "api_calls": [{"method": "GET", "path": "/users/{id}", "success": true}],
  115. "trace_id": "62ee6f56fc839a7291d09935a0974727"
  116. },
  117. "error": null
  118. }
  119. ```
  120. For GraphQL debug responses, calls are returned under `debug.queries`. For REST debug responses, calls are returned under `debug.api_calls`.
  121. `debug.trace_id` is included only when OTEL tracing is enabled and a trace is active.
  122. **Recipe tools** (dynamically added as the agent learns):
  123. | Tool | Input | Output |
  124. | ---------- | ------------------------------------------------------------- | --------------- |
  125. | `r_{slug}` | Intent args | CSV |
  126. - Slug derived from LLM-suggested recipe name, max 49 chars total including `r_`.
  127. - All declared tool args are **required** top-level fields.
  128. - Recipe tools always return directly as CSV.
  129. **Schema tools** (agent-internal):
  130. 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.
  131. ### Configuration
  132. 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.
  133. | TOML key | Default | Notes |
  134. | --- | --- | --- |
  135. | `[mcp].name` | `API Agent` | MCP display name |
  136. | `[server].host` | `0.0.0.0` | bind host |
  137. | `[server].port` | `3000` | bind port; env `PORT` may override |
  138. | `[server].transport` | `streamable-http` | `http`, `streamable-http`, or `sse` |
  139. | `[server].stateless_http` | `true` | stateless MCP HTTP mode |
  140. | `[server].cors_allowed_origins` | empty | comma-separated browser origins; requests with any other `Origin` get 403; `*` allows all |
  141. | `[server].allowed_target_hosts` | empty | comma-separated host globs (e.g. `*.example.com`) for `X-Target-URL`/`X-Base-URL`; empty allows any host |
  142. | `[server].debug` | `false` | debug logging |
  143. | `[model].api` | `responses` | `responses` or `chat_completions` |
  144. | `[model].name` | `gpt-5.5` | model name |
  145. | `[model].openai_base_url` | `https://api.openai.com/v1` | env `OPENAI_BASE_URL` may override |
  146. | `[model].reasoning_effort` | `low` | model reasoning effort |
  147. | `[description].model_name` | `gpt-5.4-mini` | optional tool description model; empty uses `[model].name` |
  148. | `[description].timeout_seconds` | `15` | tool description generation timeout |
  149. | `[agent].max_turns` | `30` | max agent turns per query |
  150. | `[agent].max_response_chars` | `50000` | max final response chars |
  151. | `[agent].max_schema_chars` | `32000` | compact schema cap |
  152. | `[agent].max_preview_rows` | `10` | result preview rows |
  153. | `[agent].max_tool_response_chars` | `32000` | tool response context cap |
  154. | `[polling].max_polls` | `20` | max REST poll attempts |
  155. | `[polling].default_delay_ms` | `3000` | default REST poll delay |
  156. | `[polling].max_delay_ms` | `3000` | max REST poll delay |
  157. | `[recipes].enabled` | `true` | enable learned recipes |
  158. | `[recipes].max_size` | `1000` | max stored recipes |
  159. | `[recipes].learn_rate` | `0.2` | deterministic sample rate |
  160. | `[storage].backend` | `memory` | `memory` or `redis` |
  161. | `[storage].namespace` | `api-agent` | Redis key namespace |
  162. | `[redis].url` | empty | required only for Redis storage |
  163. 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.
  164. `[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.
  165. ---
  166. ## How It Works
  167. ```mermaid
  168. sequenceDiagram
  169. participant U as User
  170. participant M as MCP Server
  171. participant A as Agent
  172. participant G as Target API
  173. U->>M: Question + Headers
  174. M->>G: Schema introspection
  175. G-->>M: Schema
  176. M->>A: Schema + question
  177. A->>G: API call
  178. G-->>A: Data → stored in DuckDB
  179. A->>A: SQL post-processing
  180. A-->>M: Summary
  181. M-->>U: {ok, data, result?}
  182. ```
  183. ## Architecture
  184. ```mermaid
  185. flowchart TB
  186. subgraph Client["MCP Client"]
  187. H["Headers: X-Target-URL, X-API-Type"]
  188. end
  189. subgraph MCP["MCP Server (FastMCP)"]
  190. Q["{prefix}_query"]
  191. R["r_{recipe_slug}"]
  192. end
  193. subgraph Agent["Agents (OpenAI Agents SDK)"]
  194. GA["GraphQL Agent"]
  195. RA["REST Agent"]
  196. end
  197. subgraph Exec["Executors"]
  198. HTTP["HTTP Client"]
  199. Duck["DuckDB"]
  200. end
  201. Client -->|NL + headers| MCP
  202. Q -->|graphql| GA
  203. Q -->|rest| RA
  204. R --> HTTP
  205. GA --> HTTP
  206. RA --> HTTP
  207. GA --> Duck
  208. RA --> Duck
  209. HTTP --> API[Target API]
  210. ```
  211. **Stack:** [FastMCP](https://github.com/jlowin/fastmcp) • [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/) • [DuckDB](https://duckdb.org)
  212. Agents use the OpenAI Responses API model path by default. Set `[model].api = "chat_completions"` only for models/endpoints that support Chat Completions.
  213. 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.
  214. 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` (resolved against the spec URL, and only if on the spec's origin), then derives the origin from the spec URL. Spec YAML anchors/aliases are not supported.
  215. ---
  216. ## REST Polling
  217. Set `X-Poll-Paths` to enable the `poll_until_done` agent tool for async REST endpoints:
  218. ```json
  219. ["/jobs", "/search"]
  220. ```
  221. 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.
  222. ---
  223. ## Recipe Learning
  224. 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.
  225. 1. **Captures** - Records successful API and SQL tool calls into one ordered `steps` list.
  226. 2. **Samples** - Uses `X-Recipe-Learn-Rate` when present, otherwise `[recipes].learn_rate`.
  227. 3. **Extracts** - Structured extractor proposes a public MCP tool contract plus private optimized execution plan.
  228. 4. **Validates** - Runs the candidate once with fixture tool args and compares final rows to the original result.
  229. Extractor prompts receive bounded result samples; deterministic replay keeps the full local result.
  230. 5. **Caches** - Stores by API id + schema hash with fingerprint deduplication.
  231. 6. **Reuses** - Similar `{prefix}_query` requests get recipe tools injected for the agent to choose.
  232. 7. **Exposes** - Learned recipes are also published as direct MCP tools named `r_<tool_name>`.
  233. ```mermaid
  234. flowchart TD
  235. Q["{prefix}_query<br/>natural language"] --> S["Load schema"]
  236. S --> M["Search recipes<br/>api id + schema hash + question"]
  237. M --> A["Agent run<br/>recipe tools + API/SQL tools"]
  238. A --> C["Capture successful ordered steps<br/>API and SQL interleaved"]
  239. C --> R["Return query response"]
  240. R --> L{"learn rate sample?"}
  241. L -- no --> Done["Done"]
  242. L -- yes --> X["Structured extractor<br/>public contract + private plan"]
  243. X --> V{"candidate result<br/>matches original result?"}
  244. V -- no --> Done
  245. V -- yes --> Store["Store recipe<br/>fingerprint dedupe"]
  246. Store --> List["Next list_tools exposes r_{slug}"]
  247. subgraph Direct["Direct recipe call"]
  248. T["r_{slug}"] --> P["Map public args to private plan<br/>run without agent reasoning"]
  249. end
  250. ```
  251. **Recipe structure:**
  252. - `public_contract` contains MCP `tool_name`, description, and public `tool_args`.
  253. - `execution_plan.steps` is a dataflow graph. Each step has `id`, `kind`, `input`, and `output.name`.
  254. - `input.mode="single"` uses public args via `input.with`; `map` and `batch` read one prior rowset via `input.from` + `input.bind`.
  255. - Multiple dependencies must first be joined by SQL into one ordered binding rowset; there is no implicit Cartesian product.
  256. - **GraphQL**: `call.query_template` with `{{param}}` placeholders.
  257. - **REST**: `call.path_params`, `call.query_params`, `call.body` with `{"$var": "name"}` refs. List query params are encoded as repeated keys.
  258. - **SQL**: `query_template` inside the same ordered `steps` list.
  259. Mapped REST dependency shape:
  260. ```json
  261. {
  262. "id": "key_results",
  263. "kind": "rest",
  264. "input": {
  265. "mode": "map",
  266. "from": "filtered_objectives",
  267. "bind": {"objective_id": "id"},
  268. "with": {}
  269. },
  270. "call": {
  271. "method": "GET",
  272. "path": "/objectives/{objective_id}/key-results",
  273. "path_params": {"objective_id": {"$var": "objective_id"}}
  274. },
  275. "output": {
  276. "name": "key_results",
  277. "attach_binding": ["objective_id"]
  278. }
  279. }
  280. ```
  281. `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.
  282. **Recipe tools:**
  283. - Each cached recipe is surfaced as an MCP tool named `r_{slug}` (slugified from LLM-suggested name, max 49 chars).
  284. - Recipe names use concise `snake_case` action-resource slugs. Descriptions are outcome-focused and do not inject API labels or implementation step counts.
  285. - If multiple recipes share the same slug, the most recently used one is exposed.
  286. - Tool args are **flat top-level fields** (not nested under `params`), all required, and must be user-intent inputs.
  287. - Clients call these tools directly — no LLM reasoning, just cached API+SQL pipeline.
  288. 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.
  289. 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.
  290. ---
  291. ## Development
  292. ```bash
  293. git clone https://github.com/agoda-com/api-agent.git
  294. cd api-agent
  295. uv sync --group dev
  296. uv lock --check
  297. uv run ruff check api_agent/ tests/
  298. uv run ruff format --check api_agent/ tests/
  299. uv run ty check
  300. uv run pytest tests/ -q
  301. ```
  302. Agent guidance lives in `AGENTS.md`. See [CONTRIBUTING.md](CONTRIBUTING.md) for
  303. contribution guidelines and [CHANGELOG.md](CHANGELOG.md) for service history.
  304. ## Observability
  305. OpenTelemetry tracing is opt-in. For local tracing, run through `opentelemetry-instrument`
  306. and set either:
  307. ```bash
  308. OTEL_SERVICE_NAME=api-agent OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
  309. uv run --no-sync opentelemetry-instrument api-agent
  310. # or
  311. OTEL_SERVICE_NAME=api-agent OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces \
  312. uv run --no-sync opentelemetry-instrument api-agent
  313. ```
  314. `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.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.