MCP server portals·续3

The decoded auth_credentials object must contain:

  • auth_mode: Must be manual.
  • config.authorization_endpoint and config.token_endpoint: The upstream provider's OAuth endpoints. issuer and revocation_endpoint are optional.
  • registration_info.client_id: The client ID issued by the upstream provider.
  • registration_info.redirect_uris: Optional when is_shared_oauth_callback_enabled is true. Cloudflare uses the shared callback URL even if you provide a different URI. This field cannot override the shared callback URL.
  • registration_info.token_endpoint_auth_method: Optional. Accepted values are none, client_secret_post, and client_secret_basic.
  • registration_info.scope: Optional space-delimited scope string.

Do not include client_secret or OAuth tokens inside auth_credentials. Send client_secret as the separate sibling field shown above.

To change the OAuth metadata, send auth_credentials in a PUT request to the update an MCP server endpoint. An existing manual OAuth server can be updated without client_secret; the stored secret remains unchanged. Send a new client_secret to rotate it. A new manual OAuth server, or a server being changed to manual OAuth, requires a non-empty client_secret.

The client secret is write-only. Cloudflare encrypts it before storage and never returns it from read, create, or update requests. Responses also omit the raw auth_credentials value. Use auth_config_summary.has_client_secret and auth_config_summary.client_secret_version to confirm that a secret is configured and identify its current version.

Bearer authentication credentials

The auth_credentials field accepts two forms:

  • A raw bearer token — the portal sends the value as the Authorization: Bearer <token> header on requests to the upstream MCP server:
  {
    "auth_type": "bearer",
    "auth_credentials": "your-bearer-token"
  }
  ```

- **A JSON-encoded object of custom headers** — for upstream MCP servers that require multiple headers or a non-standard header name:

```json
  {
    "auth_type": "bearer",
    "auth_credentials": "{\"headers\":{\"X-Api-Key\":\"<api-key>\",\"X-Client-Id\":\"<client-id>\"}}"
  }
  ```

The value of `auth_credentials` must be a JSON string. The parsed object must have a `headers` field mapping header names to string values. The portal forwards all headers verbatim to the upstream MCP server.

### View tool-call analytics

Use the account endpoint to retrieve daily or monthly MCP tool-call counts across the account:

```bash
curl "https://api.cloudflare.com/client/v4/accounts/%7Baccount_id%7D/access/ai-controls/mcp/analytics/tool-calls/timeseries?granularity=daily&aggregate=false&tz=utc&days=30" \
    --request GET \
    --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

The same query parameters apply to each endpoint:

Parameter Values and behavior
granularity daily or monthly. Defaults to daily.
aggregate true or false. Defaults to false. Set to true to request aggregated counts.
tz utc, Z, or a fixed +HH:MM or -HH:MM offset. Defaults to utc. Offsets range from -12:00 through +14:00; +14:00 and -12:00 are the limits. The offset is used for local-day bucketing and does not account for daylight saving time changes within the window.
days An integer from 1 to 179. For daily results, this sets the trailing window and defaults to 7. It is ignored when granularity=monthly.

The response result includes the selected granularity, aggregate, and tz, the start and end of the window as epoch milliseconds, a series of day and count values, and the total count. The window includes start and excludes end. Daily day values use YYYY-MM-DD in the requested timezone offset.

Use a scoped endpoint to limit the counts:

  • Server: GET /accounts/{account_id}/access/ai-controls/mcp/analytics/servers/{server_id}/tool-calls/timeseries
  • Portal: GET /accounts/{account_id}/access/ai-controls/mcp/analytics/portals/{portal_id}/tool-calls/timeseries

Force sync an MCP server

To manually trigger a synchronization of tools and prompts from an upstream MCP server:

curl "https://api.cloudflare.com/client/v4/accounts/%7Baccount_id%7D/access/ai-controls/mcp/servers/%7Bserver_id%7D/sync" \
    --request POST \
    --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

Delete a portal

curl "https://api.cloudflare.com/client/v4/accounts/%7Baccount_id%7D/access/ai-controls/mcp/portals/%7Bid%7D" \
    --request DELETE \
    --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

Configure via Terraform

