Repository navigation
Description
Overview
Add an optional embedded OAuth authorization server (AS) to vMCP. When enabled, the AS acts as the OIDC issuer for incoming clients: it drives users through one or more upstream IDPs, accumulates their tokens, and issues a ToolHive JWT. The OIDC middleware validates that TH-JWT via a self-referencing loopback and eagerly loads the upstream tokens into `identity.UpstreamTokens`. Existing behavior when no AS is configured (Mode A) is byte-for-byte unchanged.
Background
vMCP today requires clients to obtain upstream IDP tokens externally before connecting — there is no mechanism for vMCP to orchestrate the auth flow itself. Additionally, upstream tokens accumulated during login have no unified path into the outgoing auth layer; the `upstream_inject` strategy (which would inject an upstream provider token into backend requests) has no source to draw from.
This RFC adds Mode B, where vMCP hosts the auth server at the same origin, handles OAuth/OIDC discovery as a loopback, and makes upstream tokens available to outgoing auth strategies via `identity.UpstreamTokens`.
RFC: stacklok/rfcs#53
Depends on: #3924 (RFC-0052 multi-upstream IDP support) for full end-to-end token flow
Task Breakdown
| Task | GitHub Issue | Title | Depends On |
|---|---|---|---|
| Phase 1 | #4140 | Foundation — add AuthServerConfig model, CRD field, and structural validation | — |
| Phase 2 | #4141 | Server wiring — mount embedded auth server routes on vMCP mux | #4140 |
| Phase 3 | #4142 | Startup validation (V-01..V-07) — upstream_inject types and validateAuthServerIntegration | #4140 |
| Phase 4 | #4143 | Operator reconciler, HTTP handler unit tests, and E2E test coverage | #4141, #4142 |
#4140 (Phase 1: Foundation)
|
+---> #4141 (Phase 2: Server wiring) \
| +---> #4143 (Phase 4: Operator + E2E)
+---> #4142 (Phase 3: Startup validation) /
Phase 1 is the root; Phases 2 and 3 can be developed in parallel; Phase 4 is the integration phase.
Acceptance Criteria
- vMCP can be configured with an embedded AS (
authServer.runConfigin YAML;spec.authServerConfigRefin K8s) and serves OAuth/OIDC endpoints at the same origin -
/.well-known/openid-configuration,/.well-known/oauth-authorization-server,/.well-known/jwks.json, and/oauth/are mounted as unauthenticated routes in Mode B; Mode A is unaffected - The
/.well-known/catch-all handler is replaced with an explicit/.well-known/oauth-protected-resourceregistration (non-breaking) - Validation rules V-01..V-07 are enforced at startup (YAML path) and at operator reconciliation (K8s path), producing actionable error messages
- The operator reconciler resolves
spec.authServerConfigRef, validates type and issuer consistency, and surfaces anAuthServerConfigValidstatus condition - Mode A behavior is byte-for-byte identical to today — all new code paths are gated on
cfg.AuthServer != nil - All linked task issues (Phase 1: Foundation — add AuthServerConfig model, CRD field, and structural validation #4140, Phase 2: Server wiring — mount embedded auth server routes on vMCP mux #4141, Phase 3: Startup validation (V-01..V-07) — upstream_inject types and validateAuthServerIntegration #4142, Phase 4: Operator reconciler, HTTP handler unit tests, and E2E test coverage for embedded AS #4143) completed and merged
- Unit tests for validation rules (V-01..V-07), server route mounting (Mode A/B), and CRD structural validation
- E2E tests for Mode A/B routing, negative validation cases, and operator condition lifecycle
Activity
tgrunnagle commentedon Mar 13, 2026
Planning Artifact: Intake
Intake: vMCP — Add Embedded Authorization Server (RFC-0053)
Original Requirements
Implement RFC-0053 (Embedded Auth Server in vMCP) as tracked by the placeholder epic issue
#4120. The RFC adds an optional embedded OAuth
authorization server to vMCP. When enabled, the AS acts as the OIDC issuer for incoming
clients: it drives users through one or more upstream IDPs, accumulates their tokens, and
issues a ToolHive JWT. Existing behavior for an external OIDC issuer is unchanged (byte-for-byte
backward compatibility).
Create exactly one GitHub issue per RFC implementation phase (4 phases total), linked as
sub-issues of #4120.
RFC document:
/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.mdExisting Documentation
/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.md— Full design: problem statement, high-level design (Mode A / Mode B), detailed config model changes, CRD changes, operator reconciler changes, HTTP route mounting, validation rules V-01..V-07, security considerations, testing strategy, and 4-phase implementation plan.identity.UpstreamTokenspopulation by the OIDC auth middleware) should link to this issue.Clarifying Questions & Answers
Issue Style
Repository & Project
stacklok/toolhive(primary — issues created here):/Users/trey/Documents/GitHub/toolhive— main service being changed; contains all affected packages (pkg/vmcp/,pkg/authserver/,cmd/vmcp/,cmd/thv-operator/)Scope & Boundaries
ExternalAuthConfigRefto its canonical location inmcpexternalauthconfig_types.goAuthServerConfigRef *ExternalAuthConfigReftoVirtualMCPServerSpecAuthServer *AuthServerConfigtopkg/vmcp/config/config.gozz_generated.deepcopy.gocmd/vmcp/app/commands.goandpkg/vmcp/server/server.go/.well-known/catch-all handler with explicit path registrationsvalidateAuthServerIntegrationwith validation rules V-01 through V-07authServerConfigRef, cross-resource validation (type check, V-04, V-07), newAuthServerConfigValidstatus conditioncmd/thv-operator/pkg/vmcpconfig/converter.godocs/arch/09-operator-architecture.md,docs/arch/02-core-concepts.md, new vMCP auth server guide)upstream_injectoutgoing auth strategy (deferred to a follow-up RFC)pkg/auth/upstreamswapmiddleware)Technical Context
pkg/vmcp/config/config.go— newAuthServer *AuthServerConfigfield andAuthServerConfigstructpkg/vmcp/config/validator.go— newvalidateAuthServerIntegrationmethod and helper functionspkg/vmcp/config/zz_generated.deepcopy.go— regeneratedpkg/authserver/runner/embeddedauthserver.go— newRegisterHandlers(mux *http.ServeMux)methodcmd/vmcp/app/commands.go— conditional AS creation; passAuthServerto server configpkg/vmcp/server/server.go— addAuthServerto serverConfig; mount AS routes; replace/.well-known/catch-allcmd/thv-operator/api/v1alpha1/mcpserver_types.go— removeExternalAuthConfigRefstruct definition (moved)cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— addExternalAuthConfigRefstruct definition (moved frommcpserver_types.go)cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go— addAuthServerConfigReffield; addvalidateAuthServerConfigmethodcmd/thv-operator/pkg/vmcpconfig/converter.go— resolveauthServerConfigReftoAuthServerConfig.RunConfigcmd/thv-operator/controllers/virtualmcpserver_controller.go— cross-resource validation, new status conditionpkg/authserver/runner.EmbeddedAuthServeris already implemented; no new AS implementation work needed in this RFC/.well-known/catch-all change is behavioral but non-breaking: the catch-all currently only servesoauth-protected-resource; all other paths return 404 in both old and new codeallowedAudiencesis derived by the operator converter from the referencingVirtualMCPServer's incoming auth audience — it is NOT an explicit field onMCPExternalAuthConfigin the CRDcfg.AuthServer != nilDependencies & Integration
identity.UpstreamTokenspopulation by the OIDC auth middleware. Phases 1–2 can be developed in parallel; full integration testing of the end-to-end flow requires RFC-0052 to be merged.upstream_injectoutgoing auth strategy (deferred to a follow-up RFC) — will consumeidentity.UpstreamTokenspopulated by this RFC's auth middleware wiringsubandclaimswill be derived from the first configured upstream IDP when Mode B is activeAcceptance & Verification
/.well-known/openid-configurationreturns a valid OIDC discovery document with the correctissuerand non-emptyjwks_uriAuthServerConfigValidstatus condition onVirtualMCPServerFailedphase with a descriptive condition message, preventing deployment until correctedDescribeTable): oneEntryper validation rule V-01..V-07, plus nilAuthServer(Mode A passes all checks) and a valid Mode B configvalidateAuthServerConfig— emptynamerejection and nil-pointer safetyoauth-protected-resourceserved in both modes)test/e2e/vmcp_authserver_test.go): Mode B startup, OIDC discovery response, 401 on unauthenticated MCP request, Mode A 404 on discoveryupstream_injectwith no AS exits with V-01 error; unknown provider exits with V-02 errorEventually): createMCPExternalAuthConfig+VirtualMCPServer, verify deployment andAuthServerConfigValidconditionDry Run Mode
Issue Labels
All phase issues inherit the epic's labels:
authentication,authorization,enhancement,go,vmcpIssue Linking
Each phase issue is linked to epic #4120 as a GitHub sub-issue using the
gh sub-issueextension.Assignees
Leave all phase issues unassigned.
Phase Breakdown
The RFC defines exactly 4 implementation phases. Each becomes one GitHub issue.
Phase 1: Foundation (no runtime behavior change)
Summary: Structural changes only — no runtime behavior changes. Move
ExternalAuthConfigRef,add new CRD and config fields, add structural validation, regenerate deepcopy.
File changes:
cmd/thv-operator/api/v1alpha1/mcpserver_types.go— removeExternalAuthConfigRefstruct (moved)cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— addExternalAuthConfigRefstruct (moved frommcpserver_types.go); all existing callers are unaffected (same package)cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go— addAuthServerConfigRef *ExternalAuthConfigReftoVirtualMCPServerSpec; addvalidateAuthServerConfig()structural validation (name non-empty check)pkg/vmcp/config/config.go— addAuthServer *AuthServerConfigtoConfig; addAuthServerConfigstruct wrappingauthserver.RunConfigpkg/vmcp/config/zz_generated.deepcopy.go— regenerateAcceptance: All existing tests pass. The new fields are optional and unused; no server behavior changes.
Dependencies: None (can start immediately)
Phase 2: Server wiring
Summary: Conditional AS creation at startup and HTTP route mounting. This is the first phase
that changes runtime behavior (when
authServeris configured in the YAML).File changes:
pkg/authserver/runner/embeddedauthserver.go— addRegisterHandlers(mux *http.ServeMux)method mounting/oauth/,/.well-known/openid-configuration,/.well-known/oauth-authorization-server,/.well-known/jwks.jsoncmd/vmcp/app/commands.go— conditional AS creation (if cfg.AuthServer != nil); passAuthServerto server config; hard failure on AS creation error (no silent fallback to Mode A)pkg/vmcp/server/server.go— addAuthServer *runner.EmbeddedAuthServerto serverConfig; callRegisterHandlersconditionally; replacemux.Handle("/.well-known/", ...)catch-all with explicit/.well-known/oauth-protected-resourceregistrationSmoke test: Start vMCP with a Mode B config; confirm
/.well-known/openid-configurationreturns AS metadata. Confirm Mode A behavior is unchanged.Dependencies: Phase 1 must be merged. Can be developed in parallel with RFC-0052 (#3924), but full end-to-end auth flow requires RFC-0052.
Phase 3: Startup validation
Summary: Add
validateAuthServerIntegrationto the config validator, covering all V-01..V-07rules, plus unit tests.
File changes:
pkg/vmcp/config/validator.go— addvalidateAuthServerIntegration(cfg *Config) errorcalled fromValidate(); add helperscollectAllBackendStrategies,hasUpstreamProvider,containsString; extendvalidateBackendAuthStrategyforupstream_injectV-01/V-06Tests:
pkg/vmcp/config/validator_test.go— table-driven GinkgoDescribeTablewith oneEntryper rule: V-01 (upstream_inject, no AS), V-02 (unknown provider), V-03 (token_exchangewarning), V-04 (issuer mismatch), V-05 (AS internal validation failure), V-06 (empty provider name), V-07 (audience not inallowedAudiences); plus Mode A pass-through and valid Mode B configcmd/thv-operator/api/v1alpha1/virtualmcpserver_types_test.go—validateAuthServerConfigcovering emptynamerejection and nil-pointer safetyDependencies: Phase 1 must be merged. Independent of Phase 2 (can be developed in parallel).
Phase 4: Operator reconciler
Summary: Kubernetes operator support — resolve
authServerConfigRef, cross-resourcevalidation, new status condition, CRD converter updates, and E2E tests.
File changes:
cmd/thv-operator/controllers/virtualmcpserver_controller.go— resolvespec.authServerConfigRefref; verify type isembeddedAuthServer; verify issuer consistency (V-04); verify audience non-empty (defense-in-depth); surfaceAuthServerConfigValidstatus condition; invalid config producesFailedphase with descriptive messagecmd/thv-operator/pkg/vmcpconfig/converter.go— resolvespec.authServerConfigRef→AuthServerConfig.RunConfig; deriveallowedAudiencesfromspec.incomingAuth.oidcConfig.inline.audienceTests:
pkg/vmcp/server/server.goHTTP handler unit tests — Mode A: AS routes return 404,oauth-protected-resourcereturns RFC 9728 response; Mode B: AS routes served,oauth-protected-resourceserved, unauthenticated MCP catch-all returns 401test/e2e/vmcp_authserver_test.go— positive: Mode B OIDC discovery returns valid document; Mode B unauthenticated MCP returns 401; Mode A discovery returns 404test/e2e/vmcp_authserver_test.go— negative: issuer mismatch → non-zero exit + V-04 stderr;upstream_injectno AS → V-01 stderr; unknown provider → V-02 stderrtest/e2e/chainsaw/operator/ortest/e2e/): createMCPExternalAuthConfig+VirtualMCPServer; verify deployment; verifyAuthServerConfigValidcondition viaEventuallyDocumentation updates:
docs/arch/09-operator-architecture.md— newVirtualMCPServerSpec.AuthServerConfigReffield and reconciliation stepsdocs/arch/02-core-concepts.md— Mode A / Mode B distinction for vMCP authdocs/— new vMCP auth server guide (config walkthrough, example YAML, troubleshooting self-referencing OIDC discovery)task docsto regenerate CRD documentationDependencies: Phases 1, 2, and 3 must be merged. RFC-0052 (#3924) is required for full integration test of the end-to-end auth flow (upstream token population).
Additional Notes
EmbeddedAuthServerimplementation inpkg/authserver/runner/already exists and is used by the proxy runner. No new AS implementation is needed for this RFC — only theRegisterHandlersmethod is new.TokenValidatoruses lazy OIDC discovery (deferred to first token validation) with exponential backoff retry.jwksAllowPrivateIP: truemust be set in the incoming auth config for in-cluster deployments.allowedAudiencesfrom the referencingVirtualMCPServer's incoming auth audience, so they are always consistent. The reconciler still checks post-conversion for defense-in-depth (empty audience guard).ExternalAuthConfigRefmove (Phase 1) is a struct definition move within the same Go package (v1alpha1). All existing callers usingv1alpha1.ExternalAuthConfigRefare unaffected — no API surface changes.tgrunnagle commentedon Mar 13, 2026
Planning Artifact: Research
Research: vMCP — Add Embedded Authorization Server (RFC-0053)
Local Repository Clones
/Users/trey/Documents/GitHub/toolhive—stacklok/toolhive(primary): main service being changed; contains all affected packages (pkg/vmcp/,pkg/authserver/,cmd/vmcp/,cmd/thv-operator/)Reference Documentation
Key documents discovered during research. Include retrieval paths for sub-agents.
In Repository
/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0053-vmcp-embedded-authserver.md— Full RFC-0053 design document: problem statement, Mode A/B design, detailed config model changes, CRD changes, operator reconciler changes, HTTP route mounting, validation rules V-01..V-07, security considerations, alternatives considered, and 4-phase implementation plan/Users/trey/Documents/GitHub/toolhive/docs/proposals/THV-0052-multi-upstream-idp-authserver.md— RFC-0052 (multi-upstream IDP support): dependency of RFC-0053; definesidentity.UpstreamTokenspopulation by the OIDC auth middleware/Users/trey/Documents/GitHub/toolhive/CONTRIBUTING.md— Contribution guidelines: DCO sign-off requirement, PR process, commit message guidelines/Users/trey/Documents/GitHub/toolhive/CLAUDE.md— Project-specific AI guidance: subagent list, build commands, architecture overview, testing strategy, coding conventions, commit/PR standards/Users/trey/Documents/GitHub/toolhive/docs/arch/09-operator-architecture.md— Kubernetes operator architecture: CRD hierarchy, reconciler design, VirtualMCPServer lifecycle; must be updated in Phase 4/Users/trey/Documents/GitHub/toolhive/docs/arch/02-core-concepts.md— Core concepts: workloads, transports, security model; must be updated in Phase 4 for Mode A/B distinction/Users/trey/Documents/GitHub/toolhive/docs/cli-best-practices.md— CLI development patterns: thin-wrapper principle, flag naming, output formatting, testing philosophy/Users/trey/Documents/GitHub/toolhive/docs/error-handling.md— Error handling guidelines: wrap with%w, no sensitive data in errors,errors.Is/errors.Asfor inspection/Users/trey/Documents/GitHub/toolhive/docs/logging.md— Logging guidelines: silent success, DEBUG for diagnostics, no sensitive dataExternal URLs
identity.UpstreamTokenspopulation; Phases 1–2 can be developed in parallel with RFC-0052, but full E2E integration requires it to be merged/.well-known/oauth-protected-resourceendpoint semanticsOrganizational Standards
Coding Conventions
go.uber.org/mock(gomock) for all mocks; generate withmockgen; place mocks inmocks/subdirectoriesfmt.Errorfwith%wfor error wrapping; never silently swallow errorserrors.Is()/errors.As()for all error inspectionrequire.NoError(t, err)preferred overt.Fatalin testsslog.Debugfor diagnostics;slog.Infosparingly (long-running ops only);slog.Warnfor non-fatal fallbacksReview Process
.github/pull_request_template.mdexactly — no placeholder text left in required sectionsfeat:,fix:,chore:, etc.)Signed-off-bytrailer (DCO)Documentation Standards
docs/arch/must be updated when components change (see CLAUDE.md table)file_pathformat (without line numbers, since they change)docs/arch/02-core-concepts.mdtask docsafter any CRD changesTesting Requirements
*_test.go);pkg/packages require thorough coveragecmd/thv/app/) tested primarily with E2E tests; only output formatting/flag validation get unit testst.TempDir()thenfilepath.EvalSymlinks(dir)on macOS (symlink resolution for path validators)math.MaxInt16) to avoid port conflictsArchitecture & Design
System Architecture
cmd/vmcp/) or as a Kubernetes Deployment managed bythv-operator.thv-operatorwatches CRDs, reconciles Kubernetes resources (Deployment, Service, ConfigMap, ServiceAccount, RBAC). The CRD-to-Config converter (cmd/thv-operator/pkg/vmcpconfig/converter.go) translates the CRD spec into a platform-agnosticpkg/vmcp/config.ConfigYAML that vMCP reads at startup.pkg/vmcp/config.Configstruct is the central configuration model shared by both the CLI YAML path and the Kubernetes path.IncomingAuth) and outgoing (vMCP → backends, configured viaOutgoingAuth). These are intentionally independent config sections.Established Patterns
pkg/vmcp/auth/factory/creates auth middleware from config.NewIncomingAuthMiddleware(ctx, cfg.IncomingAuth)returns(authMw, authzMw, authInfoHandler, err). New AS creation follows the same conditional creation pattern already used for other components.cmd/thv-operator/pkg/vmcpconfig/converter.goConvert()starts withconfig := vmcp.Spec.Config.DeepCopy()then conditionally overrides each section. NewauthServerConfigRefresolution follows the same pattern as existingconvertIncomingAuth.cmd/thv-operator/controllers/virtualmcpserver_controller.gousesmetav1.Conditionslices andAuthConfigErrortype to surface per-resource validation failures. NewAuthServerConfigValidcondition follows this established pattern.+kubebuilder:object:generate=trueannotation: Used on structs that need deepcopy generated. Adding toAuthServerConfigtriggers regeneration ofzz_generated.deepcopy.go.omitemptyfor optional fields: All optional config fields usejson:"fieldName,omitempty" yaml:"fieldName,omitempty"tags.cfg.AuthServer != nil(YAML path) ors.config.AuthServer != nil(server path), ensuring byte-for-byte Mode A compatibility.Prior Decisions
ExternalAuthConfigRefreuse for vMCP auth server reference: Rather than embeddingEmbeddedAuthServerConfigdirectly inVirtualMCPServerSpecor creating a new CRD, RFC-0053 reuses the existingMCPExternalAuthConfigpattern. This is consistent with howMCPServer.spec.externalAuthConfigRefworks and allows sharing config across multipleVirtualMCPServerresources. See Alternatives Considered section of RFC-0053.allowedAudiencesderived by converter, not stored in CRD: TheMCPExternalAuthConfig.embeddedAuthServerspec intentionally omitsallowedAudiencesbecause its correct value depends on the referencingVirtualMCPServer. The converter derives it fromspec.incomingAuth.oidcConfig.inline.audience.MCPExternalAuthConfig.embeddedAuthServer.issuer. No auto-derivation from service name. (RFC-0053, Decisions section.)RedisStorageConfigdoes not expose TLS fields in the CRD; encryption in transit is the responsibility of the cluster service mesh.TokenValidatoruses lazy OIDC discovery with exponential backoff retry (deferred to first token validation, not server startup). This means the loopback to the embedded AS works because the AS is serving before the first client token arrives.API Contracts
pkg/authserver/runner.EmbeddedAuthServer: Already implemented. Public interface:NewEmbeddedAuthServer(ctx, *authserver.RunConfig) (*EmbeddedAuthServer, error),Handler() http.Handler,Close() error,IDPTokenStorage() storage.UpstreamTokenStorage,UpstreamTokenRefresher() storage.UpstreamTokenRefresher. The new methodRegisterHandlers(mux *http.ServeMux)is additive.pkg/vmcp/server.Config: Existing fields includeAuthMiddleware,AuthzMiddleware,AuthInfoHandler http.Handler. New fieldAuthServer *runner.EmbeddedAuthServeris additive.pkg/vmcp/config.Config: Existing fields includeIncomingAuth,OutgoingAuth,Aggregation, etc. New fieldAuthServer *AuthServerConfigis additive withomitempty.pkg/vmcp/auth/types: Existing constants:StrategyTypeUnauthenticated,StrategyTypeHeaderInjection,StrategyTypeTokenExchange. New constantStrategyTypeUpstreamInject = "upstream_inject"must be added (Phase 3).Known Constraints
/.well-known/catch-all replacement is behavioral but non-breaking: Currentlymux.Handle("/.well-known/", wellKnownHandler)at line 485 ofpkg/vmcp/server/server.goserves only/.well-known/oauth-protected-resource; all other/.well-known/paths return 404. Replacing with explicit path registration preserves this behavior while allowing the AS to register its own well-known paths.cfg.AuthServer != nil. Existing configs that omitauthServerare unaffected.ExternalAuthConfigRefmove is within the same package: Moving the struct definition frommcpserver_types.gotomcpexternalauthconfig_types.gois within packagev1alpha1. All existing callers usingv1alpha1.ExternalAuthConfigRefare unaffected — no API surface changes.allowedAudiencesis derived by the converter from the referencingVirtualMCPServer's incoming auth audience, making the check structurally satisfied. The reconciler checks post-conversion only as a defense-in-depth empty-audience guard.jwksAllowPrivateIPis a gap: The RFC example YAML usesjwksAllowPrivateIP: trueinIncomingAuth.OIDCConfig. The currentpkg/vmcp/config.OIDCConfigstruct does not have this field. The underlyingpkg/auth.TokenValidatorConfig.AllowPrivateIPexists, and the currentProtectedResourceAllowPrivateIPfield already maps to it. Phase 1 or 2 must add a dedicatedJwksAllowPrivateIP boolfield toconfig.OIDCConfigand wire it throughpkg/vmcp/auth/factory/incoming.go'snewOIDCAuthMiddleware, so in-cluster loopback OIDC discovery works for Mode B.StrategyTypeUpstreamInjectdoes not yet exist: The constant and correspondingBackendAuthStrategyfield (UpstreamInject *UpstreamInjectConfig) must be added topkg/vmcp/auth/types/types.goin Phase 3, alongside thevalidateBackendAuthStrategyextension.AuthServerConfig(with+kubebuilder:object:generate=true) topkg/vmcp/config/config.go,zz_generated.deepcopy.gomust be regenerated. Incmd/thv-operator/: after any CRD type changes,task operator-generate,task operator-manifests, andtask crdref-genmust be run.Codebase Analysis
Relevant Directories
/Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/— Platform-agnostic vMCP config model:Configstruct,IncomingAuthConfig,OIDCConfig,OutgoingAuthConfig,DefaultValidator,zz_generated.deepcopy.go. Primary location for Phase 1 and Phase 3 changes./Users/trey/Documents/GitHub/toolhive/pkg/vmcp/server/— HTTP server implementation:Configstruct,Handler()method with mux registration, middleware chain. Phase 2 changes here./Users/trey/Documents/GitHub/toolhive/pkg/authserver/runner/—EmbeddedAuthServerwrapper:NewEmbeddedAuthServer,Handler(),Close(). NewRegisterHandlersmethod added in Phase 2./Users/trey/Documents/GitHub/toolhive/pkg/vmcp/auth/— vMCP auth layer:factory/incoming.gocreates incoming middleware from config;factory/outgoing.gocreates outgoing registry;types/types.godefines strategy type constants andBackendAuthStrategystruct./Users/trey/Documents/GitHub/toolhive/cmd/vmcp/app/— vMCP CLI entry point:commands.gocontainsrunServe,loadAndValidateConfig,discoverBackends. Phase 2 inserts conditional AS creation and wires it toserverCfg.AuthServer./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/— CRD type definitions:mcpserver_types.go(containsExternalAuthConfigRefto move),mcpexternalauthconfig_types.go(receivesExternalAuthConfigRef, already hasEmbeddedAuthServerConfig),virtualmcpserver_types.go(receivesAuthServerConfigReffield). Phase 1 and Phase 4 changes./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/pkg/vmcpconfig/— CRD-to-Config converter:converter.goConvert()method. Phase 4 addsauthServerConfigRefresolution step./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/controllers/— Operator reconcilers:virtualmcpserver_controller.gohandles the VirtualMCPServer reconciliation loop. Phase 4 adds cross-resource validation andAuthServerConfigValidstatus condition./Users/trey/Documents/GitHub/toolhive/test/e2e/— E2E tests: Ginkgo v2 + Gomega, packagee2e_test. New filevmcp_authserver_test.gogoes here (Phase 4).Key File Details
/Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/config.goConfigstruct: lines 89–159. HasIncomingAuth *IncomingAuthConfig,OutgoingAuth *OutgoingAuthConfig, etc. AddAuthServer *AuthServerConfighere withomitemptyJSON/YAML tags and a+optionalkubebuilder comment.IncomingAuthConfigstruct: lines 172–181. ContainsType string,OIDC *OIDCConfig,Authz *AuthzConfig.OIDCConfigstruct: lines 186–218. HasIssuer,ClientID,Audience,ProtectedResourceAllowPrivateIP,InsecureAllowHTTP. Needs a newJwksAllowPrivateIP boolfield for Mode B loopback OIDC discovery.AuthServerConfig(wrapsauthserver.RunConfig) with+kubebuilder:object:generate=true./Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/validator.goDefaultValidator.Validate(): lines 31–81. Calls a series of sub-validators and accumulates errors. NewvalidateAuthServerIntegration(cfg)call is added here.validateBackendAuthStrategy(): lines 182–223. Currently allowsunauthenticated,header_injection,token_exchange. Must addupstream_injecttovalidTypesand add a case in the switch for V-01/V-02/V-06.contains(slice []string, item string) boolat line 441 can be aliased ascontainsString./Users/trey/Documents/GitHub/toolhive/pkg/vmcp/server/server.goConfigstruct: lines 84–~160. HasAuthMiddleware,AuthzMiddleware,AuthInfoHandler. AddAuthServer *runner.EmbeddedAuthServerhere.Handler()method: line 444. The/.well-known/catch-all is at line 485. Replace with explicit/.well-known/oauth-protected-resourceregistration. Add conditional AS route mounting after (or before) the well-known block./Users/trey/Documents/GitHub/toolhive/pkg/authserver/runner/embeddedauthserver.goEmbeddedAuthServerstruct: lines 39–43.Handler()method: lines 115–117. Returns the underlying server's HTTP handler, which serves all/oauth/*and/.well-known/*paths.RegisterHandlerswill calle.Handler()once and register it on the provided mux at specific paths./Users/trey/Documents/GitHub/toolhive/cmd/vmcp/app/commands.gorunServe(): lines 345–576. Aftercfg, err := loadAndValidateConfig(configPath)and before buildingserverCfg, insert: conditionalrunner.NewEmbeddedAuthServer(ctx, cfg.AuthServer.RunConfig)with hard failure on error, and setserverCfg.AuthServer = authServer.loadAndValidateConfig(): lines 203–229. Callsconfig.NewValidator().Validate(cfg). No changes needed here; V-01..V-07 are invoked viaValidate()./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/mcpserver_types.goExternalAuthConfigRefstruct: lines 632–638. Definition to be moved tomcpexternalauthconfig_types.go./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.goEmbeddedAuthServerConfigstruct: lines 152–200. DefinesIssuer,SigningKeySecretRefs,HMACSecretRefs,TokenLifespans,UpstreamProviders,Storage. Note:AllowedAudiencesfield is intentionally absent (derived by converter). Receives the movedExternalAuthConfigRefstruct.MCPExternalAuthConfig.Validate(): lines 714–736. Already handlesExternalAuthTypeEmbeddedAuthServercase./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.goVirtualMCPServerSpec: lines 17–76. HasIncomingAuth,OutgoingAuth,Config,EmbeddingServerRef. AddAuthServerConfigRef *ExternalAuthConfigRefhere with+optionalmarker.VirtualMCPServer.Validate(): lines 364–398. Add call tor.validateAuthServerConfig()at the end (beforereturn r.validateEmbeddingServer()).ConditionTypeAuthServerConfigValid = "AuthServerConfigValid"here./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/pkg/vmcpconfig/converter.goConvert(): lines 68–150. After existing conversions, add a new resolution step: ifvmcp.Spec.AuthServerConfigRef != nil, fetch theMCPExternalAuthConfig, verify type isembeddedAuthServer, call a new helper to convertEmbeddedAuthServerConfig→authserver.RunConfig, deriveallowedAudiencesfromvmcp.Spec.IncomingAuth.OIDCConfig.Inline.Audience, and setconfig.AuthServer./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/controllers/virtualmcpserver_controller.goVirtualMCPServerReconciler.Reconcile(): line 114. Phase 4 adds a new reconciliation step to resolveauthServerConfigRef, verify type and issuer consistency, surfaceAuthServerConfigValidstatus condition, and produceFailedphase with descriptive message on invalid config./Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/zz_generated.deepcopy.goDeepCopyIntoandDeepCopyfunctions. After addingAuthServerConfigwith+kubebuilder:object:generate=true, regenerate withtask genorcontroller-gen.Similar Implementations
/Users/trey/Documents/GitHub/toolhive/pkg/vmcp/auth/factory/incoming.go— Pattern for conditionally creating a component from config (OIDC vs. local vs. anonymous). The AS creation incommands.gofollows the same "check config, construct component, hard-fail on error" pattern./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/pkg/vmcpconfig/converter.goconvertIncomingAuth()— Pattern for resolving a CRD reference (OIDC resolver) and mapping it to apkg/vmcp/configtype. TheauthServerConfigRefresolution follows this exact structure./Users/trey/Documents/GitHub/toolhive/cmd/thv-operator/controllers/virtualmcpserver_controller.go—AuthConfigErrorstruct and status condition surfacing — template for the newAuthServerConfigValidcondition.Test Patterns
/Users/trey/Documents/GitHub/toolhive/pkg/vmcp/config/validator_test.go— Current pattern for validator tests: standard Gotestingpackage with table-driven[]struct{name, cfg, wantErr, errMsg}. The RFC calls for GinkgoDescribeTablefor the new V-01..V-07 entries. Implementers can either add a separate_test.gofile using Ginkgo (consistent with RFC spec) or add Go-native table-driven tests to the existing file (consistent with the current file style). If using Ginkgo, a Ginkgo test suite bootstrap is needed for theconfigpackage./Users/trey/Documents/GitHub/toolhive/test/e2e/e2e_suite_test.go— E2E suite setup:TestE2e(t)registers Ginkgo,BeforeSuite/AfterSuitemanage shared config dir. Newvmcp_authserver_test.gojoins the existing suite automatically./Users/trey/Documents/GitHub/toolhive/test/e2e/proxy_oauth_test.go— Best reference for vMCP auth E2E tests: starts a mock OIDC server, runs a process, makes HTTP requests, usesBy()for test narration, usesEventually()for async assertions./Users/trey/Documents/GitHub/toolhive/test/e2e/oidc_mock.go—OIDCMockServerhelper: reusable mock OIDC server backed by Ory Fosite. Mode B E2E tests can reuse this as an upstream IDP.File Naming Conventions
{resource}_types.go(e.g.,mcpserver_types.go,virtualmcpserver_types.go){resource}_controller.goconverter.go(within a purpose-named package likevmcpconfig){source_file}_test.goalongside the source, or{feature}_test.gointest/e2e/zz_generated.deepcopy.goRelated Work
Open Issues
identity.UpstreamTokenspopulation by the OIDC auth middleware; Phases 1–2 can be developed in parallel, full E2E requires RFC-0052 mergedRecent PRs
Known Tech Debt
validateBackendAuthStrategyhas aTODOcomment at line 191–192 ofvalidator.gonoting strategies to add later:"pass_through","client_credentials","oauth_proxy". Phase 3 addsupstream_injectto this list.OIDCConfigstruct currently reusesProtectedResourceAllowPrivateIPfor both the protected resource metadata endpoint and JWKS/OIDC discovery endpoint. For Mode B, a distinctJwksAllowPrivateIPfield is needed to allow the loopback self-referencing OIDC discovery without also enabling private IPs for the protected resource endpoint.Gaps & Open Questions
jwksAllowPrivateIPfield missing fromconfig.OIDCConfig: The RFC's example YAML usesjwksAllowPrivateIP: true. The currentconfig.OIDCConfigstruct inpkg/vmcp/config/config.goonly hasProtectedResourceAllowPrivateIP(which maps toauth.TokenValidatorConfig.AllowPrivateIP). A new dedicatedJwksAllowPrivateIP boolfield must be added toOIDCConfigand wired throughpkg/vmcp/auth/factory/incoming.go. This should be treated as a Phase 1 or Phase 2 task.StrategyTypeUpstreamInjectandUpstreamInjectConfignot yet inpkg/vmcp/auth/types/types.go: The constant and struct must be added in Phase 3 alongside thevalidateBackendAuthStrategyextension. TheBackendAuthStrategystruct will need anUpstreamInject *UpstreamInjectConfigfield.UpstreamInjectConfigneeds at minimum aProviderName stringfield (referenced in RFC V-02 and V-06 checks).Ginkgo suite bootstrap for
pkg/vmcp/config/package: The currentvalidator_test.gouses standardtesting, not Ginkgo. If the RFC's GinkgoDescribeTablestyle is followed for V-01..V-07 tests, a Ginkgo suite bootstrap (_suite_test.gowithRunSpecs) must be added to theconfigpackage. Alternatively, the new tests can follow the existingtestingtable-driven style — this is a style decision for the planner to resolve.OIDCConfigRef.Inline field access in converter: The converter derives
allowedAudiencesfromvmcp.Spec.IncomingAuth.OIDCConfig.Inline.Audience. TheOIDCConfigReftype invirtualmcpserver_types.goneeds verification that.Inlineexists and has anAudiencefield (this is the CRD-side type, distinct fromconfig.OIDCConfig).Operator RBAC for
MCPExternalAuthConfigget: The reconciler already has// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpexternalauthconfigs,verbs=get;list;watchat line 98 ofvirtualmcpserver_controller.go. No new RBAC markers needed.Phase 4 E2E test location for operator tests: The intake lists both
test/e2e/chainsaw/operator/andtest/e2e/as potential locations for the operator E2E test. The planner should clarify which location to use based on the team's current operator testing approach.tgrunnagle commentedon Mar 13, 2026
Planning Artifact: Architecture
Architecture: vMCP — Add Embedded Authorization Server (RFC-0053)
Overview
Add an optional embedded OAuth authorization server to vMCP. When
Config.AuthServeris nil(Mode A), behavior is byte-for-byte identical to today. When set (Mode B), the AS mounts
OAuth/OIDC endpoints on the same mux as vMCP, drives clients through upstream IDPs, issues
TH-JWTs, and populates
identity.UpstreamTokensfor downstream auth strategies.Mode A / Mode B
Config.AuthServernil*AuthServerConfig/oauth/, 3/.well-known/pathsidentity.Tokenidentity.UpstreamTokensnilidentity.Claims["tsid"]Invariant: all new Mode B code paths are gated on
cfg.AuthServer != nil(config/validationlayer) or
s.config.AuthServer != nil(server layer). Mode A executes zero new lines.Code Structure
New Code Locations
pkg/vmcp/config/config.go—AuthServerConfigstruct;AuthServer *AuthServerConfigfield onConfigpkg/vmcp/config/validator.go—validateAuthServerIntegration; helperscollectAllBackendStrategies,hasUpstreamProviderpkg/vmcp/auth/types/types.go—StrategyTypeUpstreamInjectconstant;UpstreamInjectConfigstruct;UpstreamInjectfield onBackendAuthStrategypkg/authserver/runner/embeddedauthserver.go—RegisterHandlers(mux *http.ServeMux)method (additive)test/e2e/thv-operator/virtualmcp/virtualmcp_authserver_test.go— operator E2E tests (Phase 4)test/e2e/vmcp_authserver_test.go— CLI/YAML-path E2E tests (Phase 4)Key Files to Modify
pkg/vmcp/config/config.go— addAuthServer *AuthServerConfigtoConfig; addJwksAllowPrivateIP booltoOIDCConfigpkg/vmcp/config/zz_generated.deepcopy.go— regenerate after addingAuthServerConfigpkg/vmcp/server/server.go— addAuthServer *runner.EmbeddedAuthServerto serverConfig; callRegisterHandlersconditionally; replacemux.Handle("/.well-known/", ...)catch-all (line ~485) with explicit/.well-known/oauth-protected-resourceregistrationcmd/vmcp/app/commands.go— conditional AS creation inrunServe()afterloadAndValidateConfig; passauthServertoserverCfg.AuthServercmd/thv-operator/api/v1alpha1/mcpserver_types.go— removeExternalAuthConfigRefstruct definition (moved)cmd/thv-operator/api/v1alpha1/mcpexternalauthconfig_types.go— addExternalAuthConfigRefstruct (received from above)cmd/thv-operator/api/v1alpha1/virtualmcpserver_types.go— addAuthServerConfigRef *ExternalAuthConfigReftoVirtualMCPServerSpec; addConditionTypeAuthServerConfigValid; addvalidateAuthServerConfig()methodcmd/thv-operator/pkg/vmcpconfig/converter.go— addauthServerConfigRefresolution step inConvert()cmd/thv-operator/controllers/virtualmcpserver_controller.go— add cross-resource validation (type check, V-04, audience guard); surfaceAuthServerConfigValidstatus conditionReference Implementations
pkg/vmcp/auth/factory/incoming.go— pattern for conditional component creation from config (check → construct → hard-fail)cmd/thv-operator/pkg/vmcpconfig/converter.goconvertIncomingAuth()— pattern for resolving a CRD reference to apkg/vmcp/configtypecmd/thv-operator/controllers/virtualmcpserver_controller.govalidateSpec()— pattern for surfacing a status condition on validation failuretest/e2e/thv-operator/virtualmcp/virtualmcp_external_auth_test.go— closest analog for operator auth E2E teststest/e2e/proxy_oauth_test.go— pattern for vMCP auth E2E tests (mock OIDC, process start, HTTP assertions,Eventually)test/e2e/oidc_mock.go— reusableOIDCMockServerfor Mode B E2E upstream IDPAPI Contracts
AuthServerConfig(new — Phase 1)Added to
pkg/vmcp/config/config.go. Shared between the YAML config model, the serverConfig, and the operator converter.Added to
Config:Added to server
Configinpkg/vmcp/server/server.go:RegisterHandlers(new — Phase 2)New method on
EmbeddedAuthServerinpkg/authserver/runner/embeddedauthserver.go.Consumed by
pkg/vmcp/server/server.go.StrategyTypeUpstreamInject+UpstreamInjectConfig(new — Phase 3)Added to
pkg/vmcp/auth/types/types.go. Consumed by validator V-01/V-02/V-06 checks.Note: the
upstream_injectoutgoing strategy implementation is deferred to a follow-up RFC;only the constant, config struct, and validation are added here.
BackendAuthStrategygains:JwksAllowPrivateIPonOIDCConfig(new — Phase 1 or 2)Added to
pkg/vmcp/config/config.goOIDCConfigstruct. Required for Mode B in-clusterloopback OIDC discovery. Must be wired through
pkg/vmcp/auth/factory/incoming.gonewOIDCAuthMiddlewaretoauth.TokenValidatorConfig.AllowPrivateIP.Validation Rules (Phase 3)
New function
validateAuthServerIntegration(cfg *Config) errorcalled at the end ofDefaultValidator.Validate()inpkg/vmcp/config/validator.go.upstream_injectused butAuthServer == nilupstream_injectProviderNamenot inAuthServer.RunConfig.Upstreamstoken_exchangeused when AS is incoming auth providerslog.Warn)AuthServer.RunConfig.Issuer≠IncomingAuth.OIDC.IssuerNewEmbeddedAuthServerinternal config validation failsupstream_injectProviderNameis empty stringIncomingAuth.OIDC.Audiencenot inAuthServer.RunConfig.AllowedAudiencesK8s path note for V-07: The converter derives
allowedAudiencesfromspec.incomingAuth.oidcConfig.inline.audience, making V-07 structurally satisfied. Thereconciler checks post-conversion only as a defense-in-depth empty-audience guard.
Integration Points
pkg/authserver/runner.EmbeddedAuthServerAlready implemented. Existing public API:
NewEmbeddedAuthServer(ctx, *authserver.RunConfig) (*EmbeddedAuthServer, error)Handler() http.HandlerClose() errorIDPTokenStorage() storage.UpstreamTokenStorageUpstreamTokenRefresher() storage.UpstreamTokenRefresherThe new
RegisterHandlersmethod is purely additive. No existing callers are affected.pkg/authserver.RunConfigThe YAML-path serializable config consumed by
EmbeddedAuthServer. Key fields relevant tovalidation:
Issuer string,AllowedAudiences []string,Upstreams []UpstreamRunConfig(each has
Name string).Operator Converter (
cmd/thv-operator/pkg/vmcpconfig/converter.go)Convert()starts withconfig := vmcp.Spec.Config.DeepCopy()and then applies explicitoverrides. The new step follows the existing
convertIncomingAuthpattern:vmcp.Spec.AuthServerConfigRef != nil, fetch theMCPExternalAuthConfigby name.spec.type == "embeddedAuthServer".EmbeddedAuthServerConfig→authserver.RunConfig.allowedAudiencesfromvmcp.Spec.IncomingAuth.OIDCConfig.Inline.Audience.config.AuthServer = &vmcpconfig.AuthServerConfig{RunConfig: runConfig}.Operator Reconciler (
cmd/thv-operator/controllers/virtualmcpserver_controller.go)Validation is performed inside
runValidations()beforeensureAllResources(). The newAuthServerConfigValidcondition follows the existingAuthConfigError/validateSpecpattern using
statusManager.SetCondition(...). Invalid config producesFailedphase witha descriptive message; reconciliation does not proceed to resource creation.
identity.UpstreamTokens(RFC-0052 dependency)identity.UpstreamTokenspopulation — extractingtsidfrom TH-JWT and loading upstreamtokens from AS storage — is defined and implemented by RFC-0052 (#3924). Phases 1–2 can be
developed in parallel with RFC-0052; full E2E integration test of the auth flow requires
RFC-0052 to be merged.
HTTP Route Table (after Phase 2)
The
/.well-known/catch-all atserver.go:485is replaced with an explicit/.well-known/oauth-protected-resourceregistration. Behavioral impact: none — the oldcatch-all only served that single path; all other
/.well-known/paths already returned 404.CRD Changes (Phase 1 + 4)
ExternalAuthConfigRefmoveStruct definition moves from
mcpserver_types.go:632tomcpexternalauthconfig_types.go.Same
v1alpha1package — all existing callers (v1alpha1.ExternalAuthConfigRef) areunaffected. No API surface change.
VirtualMCPServerSpecnew fieldNew status condition type
After CRD changes, run:
Core Principles
Mode A nil-gate: Every Mode B code path must start with
if cfg.AuthServer != nilorif s.config.AuthServer != nil. Mode A must pass all existing tests unchanged.(see
pkg/vmcp/auth/factory/incoming.gofor the creation pattern)Hard fail, no silent fallback: If
NewEmbeddedAuthServerreturns an error in Mode B,the process must exit with that error. Never silently fall back to Mode A.
(see
cmd/vmcp/app/commands.gorunServe()pattern)Converter derives, validator checks: In the K8s path,
allowedAudiencesis derivedby the converter (never stored in the CRD). In the YAML path, it is explicit and validated
by V-07. Do not add
allowedAudiencesas a field onEmbeddedAuthServerConfigin the CRD.Additive only:
AuthServerConfig,RegisterHandlers,UpstreamInjectConfigare alladditive — no existing struct fields are removed or renamed, no existing method signatures
change.
omitemptyon all optional fields:AuthServer,AuthServerConfigRef, andJwksAllowPrivateIPall useomitemptyso existing configs round-trip without changes.Constraints
identity.UpstreamTokenspopulation requires RFC-0052 (Auth Server: multi-upstream provider support #3924).Phase 4 E2E tests that verify the full token flow must wait for RFC-0052 to land.
jwksAllowPrivateIPgap:OIDCConfigcurrently lacks this field. It must be added inPhase 1 or 2 and wired through
pkg/vmcp/auth/factory/incoming.gobefore Mode B in-clusterOIDC loopback works.
StrategyTypeUpstreamInjectgap: The constant andUpstreamInjectConfigdo not yetexist in
pkg/vmcp/auth/types/types.go. They must be added in Phase 3 alongside validatorchanges; the actual outgoing strategy implementation is deferred to a follow-up RFC.
testinginpkg/vmcp/config/: Currentvalidator_test.gouses standardtesting. If Phase 3 adds GinkgoDescribeTabletests, a Ginkgo suite bootstrap(
_suite_test.gowithRunSpecs) must also be added to theconfigpackage. Alternatively,use the existing
testingtable-driven style to avoid the bootstrap.normalization is applied. Operators must use the identical string in both the AS config and
the incoming auth config.
RedisStorageConfigdoes not expose TLS fields in theCRD. TLS in transit is the cluster service mesh's responsibility.
Out of Scope
upstream_injectoutgoing strategy implementation (deferred to follow-up RFC)pkg/auth/upstreamswap)jhrozek commentedon Mar 27, 2026
subtasks done, closing