Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install api-gateway-mcp-server@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin api-gateway-mcp-server v1.0.0 follows the Agent Plugins spec.
gh skills-hub install api-gateway-mcp-server Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/api-gateway-mcp-server/ Extract the ZIP to .github/skills/ in your repo. The folder name must match api-gateway-mcp-server for Copilot to auto-discover it.
Skill Files (7)
SKILL.md 19.7 KB
---
name: api-gateway-mcp-server
metadata:
version: "1.1.0"
category: AiAndMachineLearning
description: >-
Configures Google Cloud API Gateway to act as a remote Model Context Protocol
(MCP) server (Public Preview) that exposes REST APIs as agent tools over HTTP
(POST /mcp). Use when exposing an API Gateway API as MCP tools, migrating
OpenAPI 2.0 specs to OpenAPI 3.x for MCP, annotating specs with
x-google-api-management.mcp and x-google-mcp-tool, securing tools/list with
JWTs or API keys, connecting Google ADK (McpToolset) or Apigee API hub and
Agent Registry, or troubleshooting MCP JSON-RPC errors (-32601, -32602,
-32000), /mcp HTTP 404 or 405 errors, and MCP errors from api-configs create.
Do not use for a migration without MCP or another OpenAPI error from
api-configs create (use api-gateway-openapi-spec-authoring), API key, JWT, or
quota setup for REST only (use
api-gateway-backend-security-and-rate-limiting), failing non-MCP requests (use
api-gateway-troubleshooting), Apigee X proxy bundles, outbound LLM model
routing, or GKE Gateway API.
---
<!-- disableFinding(LINE_OVER_80) -->
# API Gateway Remote MCP Server (Public Preview)
This skill converts new or existing REST APIs on Google Cloud API Gateway into remote Model Context Protocol (MCP) servers (`POST https://{default_hostname}/mcp`, **Public Preview**). By annotating an OpenAPI 3.x (3.0.x or 3.1.x) specification with `x-google-api-management.mcp` and `x-google-mcp-tool`, API Gateway translates MCP JSON-RPC 2.0 requests (`initialize`, `notifications/initialized`, `tools/list`, `tools/call`) into standard HTTP REST requests to your backend while enforcing existing authentication and quota policies.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Prerequisites
1. **Install the Google Cloud CLI and the validator dependency:**
- If the Google Cloud CLI is not installed, give the user the [install guide](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt). Do not install it yourself. Until it is installed, give the user the commands to run, and continue from the output that they paste. An old CLI can fail when it uploads an OpenAPI 3.x API config. Ask the user before you run `gcloud components update`.
- Install Python 3.10 or later and `PyYAML` for the local OpenAPI MCP validator script. Ask the user before you install it:
```bash
pip install "PyYAML>=6.0,<7.0"
```
2. **Authenticate your environment:**
- Local CLI session: `gcloud auth login`
- Application Default Credentials (SDKs / ADK): `gcloud auth application-default login`
3. **Select or create a project, confirm billing, and pick a supported gateway location:**
- Ask the user which project to use, and use that ID as `{project_id}`. If no project exists, create one (`gcloud projects create {project_id}`). Pass `--project={project_id}` on every command. Do not change the active project with `gcloud config set project`.
- Confirm that an active billing account is linked to `{project_id}`. API Gateway has a free monthly allowance of API calls for each billing account, but you still need an active billing account to deploy. Calls above the allowance and network data transfer out are charged. For current prices, see [API Gateway pricing](https://cloud.google.com/api-gateway/pricing).
- Use `us-central1` as the default `--location` for gateway commands. For the other supported regions, see [API Gateway deployment model](https://docs.cloud.google.com/api-gateway/docs/deployment-model.md.txt).
4. **Enable the required Google Cloud APIs:**
```bash
gcloud services enable \
apigateway.googleapis.com \
servicemanagement.googleapis.com \
servicecontrol.googleapis.com \
--project={project_id}
```
For API hub discovery (optional), enable the API hub API in the API hub host project: `gcloud services enable apihub.googleapis.com --project={hub_project_id}`. To query Agent Registry (optional), also run `gcloud services enable agentregistry.googleapis.com --project={project_id}`.
5. **Verify the IAM roles (use the most restrictive role for each step):**
- To create and update the API, API configs, and gateways: API Gateway Admin (`roles/apigateway.admin`) on `{project_id}`. To run the `gcloud services enable` commands: Service Usage Admin (`roles/serviceusage.serviceUsageAdmin`) on that project.
- To reference the gateway service account in an API config: Service Account User (`roles/iam.serviceAccountUser`) on `{gateway_sa_name}@{project_id}.iam.gserviceaccount.com`.
- For a Cloud Run backend: grant the gateway service account the Cloud Run Invoker role (`roles/run.invoker`) on the service.
- To mint test ID tokens as a caller service account: Service Account Token Creator (`roles/iam.serviceAccountTokenCreator`) on `{caller_sa_email}`.
- Reference: [Configure the development environment](https://docs.cloud.google.com/api-gateway/docs/configure-dev-env.md.txt).
## Decision Matrix: MCP Server Configuration and Client Integration
| Task | Required Mechanism | Critical Guardrail | Detailed Reference |
| --- | --- | --- | --- |
| Migrate OpenAPI 2.0 (`swagger: "2.0"`) or author OpenAPI 3.x for MCP | Root `x-google-api-management.mcp` + named `backends` + operation-level `x-google-mcp-tool` | NEVER add MCP extensions to an OpenAPI 2.0 spec. **Rationale:** MCP is not supported for OpenAPI 2.0. Use OpenAPI 3.0.x or 3.1.x, and deploy the spec with `gcloud api-gateway api-configs create`. For the general 2.0 to 3.x conversion, use the `api-gateway-openapi-spec-authoring` skill. If it is not installed, use the fallback in the migration reference. Keep all MCP operations in one OpenAPI document. If only one document of the API config has MCP extensions, only its operations become tools. API Gateway fails to create an API config that has MCP extensions in more than one document, and the error does not say why. | [OpenAPI 2.0 to 3.x Migration](references/openapi-v2-to-v3-mcp-migration.md) |
| Optimize tool names, descriptions, and schemas for LLM tool selection | `x-google-mcp-tool` (`name`, `description`, `false`) + described `requestBody` properties | Every operation MUST have an `operationId`, with or without MCP. Every exposed tool MUST resolve to a unique name that matches `[A-Za-z0-9_.-]{1,128}` (`x-google-mcp-tool.name`, or else the `operationId`), a non-empty description, and a non-empty response body (`HTTP 204` is unsupported). Only `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` operations can be tools, and a gateway serves at most 1,000 tools. API Gateway rejects complex nested schemas when you create the API config, but a simple nested object body works. In OpenAPI 3.1, give each schema one `type`, because API Gateway also rejects a type list such as `type: ["string", "null"]`. Describe each property, and check each tool's `inputSchema` in `tools/list` after you deploy. | [OpenAPI Agent Tool Optimizer](references/openapi-agent-tool-optimizer.md) |
| Secure `tools/list` and hide internal/admin routes | `x-google-api-management.mcp.tools-list.security` (exactly one JWT or API key scheme; a JWT scheme is also listed in root `security`) + `x-google-mcp-tool: false` | `tools/list` is unauthenticated by default. An empty `tools-list.security` map (`{}`) also leaves it open. It accepts one JWT scheme, or one API key scheme sent in the `x-api-key` header. API Gateway rejects a config whose JWT `tools-list.security` scheme is missing from the root `security` list, and that root entry also requires the JWT on every REST operation without its own `security`. If the root list already has an API key scheme, add the JWT to the same requirement object (AND). API Gateway rejects alternative (OR) requirements in which only some alternatives have the API key. An `mcp` object (for `tools-list`) also enables MCP for every eligible operation, so opt out each operation that agents must not use. `x-google-mcp-tool: false` hides a route from MCP only; keep REST `security` on admin routes. | [OpenAPI 2.0 to 3.x Migration](references/openapi-v2-to-v3-mcp-migration.md) |
| Connect Google ADK (`McpToolset`) and discover in API hub / Agent Registry | `McpToolset` (`StreamableHTTPConnectionParams`) + API hub project attachment | No separate registration step is needed. After you attach the API Gateway project to API hub, the MCP server appears in API hub as `{your_api} (MCP)` and in Agent Registry automatically. | [ADK and API Hub Discovery](references/adk-and-api-hub-discovery.md) |
| Verify `/mcp` JSON-RPC lifecycle and troubleshoot `-32601` / `-32602` / `-32000` errors | `POST https://{default_hostname}/mcp` with `MCP-Protocol-Version: 2025-11-25` | Keep `/mcp` at the host root: a `servers` base path (such as `/v2`) applies to REST paths only, and `{basepath}/mcp` returns HTTP 404. Nest JSON request bodies under `params.arguments.body` (`{"body": {...}}`). NEVER combine `x-google-api-management.mcp` with `x-google-model-router` in one config. **Rationale:** API Gateway does not allow MCP and model routing in the same API config. | [MCP Verification and Troubleshooting](references/mcp-limitations-and-troubleshooting.md) |
## Execution Workflow and Validation Loop
1. **Upgrade and annotate the OpenAPI 3.x specification:**
- For the general OpenAPI 2.0 to 3.x conversion, use the `api-gateway-openapi-spec-authoring` skill, and then add the MCP settings with this skill. If that skill is not installed, use the [General Conversion Fallback](references/openapi-v2-to-v3-mcp-migration.md#general-conversion-fallback). The [Complete Converted Example](references/openapi-v2-to-v3-mcp-migration.md#complete-converted-example) shows a finished MCP spec with a Google ID token scheme.
- Follow [OpenAPI 2.0 to 3.x Migration](references/openapi-v2-to-v3-mcp-migration.md) and [OpenAPI Agent Tool Optimizer](references/openapi-agent-tool-optimizer.md) to set `openapi` to a 3.0.x or 3.1.x version (the examples use `3.0.4`), remove unsupported OpenAPI 2.0 fields (`x-google-allow`), define `x-google-api-management.backends`, configure `x-google-api-management.mcp.tools-list.security` with exactly one JWT or API key scheme (add a JWT scheme to the root `security` list too, in the same requirement object as any API key scheme), author `x-google-mcp-tool` descriptions stating *when and why* to invoke each tool, and opt out administrative routes (`x-google-mcp-tool: false`).
- Set an explicit `pathTranslation` on each backend. In a migration, keep the OpenAPI 2.0 behavior: `APPEND_PATH_TO_ADDRESS` for a root backend, and `CONSTANT_ADDRESS` for an operation-level backend. For a new spec, if you do not know which value the backend expects, ask the user.
- Give every operation a backend at the root or operation level, also each operation with `x-google-mcp-tool: false`.
- Before you deploy, give the user a short summary that states each of these points, and get approval:
- MCP is not supported for OpenAPI 2.0, so you converted the spec to OpenAPI 3.x.
- Which operations you exposed as tools, and which you opted out with `x-google-mcp-tool: false`. Opted-out operations stay on REST.
- If `tools/list` uses a JWT scheme, the root `security` entry makes every REST operation without its own `security` require the JWT. The gateway rejects REST callers without it.
- The MCP endpoint is `https://{default_hostname}/mcp`, at the host root even when the spec sets a `servers` base path.
- The limits that apply: only `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` operations can be tools, a gateway serves at most 1,000 tools, request parameters must be primitive types, API Gateway rejects complex nested schemas and OpenAPI 3.1 type lists (such as `type: ["string", "null"]`) when you create the API config, tools cannot return `HTTP 204`, and MCP is stateless with UTF-8 text responses only.
- Give the same points when the user only asks for the converted spec or for advice, without a deploy.
- Preserve exact quota metric names in `x-google-api-management.metrics` across API configs so existing gateways do not fail with HTTP 500 `Failed to call Service Control Quota`. If the spec has quotas, load the `api-gateway-backend-security-and-rate-limiting` skill, and run its `scripts/check_quota_metrics.py` before `api-configs create`. If that skill is not installed, keep every metric and its quota limit that a running API config uses.
2. **Run the deterministic MCP OpenAPI validation loop before creating the API config:**
- Execute `scripts/validate_mcp_openapi.py` on `{candidate_openapi_spec}`:
```bash
python3 scripts/validate_mcp_openapi.py --spec={candidate_openapi_spec}
```
- If `scripts/validate_mcp_openapi.py` exits with code `1` (`status: "FAIL"`), fix every reported error in `{candidate_openapi_spec}` (such as OpenAPI 2.0 syntax, `x-google-allow`, path-level `x-google-mcp-tool`, undefined backend names, an operation without an `operationId`, missing descriptions, invalid or duplicate tool names, a header parameter with the reserved `x-google-` prefix, a `tools-list.security` scheme that is neither an `oauth2` JWT nor an `apiKey` scheme, a JWT `tools-list.security` scheme missing from the root `security` list, alternative (OR) security requirements in which only some alternatives have an API key, or an `x-google-model-router` operation in an MCP spec) and re-run the script until it exits with code `0` (`status: "PASS"`). If it exits with code `2`, fix the file path or YAML syntax error printed to stderr.
- Read every warning (such as an `HTTP 204` response, a request parameter that is not a primitive type, or operations that an `mcp` object exposes by default). Fix it, or tell the user why you keep it.
3. **Create the API (if new), create the API config, deploy the gateway, and enable the managed service (request human approval before updating a production gateway):**
```bash
gcloud api-gateway apis create {api_id} --project={project_id}
gcloud api-gateway api-configs create {config_id} \
--api={api_id} \
--openapi-spec={candidate_openapi_spec} \
--backend-auth-service-account={gateway_sa_name}@{project_id}.iam.gserviceaccount.com \
--project={project_id}
gcloud api-gateway gateways update {gateway_id} \
--api={api_id} \
--api-config={config_id} \
--location={region} \
--project={project_id}
gcloud services enable $(gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)") --project={project_id}
```
*(For a brand-new gateway, run `gcloud api-gateway gateways create {gateway_id} ...` instead of `gateways update`).*
- Run one `api-configs create` at a time per API. Wait for it to finish before you start the next one, because API Gateway creates only one config for an API at a time. A complex API config can take up to ten minutes to create.
- If clients use API keys from other projects, enable the managed service in each of those projects too. API Gateway rejects an API key unless the API is enabled in the project that created the key. For other API key setup, use the `api-gateway-backend-security-and-rate-limiting` skill. If it is not installed, see [Authenticate with API keys](https://docs.cloud.google.com/api-gateway/docs/authenticate-api-keys.md.txt).
4. **Verify the JSON-RPC 2.0 lifecycle and connect ADK / API hub:**
- Send every probe to `https://{default_hostname}/mcp`, even when the spec sets a `servers` base path.
- An HTML `404 Page not found` means that the gateway may not be deployed correctly, or that the last create or update did not finish. Check that the gateway state is `ACTIVE` and that the last create or update finished, and retry before you change the config. During a gateway update, some requests can still reach the previous API config. A JSON 404 (`The current request is not defined by this API.`) means that the active config does not define the path.
- If REST requests return HTTP 401, 403, or 5xx errors, use the `api-gateway-troubleshooting` skill. If it is not installed, use the tables in [MCP Verification and Troubleshooting](references/mcp-limitations-and-troubleshooting.md#json-rpc-and-http-error-diagnosis-on-mcp).
- If `tools/list` requires a JWT, mint a Google ID token whose audience is in `x-google-auth.audiences`: `gcloud auth print-identity-token --impersonate-service-account={caller_sa_email} --audiences={jwt_audience}`. If `tools/list` requires an API key, send it in the `x-api-key` header.
- Run the `initialize`, `notifications/initialized`, `tools/list`, and `tools/call` verification probes in [MCP Verification and Troubleshooting](references/mcp-limitations-and-troubleshooting.md).
- Connect Google ADK (`McpToolset`) and verify automatic catalog discovery in Apigee API hub (`{your_api} (MCP)`) and Agent Registry using [ADK and API Hub Discovery](references/adk-and-api-hub-discovery.md).
## Pre-Deployment Checklist
- [ ] Specification version is `openapi: 3.0.x` or `3.1.x` (not `swagger: "2.0"`), omits `x-google-allow`, and does not contain `x-google-model-router`.
- [ ] `python3 scripts/validate_mcp_openapi.py --spec={candidate_openapi_spec}` returns `status: "PASS"` (exit code `0`).
- [ ] Every operation has an `operationId` and a backend, and all MCP operations are in one OpenAPI document.
- [ ] Each backend sets an explicit `pathTranslation`.
- [ ] `x-google-api-management.mcp.tools-list.security` names exactly one scheme: an `oauth2` JWT scheme with `x-google-auth` that the root `security` list also references, or an `apiKey` scheme with `in: header` and `name: x-api-key`. If it is missing, the user accepts an open `tools/list`. Do not write an empty map (`{}`), because it also leaves `tools/list` open.
- [ ] If `tools/list` uses a JWT scheme, the user knows that REST operations without their own `security` now require that JWT.
- [ ] Administrative, health-check, and `HTTP 204` endpoints are opted out with `x-google-mcp-tool: false`, and opted-out admin paths remain protected on REST.
- [ ] MCP clients call `https://{default_hostname}/mcp` (not `{basepath}/mcp`), nest `tools/call` JSON request bodies inside `params.arguments.body`, and send `MCP-Protocol-Version: 2025-11-25`.
## Resource Cleanup
To avoid ongoing charges when tearing down a test or staging environment, request human approval and delete the gateway, API config, and API in dependency order:
```bash
gcloud api-gateway gateways delete {gateway_id} --location={region} --project={project_id}
gcloud api-gateway api-configs delete {config_id} --api={api_id} --project={project_id}
gcloud api-gateway apis delete {api_id} --project={project_id}
```
Delete the service account only if no other API config or gateway uses it. If you are not sure, ask the user. Then delete it:
```bash
gcloud iam service-accounts delete {gateway_sa_name}@{project_id}.iam.gserviceaccount.com --project={project_id}
```
## Related skills
| Need | Skill |
| :--- | :--- |
| Convert an OpenAPI 2.0 spec to 3.x, write a spec without MCP, or fix an OpenAPI error from `api-configs create` | `api-gateway-openapi-spec-authoring` |
| Set up API keys, JWT, backend lockdown, or quotas, and check quota metrics before `api-configs create` | `api-gateway-backend-security-and-rate-limiting` |
| Find why REST requests through the gateway fail (4xx, 5xx, timeouts) | `api-gateway-troubleshooting` |
| Deploy or change the Cloud Run backend | `cloud-run-basics` |
If an API Gateway skill in this table is not installed, give the user this command to install the four API Gateway skills. Until it is installed, use the fallback in this skill.
```bash
npx skills add google/skills --skill api-gateway-mcp-server --skill api-gateway-backend-security-and-rate-limiting --skill api-gateway-openapi-spec-authoring --skill api-gateway-troubleshooting
```
For another skill in this table, give the user the same command with `--skill {skill_name}`.
adk-and-api-hub-discovery.md 6.6 KB
# Google ADK Integration and API Hub / Agent Registry Discovery Reference
- [Google ADK (McpToolset) Connection to API Gateway](#google-adk-mcptoolset-connection-to-api-gateway): Lines 6-59
- [Automatic Discovery in Apigee API Hub and Agent Registry](#automatic-discovery-in-apigee-api-hub-and-agent-registry): Lines 61-100
## Google ADK (`McpToolset`) Connection to API Gateway
Google's Agent Development Kit (ADK) connects natively to an API Gateway `/mcp` endpoint over `StreamableHTTP` using `McpToolset` and `StreamableHTTPConnectionParams`.
1. Install the Google ADK Python package with the MCP extra, pinned to the 2.x major version:
```bash
pip install "google-adk[mcp]>=2.0.0,<3.0.0"
```
2. Retrieve the gateway's `defaultHostname`:
```bash
gcloud api-gateway gateways describe {gateway_id} \
--location={region} \
--project={project_id} \
--format="value(defaultHostname)"
```
3. Configure `McpToolset` with `StreamableHTTPConnectionParams` pointing to `https://{default_hostname}/mcp` (keep `/mcp` at the host root, even when a `servers` base path such as `/v1` is configured with `x-google-endpoint`). If `tools-list.security` is set, pass its credential: a JWT in `Authorization: Bearer {jwt_token}`, or an API key in `x-api-key`. For `tools/call`, pass the credentials that the underlying REST operation requires:
```python
import os
from google.adk.agents import Agent
from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams
gateway_host = os.environ["APIGW_DEFAULT_HOSTNAME"]
headers = {}
if os.environ.get("APIGW_API_KEY"):
headers["x-api-key"] = os.environ["APIGW_API_KEY"]
if os.environ.get("APIGW_JWT_TOKEN"):
headers["Authorization"] = f"Bearer {os.environ['APIGW_JWT_TOKEN']}"
gateway_mcp_tools = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url=f"https://{gateway_host}/mcp",
headers=headers,
)
)
root_agent = Agent(
model="gemini-3.8-flash", # Use a current Gemini model.
name="order_support_agent",
instruction="Use the API Gateway MCP tools to look up orders and process approved returns.",
tools=[gateway_mcp_tools],
)
```
Google ID tokens are short-lived. For a long-running agent, mint a new token before the old one expires, and give the toolset the new `Authorization` header.
4. **Structure OpenAPI `x-google-mcp-tool` descriptions and schemas for reliable ADK tool calling:**
- Every exposed MCP operation MUST resolve to a non-empty description (`x-google-mcp-tool.description`, operation `description`, or `summary`); operations without a resolvable description are rejected at API config creation time.
- Write `x-google-mcp-tool.description` to state **when and why** the LLM should invoke the tool, not only what data the endpoint returns. Recommendation: name the read tools to call first, if the tool needs their output.
- API Gateway rejects complex nested schemas when you create the API config, but a simple nested object body works. If `gcloud api-gateway api-configs create` fails with a schema error, simplify that schema. Recommendations: prefer shallow request schemas for new tools, give each `requestBody` property a `description`, and check the tool's `inputSchema` in `tools/list` after you deploy. API Gateway does not emit MCP tool annotations (`destructiveHint`, `readOnlyHint`) in Public Preview.
References:
- [Turn your REST APIs into MCP tools with Google Cloud API Gateway](https://developers.googleblog.com/turn-your-rest-apis-into-mcp-tools-with-google-cloud-api-gateway/) (the source of the ADK sample). This post predates the September 30, 2026 release that added API key support for `tools/list`. See the [API Gateway release notes](https://docs.cloud.google.com/api-gateway/docs/release-notes.md.txt).
- [ADK Model Context Protocol tools](https://google.github.io/adk-docs/tools-custom/mcp-tools/)
## Automatic Discovery in Apigee API Hub and Agent Registry
When you connect API Gateway to Apigee API hub, API hub publishes an MCP-enabled gateway as an MCP server with MCP-specific metadata, and the server also appears in **Google Cloud Agent Registry**. These catalogs let developers and agents find MCP servers and their tools without knowing each gateway URL. No separate registration step is needed, so do not write a registration script or upload tool schemas.
1. **Complete the API hub prerequisites:** provision API hub in a host project (`{hub_project_id}`, location `{hub_location}`), and grant the roles that connect API Gateway with API hub, such as `roles/apihub.runTimeProjectAttachmentsEditor` in the API Gateway project. For the steps, see [Connect API Gateway with API hub](https://docs.cloud.google.com/api-gateway/docs/api-hub-connect.md.txt).
2. **Attach the API Gateway project to API hub, and turn on metadata sync** (request human approval first):
```bash
gcloud apihub runtime-project-attachments create {project_id} \
--project={hub_project_id} \
--location={hub_location} \
--runtime-project=projects/{project_id}
gcloud apihub plugins instances create {plugin_instance_id} \
--plugin=system-api-gateway \
--project={hub_project_id} \
--location={hub_location} \
--display-name="API Gateway metadata sync" \
--source-project-id={project_id} \
--actions=actionId=sync-metadata
```
If the project is already attached, these commands return `ALREADY_EXISTS`, and you can continue. In the Google Cloud console, the same steps are in **API hub** > **Settings** > **Project associations** > **Attach runtime project**. If you select to import API Gateway assets when you attach the project in the console, API hub creates the API Gateway plugin instance for real-time metadata ingestion.
3. **Find the MCP server in API hub.** API hub adds a second entry named `{your_api} (MCP)` next to the REST API entry:
```bash
gcloud apihub apis list \
--project={hub_project_id} \
--location={hub_location} \
--filter='displayName~"\(MCP\)$"'
```
4. **Find the MCP server in Agent Registry.** Enable the Agent Registry API, and list the MCP servers in the API hub location. The display name of the entry is `{region}/{gateway_id}`. If the list is empty, run the same command with `--project={project_id}`.
```bash
gcloud services enable agentregistry.googleapis.com --project={hub_project_id}
gcloud agent-registry mcp-servers list \
--project={hub_project_id} \
--location={hub_location}
```
References:
- [Model Context Protocol overview - Discovery through API Hub and Agent Registry](https://docs.cloud.google.com/api-gateway/docs/mcp-overview.md.txt)
- [Connect API Gateway with API hub](https://docs.cloud.google.com/api-gateway/docs/api-hub-connect.md.txt)
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:api-gateway-mcp-server)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include `agent-skills/1.0 (skill:api-gateway-mcp-server)` in the
`User-Agent` header. If a `User-Agent` header is already specified, append
this string to the end of it rather than overwriting existing `User-Agent`
data — the collection pipeline parses the `agent-skills/<version>` and
`skill:<name>` tokens, so any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:api-gateway-mcp-server)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
mcp-limitations-and-troubleshooting.md 11.4 KB
<!-- disableFinding(LINE_OVER_80) -->
# MCP Verification, Limitations, and Troubleshooting Reference
- [MCP Endpoint Verification with curl (JSON-RPC 2.0 Lifecycle)](#mcp-endpoint-verification-with-curl-json-rpc-20-lifecycle): Lines 9-95
- [JSON-RPC and HTTP Error Diagnosis on /mcp](#json-rpc-and-http-error-diagnosis-on-mcp): Lines 97-141
- [Mutual Exclusion with Model Routing and Preview Limits](#mutual-exclusion-with-model-routing-and-preview-limits): Lines 143-158
## MCP Endpoint Verification with `curl` (JSON-RPC 2.0 Lifecycle)
API Gateway exposes MCP over stateless HTTP `POST` at `https://{default_hostname}/mcp`. The `/mcp` path stays at the host root: a `servers` base path set with `x-google-endpoint` (such as `/v2`) applies to REST paths only, and `https://{default_hostname}/{basepath}/mcp` returns HTTP 404. Send the `MCP-Protocol-Version: 2025-11-25` header on every request after `initialize` (if omitted, the gateway falls back to `2025-03-26`).
### 1. Handshake (`initialize`)
`initialize` requires no authentication:
```bash
curl -sS -X POST "https://{default_hostname}/mcp" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "verify-client", "version": "1.0.0"}
}
}'
```
### 2. Acknowledge Handshake (`notifications/initialized`)
The gateway responds with `HTTP 202 Accepted`. Include the `MCP-Protocol-Version: 2025-11-25` header on `notifications/initialized` and on all later requests (`tools/list`, `tools/call`). If the header is omitted, API Gateway falls back to protocol version `2025-03-26`:
```bash
curl -i -sS -X POST "https://{default_hostname}/mcp" \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-11-25" \
-d '{"jsonrpc": "2.0", "method": "notifications/initialized"}'
```
### 3. Discover Tools (`tools/list`)
Include `Authorization: Bearer <token>` when `x-google-api-management.mcp.tools-list.security` names a JWT scheme, or `x-api-key: {api_key}` when it names an API key scheme (`tools/list` does not read API keys from query parameters).
For a test token, mint a Google ID token for a caller service account (you need `roles/iam.serviceAccountTokenCreator` on `{caller_sa_email}`). The token audience must be in the `x-google-auth.audiences` list of the JWT scheme in the API config's OpenAPI spec. If you do not have the spec file, print the spec of the config that the gateway serves:
```bash
config_id="$(gcloud api-gateway gateways describe {gateway_id} \
--location={region} --project={project_id} \
--format="value(apiConfig.basename())")"
gcloud api-gateway api-configs describe "${config_id}" \
--api={api_id} --project={project_id} --view=FULL \
--format="value(openapiDocuments[0].document.contents)" \
| tr '_-' '/+' | base64 --decode
```
Then mint the token and list the tools:
```bash
jwt_token="$(gcloud auth print-identity-token \
--impersonate-service-account={caller_sa_email} \
--audiences={jwt_audience})"
curl -sS -X POST "https://{default_hostname}/mcp" \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-11-25" \
-H "Authorization: Bearer ${jwt_token}" \
-d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}'
```
### 4. Invoke a Tool (`tools/call`)
Include the credentials required by the underlying REST operation (`x-api-key` and/or `Authorization: Bearer <token>`), and nest any JSON request body inside `arguments.body`:
```bash
curl -sS -X POST "https://{default_hostname}/mcp" \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-11-25" \
-H "x-api-key: {api_key}" \
-H "Authorization: Bearer ${jwt_token}" \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_order_status",
"arguments": {"orderId": "ORD-10042"}
}
}'
```
Reference: [Configure Model Context Protocol - Verify MCP support](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt)
## JSON-RPC and HTTP Error Diagnosis on `/mcp`
Most MCP errors return `HTTP 200` with a JSON-RPC `error` object, because many MCP clients fail at the HTTP transport layer on a non-200 response. The exceptions are `400`, `401`, `403`, `404`, `405`, and `413`. Check both the HTTP status and the JSON-RPC `error` field, then find the symptom in the tables below.
### Connection and routing
| What you see | Cause | Fix |
| --- | --- | --- |
| HTTP `404` with an HTML `Page not found` page | The gateway may not be deployed correctly, or a gateway create or update has not finished. | Check that the gateway state is `ACTIVE` (`gcloud api-gateway gateways describe {gateway_id} --location={region} --project={project_id}`) and that the last operation finished. During an update, some requests can still reach the previous API config, so retry for a few minutes before you change the config. If the 404 does not go away, compare the gateway `apiConfig` with the config that you deployed. |
| HTTP `404` with the JSON message `The current request is not defined by this API.` | The request went to `{basepath}/mcp`, or the active API config does not enable MCP. | Send requests to `https://{default_hostname}/mcp` at the host root, and check that the deployed spec has `x-google-api-management.mcp`. |
| HTTP `405` `Method Not Allowed` | The client sent `GET` or `OPTIONS` to `/mcp`. | Send HTTP `POST` only. The gateway has no SSE `GET` stream and does not handle CORS preflight (`OPTIONS`) on `/mcp`. |
| HTTP `413` (transport body too large) | The raw HTTP request body is larger than the gateway transport limit. | Send a smaller request. |
### Authentication
| What you see | Cause | Fix |
| --- | --- | --- |
| HTTP `401` or `403`, JSON-RPC `-32000` `Tool list response is invalid or has error status code.` (JWT scheme on `tools/list`) | `401`: the JWT is missing or malformed. `403`: the JWT has a wrong audience. The message does not name the cause. Today every failed `tools/list` request with a JWT scheme returns this code and message. Both can change, so check the HTTP status first. | Send `Authorization: Bearer <token>` with an audience from `x-google-auth.audiences`. The `WWW-Authenticate` header points at the protected resource metadata. |
| HTTP `401` or `200`, JSON-RPC `-32000` with a message such as `Method doesn't allow unregistered callers` or `API key not valid` (API key scheme on `tools/list`) | `401`: the API key is missing, or the client sent it only as a query parameter. `200`: the API key is not valid. The code, the messages, and the HTTP `200` are today's behavior and can change. | Send a valid key in the `x-api-key` header. Because an invalid key returns HTTP `200`, check the JSON-RPC `error` field as well as the HTTP status. |
These rows cover `tools/list` only. If REST requests to the gateway return HTTP `401` or `403`, use the `api-gateway-troubleshooting` skill. If it is not installed, check that the request sends the credentials that the `security` of the operation requires.
### Protocol
| What you see | Cause | Fix |
| --- | --- | --- |
| HTTP `400`, JSON-RPC `-32700` (parse error) | The request body is not valid JSON. | Send valid JSON. |
| HTTP `200`, JSON-RPC `-32600` (invalid request) | The body is valid JSON but not a valid JSON-RPC request. | Set the required fields `jsonrpc`, `method`, and `id`. |
| HTTP `200`, JSON-RPC `-32601` `Method ... is not supported` | The client called a method that the gateway does not support, such as `resources/*`, `prompts/*`, `sampling/*`, `completion/*`, or `logging/*`. | Use only `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call`. |
| HTTP `400`, JSON-RPC `-32602` `Unsupported protocol version` | A request after `initialize` sent an `MCP-Protocol-Version` header that the gateway does not support. `initialize` itself does not fail on an unknown `protocolVersion`: the gateway answers with `2025-11-25`. | Send `MCP-Protocol-Version: 2025-11-25`. |
| HTTP `200`, JSON-RPC `-32602` `Missing valid protocolVersion in initialize request` | The `initialize` params omit `protocolVersion`, or its value is not a string. | Send `"protocolVersion": "2025-11-25"` in the `initialize` params. |
### Tool calls
| What you see | Cause | Fix |
| --- | --- | --- |
| HTTP `200`, JSON-RPC `-32602` (unknown tool) | `params.name` does not match an exposed tool in the active API config, or the operation is opted out with `x-google-mcp-tool: false`. | Run `tools/list` again, and call a listed tool name. |
| HTTP `200`, JSON-RPC `-32602` (invalid tool arguments) | `params.arguments` misses required parameters, or the JSON request body is not nested inside `"body": { ... }`. | Pass path and query parameters as top-level arguments, and nest the request body under `arguments.body`. |
| HTTP `200`, `result.isError: true` | The backend returned a 4xx or 5xx error. | Read `result.content[0].text` for the backend's error body, and fix the request or the backend. |
| HTTP `200`, JSON-RPC `-32000` (body too large) | The backend response is larger than the size limit. | Return a smaller response, for example with paging. |
| HTTP `200`, JSON-RPC `-32000` `Server error` | An internal gateway error. It is not a backend error: backend errors return `result.isError: true`. | Retry. If the error continues, contact Cloud Customer Care. |
If a backend error in `result.isError` also occurs on REST requests, or REST requests return HTTP `5xx` errors, use the `api-gateway-troubleshooting` skill. If it is not installed, read the backend error body in `result.content[0].text` and the backend logs.
Reference: [Configure Model Context Protocol - Troubleshooting MCP failures](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt)
## Mutual Exclusion with Model Routing and Preview Limits
- **Model Routing mutual exclusion:** NEVER set `x-google-api-management.mcp` and use `x-google-model-router` on an operation in the same OpenAPI specification. Model routers are defined in `x-google-api-management.ai.models.routing`. **Rationale:** API Gateway does not allow MCP and Model Routing in the same API config. If you need both an inbound `/mcp` server and an outbound LLM model router, deploy two separate API configs and gateways.
- **Stateless UTF-8 text only:** Session headers (`MCP-Session-Id`), SSE streaming, binary/multi-modal responses (such as raw PDF or image downloads; return a UTF-8 JSON object with a signed URL or opt out binary endpoints with `x-google-mcp-tool: false`), and empty `HTTP 204` responses are not supported in Public Preview.
- **Other Public Preview limits:**
- JSON-RPC batch arrays are rejected. Send one JSON-RPC request in each HTTP `POST`.
- The stdio transport is not supported. Clients connect over HTTP `POST` only.
- OpenAPI 2.0 is not supported. Use OpenAPI 3.0.x or 3.1.x.
- A gateway serves at most 1,000 MCP tools.
- Tool declarations do not include annotations such as `destructiveHint` or `readOnlyHint`.
- API Gateway rejects complex nested schemas when you create the API config. A simple nested object body works.
- In OpenAPI 3.1, each schema needs one `type`. A type list such as `type: ["string", "null"]` fails config creation with `Schema has multiple types defined. More than one type is not supported, please define only one type.`
References:
- [Model Context Protocol overview - Limitations](https://docs.cloud.google.com/api-gateway/docs/mcp-overview.md.txt)
- [OpenAPI 3.x feature limitations - MCP limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)
openapi-agent-tool-optimizer.md 5.5 KB
# OpenAPI Agent Tool Optimizer Reference
- [High-Accuracy Tool Descriptions](#high-accuracy-tool-descriptions): Lines 7-24
- [Schema Rendering and OpenAPI 3.x MCP Limits](#schema-rendering-and-openapi-3x-mcp-limits): Lines 26-39
- [Chatty CRUD and Destructive Endpoint Rules](#chatty-crud-and-destructive-endpoint-rules): Lines 41-45
## High-Accuracy Tool Descriptions
Every exposed MCP operation MUST resolve to a non-empty description (taken from `x-google-mcp-tool.description`, the operation `description`, or `summary`); operations without a resolvable description are rejected by API Gateway when creating the API config. The tool description is the primary signal an LLM uses for tool selection. Standard OpenAPI summaries ("Gets an order", "Creates an RMA") describe *what* an endpoint returns, but omit *when* and *why* an agent should call it.
Use `x-google-mcp-tool.description` on each exposed operation to set the LLM-facing description. The operation's own `description` stays unchanged for REST documentation:
1. **State the trigger condition ("Use this tool when..."):** Specify the exact user intent or prerequisite state that requires calling this tool.
2. **Specify ordering dependencies:** If a write tool (`create_return_rma`) requires an identifier (`itemSku`) returned by a read tool (`get_order_status`), instruct the agent in `x-google-mcp-tool.description` to call the read tool first whenever that identifier is unknown.
3. **Document parameter formats inline:** Add concrete format examples (`ORD-XXXXX`, ISO-8601 dates, allowed `enum` values) to each parameter's `description` field so the model formats arguments accurately on the first attempt.
```yaml
x-google-mcp-tool:
name: create_return_rma
description: >-
Create a Return Merchandise Authorization (RMA) and generate a prepaid return label for a delivered order.
Use this tool when a customer asks to return or replace an item.
Call get_order_status first if you do not yet know the itemSku or if you have not verified that the order status is DELIVERED.
```
## Schema Rendering and OpenAPI 3.x MCP Limits
API Gateway enforces specific schema and payload rules when generating MCP tool declarations from an OpenAPI 3.x specification:
| Constraint | API Gateway MCP Behavior | Required OpenAPI Refactoring |
| --- | --- | --- |
| Nested object schemas | API Gateway rejects complex nested schemas when you create the API config. A simple nested object body works. | Prefer shallow request schemas for new tools. If `gcloud api-gateway api-configs create` fails with a schema error, simplify that schema. Add a `description` with the expected format to each property, and check the tool's `inputSchema` in `tools/list` after you deploy. |
| Request parameter types | API Gateway supports only primitive types in request parameters. | Use primitive types (`string`, `integer`, `number`, `boolean`) for path, query, and header parameters of a tool. Otherwise, set `x-google-mcp-tool: false` on the operation. |
| Empty response bodies (`HTTP 204`) | Operations that return empty response bodies (such as `204 No Content`) are NOT supported as MCP tools. | Update the backend and OpenAPI `responses` block to return `200 OK` with a JSON confirmation object (for example, `{"deleted": true, "id": "..."}`), or set `x-google-mcp-tool: false` on `204` endpoints. |
| External `$ref` references and file limits | External `$ref` URLs are rejected. API Gateway rejects a YAML alias to a mapping or a sequence. Uploaded OpenAPI 3.x files are limited to `10 MB` total and `50` files. | Inline external `$ref` definitions into local `#/components/schemas/`. Do not use a YAML alias to a mapping or a sequence. Write out the content in full. |
| Tool count limit | Maximum of `1,000` MCP tools per gateway. | Expose only curated, task-oriented operations rather than every raw database table route. |
| Supported HTTP methods | Only `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` can be exposed as MCP tools. `HEAD`, `OPTIONS`, and `TRACE` are not supported. | Global MCP enablement does not expose `HEAD`, `OPTIONS`, or `TRACE` operations. Do not set `x-google-mcp-tool` to `true` or an object on them: the validator reports an error. |
Reference: [OpenAPI 3.x feature limitations - MCP limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)
## Chatty CRUD and Destructive Endpoint Rules
1. **Opt out internal and administrative routes:** When `x-google-api-management.mcp` is set to `true` (or configured as an object for `tools-list`), every eligible `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` operation in the specification becomes an MCP tool by default. Explicitly set `x-google-mcp-tool: false` on health checks (`/healthz`), metrics endpoints, bulk-delete operations, and internal admin routes.
2. **Keep REST security on opted-out routes:** NEVER rely on `x-google-mcp-tool: false` to secure an administrative operation. **Rationale:** Setting `x-google-mcp-tool: false` only omits the operation from MCP `tools/list` and blocks `tools/call`, while the underlying REST path remains live on the gateway hostname unless protected by a strict `security` requirement or removed from the OpenAPI specification.
3. **Warn on destructive tools:** Because API Gateway does not emit `destructiveHint` or `readOnlyHint` annotations in Public Preview, include an explicit warning in `x-google-mcp-tool.description` on any `DELETE` or `PUT` operation that remains exposed (for example, *"Permanently deletes the resource. Call only after explicit user confirmation."*).
openapi-v2-to-v3-mcp-migration.md 17.2 KB
<!-- disableFinding(LINE_OVER_80) -->
# OpenAPI 2.0 to 3.x Migration and MCP Extension Reference
- [Why OpenAPI 3.x Is Required for MCP](#why-openapi-3x-is-required-for-mcp): Lines 13-20
- [General OpenAPI 2.0 to 3.x Conversion](#general-openapi-20-to-3x-conversion): Lines 22-45
- [Swagger 2.0 Construct Conversion Map](#swagger-20-construct-conversion-map): Lines 47-61
- [Configuration of x-google-api-management.mcp and x-google-mcp-tool](#configuration-of-x-google-api-managementmcp-and-x-google-mcp-tool): Lines 63-141
- [Tool Discovery Security (tools/list) vs Tool Calls (tools/call)](#tool-discovery-security-toolslist-vs-tool-calls-toolscall): Lines 143-149
- [How MCP tools/call Arguments Map to REST Requests](#how-mcp-toolscall-arguments-map-to-rest-requests): Lines 151-157
- [Complete Converted Example](#complete-converted-example): Lines 159-259
## Why OpenAPI 3.x Is Required for MCP
Model Context Protocol (MCP) support in Google Cloud API Gateway (Public Preview) requires an OpenAPI 3.x specification: OpenAPI 3.0.x or 3.1.x. The examples in this reference use `openapi: 3.0.4`.
- NEVER add `x-google-api-management.mcp` or `x-google-mcp-tool` to an OpenAPI 2.0 (`swagger: "2.0"`) specification. **Rationale:** MCP is not supported for OpenAPI 2.0, and the MCP extensions are defined only for OpenAPI 3.x.
- If an existing gateway runs an OpenAPI 2.0 specification, start from the spec file in the user's repository. If there is no file, find the active config ID with `gcloud api-gateway gateways describe {gateway_id} --location={region} --project={project_id} --format="value(apiConfig.basename())"`, and print its spec with `gcloud api-gateway api-configs describe {config_id} --api={api_id} --project={project_id} --view=FULL --format=json | python3 -c 'import base64,json,sys; [print(base64.urlsafe_b64decode(d["document"]["contents"]).decode()) for d in json.load(sys.stdin)["openapiDocuments"]]'`. gcloud prints the contents as URL-safe base64, so `base64.b64decode` can silently corrupt the spec. Then convert it as [General OpenAPI 2.0 to 3.x Conversion](#general-openapi-20-to-3x-conversion) describes, apply the [Swagger 2.0 Construct Conversion Map](#swagger-20-construct-conversion-map), and compare your result with the [Complete Converted Example](#complete-converted-example).
References: [Supported OpenAPI versions](https://docs.cloud.google.com/api-gateway/docs/openapi-overview.md.txt) and [Modify a gateway to use OpenAPI 3.x](https://docs.cloud.google.com/api-gateway/docs/migrate-oasv3.md.txt)
## General OpenAPI 2.0 to 3.x Conversion
For the general conversion (standard fields, backends, JWT settings, quotas, endpoints, and the API name), use the `api-gateway-openapi-spec-authoring` skill. Then add the MCP settings in this reference. If that skill is not installed, use the [General Conversion Fallback](#general-conversion-fallback).
MCP has no OpenAPI 2.0 form. In OpenAPI 3.x, enable it with `x-google-api-management.mcp` at the root, and customize or opt out each operation with `x-google-mcp-tool`. See [Configuration of x-google-api-management.mcp and x-google-mcp-tool](#configuration-of-x-google-api-managementmcp-and-x-google-mcp-tool).
### General Conversion Fallback
Standard OpenAPI 2.0 to 3.0 converters change the standard fields (`swagger` to `openapi`, `securityDefinitions` to `components.securitySchemes`), but they keep the Google extensions in their OpenAPI 2.0 form. API Gateway rejects these OpenAPI 2.0 extensions in a 3.x spec. Replace or remove each of them:
- `x-google-management`
- `x-google-endpoints`
- `x-google-api-name`
- `x-google-allow`
- `x-google-issuer`, `x-google-jwks_uri`, and `x-google-audiences` on a security scheme
- `x-google-backend` as an inline object
- `x-google-jwt-locations` on a security scheme
In OpenAPI 3.x, `x-google-backend` is a string that names a backend in `x-google-api-management.backends`. JWT settings, including `jwtLocations`, go in `x-google-auth` on the security scheme. Put `x-google-quota` on each operation, because API Gateway ignores it at the root or on a path item. Use `x-google-parameter: {pattern: "**"}` on a path parameter, not `{name=**}` in the path.
For the 3.x form of each extension, read these pages:
- [Modify a gateway to use OpenAPI 3.x](https://docs.cloud.google.com/api-gateway/docs/migrate-oasv3.md.txt)
- [OpenAPI 3.x extensions in API Gateway](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)
## Swagger 2.0 Construct Conversion Map
Convert these Swagger 2.0 constructs as shown for MCP. For the other constructs, see [General OpenAPI 2.0 to 3.x Conversion](#general-openapi-20-to-3x-conversion). Where a row says to ask the user, the choice belongs to the user.
| Swagger 2.0 construct | OpenAPI 3.x for API Gateway MCP |
| --- | --- |
| `basePath: /v2` (with or without `host`) | `servers: [{url: /v2, x-google-endpoint: {}}]`. If the API has a managed service that you chose, and not the default `*.apigateway.{project_id}.cloud.goog` service, use `url: https://{managed_service}/v2`, because a relative URL then fails with `Service name must be provided either explicitly or in OpenAPI 'host' value.` REST paths stay under `/v2`. MCP stays at `https://{default_hostname}/mcp`. |
| `consumes` / `produces` | Use `application/json` in `requestBody.content` and `responses.content` for tool operations: `tools/call` sends the request body as JSON in `arguments.body`, and tool responses are limited to UTF-8 text. |
| `in: formData` (`application/x-www-form-urlencoded`) | `requestBody` with that media type. Recommendation: set `x-google-mcp-tool: false`, because MCP clients pass the request body as JSON in `arguments.body`. |
| `type: file` (file upload) | `requestBody` with `multipart/form-data` and a `type: string, format: binary` property. Recommendation: set `x-google-mcp-tool: false`, because MCP tool arguments are JSON values. |
| `collectionFormat` array parameter | API Gateway supports only primitive types in request parameters. Ask the user: keep the array for REST and set `x-google-mcp-tool: false`, or change the parameter to a primitive type (such as a comma-separated `string`) that the backend accepts. |
| `deprecated: true` operation | Keep it for REST. Ask the user before you expose it as a tool, because agents can start to depend on it. |
| Operation with only `4xx` responses | Add the success response that the backend returns, with its JSON schema. Tools cannot return an empty body (`HTTP 204`). |
| `DELETE` or other destructive operation | Ask the user before you expose it. If you expose it, warn in the tool description, because API Gateway does not emit `destructiveHint` annotations. |
| No `security` | Add the scheme that the user asks for to `x-google-api-management.mcp.tools-list.security`. If it is a JWT scheme, also list it in the root `security`. See [Complete Converted Example](#complete-converted-example). |
## Configuration of `x-google-api-management.mcp` and `x-google-mcp-tool`
You can enable MCP globally at the document root (`x-google-api-management.mcp: true` or object form) and customize or opt out individual operations using `x-google-mcp-tool` at the operation level.
- Place `x-google-mcp-tool` ONLY on individual HTTP operation objects (`get`, `post`, `put`, `patch`, `delete`). NEVER place `x-google-mcp-tool` at the path item level. **Rationale:** API Gateway rejects specifications that declare `x-google-mcp-tool` at the path level.
- Every operation MUST have an `operationId`, with or without MCP. **Rationale:** API Gateway rejects an API config that has an operation without an `operationId`.
- Every operation MUST have a backend (`x-google-backend` at the root or operation level), also an operation with `x-google-mcp-tool: false`. **Rationale:** API Gateway rejects the API config with `operation name (normalized) ... has no backend configured at the operation or API level`.
- Set an explicit `pathTranslation` on each backend. In a migration, keep the OpenAPI 2.0 behavior: `APPEND_PATH_TO_ADDRESS` for a root backend, and `CONSTANT_ADDRESS` for an operation-level backend. `APPEND_PATH_TO_ADDRESS` appends the request path to the address. `CONSTANT_ADDRESS` sends every request to the address and sends path parameters as query parameters. For a new spec, if you do not know which value the backend expects, ask the user.
- Every exposed operation MUST also have a unique tool name that matches `[A-Za-z0-9_.-]{1,128}` (`x-google-mcp-tool.name`, or else the `operationId`), and a non-empty description (`x-google-mcp-tool.description`, operation `description`, or `summary`).
- Keep all MCP operations in one OpenAPI document. **Rationale:** If only one document of the API config has MCP extensions, only its operations become tools. API Gateway fails to create an API config that has MCP extensions in more than one OpenAPI document, and the error does not say why.
```yaml
openapi: 3.0.4
info:
title: Orders API
version: 1.0.0
x-google-api-management:
mcp:
tools-list:
security:
agent_jwt: []
backends:
orders-backend:
address: https://{backend_service}-{hash}.a.run.app
jwtAudience: https://{backend_service}-{hash}.a.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
x-google-backend: orders-backend
components:
securitySchemes:
api_key:
type: apiKey
name: x-api-key
in: header
agent_jwt:
type: oauth2
flows:
implicit:
authorizationUrl: ""
scopes: {}
x-google-auth:
issuer: "https://accounts.google.com"
jwksUri: "https://www.googleapis.com/oauth2/v3/certs"
audiences:
- "{oauth_client_id}"
security:
- api_key: []
agent_jwt: []
paths:
/v1/orders/{orderId}:
get:
operationId: getOrderStatus
summary: Get order status
description: Returns fulfillment status, carrier tracking number, and ETA for an order.
x-google-mcp-tool:
name: get_order_status
description: >-
Look up the fulfillment status, carrier tracking number, and delivery ETA for a customer order.
Call this tool when the user asks where an order is or needs the SKU before creating a return.
parameters:
- name: orderId
in: path
required: true
schema:
type: string
responses:
"200":
description: Order details
/v1/admin/orders/purge:
delete:
operationId: purgeOrders
summary: Purge archived orders
description: Administrative operation to purge archived order records.
x-google-mcp-tool: false
responses:
"200":
description: Purge status
```
Reference: [Configure Model Context Protocol](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt)
## Tool Discovery Security (`tools/list`) vs Tool Calls (`tools/call`)
| MCP Method | Default Security | How to Configure | Critical Constraint |
| --- | --- | --- | --- |
| `initialize` and `notifications/initialized` | Unauthenticated | No configuration | These protocol lifecycle methods are always unauthenticated. |
| `tools/list` | Unauthenticated by default, also with an empty `tools-list.security` map (`{}`) | `x-google-api-management.mcp.tools-list.security` (+ the same scheme in the root `security` list for a JWT scheme) | Must reference **exactly one** scheme in `components.securitySchemes`: a JWT scheme (`oauth2` with `x-google-auth`) or an API key scheme (`apiKey`). For a JWT scheme, the root `security` list MUST also reference it (API Gateway rejects the config otherwise), and that root entry also requires the JWT on every REST operation without its own `security`. If the root list has an API key scheme, put the JWT in the same requirement object (AND). API Gateway rejects alternative (OR) requirements in which only some alternatives have the API key. For an API key scheme, use `in: header` and `name: x-api-key`, because `tools/list` reads API keys only from the `x-api-key` header. Configuring `mcp` as an object also enables MCP globally for all eligible operations. |
| `tools/call` | Inherits the operation's `security` requirement | Operation or root `security` block (`apiKey` and/or `oauth2` JWT) | Shares the exact same authentication and `x-google-quota` allocation as direct REST calls to that operation. |
## How MCP `tools/call` Arguments Map to REST Requests
When an MCP client invokes `tools/call`, API Gateway synthesizes the tool's `inputSchema` and maps `params.arguments` into the outbound HTTP REST request as follows:
1. **Path and query parameters (`in: path`, `in: query`):** Become top-level properties inside `params.arguments`, keyed by their exact OpenAPI parameter `name` (for example, `"arguments": {"orderId": "ORD-10042"}`).
2. **JSON request body (`requestBody`):** Nested under a single top-level property named `body` inside `params.arguments` (for example, `"arguments": {"orderId": "ORD-10042", "body": {"itemSku": "SKU-1", "reason": "DEFECTIVE"}}`). Passing body fields at the top level of `arguments` without the `body` wrapper fails validation with JSON-RPC error `-32602` (`Invalid tool arguments`).
3. **Header parameters (`in: header`):** Become top-level properties inside `params.arguments` and are injected as HTTP headers on the backend call. You cannot bind parameters to reserved system headers or headers starting with `x-google-`.
## Complete Converted Example
This example is a Swagger 2.0 API with `basePath: /v2`, a root `x-google-backend`, a `GET`, a `POST` with a body, and a `DELETE`, converted for MCP. To list or call tools, a caller needs a valid Google ID token whose audience is `{jwt_audience}`.
```yaml
openapi: 3.0.4
info:
title: Petstore API
version: 1.4.0
servers:
- url: /v2
x-google-endpoint: {}
x-google-api-management:
mcp:
tools-list:
security:
google_id_token: []
backends:
petstore-backend:
address: https://{backend_service}-{project_number}.{region}.run.app
jwtAudience: https://{backend_service}-{project_number}.{region}.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
x-google-backend: petstore-backend
security:
- google_id_token: []
components:
securitySchemes:
google_id_token:
type: oauth2
flows:
implicit:
authorizationUrl: ""
scopes: {}
x-google-auth:
issuer: https://accounts.google.com
jwksUri: https://www.googleapis.com/oauth2/v3/certs
audiences:
- "{jwt_audience}"
schemas:
Pet:
type: object
required: [name]
properties:
id: {type: integer, format: int64}
name: {type: string, description: 'Pet name, for example "Buddy".'}
status: {type: string, enum: [available, pending, sold]}
paths:
/pet/{petId}:
get:
operationId: getPetById
summary: Find pet by ID
x-google-mcp-tool:
name: get_pet
description: >-
Get one pet by its numeric ID. Use this when the user asks about a specific pet.
parameters:
- {name: petId, in: path, required: true, schema: {type: integer, format: int64}}
responses:
"200":
description: The pet
content:
application/json:
schema: {$ref: '#/components/schemas/Pet'}
delete:
operationId: deletePet
summary: Delete a pet
x-google-mcp-tool: false
parameters:
- {name: petId, in: path, required: true, schema: {type: integer, format: int64}}
responses:
"200":
description: The pet was deleted
/pet:
post:
operationId: addPet
summary: Add a new pet to the store
x-google-mcp-tool:
name: add_pet
description: >-
Add a new pet to the store catalog. Use this when the user wants to list a new pet for sale.
requestBody:
required: true
content:
application/json:
schema: {$ref: '#/components/schemas/Pet'}
responses:
"200":
description: The created pet
content:
application/json:
schema: {$ref: '#/components/schemas/Pet'}
```
Values to fill in:
- `{jwt_audience}`: the audience that callers request when they mint a token, such as `https://{managed_service}`. Get `{managed_service}` with `gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)"`. Do not use an IP address or an internal address, because API Gateway does not accept them in the `aud` claim. A caller gets a matching token with `gcloud auth print-identity-token --impersonate-service-account={caller_sa_email} --audiences={jwt_audience}`. The token has `iss: https://accounts.google.com` and `aud: {jwt_audience}`.
- API Gateway checks the token claims against the scheme. It does not check the IAM permissions that you granted to the caller's service account. A Google ID token scheme accepts every caller that can get a Google ID token with this audience. To accept only one service account, check the `email` claim in the backend (API Gateway forwards the JWT payload in the `X-Apigateway-Api-Userinfo` header), or use a self-signed JWT with `issuer` set to the service account email.
References:
- [Using Google ID tokens to authenticate users](https://docs.cloud.google.com/api-gateway/docs/authenticating-users-googleid.md.txt)
- [Authentication between services](https://docs.cloud.google.com/api-gateway/docs/authenticate-service-account.md.txt)
validate_mcp_openapi.py 22.1 KB
#!/usr/bin/env python3
"""Validates an OpenAPI spec against Google Cloud API Gateway MCP rules.
Errors are rules that the API Gateway documentation states. Warnings are
documented limits that need a decision from the user.
The script checks that the specification uses OpenAPI 3.0.x or 3.1.x, omits
x-google-allow, gives each schema one type, declares
x-google-api-management.backends, references only
defined backends, uses at most one server with x-google-endpoint, gives every
operation an operationId, and places x-google-mcp-tool only at the operation
level. It checks that an MCP
specification has no x-google-model-router operation, and that each exposed
tool has a backend, a unique name that matches [A-Za-z0-9_.-]{1,128}, a
non-empty description, and no header parameter with the reserved x-google-
prefix. It checks that tools-list.security names exactly one JWT or API key
scheme, that a JWT scheme is also in the root security list, and that no
security list gives alternative (OR) requirements with an API key scheme in
only some of them.
It warns about HTTP 204 responses, request parameters that are not primitive
types, API key schemes that are not read from the x-api-key header, the
OpenAPI 2.0 x-google-management extension, a model routing "ai" block in an
MCP specification, operations that an mcp object exposes by default, and
operations that global MCP enablement skips because they have no backend.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from typing import Any
try:
import yaml
_HAS_YAML = True
except ImportError:
_HAS_YAML = False
_TOOL_NAME_RE = re.compile(r'^[A-Za-z0-9_.-]{1,128}$')
_OAS3_RE = re.compile(r'^3\.[01]\.\d+$')
_HTTP_METHODS = frozenset(
{'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'}
)
_SUPPORTED_MCP_METHODS = frozenset({'get', 'post', 'put', 'patch', 'delete'})
_MAX_TOOLS_PER_GATEWAY = 1000
# Keys whose values are data, not schemas. A "type" list inside them is not a
# schema type list. The check also skips vendor extensions (x-*).
_NON_SCHEMA_KEYS = frozenset(
{'const', 'default', 'enum', 'example', 'examples'}
)
def _load_spec(path: str) -> dict[str, Any]:
"""Reads the OpenAPI specification file at path as JSON or YAML."""
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
try:
data = json.loads(content)
except json.JSONDecodeError:
pass
else:
if isinstance(data, dict):
return data
if not _HAS_YAML:
raise RuntimeError(
'PyYAML is required to parse YAML files. Install with: '
'pip install "PyYAML>=6.0,<7.0"'
)
try:
data = yaml.safe_load(content)
except yaml.YAMLError as exc:
raise ValueError(f'{path} is not valid JSON or YAML: {exc}') from exc
if not isinstance(data, dict):
raise ValueError(f'{path} did not parse as a YAML/JSON mapping.')
return data
def _resolve(spec: dict[str, Any], obj: Any) -> Any:
"""Follows local '#/...' $ref pointers. Returns obj if it cannot resolve."""
seen: set[str] = set()
while isinstance(obj, dict) and isinstance(obj.get('$ref'), str):
reference = obj['$ref']
if not reference.startswith('#/') or reference in seen:
return obj
seen.add(reference)
target: Any = spec
for part in reference[2:].split('/'):
part = part.replace('~1', '/').replace('~0', '~')
if not isinstance(target, dict) or part not in target:
return obj
target = target[part]
obj = target
return obj
def _requirement_names(security: Any) -> list[set[str]]:
"""Returns the scheme names of each non-empty security requirement."""
if not isinstance(security, list):
return []
return [
{str(name) for name in requirement}
for requirement in security
if isinstance(requirement, dict) and requirement
]
def _or_with_api_key_error(
security: Any, schemes: dict[str, Any], where: str
) -> str | None:
"""Returns an error if only some OR requirements of a list use an API key.
Args:
security: The value of a "security" list.
schemes: The security schemes from components.securitySchemes.
where: The location of the "security" list, for the error message.
Returns:
The error message, or None if the security list is valid.
"""
requirements = _requirement_names(security)
with_api_key = 0
for requirement in requirements:
if any(
isinstance(schemes.get(name), dict)
and schemes[name].get('type') == 'apiKey'
for name in requirement
):
with_api_key += 1
if 0 < with_api_key < len(requirements):
return (
f'The "security" list of {where} gives alternative (OR)'
' requirements, and only some of them use an API key scheme. API'
' Gateway supports OR requirements with an API key only if every'
' alternative has one. Put the API key in every alternative.'
)
return None
def _type_list_schemas(node: Any, location: str) -> list[tuple[str, str]]:
"""Finds the schemas whose "type" is a list of more than one type.
API Gateway rejects such a schema, for example `type: ["string", "null"]`,
when you create the API config.
Args:
node: A part of the OpenAPI specification.
location: The JSON pointer of node in the specification.
Returns:
The JSON pointer and the type list of each schema with more than one type.
"""
found: list[tuple[str, str]] = []
if isinstance(node, dict):
node_type = node.get('type')
if isinstance(node_type, list) and len(node_type) > 1:
found.append((location or '/', json.dumps(node_type)))
for key, value in node.items():
key_text = str(key)
if key_text in _NON_SCHEMA_KEYS or key_text.startswith('x-'):
continue
escaped_key = key_text.replace('~', '~0').replace('/', '~1')
found.extend(_type_list_schemas(value, f'{location}/{escaped_key}'))
elif isinstance(node, list):
for index, item in enumerate(node):
found.extend(_type_list_schemas(item, f'{location}/{index}'))
return found
def validate_mcp_spec(
spec: dict[str, Any],
) -> tuple[list[str], list[str], list[dict[str, str]]]:
"""Returns (errors, warnings, exposed_tools) for an OpenAPI spec."""
errors: list[str] = []
warnings: list[str] = []
exposed_tools: list[dict[str, str]] = []
openapi_version = str(spec.get('openapi', ''))
if 'swagger' in spec:
errors.append(
'OpenAPI 2.0 (swagger: "2.0") is not supported for API Gateway MCP.'
' Convert the specification to OpenAPI 3.0.x or 3.1.x (for example,'
' openapi: 3.0.4).'
)
elif not _OAS3_RE.match(openapi_version):
errors.append(
'Expected openapi version 3.0.x or 3.1.x (for example, 3.0.4 or'
f' 3.1.0), got "{openapi_version}".'
)
if 'x-google-allow' in spec:
errors.append(
'Extension "x-google-allow" is not supported in OpenAPI 3.x and must '
'be removed.'
)
for location, type_list in _type_list_schemas(spec, ''):
errors.append(
f'The schema at {location} has more than one type ({type_list}). API'
' Gateway rejects a type list when you create the API config. Give the'
' schema one type.'
)
if 'x-google-management' in spec:
warnings.append(
'Found the OpenAPI 2.0 extension "x-google-management". In OpenAPI'
' 3.x, move the metrics and quota settings into'
' "x-google-api-management".'
)
servers = spec.get('servers', [])
if isinstance(servers, list):
endpoint_count = sum(
1
for server in servers
if isinstance(server, dict) and 'x-google-endpoint' in server
)
if endpoint_count > 1:
errors.append(
f'Found {endpoint_count} servers with "x-google-endpoint"; API'
' Gateway permits at most one server with x-google-endpoint.'
)
management = spec.get('x-google-api-management')
if not isinstance(management, dict):
errors.append('Missing required root "x-google-api-management" mapping.')
return errors, warnings, exposed_tools
backends = management.get('backends')
backend_names: set[str] = set()
if not isinstance(backends, dict) or not backends:
errors.append(
'"x-google-api-management.backends" must define at least one named'
' backend.'
)
else:
for backend_name, backend_config in backends.items():
backend_names.add(str(backend_name))
if not isinstance(backend_config, dict) or not backend_config.get(
'address'
):
errors.append(
f'Backend "{backend_name}" is missing a required "address".'
)
components = spec.get('components')
schemes = (
components.get('securitySchemes', {})
if isinstance(components, dict)
else {}
)
if not isinstance(schemes, dict):
schemes = {}
root_or_error = _or_with_api_key_error(
spec.get('security'), schemes, 'the root'
)
if root_or_error:
errors.append(root_or_error)
mcp_config = management.get('mcp')
global_mcp_enabled = False
if isinstance(mcp_config, bool):
global_mcp_enabled = mcp_config
if mcp_config:
warnings.append(
'tools/list is unauthenticated ("mcp: true"). Configure '
'x-google-api-management.mcp.tools-list.security with a JWT or API '
'key scheme for production.'
)
elif isinstance(mcp_config, dict):
global_mcp_enabled = True
tools_list = mcp_config.get('tools-list', {})
if isinstance(tools_list, dict) and 'security' in tools_list:
tools_list_security = tools_list.get('security')
if (
not isinstance(tools_list_security, dict)
or len(tools_list_security) != 1
):
errors.append(
'"x-google-api-management.mcp.tools-list.security" must be a map '
'naming exactly one JWT or API key security scheme.'
)
else:
scheme_name = str(next(iter(tools_list_security.keys())))
scheme_def = schemes.get(scheme_name)
is_jwt = isinstance(scheme_def, dict) and (
scheme_def.get('type') == 'oauth2'
and isinstance(scheme_def.get('x-google-auth'), dict)
)
is_api_key = (
isinstance(scheme_def, dict) and scheme_def.get('type') == 'apiKey'
)
if not isinstance(scheme_def, dict):
errors.append(
'tools-list.security references unknown security scheme'
f' "{scheme_name}" not defined under components.securitySchemes.'
)
elif not is_jwt and not is_api_key:
errors.append(
f'tools-list.security scheme "{scheme_name}" must be a JWT scheme'
' (type "oauth2" with an "x-google-auth" configuration) or an API'
' key scheme (type "apiKey").'
)
elif is_api_key:
if (
scheme_def.get('in') != 'header'
or str(scheme_def.get('name', '')).lower() != 'x-api-key'
):
warnings.append(
f'tools-list.security names API key scheme "{scheme_name}",'
' but tools/list reads API keys only from the "x-api-key"'
' header. Define the scheme with "in: header" and "name:'
' x-api-key".'
)
else:
root_requirements = _requirement_names(spec.get('security'))
if not any(
scheme_name in requirement for requirement in root_requirements
):
errors.append(
f'tools-list.security names JWT scheme "{scheme_name}", but the'
' root "security" list does not reference it. API Gateway'
f' rejects this config. Add "{scheme_name}: []" to the root'
' "security" list (in the same requirement object as an API'
' key scheme, if there is one).'
)
elif all(
scheme_name in requirement for requirement in root_requirements
):
warnings.append(
f'The root "security" list requires "{scheme_name}" on every'
' REST operation that does not set its own "security". Tell the'
' user that the gateway rejects REST callers without this JWT.'
)
else:
warnings.append(
f'The root "security" list names "{scheme_name}" as one of'
' several alternatives. REST operations that do not set their'
' own "security" accept any of the alternatives.'
)
else:
warnings.append(
'x-google-api-management.mcp does not configure tools-list.security; '
'tools/list will be unauthenticated.'
)
root_backend = spec.get('x-google-backend')
if isinstance(root_backend, dict):
errors.append(
'Root "x-google-backend" must be a string referencing a backend in '
'x-google-api-management.backends, not an inline OpenAPI 2.0 object.'
)
elif (
isinstance(root_backend, str)
and backend_names
and root_backend not in backend_names
):
errors.append(
f'Root x-google-backend "{root_backend}" is not defined in '
'x-google-api-management.backends.'
)
seen_names: set[str] = set()
router_operations: list[str] = []
explicit_opt_in = False
implicit_tool_count = 0
paths = spec.get('paths', {})
if isinstance(paths, dict):
for path_str, path_item in paths.items():
if not isinstance(path_item, dict):
continue
if 'x-google-mcp-tool' in path_item:
errors.append(
f'Path "{path_str}" declares "x-google-mcp-tool" at the path level.'
' It must only be specified at the individual operation level.'
)
path_parameters = path_item.get('parameters')
for raw_method, operation in path_item.items():
method = str(raw_method).lower()
if method not in _HTTP_METHODS or not isinstance(operation, dict):
continue
label = f'{method.upper()} {path_str}'
if not str(operation.get('operationId') or '').strip():
errors.append(
f'Operation {label} has no operationId. API Gateway requires an'
' operationId on every operation, with or without MCP.'
)
mcp_tool = operation.get('x-google-mcp-tool')
if 'x-google-model-router' in operation:
router_operations.append(label)
if mcp_tool is True or isinstance(mcp_tool, dict):
explicit_opt_in = True
continue
if 'security' in operation:
operation_or_error = _or_with_api_key_error(
operation.get('security'), schemes, f'operation {label}'
)
if operation_or_error:
errors.append(operation_or_error)
operation_backend = operation.get('x-google-backend', root_backend)
if isinstance(operation.get('x-google-backend'), dict):
errors.append(
f'Operation {label} uses an inline "x-google-backend" object'
' instead of a string backend name.'
)
elif (
isinstance(operation_backend, str)
and backend_names
and operation_backend not in backend_names
):
errors.append(
f'Operation {label} references undefined backend'
f' "{operation_backend}".'
)
if mcp_tool is not None and not isinstance(mcp_tool, (bool, dict)):
errors.append(
f'Operation {label} has invalid x-google-mcp-tool type (must be'
' boolean or object).'
)
continue
if mcp_tool is False:
continue
explicit = mcp_tool is True or isinstance(mcp_tool, dict)
if explicit:
explicit_opt_in = True
elif not global_mcp_enabled:
continue
if method not in _SUPPORTED_MCP_METHODS:
if explicit:
errors.append(
f'Operation {label} explicitly opts into MCP, but HTTP method'
f' {method.upper()} is not supported (only GET, POST, PUT,'
' PATCH, DELETE).'
)
continue
if not operation_backend:
if explicit:
errors.append(
f'Operation {label} opts into MCP, but it has no'
' x-google-backend. Each exposed operation needs a backend.'
)
else:
warnings.append(
f'Operation {label} has no x-google-backend, so it is not'
' eligible as an MCP tool.'
)
continue
parameters = []
for parameter_list in (path_parameters, operation.get('parameters')):
if isinstance(parameter_list, list):
parameters.extend(
_resolve(spec, parameter) for parameter in parameter_list
)
for parameter in parameters:
if not isinstance(parameter, dict):
continue
parameter_name = str(parameter.get('name', ''))
if str(parameter.get('in', '')).lower() == 'header' and (
parameter_name.lower().startswith('x-google-')
):
errors.append(
f'Operation {label} binds a header parameter to reserved'
f' prefix "{parameter_name}".'
)
schema = _resolve(spec, parameter.get('schema'))
if isinstance(schema, dict) and (
schema.get('type') in ('array', 'object')
or 'items' in schema
or 'properties' in schema
):
warnings.append(
f'Operation {label} parameter "{parameter_name}" is not a'
' primitive type. API Gateway supports only primitive types in'
' request parameters. Change it to a primitive type, or set'
' "x-google-mcp-tool: false" on the operation.'
)
if isinstance(mcp_tool, dict) and 'name' in mcp_tool:
raw_name = mcp_tool['name']
if not isinstance(raw_name, str) or not _TOOL_NAME_RE.match(raw_name):
errors.append(
f'x-google-mcp-tool.name on {label} must be a string that'
f' matches [A-Za-z0-9_.-]{{1,128}}, got {raw_name!r}.'
)
continue
tool_name = raw_name
else:
tool_name = str(operation.get('operationId') or '')
if not tool_name:
# Reported above: every operation needs an operationId.
continue
if not _TOOL_NAME_RE.match(tool_name):
errors.append(
f'Tool name "{tool_name}" (the operationId of {label}) does not'
' match [A-Za-z0-9_.-]{1,128}. Set x-google-mcp-tool.name.'
)
if tool_name in seen_names:
errors.append(f'Duplicate MCP tool name "{tool_name}".')
seen_names.add(tool_name)
override_description = (
mcp_tool.get('description') if isinstance(mcp_tool, dict) else None
)
tool_description = str(
override_description
or operation.get('description')
or operation.get('summary')
or ''
).strip()
if not tool_description:
errors.append(
f'Exposed MCP operation {label} ("{tool_name}") has no'
' resolvable description or summary.'
)
responses = operation.get('responses', {})
if isinstance(responses, dict) and (
'204' in responses or 204 in responses
):
warnings.append(
f'Operation {label} ("{tool_name}") declares an HTTP 204'
' response. MCP does not support operations that return an empty'
' body. Return 200 with a JSON body, or set'
' "x-google-mcp-tool: false".'
)
if not explicit:
implicit_tool_count += 1
exposed_tools.append({
'name': tool_name,
'method': method.upper(),
'path': path_str,
})
if global_mcp_enabled or explicit_opt_in:
for label in router_operations:
errors.append(
f'Operation {label} uses "x-google-model-router". MCP and model'
' routing cannot be used in the same API configuration.'
)
if 'ai' in management and not router_operations:
warnings.append(
'"x-google-api-management.ai" configures model routing. MCP and model'
' routing cannot be used in the same API configuration. Remove the'
' "ai" block, or move model routing to a separate API config.'
)
if isinstance(mcp_config, dict) and implicit_tool_count:
warnings.append(
'x-google-api-management.mcp is an object, so MCP also exposes'
f' {implicit_tool_count} operation(s) that do not set'
' x-google-mcp-tool. Check exposed_tools, and set'
' "x-google-mcp-tool: false" on operations that agents must not call.'
)
if not exposed_tools:
warnings.append(
'No operations resolved as exposed MCP tools; /mcp will expose 0 tools.'
)
elif len(exposed_tools) > _MAX_TOOLS_PER_GATEWAY:
errors.append(
f'This file exposes {len(exposed_tools)} MCP tools. A gateway serves at'
f' most {_MAX_TOOLS_PER_GATEWAY:,} MCP tools.'
)
return errors, warnings, exposed_tools
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=(
'Validate an OpenAPI specification against Google Cloud API Gateway '
'MCP Public Preview constraints.'
)
)
parser.add_argument(
'--spec',
required=True,
help='Path to the OpenAPI YAML or JSON specification file to validate.',
)
args = parser.parse_args(argv)
try:
spec = _load_spec(args.spec)
errors, warnings, exposed_tools = validate_mcp_spec(spec)
except (OSError, RuntimeError, ValueError) as exc:
print(f'Error: {exc}', file=sys.stderr)
return 2
status = 'FAIL' if errors else 'PASS'
report = {
'status': status,
'spec': args.spec,
'exposed_tool_count': len(exposed_tools),
'exposed_tools': exposed_tools,
'errors': errors,
'warnings': warnings,
}
print(json.dumps(report, indent=2))
if errors:
print(
f'MCP OpenAPI validation failed with {len(errors)} error(s).',
file=sys.stderr,
)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE