Skip to content
Control access

Require the Gateway for your own MCP server

Put an MCP server that verifies tokens from your Zone behind a Unified Access Gateway and have it accept only the Gateway's tokens, so an agent can't skip per-tool policy by calling the server directly

A Unified Access Gateway checks every tool call it forwards against your per-tool policies. If the upstream is an MCP server you run that verifies tokens from your Zone, an agent with access through the Gateway can also request its own token for the server. It can then call the server directly, where no tool is checked. This page sets the server to accept only tokens the Gateway obtained, which keeps every call on the path where tool policy applies.

Each tool call through the Gateway is a token exchange. The Gateway asks Keycard for a token for your server, names the tool in the request, and Keycard checks that tool against your policies before it issues anything. The token itself doesn’t name the tool, so your server can confirm that a token comes from your Zone and is meant for it, but not which tool it was approved for.

Keycard checks the agent’s own access to your server the same way on both paths: the agent is the principal and context.on_behalf is false. When the agent requests a token for the server itself, Keycard checks only the any action. The Gateway path needs a permit on any too, so the permit that lets the agent work through the Gateway also lets it get a token for the server directly. Requiring context.on_behalf == true on the agent’s permits doesn’t separate the two, because it refuses the Gateway path too.

The difference your server can see is who obtained the token:

Token Obtained by client_id claim
Forwarded by the Gateway The Gateway, in an exchange that checked the tool The Gateway’s client ID, https://<gateway-host>/oauth_client
Requested by the agent The agent, for itself The agent’s own credential

Calls that people make through the Gateway carry the Gateway’s client ID too, so one check on the server covers people and agents. For people, Fine-Grained Authorization can also keep other Applications off your server with a delegation rule. An agent acting as itself has no delegation to restrict, which is why the server makes this check.

  • Manager access to the Zone (see Roles & Permissions)
  • Your MCP server registered as a Resource with MCP Server turned on and Zone Provider (badge Keycard STS) as its Credential Provider, and verifying each token’s signature, iss, and aud (see Add a custom resource and Verifying tokens). A Resource with MCP Server off doesn’t appear in the Gateway’s Add MCP Server picker.
  • A Unified Access Gateway with the server attached on its MCP Servers tab (see Unified Access Gateway)
  • The agent registered as an Application with a credential (see Applications)
  1. Find the Gateway’s client ID

    Open the Gateway’s Application settings page and copy its MCP Access URL, which has the form https://unified-<gateway-slug>-<zone-id>.mcp.gateway.context.cloud/mcp. Replace the trailing /mcp with /oauth_client. The result is the Gateway’s client ID.

    The Gateway publishes its client metadata at that URL, so you can confirm the value before you deploy anything:

    Terminal window
    curl https://unified-<gateway-slug>-<zone-id>.mcp.gateway.context.cloud/oauth_client
    {
    "client_id": "https://unified-<gateway-slug>-<zone-id>.mcp.gateway.context.cloud/oauth_client",
    "grant_types": [
    "client_credentials",
    "urn:ietf:params:oauth:grant-type:token-exchange"
    ],
    "jwks_uri": "https://unified-<gateway-slug>-<zone-id>.mcp.gateway.context.cloud/.well-known/jwks.json",
    "response_types": ["token"],
    "token_endpoint_auth_method": "private_key_jwt",
    "token_endpoint_auth_signing_alg": "RS256"
    }

    client_id is the same URL you requested. The Gateway signs its token requests with a private key (private_key_jwt), so no other client can obtain a token that carries this client ID.

  2. Check client_id on your server

    After your server verifies a token’s signature, iss, and aud, reject the token unless its client_id claim is the Gateway’s client ID, and answer the request as you would an invalid token. Keep the aud check in place alongside this one.

    This FastMCP server makes the check in its token verifier. Set ALLOWED_CLIENT_IDS to the Gateway’s client ID, or to a comma-separated list if more than one Gateway serves the server:

    import logging
    import os
    from fastmcp import FastMCP
    from fastmcp.server.auth import AccessToken
    from fastmcp.server.auth.providers.jwt import JWTVerifier
    logger = logging.getLogger(__name__)
    KEYCARD_ISSUER = os.environ["KEYCARD_ISSUER"].rstrip("/")
    # This server's Resource identifier: the aud it accepts.
    MCP_SERVER_URL = os.environ["MCP_SERVER_URL"]
    # https://<gateway-host>/oauth_client for each Gateway that serves this server.
    ALLOWED_CLIENT_IDS = frozenset(
    c.strip() for c in os.environ["ALLOWED_CLIENT_IDS"].split(",") if c.strip()
    )
    class GatewayOnlyVerifier(JWTVerifier):
    """Verify a Zone token, then accept it only if a Gateway obtained it."""
    async def verify_token(self, token: str) -> AccessToken | None:
    access_token = await super().verify_token(token)
    if access_token is None:
    return None
    # Read the claim itself: AccessToken.client_id falls back to azp or sub.
    client_id = access_token.claims.get("client_id")
    if client_id not in ALLOWED_CLIENT_IDS:
    logger.warning("rejected token from client_id=%s", client_id)
    return None
    return access_token
    verifier = GatewayOnlyVerifier(
    jwks_uri=f"{KEYCARD_ISSUER}/openidconnect/jwks",
    issuer=KEYCARD_ISSUER,
    audience=MCP_SERVER_URL,
    )
    mcp = FastMCP("<server-name>", auth=verifier)

    Register tools on mcp as usual. A token the verifier rejects gets HTTP 401 with error="invalid_token", the same answer as an expired token. On a server built with a Keycard SDK, make the same comparison after the SDK verifies the token: the verified token exposes the claim as client_id in Python and Ruby, clientId in TypeScript, and ClientID in Go.

