# MCP Gateway
source: https://docs.chalk.ai/docs/mcp-gateway

## Register backends, connect agents, and control access through the MCP Gateway.

The Chalk MCP Gateway connects your agents to registered
Model Context Protocol (MCP) servers, HTTP APIs described by
OpenAPI, and Chalk functions. You register each backend once, and agents reach its tools,
resources, and prompts through a single connection. The gateway manages backend credentials,
enforces authorization policies, and audits operations.

The MCP Gateway is distinct from the MCP Server. The MCP Server
exposes Chalk itself to agents (run queries, execute Chalk SQL, inspect your deployment).
The MCP Gateway sits in front of other MCP servers and governs your agents' access to them.

### Deploying the gateway

The gateway runs as a service in your Chalk environment, alongside the engine. Chalk deploys it
the first time you register an MCP server in an environment, and adds
it to that environment's default resource group. Registering the first server takes a few minutes
while the gateway starts. If the gateway is still starting when the request times out,
registration fails with MCP Gateway is still starting; try the connection again shortly.
Register the server again.

Registering the first server requires the deploy.create permission, which the built-in Admin
and Owner roles have. Chalk turns on the MCP Gateway for each environment. If MCP Gateway does
not appear in the dashboard, contact Chalk support.

To change the gateway's resource request after it is deployed, edit the MCP Gateway service
in Infrastructure → Resources. See Resource Configuration for
how services and resource groups work.

### Registering MCP servers

Register and manage backend servers from MCP Gateway → MCP servers in the Chalk dashboard.
Each server has:

