Repository navigation
feat: add gateway Code Mode - #6978
Conversation
🦋 Changeset detectedLatest commit: e07329e The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
This comment has been minimized.
This comment has been minimized.
fb76b5a to
f01e010
Compare
f01e010 to
1f8dc6d
Compare
1f8dc6d to
986d36a
Compare
986d36a to
f2772c9
Compare
f2772c9 to
ef940b3
Compare
ef940b3 to
35bb2b2
Compare
35bb2b2 to
beefb03
Compare
There was a problem hiding this comment.
All reported issues were addressed
This PR changes authentication, authorization, or input validation. Ultrareviews find 2.4x more serious bugs than standard reviews. Comment @cubic-dev-ai ultrareview to run one.
View guided diff | Turn on auto-fix | Re-trigger cubic
beefb03 to
8f539b0
Compare
…ommand K coverage
…l in the Inspect reload test
…he repository root
…arden worker isolation probes
…ighten code runner tests
…read errors as unavailable
…s after handshake cancellation
…ing in wall time test
…replacements pooled
There was a problem hiding this comment.
All reported issues were addressed across 69 files (changes from recent commits).
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
# Conflicts: # server/internal/authz/context.go # server/internal/authz/mandatory.go
There was a problem hiding this comment.
All reported issues were addressed across 24 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
# Conflicts: # server/internal/mcpservers/upstreamclients/authclientbackfill/queries.sql # server/internal/productfeatures/features.go
# Conflicts: # seed/demo/PAGES.md # server/internal/demoseed/queries/09_postflight_identity.sql # server/internal/demoseed/repo/04_servers.sql.go # server/internal/platformmcp/connection_settings.go # server/internal/platformmcp/tool_connection_settings.go
# Conflicts: # server/internal/demoseed/local.go # server/internal/demoseed/seed_09_postflight_identity.go # server/internal/mcp/serve_meta_tools.go
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 oneexecutetool 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-runnercontent-addressed byagents/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-smokeclaims 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 noos. It also times warm and concurrent runs. Running it inside a deployed server pod checks a live runtime end to end, and--holdkeeps the claim so the runner's network policy can be probed. The command's test runs against a real local runner intest: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
okfalse,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, stayunknownand are never replayed.tools.servers,tools.searchandtools.describereuse the consent catalogue captured in #6816 instead of listing members; calls use the live member dispatchers. Hosted input-schema refusals also come back astool_call_rejectedwith the validation message. A member whose configuration or authentication changed since consent stays listed: search reports it underfailed_memberswith reasonconsent_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,describeandsearchon 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.tools/callis never resent otherwise.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
Authorizationheader is present, so a made-up bearer is still treated as anonymous. Anonymous callers must keep their MCP session:executewithoutMcp-Session-Idis 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_modegateways 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'sget_mcp_connection_settingsreports the stored mode, so acode_modegateway served as Progressive while the runtime is off still reportscode_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_dispatchedin 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_IMAGEto use the samerepository:tag@sha256:reference. CI publishes tags;deploy:prepare:explicitresolves and pins the digest (speakeasy-api/gram-infra#4535). Mutable image references are refused, except in preview mode: withGRAM_IS_PREVIEW=truethe server accepts the PR'spr-<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=trueandGRAM_CODE_RUNTIME_PREVIEW_TOKEN, with a namespace, templates and token secret separate from development (speakeasy-api/gram-infra#4535 providesgram-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 thepreview-code-modelabel 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
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./<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./<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.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
Gram Preview Bot