You can manage MCP servers and portals using the Cloudflare Terraform provider. Use the cloudflare_zero_trust_access_ai_controls_mcp_server ↗︎ and cloudflare_zero_trust_access_ai_controls_mcp_portal ↗︎ resources.

Caution

Unlike the dashboard, the Terraform provider does not automatically create DNS records for your portal hostname. You must create a CNAME record that points your portal subdomain to gateway.agents.cloudflare.com. Without this record, the portal will return 522 errors.

The following example creates an unauthenticated upstream MCP server, a portal, and the Access resources required for a service token to use the server through the portal:

MCP server portal with service token accesshcl

resource "cloudflare_zero_trust_access_service_token" "mcp_bot" {
  account_id = var.cloudflare_account_id
  name       = "MCP bot"
  duration   = "8760h"
}

resource "cloudflare_zero_trust_access_policy" "mcp_bot" {
  account_id = var.cloudflare_account_id
  name       = "Allow MCP bot"
  decision   = "non_identity"

include = [{
    service_token = {
      token_id = cloudflare_zero_trust_access_service_token.mcp_bot.id
    }
  }]
}

resource "cloudflare_zero_trust_access_ai_controls_mcp_server" "docs" {
  account_id = var.cloudflare_account_id
  id         = "cloudflare-docs"
  name       = "Cloudflare documentation"
  hostname   = "https://docs.mcp.cloudflare.com/mcp"
  auth_type  = "unauthenticated"
}

resource "cloudflare_zero_trust_access_application" "docs" {
  account_id = var.cloudflare_account_id
  name       = "Cloudflare documentation"
  type       = "mcp"

destinations = [{
    type          = "via_mcp_server_portal"
    mcp_server_id = cloudflare_zero_trust_access_ai_controls_mcp_server.docs.id
  }]

policies = [{
    id         = cloudflare_zero_trust_access_policy.mcp_bot.id
    precedence = 1
  }]
}

resource "cloudflare_zero_trust_access_ai_controls_mcp_portal" "engineering" {
  account_id = var.cloudflare_account_id
  id         = "engineering"
  name       = "Engineering Portal"
  hostname   = "mcp.example.com"

servers = [{
    server_id = cloudflare_zero_trust_access_ai_controls_mcp_server.docs.id
    on_behalf = false
  }]
}

resource "cloudflare_zero_trust_access_application" "engineering" {
  account_id = var.cloudflare_account_id
  name       = "Engineering Portal"
  type       = "mcp_portal"
  domain     = cloudflare_zero_trust_access_ai_controls_mcp_portal.engineering.hostname

destinations = [{
    type = "public"
    uri  = cloudflare_zero_trust_access_ai_controls_mcp_portal.engineering.hostname
  }]

policies = [{
    id         = cloudflare_zero_trust_access_policy.mcp_bot.id
    precedence = 1
  }]
}

resource "cloudflare_dns_record" "mcp_portal" {
  zone_id = var.cloudflare_zone_id
  name    = "mcp"
  content = "gateway.agents.cloudflare.com"
  type    = "CNAME"
  proxied = true
  ttl     = 1
}

The provider marks the service token's client_secret as sensitive, but Terraform still stores it in state. Store Terraform state securely and pass the credentials to your MCP client through a secret manager or environment variables.

Code Mode

Code Mode reduces context window usage by replacing upstream tool definitions with two tools for search and code execution. The connected AI agent writes JavaScript that calls typed codemode.* methods. The generated code runs in an isolated Dynamic Worker environment. Authentication credentials and environment variables remain outside the model context.

Code Mode is useful for portals with many MCP servers or tools. Context window usage stays fixed as the portal adds tools.

Code Mode policies

Each portal has a Code Mode policy. The default policy is Opt-in.

Policy API value Default behavior Client override
Off off Code Mode is unavailable Query parameters are ignored
Opt-in opt_in Code Mode is off Add ?codemode=search_and_execute to turn it on
On by default default_on Code Mode is on Add ?codemode=off to turn it off
Enforced enforced Code Mode is on Query parameters are ignored

Use Opt-in or On by default if some clients run their own Code Mode implementation. These policies let clients avoid nested code execution.

Upstream servers with Code Mode turned on