Through the Gateway, the agent needs permits for the Gateway itself, for any and tool discovery on your server, and for each tool it may call. Autonomous Agent Access covers the agent’s side of the connection; the policy here names tools instead of permitting the whole server.

  1. Author the agent’s policy

    <upstream-mcp-url> is your server’s Resource identifier, the aud it checks. This example permits one tool, search_documents:

    @id("search-agent-gateway")
    @description("The agent may get a token for the Gateway as itself")
    permit (
    principal is Keycard::Application,
    action,
    resource
    ) when {
    principal.identifier == "<agent-app-identifier>" &&
    resource.identifier == "<gateway-mcp-access-url>"
    };
    @id("search-agent-server-any")
    @description("The any check on every exchange for the server")
    permit (
    principal is Keycard::Application,
    action == Keycard::Action::"any",
    resource
    ) when {
    principal.identifier == "<agent-app-identifier>" &&
    resource.identifier == "<upstream-mcp-url>"
    };
    @id("search-agent-server-discovery")
    @description("Tool discovery on the server")
    permit (
    principal is Keycard::Application,
    action == Keycard::Action::"mcp::tools/list",
    resource
    ) when {
    principal.identifier == "<agent-app-identifier>" &&
    resource.identifier == "<upstream-mcp-url>"
    };
    @id("search-agent-search")
    @description("The one tool this agent may call")
    permit (
    principal is Keycard::Application,
    action == Keycard::Action::"mcp::tools/call::search_documents",
    resource
    ) when {
    principal.identifier == "<agent-app-identifier>" &&
    resource.identifier == "<upstream-mcp-url>"
    };

    Neither any nor mcp::tools/list grants a tool by itself. Through the Gateway, each call is checked again with its own mcp::tools/call::<tool-name> action, so a tool with no permit, such as analyze_document, is refused. A token request straight to the server checks only any, and the server’s client_id check is what refuses that path. Use the bare tool name, as described in Fine-Grained Authorization.

  2. Cover the Gateway’s own checks

    The Gateway is checked twice on your server. When the agent gets its Gateway token, Keycard checks the Gateway’s own access to the server with nobody behind the call (context.on_behalf == false). On every call after that, it checks the Gateway acting on the agent’s behalf (context.on_behalf == true). The managed default-app-direct-access and default-app-delegation policies cover these two checks. If your Policy Set is missing either one, add the matching rule:

    @id("gateway-server-direct")
    @description("The Gateway's own check on the server when an agent signs in as itself")
    permit (
    principal is Keycard::Application,
    action == Keycard::Action::"any",
    resource
    ) when {
    principal.identifier == "<gateway-mcp-access-url>" &&
    resource.identifier == "<upstream-mcp-url>" &&
    context.on_behalf == false
    };
    @id("gateway-server-on-behalf")
    @description("The Gateway may exchange for the server on a caller's behalf")
    permit (
    principal is Keycard::Application,
    action,
    resource
    ) when {
    principal.identifier == "<gateway-mcp-access-url>" &&
    resource.identifier == "<upstream-mcp-url>" &&
    context.on_behalf == true
    };

    If you replaced default-app-delegation with the Gateway-only delegation rule from Fine-Grained Authorization, that rule already covers the second check for every upstream it lists.

  3. Add the policies to your Policy Set

    Add the policies to your Policy Set and activate it. See Build a custom Policy Set for the Console steps. If the Zone still runs the managed default-zone-policies, which you can’t edit, create your own set and choose schema 2026-06-18 for it: a set on the default schema, 2026-03-16, can’t include managed policies. Add the managed policies you rely on along with these, then activate it. If you create policies on the new set’s page, open each one in the published version and check its Cedar before you activate: Publish as Candidate keeps the Cedar of only the policy open in the editor, as step 5 of Fine-Grained Authorization describes. Changes to tool rules take effect on the agent’s next call.

