# Expose REST APIs as MCP Tools for AI Agents

The [`openapi-to-mcp`](https://docs.api7.ai/hub/openapi-to-mcp.md) plugin exposes existing REST APIs as tools that AI agents can discover and invoke through MCP (Model Context Protocol). Existing APIs stay unchanged, and their OpenAPI 3.x documents provide the tool definitions instead of requiring custom agent integrations.

The plugin forwards MCP traffic to the OpenAPI-to-MCP service deployed alongside the gateway. The service publishes each OpenAPI operation as a tool and translates tool calls into upstream HTTP requests.

## How MCP Gateway Works[​](#how-mcp-gateway-works "Direct link to How MCP Gateway Works")

The request path is:

```
AI Agent -> MCP Client -> API7 Gateway -> OpenAPI-to-MCP Service -> Upstream REST APIs
```

The plugin does not start an MCP server. It proxies requests to the separately deployed OpenAPI-to-MCP service at `127.0.0.1:3000` by default. The service must share the gateway's network namespace and exposes two transport modes:

* `sse` (default):

  <!-- -->

  * `GET /.api7_mcp/sse` for the event stream
  * `POST` messages on the MCP message endpoint

* `streamable_http`:
  <!-- -->
  * Stateless `POST /.api7_mcp/mcp_stateless`

For the SSE connection request and for Streamable HTTP requests, the plugin automatically injects `x-openapi2mcp-base-url` and `x-openapi2mcp-openapi-spec` headers from the plugin configuration before forwarding the request to the MCP sidecar. You do not need to set these headers manually.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

Before you begin, make sure you have:

* API7 Gateway running.

* Create a [token from the Dashboard](https://docs.api7.ai/api7-gateway/reference/obtain-dashboard-token.md) and save it to an environment variable:

  ```
  export API_KEY=your-dashboard-token   # replace with your Dashboard token
  ```

* Replace `{gateway_group_id}` with your gateway group ID. Use `default` if you are following the quickstart.

* If you are following the Admin API examples, create or reuse a service in API7 Gateway. If you do not have one yet, follow [Create or Reuse a Service](https://docs.api7.ai/api7-gateway/ai-gateway/get-started.md#create-or-reuse-a-service), then save its ID to an environment variable:

  ```
  export SERVICE_ID=your-service-id         # replace with your service ID
  ```

* An MCP client (for example, Claude Desktop or another MCP-compatible client) for validation.

## Deploy the OpenAPI-to-MCP Service[​](#deploy-the-openapi-to-mcp-service "Direct link to Deploy the OpenAPI-to-MCP Service")

The service must share the gateway's network namespace because the plugin connects to `127.0.0.1:3000` by default.

* **Kubernetes (Helm)**: Set `openapiToMcp.enabled: true` in the API7 Gateway chart values.

* **Docker or bare metal**: Run `api7/openapi-to-mcp:1.0.9` with the gateway network namespace. For Docker, add the following service to the Dashboard-generated `docker-compose.yaml`:

  docker-compose.yaml

  ```
  services:

    openapi-to-mcp:

      image: api7/openapi-to-mcp:1.0.9

      network_mode: "service:gateway"

      restart: always
  ```

  If the generated gateway service has another name, replace `gateway` in `network_mode` with that name. Then start or update the services with `docker compose up -d`.

For port, cache, and backend timeout settings, see [Static Configurations](https://docs.api7.ai/hub/openapi-to-mcp/configuration.md#static-configurations).

## Configure the MCP Gateway[​](#configure-the-mcp-gateway "Direct link to Configure the MCP Gateway")

Configure a route that exposes the public Petstore API as MCP tools. Petstore provides both the OpenAPI document and the API used by the generated tools.

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/openapi-to-mcp-route?gateway_group_id={gateway_group_id}" -X PUT \

  -H "X-API-KEY: ${API_KEY}" \

  -H "Content-Type: application/json" \

  --data-binary @- <<EOF

  {

    "name": "openapi-to-mcp-route",

    "service_id": "$SERVICE_ID",

    "paths": ["/.api7_mcp/*"],

    "plugins": {

      "openapi-to-mcp": {

        "openapi_url": "https://petstore3.swagger.io/api/v3/openapi.json",

        "base_url": "https://petstore3.swagger.io/api/v3",

        "transport": "sse",

        "headers": {},

        "flatten_parameters": false

      }

    }

  }

EOF
```

❶ `openapi_url` points to your OpenAPI 3.x document. The OpenAPI-to-MCP service parses this spec and builds MCP tools from its operations.

❷ `base_url` is the upstream REST API base address used when a tool is invoked.

❸ `transport` selects the MCP transport. Use `sse` (default) or `streamable_http`.

❹ `flatten_parameters` controls whether nested parameters are flattened when generating tool input schemas.

adc.yaml

```
services:

  - name: MCP Gateway

    labels:

      docs-example: openapi-to-mcp-guide

    upstream:

      type: roundrobin

      scheme: https

      pass_host: node

      nodes:

        - host: petstore3.swagger.io

          port: 443

          weight: 1

    routes:

      - uris:

          - /.api7_mcp/*

        name: openapi-to-mcp-route

        plugins:

          openapi-to-mcp:

            openapi_url: https://petstore3.swagger.io/api/v3/openapi.json

            base_url: https://petstore3.swagger.io/api/v3

            transport: sse

            headers: {}

            flatten_parameters: false
```

❶ `openapi_url` points to your OpenAPI 3.x document. The OpenAPI-to-MCP service parses this spec and builds MCP tools from its operations.

❷ `base_url` is the upstream REST API base address used when a tool is invoked.

❸ `transport` selects the MCP transport. Use `sse` (default) or `streamable_http`.

❹ `flatten_parameters` controls whether nested parameters are flattened when generating tool input schemas.

Preview the tutorial service and confirm that the diff contains no unintended updates or deletions:

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=openapi-to-mcp-guide
```

Synchronize the reviewed service configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=openapi-to-mcp-guide
```

## Validate with an MCP Client[​](#validate-with-an-mcp-client "Direct link to Validate with an MCP Client")

### Step 1 — Connect and Discover Tools[​](#step-1--connect-and-discover-tools "Direct link to Step 1 — Connect and Discover Tools")

#### SSE Mode[​](#sse-mode "Direct link to SSE Mode")

Connect the MCP client to the SSE endpoint:

```
curl -N "http://127.0.0.1:9080/.api7_mcp/sse"
```

A successful connection returns an event stream with a session-specific endpoint:

```
event: endpoint

data: /.api7_mcp/sse?sessionId=abc123xyz
```

The `sessionId` value identifies the SSE session created by the MCP sidecar. Use the session-specific endpoint returned by the event stream instead of the route pattern configured on the gateway.

#### Streamable HTTP Mode[​](#streamable-http-mode "Direct link to Streamable HTTP Mode")

The two transports are mutually exclusive for a route. Before using the Streamable HTTP examples, change `transport` from `sse` to `streamable_http` in the route configuration shown earlier, then reapply that configuration with the Admin API or `adc sync`.

Send a `tools/list` request to discover available tools:

```
curl -s "http://127.0.0.1:9080/.api7_mcp/mcp_stateless" \

  -X POST \

  -H "Content-Type: application/json" \

  -H "Accept: application/json, text/event-stream" \

  -d '{

    "jsonrpc": "2.0",

    "id": 2,

    "method": "tools/list",

    "params": {}

  }'
```

The response should be an SSE `message` event whose tool list includes an entry similar to:

```
{

  "name": "getPetById",

  "description": "Returns a single pet"

}
```

### Step 2 — Invoke a Tool[​](#step-2--invoke-a-tool "Direct link to Step 2 — Invoke a Tool")

With the route configured for `streamable_http`, call a tool to verify end-to-end REST forwarding. The following example calls `findPetsByStatus`, which accepts a query parameter. Because `flatten_parameters` is `false`, provide the parameter under `queryParameters`.

```
curl -s "http://127.0.0.1:9080/.api7_mcp/mcp_stateless" \

  -X POST \

  -H "Content-Type: application/json" \

  -H "Accept: application/json, text/event-stream" \

  -d '{

    "jsonrpc": "2.0",

    "id": 4,

    "method": "tools/call",

    "params": {

      "name": "findPetsByStatus",

      "arguments": {

        "queryParameters": {

          "status": "available"

        }

      }

    }

  }'
```

A successful call returns HTTP 200 and an MCP result containing the currently available Petstore resources. Depending on the deployed OpenAPI-to-MCP service version, the resources can appear in a JSON-encoded upstream response envelope or directly in the result, including as `structuredContent`.

## Security Considerations[​](#security-considerations "Direct link to Security Considerations")

When exposing APIs as MCP tools, apply the same controls as production API traffic:

* **Authentication**: enforce gateway auth (API key, JWT, mTLS) before MCP tool calls reach the OpenAPI-to-MCP service.
* **Authorization**: restrict which routes and operations an agent identity can access.
* **Rate limiting**: apply request or token-based limits to prevent abusive or runaway agent traffic.
* **Sidecar egress**: restrict network egress from the OpenAPI-to-MCP service because it fetches the OpenAPI document and sends upstream requests directly. Configure `allowed_hosts` when `base_url` contains variables.

## Next Steps[​](#next-steps "Direct link to Next Steps")

* [Token-Based Rate Limiting and Quota Management](https://docs.api7.ai/api7-gateway/ai-gateway/use-cases/token-rate-limiting-and-quota-management.md) — Control agent traffic and cost.
* [AI Observability and Cost Tracking](https://docs.api7.ai/api7-gateway/ai-gateway/use-cases/ai-observability-and-cost-tracking.md) — Monitor tool usage and latency.
* See the [`openapi-to-mcp` configuration reference](https://docs.api7.ai/hub/openapi-to-mcp/configuration.md) for all fields and product-specific availability.