MCP portals do not support upstream MCP servers that have their own Code Mode turned on. When adding a server to your portal, connect to a version of the server that returns its full tool list. If the upstream server runs its own Code Mode, use the server's opt-out mechanism if available. Alternatively, consider turning off Code Mode on your MCP portal.

Configure a Code Mode policy

  1. Get your existing MCP portal configuration:
   curl "https://api.cloudflare.com/client/v4/accounts/%7Baccount_id%7D/access/ai-controls/mcp/portals/%7Bid%7D" \
    --request GET \
    --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
   ```

2. Add `code_mode` to the response body. Set the value to `off`, `opt_in`, `default_on`, or `enforced`.
3. Send the complete body in a `PUT` request to the [Update a MCP Portal](https://developers.cloudflare.com/api/resources/zero_trust/subresources/access/subresources/ai_controls/subresources/mcp/subresources/portals/methods/update/) endpoint. Including the complete body prevents other portal settings from being overwritten.

The `allow_code_mode` API field is deprecated. Use `code_mode` for new integrations.

### Connect with Code Mode

The portal policy determines whether the MCP client needs a query parameter. For *Opt-in*, append `?codemode=search_and_execute` to the portal URL. For *On by default*, clients can append `?codemode=off` instead.

For example, an *Opt-in* portal at `https://<subdomain>.<domain>/mcp` uses this URL:

```txt
https://<subdomain>.<domain>/mcp?codemode=search_and_execute

For MCP clients with server configuration files, use the portal URL with the query string parameter:

MCP client configuration with Code Modejson

{
    "mcpServers": {
        "example-portal": {
            "url": "https://<subdomain>.<domain>/mcp?codemode=search_and_execute"
        }
    }
}

When Code Mode is active, the portal advertises portal_codemode_search and portal_codemode_execute. The AI agent can discover tools and compose multiple tool calls in one execution.

For more information on building with Code Mode, refer to the Code Mode SDK reference.

Route portal traffic through Gateway

When Gateway routing is turned on, calls to MCP servers protected by your MCP server portal are routed through Cloudflare Gateway. This makes portal traffic appear in your Gateway HTTP logs alongside the rest of your organization's HTTP traffic. You can then create Data Loss Prevention (DLP) policies to detect and block sensitive data from being sent to your upstream MCP servers.

How Gateway routing works

When a user calls a tool through the portal, the portal proxies the request to the upstream MCP server. With Gateway routing turned on, this outbound request passes through Cloudflare Gateway before reaching the upstream server. Gateway inspects the traffic and applies any matching HTTP policies, including DLP scanning.

Because portal traffic routes through Gateway, it also respects Gateway egress policies. This means outbound requests to upstream MCP servers will originate from your dedicated egress IPs or Gateway IP ranges rather than generic Cloudflare IPs. If your upstream MCP servers restrict inbound traffic by source IP (for example, to a VPN or corporate IP range), you can use egress policies to ensure portal traffic comes from a predictable set of IPs.

Note

Server-level Gateway routing also applies to DCR and admin credential synchronization. Portal-level Gateway routing applies only to real-time requests through that portal.

TLS decryption

DLP inspection requires Gateway to decrypt TLS traffic. For portal traffic, Gateway decrypts and inspects the payload automatically — you do not need to turn on the account-level TLS decryption setting. Because the portal terminates the connection from the MCP client and re-originates the request through Gateway, Gateway decrypts portal traffic regardless of whether the global TLS decryption setting is on.

This automatic decryption applies only to traffic that flows through the portal. To inspect MCP traffic that does not pass through the portal — for example, an agent on a device running the WARP client connecting directly to an upstream MCP server — you must turn on TLS decryption as you would for any other HTTP policy.

Note

Portal traffic ignores the global TLS decryption setting, but it still respects Do Not Inspect HTTP policies. If a Do Not Inspect policy matches portal traffic, Gateway does not decrypt it and DLP cannot scan it. Check that your Do Not Inspect policies do not unintentionally exempt your upstream MCP servers from inspection.

Supported transports

Gateway routing supports Streamable HTTP ↗︎ connections only. If an upstream MCP server is configured with a Server-Sent Events (SSE) endpoint (a URL ending in /sse), the portal will automatically attempt to connect using Streamable HTTP instead. If the upstream server does not support Streamable HTTP, the connection will fail when Gateway routing is turned on.