API Agent 标志

API Agent

组织
agoda-com

Universal MCP server for GraphQL/REST APIs

发布者agoda-com
代码仓库api-agent
语言Python
复刻数
43
星标数
291
可用工具
0
传输类型stdio, streamable-http
分类
许可协议MIT
链接
  • 将工具接入 AI 工作流

    API Agent 提供 MCP 功能,可供兼容的 AI 客户端和智能体使用。

  • 0 个可用工具

    浏览下方可调用的操作;如果服务器提供了名称和描述,也会一并显示。

  • 可直接复制的配置

    使用安装配置片段,在您首选的 MCP 客户端中配置此服务器。

  • 开源社区热度

    关联的代码仓库有 291 个 Star 和 43 个 Fork。

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.

安装

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

将 API Agent MCP 与多个 AI 模型配合使用

TypingMind 在工作区级别连接 MCP 工具,因此连接 API Agent 后,您就可以在 TypingMind 中搭配不同的 AI 模型使用,无需为每个模型单独设置。 您可以在自己的设备上本地运行 MCP,也可以通过 URL 连接远程 MCP 服务器。

方式 1:使用本地连接器

如果 MCP 服务器需要访问您电脑上的本地文件、应用或私有资源,请选择此方式。

1

打开 MCP 设置

在 TypingMind 中,依次前往“设置”、“高级设置”和“模型上下文协议”,然后选择“设置连接器”。

  1. 在您的浏览器中打开 TypingMind。
  2. 点击“设置”图标。
  3. 进入“高级设置”。
  4. 打开“模型上下文协议”部分。
  5. 点击“设置连接器”,然后选择“此设备”。
TypingMind MCP 连接器设置界面,已选择“此设备”
2

运行连接器命令

选择“此设备”,从 TypingMind 复制命令并在终端中运行。使用 MCP 时,请保持该进程运行。

  1. 复制 TypingMind 显示的设置命令。
  2. 在 macOS 上打开“终端”,或在 Windows 上打开 Windows Terminal。
  3. 粘贴并运行命令。
  4. 如果终端询问您是否继续,请确认安装软件包。
  5. 使用 MCP 工具时,请保持终端窗口及其中的进程运行。
3

将 API Agent 添加为服务器

当连接器状态为“就绪”时,点击“编辑服务器”,然后粘贴 MCP 服务器配置。

  1. 等待连接器状态显示为“就绪”。
  2. 点击“编辑服务器”。
  3. 粘贴 API Agent MCP 服务器配置。
  4. 保存服务器列表。
  5. 如需确认连接器是否仍处于就绪状态,请刷新。
TypingMind MCP 设置界面,显示正在运行的服务器和“编辑服务器”按钮
{
  "mcpServers": {
    "api-agent": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

在不同模型中使用同一连接

保存服务器列表,打开“插件”,启用 API Agent MCP 工具,然后在 TypingMind 中选择任意受支持的 AI 模型,即可在聊天中使用这些工具,或将其分配给智能体。

  1. 在 TypingMind 中打开“插件”页面。
  2. 启用 API Agent MCP 工具。
  3. 开始聊天并选择您想使用的 AI 模型。
  4. 在聊天中使用 MCP 工具,或将其分配给 AI 智能体。
  5. 根据需要随时切换到其他 AI 模型,无需重新连接 MCP。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 API Agent 帮我完成这项任务吗?
API Agent
当然。我已阅读。
以下是我使用 API Agent 得到的结果。

方式 2:添加 MCP 服务器 URL

如果 API Agent 已托管在远程服务器上,或您的团队希望让多个用户共用一个连接器,请选择此方式。

1

打开 MCP 连接器

在 TypingMind 中,前往“插件”,打开“MCP 连接器”,然后选择“添加 URL”。

  1. 在您的浏览器中打开 TypingMind。
  2. 进入“插件”。
  3. 打开“MCP 连接器”。
  4. 点击“添加 URL”。
TypingMind 的“添加自定义 MCP 服务器 URL”表单
2

粘贴服务器 URL

在“服务器 URL”字段中输入 提供商提供的 MCP 服务器 URL。根据服务器要求,添加连接名称、描述、图标、自定义 HTTP 请求头或 OAuth 客户端设置。

  1. 将 提供商提供的 MCP 服务器 URL 粘贴到“服务器 URL”字段中。
  2. 为 API Agent 输入连接名称。
  3. 您可以添加描述和图标,以便更容易识别此连接。
  4. 如果服务器需要身份验证,请添加自定义 HTTP 请求头或 OAuth 客户端信息。
3

创建连接

点击“创建连接”,然后返回插件列表,确认新的 MCP 连接显示为“有效”。

  1. 点击“创建连接”。
  2. 返回 MCP 连接器列表。
  3. 确认 API Agent 连接显示为“有效”。
  4. 如果连接未立即出现,请刷新插件列表。
4

切换模型,无需重新连接

使用您偏好的模型开始聊天,在“插件”中启用 API Agent 工具,并根据需要随时切换到其他模型。该 MCP 连接在 TypingMind 工作区中仍然可用。

  1. 在 TypingMind 中开始新聊天。
  2. 选择您想使用的 AI 模型。
  3. 在“插件”中启用 API Agent 工具。
  4. 需要时,请让模型使用该工具。
  5. 切换到其他 AI 模型,继续使用同一个 MCP 连接。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 API Agent 帮我完成这项任务吗?
API Agent
当然。我已阅读。
以下是我使用 API Agent 得到的结果。

常见问题

API Agent MCP 服务器有什么用途?

API Agent 是一个 MCP 服务器,可让兼容的 AI 客户端连接外部工具并获取上下文。在 TypingMind 中,只需添加一次此 MCP 服务器,即可在您的 AI 工作区中使用其工具。

可以在 TypingMind 中让多个 AI 模型使用 API Agent MCP 吗?

可以。TypingMind 在工作区层面连接 MCP 工具,因此您可以让 Claude、ChatGPT、Gemini 等不同 AI 模型,或您在 TypingMind 中配置的其他模型使用 API Agent,而无需为每个模型单独配置 MCP 服务器。

为什么在 TypingMind 中使用 API Agent MCP?

TypingMind 将多个 AI 模型、提示词、插件、AI 智能体、API 密钥和 MCP 工具整合到同一个工作区中,是优秀的大语言模型聊天前端之一。连接 API Agent 后,您可以在偏好的不同模型中使用其 MCP 工具,同时在 TypingMind 中井然有序地管理聊天工作流程。

如何将 API Agent MCP 连接到 TypingMind?

您可以通过本地 MCP 连接器,或添加远程 MCP 服务器 URL,在 TypingMind 中连接 API Agent。当服务器需要访问您设备上的文件、应用或私有资源时,请使用本地连接器;当 MCP 服务器托管在远程时,请使用服务器 URL。

API Agent MCP 在 TypingMind 中提供哪些工具?

API Agent 提供 MCP 功能,您可以在 TypingMind 的插件页面启用这些功能,然后在聊天中使用,或将其分配给 AI 智能体。

使用 API Agent MCP 需要向 TypingMind 提供我的 API 密钥吗?

不需要。TypingMind 采用本地优先的设计,让您自行掌控模型提供商、API 密钥、提示词和 MCP 配置。如果 API Agent 需要身份验证,请在创建连接时,为该 MCP 服务器添加所需的请求头、OAuth 设置或本地配置。

相关 MCP 服务器

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