| Field          | Description                                                          |
| -------------- | -------------------------------------------------------------------- |
| **Name**       | A unique name for the backend.                                       |
| **Transport**  | `HTTP`, `stdio`, `OpenAPI`, or `Chalk function`, as described below. |
| **Credential** | The credential used to connect (see [Credentials](#credentials)).    |

Once a server is registered and connected, the dashboard shows its connection status and lets you
browse everything it exposes: its tools (with input schemas), resources (with URI, MIME
type, and description), and prompts (with arguments). You can also call a tool directly from
the UI to verify it works. Tools appear to clients as <backend>__<tool>, for example
github__get_issue.

Choose a transport based on what you are registering:

| Transport          | Configuration                                                                                                                                                                                                                                                   |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **HTTP**           | Set the URL of a remote MCP server.                                                                                                                                                                                                                             |
| **stdio**          | Set the command and arguments of an MCP process that runs alongside the gateway. The command must be available in the gateway's runtime.                                                                                                                        |
| **OpenAPI**        | Set a spec URL, optional operationIds, and an optional API base URL. The gateway generates tools and makes HTTP requests to the API.                                                                                                                            |
| **Chalk function** | Select deployed functions from the current environment and set the Chalk API URL. For service authentication, use the `headers` credential with `x-chalk-client-id` and `x-chalk-client-secret` from a service token with deploy read and redeploy permissions. |

Server changes take effect without a gateway restart, after a cache delay of up to 10 seconds
by default.

### Managing servers with the CLI

Apply a gateway seed file, including import-litellm output, with Chalk CLI v1.57.1 or later.
Set the credential environment variables referenced in the file first.

```
chalk mcp-gateway apply -f backends.seed.json --dry-run
chalk mcp-gateway apply -f backends.seed.json
chalk mcp-gateway export > backends.export.json
chalk mcp-gateway servers callback-url github
```

apply updates existing servers and preserves same-kind credentials unless you pass
--rotate-credentials. Pass --prune to delete servers missing from the file. Exported files
omit secrets. callback-url prints the redirect URI to register with your OAuth provider.

### Registering an OpenAPI API

An OpenAPI backend generates tools from a Swagger 2.0 or OpenAPI 3.0/3.1 document in JSON or YAML
(up to 32 MiB). Each supported operation becomes a tool.

- Operations: Selects operationIds to expose, with * for patterns. An empty selection includes all supported, non-deprecated operations. Deprecated operations require an exact operationId. Registration fails if an exact operationId is missing.
- API base URL: Overrides the spec's server URL, for example to use a tenant-specific host. The URL must be absolute HTTP or HTTPS with no credentials, query, or fragment. Its path prefix is preserved: https://api.example.com/v1 plus /users calls https://api.example.com/v1/users.

Tools use the operationId, normalized to a valid tool name, or a name derived from the HTTP method
and path when no operationId exists. Public names have the form <backend>__<tool> and fit within
64 bytes. OpenAPI and Chalk function backend names are limited to 61 bytes; shorter names leave
more room for tool names. Use the generated names when selecting tools for policies or belts.

Path, query, header, and cookie parameters become tool arguments; the request body becomes body.
JSON, form-encoded, and text bodies are supported. Operations requiring multipart or binary bodies
are skipped. Review the registration diagnostics for skipped operations. Credential headers are
excluded from tool arguments.

Update the server registration to load changes to the spec. For per-user OAuth,
the spec must be readable without authentication.

### Previewing an OpenAPI spec

OpenAPI preview shows the tools an API would expose before you register it: generated names, HTTP
destinations, input schemas, annotations, and diagnostics for unsupported operations. Use it to
check the catalog and operation selection before making the API available to agents.

Preview accepts a spec URL or an inline document. The server name, operation selection, and API
base URL affect the result; use the same values when registering the backend. An inline spec with
relative server URLs needs a spec URL or an explicit API base URL to resolve destinations.

Preview can use bearer or header credentials to fetch a protected spec. Specs for per-user OAuth
backends must be readable without a user token. Preview does not register a server or deploy a
gateway.

### Configuring tools and instructions

Tool settings control which tools a backend exposes and how agents see them. You can update
these settings independently of connection details and credentials.

| Setting            | Behavior                                                                                                                                                    |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Allowed tools**  | Expose only matching upstream tool names or `*` patterns, such as `get_*`. An empty list exposes all tools. Use `get_issue`, without the `github__` prefix. |
| **Tool overrides** | Replace tool titles or descriptions with JSON keyed by upstream tool name. Tool names, arguments, and execution stay the same.                              |
| **Instructions**   | Add MCP initialization instructions for clients that can access this backend.                                                                               |

For example, set Tool overrides to:

```
{
  "search_issues": {
    "title": "Search support issues",
    "description": "Find support issues before fetching a specific issue."
  }
}
```

Allowed tools filters listings, search, and direct calls, including calls through belts.
Resources and prompts are unaffected. For OpenAPI backends, Operations selects operationIds
from the spec, and Allowed tools filters the generated tool names.

### Forwarding caller identity

Caller identity forwarding lets a backend identify who made an operation, even when the gateway
uses shared upstream credentials. Forwarded values come from the verified caller identity.
Forwarding is disabled by default.

- MCP metadata: HTTP and stdio backends receive _meta["ai.chalk/caller"] with subject, kind, and an optional issuer.
- HTTP headers: HTTP and OpenAPI backends receive configured headers mapped to caller attributes.

For example:

```
X-On-Behalf-Of: user
X-Caller-Kind: kind
```

| Attribute    | Value                                                                                              |
| ------------ | -------------------------------------------------------------------------------------------------- |
| `subject`    | The authenticated subject: a Chalk user ID, service token ID, or mapped trusted-issuer agent name. |
| `user`       | The subject for a Chalk user; absent for machine callers.                                          |
| `kind`       | `user`, `service_token`, `trusted_issuer`, or `other`.                                             |
| `issuer`     | The trusted issuer URL; absent for other callers.                                                  |
| `attribute:` | A scalar attribute from a trusted issuer's claims mapping, such as `attribute:email`.              |

Chalk user subjects are user IDs. To forward an email address, the trusted issuer must expose it
as an attribute.

A missing caller attribute blocks the call by default. For advisory headers, you can allow the
call to proceed with that header omitted. Identity headers cannot overlap credential headers,
and OpenAPI excludes them from tool arguments.

Identity is forwarded on tool calls, resource reads, and prompt fetches. Initialization and
catalog requests carry no caller identity.

### Credentials

The gateway stores backend credentials encrypted and uses them when contacting a backend.
Agents authenticate to Chalk separately. Choose a credential kind for the backend's transport:

| Kind                      | Use for                                                                                                         |
| ------------------------- | --------------------------------------------------------------------------------------------------------------- |
| **Bearer token**          | A server that accepts a static `Authorization: Bearer` token.                                                   |
| **Headers**               | A server that needs one or more custom HTTP headers.                                                            |
| **Environment variables** | A `stdio` server that reads secrets from its environment.                                                       |
| **OAuth (user)**          | A server behind an OAuth 2.0 user flow (authorize/token URLs, client ID/secret, scopes).                        |
| **OAuth (DCR)**           | A server that supports OAuth Dynamic Client Registration, with scopes and an optional issuer for HTTP backends. |

For HTTP backends, choose bearer, headers, or either OAuth kind as needed. Use environment
variables for stdio processes. Chalk function backends require bearer or headers credentials.
HTTP, stdio, and OpenAPI backends can also have no credential.

The dashboard's OpenAPI form offers bearer and headers credentials. HTTP Basic authentication
uses a custom Authorization: Basic <base64-encoded-username:password> header.

### Configuring per-user OAuth

Each user links an account to call OAuth (user) and OAuth (DCR) backends. Service tokens,
sandbox workload identities, and trusted-issuer machine identities cannot call these backends.

An OAuth (user) configuration contains the provider's authorization URL, token URL, client ID,
optional client secret, scopes, and any extra authorization parameters it requires. Use HTTPS and
final endpoint URLs: token exchange and discovery do not follow redirects.

When creating the provider's OAuth application, register this redirect URI:

```
https://<your-chalk-api-host>/v1/mcp/oauth/callback
```

For Chalk's hosted metadata plane this is https://api.chalk.ai/v1/mcp/oauth/callback. The
same URI serves every server and environment, so one OAuth application can back several servers.
Start and finish linking in the same browser.

The token endpoint client authentication method must match the provider:

| Method                | Behavior                                                                                                      |
| --------------------- | ------------------------------------------------------------------------------------------------------------- |
| Default               | Uses `client_secret_basic` with a client secret, or `none` without one.                                       |
| `client_secret_basic` | Sends credentials using HTTP Basic authentication. Requires a client secret.                                  |
| `client_secret_post`  | Sends credentials in the request body. Requires a client secret. Use for providers such as Slack and HubSpot. |
| `none`                | Sends the client ID without a client secret.                                                                  |

For OAuth (DCR):

- Issuer: HTTP backends can discover the authorization server from the MCP endpoint when no issuer is configured. OpenAPI backends require an explicit issuer.
- Scopes: Configured scopes override the server's requested scopes; an empty configuration uses the requested scopes.
- Resource parameter: The server's URI is sent as the RFC 8707 resource parameter by default. This can be disabled for providers that reject it.

### Linking and refreshing accounts

Each user links their own upstream accounts from the MCP Gateway dashboard. A linked account
lets the gateway call that backend with the user's upstream permissions. Users can re-link an
account to renew consent or unlink it to remove the stored credentials.

If an MCP call requires linking or additional scopes, open the returned API-host link while
signed into the Chalk dashboard. Complete authorization in the same browser, then retry the call.
Keep the link's env_id and scope parameters.

The gateway refreshes linked tokens on use when a refresh token is available. Re-link when a grant
expires, is revoked, or needs additional scopes. Without a refresh token, re-link after the access
token expires. Changes to a server's OAuth settings, URL, or transport can require re-linking;
rotating only the client secret preserves links.

Team admins can inspect linked accounts across the environment, including each link's user,
server, scopes, expiry, and refresh status. This helps identify accounts that need re-linking.
Tokens are never displayed.

### Connecting an agent

Agents connect to the gateway over MCP's Streamable HTTP transport at your Chalk API host:

```
https://<your-chalk-api-host>/v1/mcp
```

For Chalk's hosted metadata plane this is https://api.chalk.ai/v1/mcp. Every request carries
X-Chalk-Env-Id, set to the environment id that chalk config reports, and one of two
credentials:

| Credential         | Headers                                                                                                                     | Lifetime                          |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| Access token       | `Authorization: Bearer `, where the token is the output of [`chalk token get`](/cli/token_get)                              | Up to 8 hours                     |
| Client credentials | `X-Chalk-Client-Id` and `X-Chalk-Client-Secret`, from `chalk config` or a [service token](#connecting-with-a-service-token) | Until the credentials are revoked |

Run chalk login once before chalk token get or chalk config. Both return credentials that
identify you, so the gateway applies your permissions and its
authorization policies to every call the agent makes. When a request
carries an Authorization header, the gateway uses it and ignores the client credential headers.

The MCP Gateway → MCP servers page in the Chalk dashboard has an Add to… menu
that generates this configuration for the current environment, for Claude Code, Codex, Cursor, Zed,
and stdio-based clients. For Claude Code, the generated commands are:

```
export CHALK_USER_TOKEN="$(chalk token get)"

claude mcp add --transport http chalk-gateway 'https://<your-chalk-api-host>/v1/mcp' \
  --header "Authorization: Bearer $CHALK_USER_TOKEN" \
  --header 'X-Chalk-Env-Id: <environment-id>'
```

Confirm the gateway answers before you configure a client by sending it an MCP initialize
request:

```
curl -sS https://<your-chalk-api-host>/v1/mcp \
  -H "Authorization: Bearer $(chalk token get)" \
  -H "X-Chalk-Env-Id: <environment-id>" \
  -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":"curl","version":"0"}}}'
```

A running gateway returns a JSON-RPC response whose result contains protocolVersion,
capabilities, and serverInfo. A 401 means the credentials are missing, expired, or rejected.
A response reading MCP gateway is not available for this environment means no gateway is
deployed in that environment.

### Connecting with a service token

To run an agent that no person is logged in for, such as a CI job or a scheduled task, connect it
with a service token's client credentials. Create the token as described in
Creating a service token in the dashboard,
and give it only the permissions the agent needs.

For Claude Code, add the gateway to the project's .mcp.json:

```
{
  "mcpServers": {
    "chalk-gateway": {
      "type": "http",
      "url": "https://<your-chalk-api-host>/v1/mcp",
      "headers": {
        "X-Chalk-Client-Id": "${CHALK_CLIENT_ID}",
        "X-Chalk-Client-Secret": "${CHALK_CLIENT_SECRET}",
        "X-Chalk-Env-Id": "<environment-id>"
      }
    }
  }
}
```

Claude Code expands ${...} references in .mcp.json when it starts, so the secret stays out of
the file. Export CHALK_CLIENT_ID and CHALK_CLIENT_SECRET in the environment the agent runs in.

A call made with a service token runs as that token, not as any user:

- The gateway applies the token's permissions.
- In a policy, input.auth.kind is service_token and input.auth.subject is the token's ID. The audit log records that ID as the agent.
- The token cannot call a server whose credential is OAuth (user) or OAuth (DCR). A tool call returns the error backend '<name>' requires a linked user account; service tokens cannot call it.
- Client credentials stay valid until you revoke the token, so store the secret the way you store other long-lived secrets.

Create one service token per agent. The audit log then names the agent behind each call, and
revoking a token disconnects only that agent.

### Tool belts

A tool belt gives a client a named subset of the environment's catalog. Use one to expose the
tools relevant to an agent's task. Team admins can create and manage belts in the MCP Gateway
dashboard.

A belt selects at least one backend or tool. Selecting a whole backend includes its tools,
resources, and prompts; selecting individual tools includes only those tools. gateway__whoami
is always included. Belt names contain 1–64 letters, digits, underscores, or hyphens.

Each belt has an MCP endpoint:

```
https://<your-chalk-api-host>/v1/mcp/belts/<belt-name>
```

This endpoint uses the same credentials and X-Chalk-Env-Id header as /v1/mcp. Belt edits take
effect on subsequent requests; removed belts return 404.

A belt rejects operations outside its selection. Allowed tools and Rego policies still apply.
The same credentials can access the full /v1/mcp endpoint, so use
authorization policies to enforce limits on a caller.

### Authorization policies

Policies decide which users and agents may call which tools, and with which arguments, independent
of the backend itself. You write them in
Rego, Open Policy Agent's policy language.
A policy has a name, its Rego source, and an enabled flag, so you can keep a policy in place and
turn it on or off without deleting it.

Enabled policies saved through the Chalk dashboard apply across backends. Match
input.gateway.backend when a rule should apply to a specific backend. Saving validates all
enabled policies together. If they fail to compile, saved policies remain unchanged. Other
replicas load policy updates every 5 seconds by default.

### Writing a policy

The gateway evaluates data.chalk.policy.deny. Write your rules in a chalk.policy package,
returning a message for each reason a request should be refused:

```
package chalk.policy

# Only the platform owner may call tools. Replace
# <platform-owner-user-id> with that user's Chalk user ID.
deny contains msg if {
	input.request.method == "tools/call"
	input.auth.subject != "<platform-owner-user-id>"
	msg := sprintf("user %v is not permitted to call tools", [input.auth.subject])
}
```

This example covers every tool call in the policy's backend scope. To restrict a specific tool,
add a condition on input.gateway.upstream_tool using its name from that backend's tool catalog.
Tool names depend on the server configuration.

A policy's Backend scope is a comma-separated list of server names. An empty scope
applies to every backend. Disabled policies remain saved but do not enforce any rules.

Policies are deny-only. A request proceeds when no deny rule matches, so a policy lists what to
refuse rather than what to permit, and an allow rule has no effect. Each message a rule produces
becomes one of the decision's reasons, and those reasons appear in the audit log.

### What a policy can read

Every evaluation receives one input document describing the request:

| Path                             | Description                                                                                                                                                                                                              |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `input.auth.subject`             | Who made the request: a Chalk user ID for a user token, the service token's ID for a service token, or the mapped agent name for a token from a trusted issuer. For Chalk users it is the user ID, not an email address. |
| `input.auth.kind`                | How the caller authenticated: `user` for a Chalk user, `service_token` for a service token, `trusted_issuer` for a token from a trusted issuer, or `other` for any other Chalk identity.                                 |
| `input.auth.scopes`              | The caller's scopes.                                                                                                                                                                                                     |
| `input.auth.issuer`              | The issuer URL for a trusted-issuer caller.                                                                                                                                                                              |
| `input.auth.attributes`          | Attributes exposed by a trusted issuer's claims mapping.                                                                                                                                                                 |
| `input.gateway.backend`          | The registered backend the request is bound for.                                                                                                                                                                         |
| `input.gateway.upstream_tool`    | The tool name on that backend, for tool calls.                                                                                                                                                                           |
| `input.gateway.upstream_uri`     | The resource URI on that backend, for resource reads.                                                                                                                                                                    |
| `input.gateway.upstream_prompt`  | The prompt name on that backend, for prompt gets.                                                                                                                                                                        |
| `input.request.method`           | `tools/call`, `resources/read`, or `prompts/get`.                                                                                                                                                                        |
| `input.request.params.arguments` | The call's arguments, for tool calls and prompt gets.                                                                                                                                                                    |
| `input.schema_version`           | The version of this document's shape. Currently `1`.                                                                                                                                                                     |

To find the ID a rule should compare against, open the policy simulator and choose a team member
or service token from its User list. The simulator shows the input.auth.subject value it sends.

Policies cover resource reads and prompt gets as well as tool calls. Match on
input.request.method when a rule should apply to only one of them.

Match against the input.gateway fields instead of their equivalents under input.request.params. The gateway
namespaces names and encodes URIs before passing them upstream, so a resource read arrives with
input.gateway.upstream_uri set to bigquery://project/dataset/table while
input.request.params.uri holds chalk-mcp://resource/v1/<backend>/bigquery%3A%2F%2F.... Matching
the encoded form works but is easy to get wrong, and a rule that fails to match allows the request.

### More examples

Restrict a tool by its arguments:

```
package chalk.policy

# The SQL tool may only run reads.
deny contains msg if {
	input.gateway.upstream_tool == "execute_sql_query"
	not startswith(lower(trim_space(input.request.params.arguments.query)), "select")
	msg := "execute_sql_query is limited to SELECT statements"
}
```

Require a scope for writes:

```
package chalk.policy

deny contains msg if {
	input.gateway.upstream_tool in {"create_issue", "update_issue"}
	not "write" in input.auth.scopes
	msg := sprintf("%v requires the write scope", [input.gateway.upstream_tool])
}
```

Keep a tool for people only:

```
package chalk.policy

# Only Chalk users may delete branches. Service tokens and other callers may not.
deny contains msg if {
	input.gateway.upstream_tool == "delete_branch"
	input.auth.kind != "user"
	msg := sprintf("%v is limited to users", [input.gateway.upstream_tool])
}
```

Protect a set of resources:

```
package chalk.policy

# Only these users may read the private tables.
private_table_readers := {"<user-id-1>", "<user-id-2>"}

deny contains msg if {
	input.request.method == "resources/read"
	startswith(input.gateway.upstream_uri, "bigquery://project/dataset/private_")
	not input.auth.subject in private_table_readers
	msg := sprintf("user %v cannot read private tables", [input.auth.subject])
}
```

### Simulating before you enable

Simulate a policy against a hypothetical request before turning it on. Supply a user, scopes,
backend, tool, and arguments, and the gateway returns the decision it would reach along with its
reasons. The backend, tool, prompt, and resource fields list what your registered MCP servers
expose, and the simulator warns when a backend, tool, or prompt you enter is not among them. A
policy that fails to deny something you expected usually has a field name or tool name wrong, since
an unmatched rule fails silently.

The dashboard simulator evaluates only the draft in the editor. It does not save changes, contact
a backend, or include other saved policies, backend access rules, Allowed tools, or belts.
An allow result applies only to that draft.

### Audit log

The gateway records every operation it handles: tool calls, resource reads, and prompt fetches. To
see them, open MCP Gateway → Policies in the Chalk dashboard and select the Audit tab. The
feed refreshes every 5 seconds, and scrolling down loads older events. For each operation, it shows:

| Column            | Description                                                                      |
| ----------------- | -------------------------------------------------------------------------------- |
| **Time**          | When the event was recorded.                                                     |
| **Agent**         | The agent, or user, that made the request.                                       |
| **Operation**     | `tools/call`, `resources/read`, or `prompts/get`.                                |
| **Target**        | The namespaced tool, resource URI, or namespaced prompt the operation addressed. |
| **Backend**       | The registered server the request was bound for.                                 |
| **Policy**        | What your policy recommended: `allow`, `deny`, `error`, or `NOT RUN`.            |
| **Outcome**       | What the gateway did: `allow`, `deny`, or `error`.                               |
| **Policy reason** | The messages your policy returned with a deny. Empty on an allow.                |
| **Arguments**     | A preview of the call arguments, truncated when long.                            |
| **Duration**      | How long the call took, in milliseconds.                                         |

### Policy and outcome

Policy is what your policy recommended. Outcome is what the gateway did. A request can be
allowed despite a deny recommendation, so the two are recorded separately.

Three combinations have specific meanings:

- Policy deny, Outcome allow: the policy ran in audit mode, which records decisions without
enforcing them.
- Policy error, Outcome allow: the policy failed to evaluate. The gateway allows the request
rather than blocking on a rule it cannot run.
- Policy NOT RUN: no policy evaluated the request, which is the case when none is enabled.

### See also

- MCP Server: connect agents to your Chalk deployment over MCP.
- Model Gateway: OpenAI-compatible LLM routing for your Chalk deployment.




