feat: add gateway Code Mode
Design: https://linear.app/speakeasy/document/gateway-code-mode-oss-monty-design-and-pr-stack-2c28223d9370
Summary
Adds discovery_mode: "code_mode" for MCP gateways. Clients receive one execute tool for fresh Python executions, with live tool search, schema descriptions and authorized calls across hosted, remote and tunneled members. Existing connection permissions and the tools chosen on the consent screen apply to every helper: search, describe and calls only reach selected tools.
Includes the OSS runtime and authenticated yamux transport, bounded execution and cancellation, native Pitchfork setup, a dedicated GKE sandbox provider, generated contracts, and Settings/consent/Inspect support.
Stacked on #6816. CI publishes gram-code-runner content-addressed by agents/code-runner: an unchanged runner is re-tagged rather than rebuilt, so every commit and PR has a runner image under the same sha and preview tags as the server. The GKE provider accepts a release tag (or a digest, which it also checks against the running container). Each caller (user, external user, API key and credential) gets its own runner pod within a project, deleted when its claim ends, so a pod never runs code for two users, projects or organizations. Connecting to a runner and opening an execution stream follow the request's cancellation and never hold the client lock across network I/O, so a cancelled request releases its slot at once. Readiness polls start at 25 ms and back off to 1 s, so adopting a warm pod costs about the controller's bind. Per-replica and per-organization caps are flags (GRAM_CODE_RUNTIME_MAX_RUNNERS, default 64; GRAM_CODE_RUNTIME_MAX_ORGANIZATION_RUNNERS, default 16). Runner pools, namespaces and the per-PR sandbox templates live in speakeasy-api/gram-infra#4147.
gram code-runtime-smoke claims a runner using the server's own configuration and runs Python through it: an expression, printed output, a tool call round trip, no state between runs and no os. It also times warm and concurrent runs. Running it inside a deployed server pod checks a live runtime end to end, and --hold keeps the claim so the runner's network policy can be probed. The command's test runs against a real local runner in test:code-mode.
Inspect puts the Python runner first in Code Mode: one editor with Run Python (โ Enter), then a status line (outcome, tool calls, duration), a bounded return value, printed output, and tool calls labeled in plain words.
Each tool callback re-runs authorization and membership. A call never lists the member's tools: the allowlist is a name filter, grants are checked before dispatch, and a member whose destination changed since admission is dropped. The member validates its own arguments. Its refusal (unknown tool or invalid arguments) comes back as a completed result with ok false, error "tool_call_rejected" and the member's reason, so the program can describe the tool and fix the call. Errors the gateway synthesizes, such as a transport failure, stay unknown and are never replayed. tools.servers, tools.search and tools.describe reuse the consent catalogue captured in #6816 instead of listing members; calls use the live member dispatchers. Hosted input-schema refusals also come back as tool_call_rejected with the validation message. A member whose configuration or authentication changed since consent stays listed: search reports it under failed_members with reason consent_required, and describe or call says the user must reconnect and give consent again.
Member sessions are reused. A member's first operation pays the MCP handshake (server/discover, initialize, notifications/initialized); later calls, describe and search on that member reuse the session and send only the request. On the preview against a tunneled member, each call had cost 4 sequential upstream requests (about 1.6 s); a reused session sends one.
- Scope. Sessions are shared within one execution, and across a verified caller's rapid successive executions on the same pod (5 minute idle TTL, 10 minute maximum age, 4096 sessions per pod). Anonymous callers share only within one execution.
- Isolation. A session's key holds the caller's verified identity, gateway credential and grants, the member's destination, its resolved route (URL, transport, configured headers; tunnel resource and affinity) and the upstream token. A change to any of them gets a new session.
- Authority stays per call. Every operation still runs admission, routes the member and rebuilds its proxy with current selection and credentials. An operation that waited on another (a connect, a listing, a health check) re-checks admission and dispatches with the refreshed authority.
- Failures. Each call keeps its own routing and outcome state, so concurrent calls on one session never share either. A failed exchange retires the session; it closes once its last in-flight call finishes. Only a member's own refusal over a 2xx response keeps the session. A call that never left the gateway is retried once; a
tools/callis never resent otherwise. - Expiry and lifecycle. A session idle for more than 30 seconds gets an MCP
pingbefore reuse, shared by concurrent borrowers. A session the member expired is replaced before any call is sent. Idle timers, eviction and shutdown retire sessions under one lock order; shutdown waits for every DELETE in flight.
Direct and Progressive dispatch are unchanged.
The organization gateway runs Code Mode too: its connections choose Code Mode on the consent page (it has no stored default, so it stays Progressive otherwise). Executions run organization-wide (Scope.OrganizationWide, no project), with their own runner pod per caller, separate from that caller's project pods and counted in the organization cap. Each callback reloads the organization gateway, rather than re-reading stored endpoint and server rows it doesn't have, and resolves members across every project the caller can reach.
Anonymous callers are identified by the admitted identity (issuer gate and auth context), not by whether an Authorization header is present, so a made-up bearer is still treated as anonymous. Anonymous callers must keep their MCP session: execute without Mcp-Session-Id is refused before a runner is requested, and a gateway's anonymous sessions share a fixed set of four runner pods per replica, so anonymous traffic cannot claim a pod per request.
When the code runtime is disabled, code_mode gateways and connections are served as Progressive with a logged warning instead of failing, so turning the runtime off is a safe kill switch. Production has no code runtime yet; it must be provisioned (infra) before Code Mode is usable there. Platform MCP's get_mcp_connection_settings reports the stored mode, so a code_mode gateway served as Progressive while the runtime is off still reports code_mode.
Executions survive brief Redis read errors: an execution is cancelled only when its record disappears, its owner changes, or five consecutive reads fail. The demo seed stores the Python Code Gateway as Progressive so the demo org works without a runtime; local fixtures switch it to code_mode. The consent discovery help text names Code Mode consistently.
Verified end to end on a local stack at the stack tip: Direct, Progressive and Code Mode discovery, the consent picker (an unselected tool is hidden and refused in all three modes, and no refused call reaches the upstream), per-connection overrides, and Code Mode execution against a real runner. Also verified locally: hosted members (including tools added after consent), the plain MCP server picker with refresh and re-consent, the runtime stopped and disabled, losing access after consent, and members with duplicate names.
Verified on the PR preview against the development sandbox cluster, with a tunneled member: Code Mode search and calls run on a GKE runner; choosing specific tools hides and refuses the others (not_dispatched in Code Mode, "tool is not approved for this session" in Direct, refused before the member is contacted); reconnecting pre-selects the previous choice; and a per-connection Direct override lists only the chosen tools.
Deployment prerequisites
In released environments, GKE requires the SandboxTemplate image and GRAM_CODE_RUNTIME_IMAGE to use the same repository:tag@sha256: reference. CI publishes tags; deploy:prepare:explicit resolves and pins the digest (speakeasy-api/gram-infra#4535). Mutable image references are refused, except in preview mode: with GRAM_IS_PREVIEW=true the server accepts the PR's pr-<number>-<head sha> tag, because the preview server runs that same PR's code and a digest would not constrain its author.
Runner authentication uses one static token per environment. It is not bound to a claim, caller or execution, and is sent over the pod network without TLS.
Preview servers must receive GRAM_IS_PREVIEW=true and GRAM_CODE_RUNTIME_PREVIEW_TOKEN, with a namespace, templates and token secret separate from development (speakeasy-api/gram-infra#4535 provides gram-code-dev-previews). A GKE preview without its token is refused. Token equality checking only catches mistakes visible in one process; infrastructure isolation and the runner NetworkPolicy provide the boundary. Previews still share the application service account, so the separate token is what keeps them off development's runners. Keep the preview-code-mode label off until that infrastructure is applied.
Motivation
Let gateway clients discover and compose permitted tools in Python without retaining interpreter state or creating an assistant conversation. Reuse the existing dispatch and authorization paths, with no discovery cache or commercial runtime dependency.
Gutternote review steps
- Setup: no feature flag or entitlement is needed; Code Mode is offered wherever a code runtime is configured. With the
preview-code-modelabel, the preview runs Code Mode on the development sandbox cluster once speakeasy-api/gram-infra#4535 is applied; locally,mise run zero:code-modesets up the runner. - Sidebar โ MCP โ open a gateway โ Settings (
/<org>/projects/<project>/mcp/gateway/<gateway>/settings). Select Code Mode and save. Without a runtime, new Code Mode choices remain unavailable and existing Code Mode gateways are served as Progressive. - Open Inspect (
/<org>/projects/<project>/mcp/gateway/<gateway>/inspect). Verify a singleexecutetool. Runawait tools.search(query="health"), describe one returned path, then call it with arguments matching its schema. Inspect shows the outcome, return value, printed output and each tool call; edit the source afterwards and the code that produced the result stays visible. Each execution starts with fresh variables. - Connect a client through the consent screen, choose Specific tools, pick one tool, and choose Code Mode under Tool discovery.
tools.search("")lists only that tool, and calling any other path fails.
Also check cancellation, unavailable runtime (a Code Mode gateway falls back to Progressive tools), an empty tool selection, connection-failure retry, and preservation of editor text during credential refresh. Existing Direct and Progressive choices remain available.
๐ Preview Environment (PR #6978)
Preview URL: https://pr-6978.dev.getgram.ai
| Component | Status | Details | Updated (UTC) |
|---|---|---|---|
| โ Database | Ready | Existing database reused | 2026-10-26 10:34:58. |
| โ Images | Available | Container images ready | 2026-10-26 10:36:02. |
Gram Preview Bot