Files
coder/coderd/mcp_http.go
T
Atif Ali 261269aff0 fix: support path-aware OAuth discovery for remote MCP (#30168)
## Problem

VS Code discovers Coder's MCP endpoint as a path-qualified OAuth
resource, but Coder advertises the deployment root. Accepting MCP-bound
tokens also requires keeping REST-backed tool calls within the
originating MCP resource rather than granting those tokens direct REST
access.

## Fix

- Publish path-aware protected resource metadata and authentication
challenges; keep authorization-server metadata at the root.
- Validate the MCP audience and delegate tool requests through a private
in-process transport that retains identity, scopes, expiry, revocation,
and streaming cancellation.
- Reject unsupported MCP path aliases and validate SDK path components
before URL resolution.
- Add discovery, audience, authorization, endpoint-isolation, and
transport lifecycle regression tests and update integration docs.

## Validation

VS Code completed OAuth and returned the authenticated user through a
real MCP tool. Official MCP SDK 1.30.1 completed discovery,
registration, PKCE, tool execution, and refresh. These live checks
preceded the final path hardening; the hardened paths are covered by
automated regressions.

Affected Go package tests, targeted race tests, backend/SDK lint, and
targeted documentation checks passed during self-review. The exact PR
commit was also checked separately from the uncommitted consent-scope
fix.

> [!NOTE]
> Tokens are MCP-audience-bound, but grants still include `coder:all`;
least-privilege scopes remain a separate requirement
([PLAT-639](https://linear.app/codercom/issue/PLAT-639)).

Preview:
https://coder.com/docs/@fix/mcp-internal-delegation/ai-coder/mcp-server

<details>
<summary>Implementation decisions and review context</summary>

1. Treat `/api/experimental/mcp/http` and its single-trailing-slash form
as supported MCP resource paths; reject other aliases and descendants
before route authentication.
2. Preserve deployment-root discovery and authorization-server metadata
for existing REST integrations.
3. Bind private delegation to the authenticated API-key ID. Revalidate
the original credential and enforce normal RBAC/scopes on every internal
REST request; do not derive delegation from HTTP headers.
4. Keep internal HTTP, streaming, and WebSocket traffic in-process with
no network fallback. Close the transport on outer-request cancellation
and normal completion.
5. Validate workspace owner/name path segments before SDK URL
construction, including tool-level tests that malformed arguments cannot
select a different REST endpoint.
6. Keep compatibility and delegated tool execution together:
discovery-only changes would allow authentication while leaving real MCP
tool calls broken.

</details>

> 🤖 This PR was created with the help of Coder Agents, and needs a human
review. 🧑💻
2026-10-09 00:58:39 +05:00

107 lines
4.0 KiB
Go

package coderd
import (
"context"
"fmt"
"net/http"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/mcp"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/toolsdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
type MCPToolset string
const (
MCPToolsetStandard MCPToolset = "standard"
MCPToolsetChatGPT MCPToolset = "chatgpt"
)
// mcpHTTPHandler creates the MCP HTTP transport handler
// It supports a "toolset" query parameter to select the set of tools to register.
func (api *API) mcpHTTPHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create MCP server instance for each request
mcpServer, err := mcp.NewServer(api.Logger.Named("mcp"))
if err != nil {
api.Logger.Error(r.Context(), "failed to create MCP server", slog.Error(err))
httpapi.Write(r.Context(), w, http.StatusInternalServerError, codersdk.Response{
Message: "MCP server initialization failed",
})
return
}
// Keep tool requests in-process. The private transport carries the
// originating MCP audience without granting external REST access.
transport, closeTransport := newMCPDelegatedTransport(api.Logger, api.RootHandler, api.AccessURL, httpmw.APIKey(r).ID)
defer closeTransport()
// The MCP SDK detaches tool cancellation and waits for in-flight tools
// before returning, so close their transport independently on disconnect.
stopClose := context.AfterFunc(r.Context(), closeTransport)
defer stopClose()
authenticatedClient := codersdk.New(api.AccessURL,
codersdk.WithSessionToken(httpmw.APITokenFromRequest(r)),
codersdk.WithHTTPClient(&http.Client{Transport: transport}))
// Wrap the agent connection function to enforce ActionSSH
// on the workspace. Without this check, a user who can read
// a workspace but lacks SSH permission could still execute
// commands through MCP tools.
toolOpt := toolsdk.WithAgentConnFunc(func(ctx context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) {
if api.Entitlements.Enabled(codersdk.FeatureBrowserOnly) {
return nil, nil, xerrors.New("non-browser connections are disabled")
}
// Use system context for the lookup because the tool
// handler context does not carry a dbauthz actor. The
// real authorization happens in the Authorize call below.
//nolint:gocritic // The system query only fetches the workspace
// object so we can perform an ActionSSH check against it
// with the real user's roles via api.Authorize.
workspace, err := api.Database.GetWorkspaceByAgentID(dbauthz.AsSystemRestricted(ctx), agentID)
if err != nil {
return nil, nil, xerrors.Errorf("get workspace by agent ID: %w", err)
}
// Enforce the same ActionSSH check that the coordinate
// endpoint uses (workspaceagents.go:1317).
if !api.Authorize(r, policy.ActionSSH, workspace) {
return nil, nil, xerrors.New("unauthorized: you do not have SSH access to this workspace")
}
return api.agentProvider.AgentConn(ctx, agentID)
})
toolset := MCPToolset(r.URL.Query().Get("toolset"))
// Default to standard toolset if no toolset is specified.
if toolset == "" {
toolset = MCPToolsetStandard
}
switch toolset {
case MCPToolsetStandard:
if err := mcpServer.RegisterTools(authenticatedClient, toolOpt); err != nil {
api.Logger.Warn(r.Context(), "failed to register MCP tools", slog.Error(err))
}
mcpServer.RegisterPrompts()
case MCPToolsetChatGPT:
if err := mcpServer.RegisterChatGPTTools(authenticatedClient, toolOpt); err != nil {
api.Logger.Warn(r.Context(), "failed to register MCP tools", slog.Error(err))
}
default:
httpapi.Write(r.Context(), w, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf("Invalid toolset: %s", toolset),
})
return
}
// Handle the MCP request
mcpServer.ServeHTTP(w, r)
})
}