Check both paths, using the agent’s own credentials.

  1. Connect the agent to the Gateway’s MCP Access URL as in Connect the agent. The tool list includes your server’s tools, each prefixed with a short name the Gateway derives from your server’s host. Read the exact names from tools/list rather than building them. A permitted tool returns its result. A tool with no permit is refused with a JSON-RPC error (-32603, access denied by policy for <upstream-mcp-url>) over HTTP 403.

  2. Go around the Gateway: request a token for your server as the agent, then send it to the server. Keycard issues the token, because the agent holds any on the server, and the server refuses it with HTTP 401. With the verifier above, the server logs rejected token from client_id= followed by the agent’s client ID. For an agent with a client secret, set KEYCARD_ISSUER to the Zone’s Issuer URL from Settings → Connection, and KEYCARD_CLIENT_ID and KEYCARD_CLIENT_SECRET to the agent’s client ID and secret:

    Terminal window
    AGENT_TOKEN=$(curl -sS "$KEYCARD_ISSUER/oauth/2/token" \
    -u "$KEYCARD_CLIENT_ID:$KEYCARD_CLIENT_SECRET" \
    -d "grant_type=client_credentials" \
    -d "resource=<upstream-mcp-url>" \
    | jq -er .access_token) || echo "Keycard issued no token"
    curl -sS -o /dev/null -w "%{http_code}\n" "<upstream-mcp-url>" \
    -H "Authorization: Bearer $AGENT_TOKEN" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json, text/event-stream" \
    -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"direct-check","version":"1.0"}}}'

    If the first command prints Keycard issued no token, the token request was refused, and the 401 that follows doesn’t test your server. Only a 401 on its own shows the server’s check.

  • Every call through the Gateway fails with 401 after the server check is deployed. The allowed value isn’t the Gateway’s client ID. It must be the /oauth_client URL from step 1, not the MCP Access URL that ends in /mcp. The server’s log line names the client_id it rejected.
  • The agent connects to the Gateway but lists none of your server’s tools, with no error. The Gateway’s own check on the server failed when the agent got its Gateway token, so the server was left out of that token. Add the managed default-app-direct-access policy or the gateway-server-direct rule, then have the agent get a new Gateway token.
  • The agent gets a Gateway token, but tools/list fails with no unified upstreams are accessible with the presented grant. Every upstream’s exchange was refused. Either the agent lacks any or mcp::tools/list on the server, or the Gateway may not act on the agent’s behalf. The Audit Log denial says which. When the Gateway is the one refused, it reads is not allowed to act on behalf of the agent’s Application. Add the missing rule from Give the agent its tools.
  • People who connected straight to the server get 401. The server now accepts only the Gateway’s tokens. Have them connect to the Gateway’s MCP Access URL instead.