-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathvirtualmcpserver_controller.go
More file actions
2874 lines (2558 loc) · 107 KB
/
virtualmcpserver_controller.go
File metadata and controls
2874 lines (2558 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0
// Package controllers contains the reconciliation logic for the VirtualMCPServer custom resource.
// It handles the creation, update, and deletion of Virtual MCP Servers in Kubernetes.
package controllers
import (
"context"
"crypto/rand"
"encoding/base64"
stderrors "errors"
"fmt"
"maps"
"reflect"
"strings"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/events"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
mcpv1alpha1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1alpha1"
ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/kubernetes/rbac"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/runconfig/configmap/checksum"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/virtualmcpserverstatus"
vmcptypes "github.com/stacklok/toolhive/pkg/vmcp"
"github.com/stacklok/toolhive/pkg/vmcp/auth/converters"
authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types"
vmcpconfig "github.com/stacklok/toolhive/pkg/vmcp/config"
"github.com/stacklok/toolhive/pkg/vmcp/workloads"
)
const (
// OutgoingAuthSourceDiscovered indicates that auth configs should be automatically discovered from MCPServers
OutgoingAuthSourceDiscovered = "discovered"
// OutgoingAuthSourceInline indicates that auth configs should be explicitly specified
OutgoingAuthSourceInline = "inline"
// Auth config error context constants
authContextDefault = "default"
authContextBackendPrefix = "backend:"
authContextDiscoveredPrefix = "discovered:"
)
// AuthConfigError represents a single auth config conversion failure.
// It captures context about which auth config failed and why, allowing the controller
// to continue in degraded mode while exposing the failure via status conditions.
//
// Context patterns:
// - "default": Default auth config (OutgoingAuth.Default)
// - "backend:<name>": Inline backend-specific config (OutgoingAuth.Backends[name])
// - "discovered:<name>": Discovered from MCPServer/MCPRemoteProxy ExternalAuthConfigRef
type AuthConfigError struct {
// Context describes where the error occurred: "default", "backend:<name>", or "discovered:<name>"
Context string
// BackendName is the backend name (empty for default auth config)
BackendName string
// Error is the underlying error that occurred during conversion
Error error
}
// SpecValidationError represents a spec validation failure that the user must fix.
// Unlike transient errors, these should NOT trigger requeue — the controller sets
// a status condition and waits for the user to update the spec.
type SpecValidationError struct {
Message string
}
func (e *SpecValidationError) Error() string {
return e.Message
}
// VirtualMCPServerReconciler reconciles a VirtualMCPServer object
//
// Resource Cleanup Strategy:
// VirtualMCPServer does NOT use finalizers because all managed resources have owner references
// set via controllerutil.SetControllerReference. Kubernetes automatically cascade-deletes
// owned resources when the VirtualMCPServer is deleted. Managed resources include:
// - Deployment (owned)
// - Service (owned)
// - ConfigMap for vmcp config (owned)
// - ServiceAccount, Role, RoleBinding via rbac.Client (owned)
//
// This differs from MCPServer which uses finalizers to explicitly delete resources that
// may not have owner references (StatefulSet, headless Service, RunConfig ConfigMap).
type VirtualMCPServerReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder events.EventRecorder
PlatformDetector *ctrlutil.SharedPlatformDetector
}
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=virtualmcpservers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=virtualmcpservers/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpgroups,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpservers,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpexternalauthconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcptoolconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=virtualmcpcompositetooldefinitions,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=services,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=roles,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=rolebindings,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=create;get;list;watch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpoidcconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpoidcconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=embeddingservers,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=embeddingservers/status,verbs=get
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *VirtualMCPServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Fetch the VirtualMCPServer instance
vmcp := &mcpv1alpha1.VirtualMCPServer{}
err := r.Get(ctx, req.NamespacedName, vmcp)
if err != nil {
if errors.IsNotFound(err) {
ctxLogger.Info("VirtualMCPServer resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
ctxLogger.Error(err, "Failed to get VirtualMCPServer")
return ctrl.Result{}, err
}
// Create status manager for batched updates
statusManager := virtualmcpserverstatus.NewStatusManager(vmcp)
// Run all pre-reconciliation validations.
// Returns (true, nil) to continue, (false, nil) when validation failed but
// should not requeue (user must fix spec), or (false, err) for transient errors
// that should trigger requeue.
if cont, err := r.runValidations(ctx, vmcp, statusManager); err != nil {
return ctrl.Result{}, err
} else if !cont {
return ctrl.Result{}, nil
}
// Validate MCPOIDCConfigRef if referenced (before resource creation).
// handleOIDCConfig is a no-op when OIDCConfigRef is nil.
if err := r.handleOIDCConfig(ctx, vmcp, statusManager); err != nil {
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after MCPOIDCConfig validation error")
}
return ctrl.Result{}, err
}
// Ensure all resources
if result, err := r.ensureAllResources(ctx, vmcp, statusManager); err != nil {
// Apply status changes before returning error
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after resource reconciliation error")
}
return ctrl.Result{}, err
} else if result.RequeueAfter > 0 {
// Apply status changes before returning requeue (e.g., waiting for EmbeddingServer)
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates before requeue")
}
return result, nil
}
// Backend discovery and health reporting is now delegated to the vMCP runtime (StatusReporter).
// The runtime reports status.discoveredBackends, status.backendCount, backend health, and
// BackendsDiscovered condition based on actual MCP connectivity and health checks.
//
// Controller responsibilities (infrastructure-only):
// - RBAC (ServiceAccount, Role, RoleBinding)
// - Deployment, Service, ConfigMap
// - GroupRef validation
// - Infrastructure conditions (DeploymentReady, ServiceReady)
// - status.URL
//
// Runtime responsibilities (via StatusReporter with VMCP_NAME/VMCP_NAMESPACE env vars):
// - Backend discovery from MCPGroup
// - Backend health monitoring (ready/degraded/unavailable)
// - status.Phase (Ready/Degraded/Failed)
// - status.discoveredBackends with health status
// - status.backendCount
// - BackendsDiscovered condition
// Fetch the latest version before updating status to ensure we use the current Generation
latestVMCP := &mcpv1alpha1.VirtualMCPServer{}
if err := r.Get(ctx, types.NamespacedName{
Name: vmcp.Name,
Namespace: vmcp.Namespace,
}, latestVMCP); err != nil {
ctxLogger.Error(err, "Failed to get latest VirtualMCPServer before status update")
return ctrl.Result{}, err
}
// Update status based on pod health using the latest Generation
if err := r.updateVirtualMCPServerStatus(ctx, latestVMCP, statusManager); err != nil {
ctxLogger.Error(err, "Failed to update VirtualMCPServer status")
return ctrl.Result{}, err
}
// Apply all collected status changes in a single batch update
if err := r.applyStatusUpdates(ctx, latestVMCP, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply final status updates")
return ctrl.Result{}, err
}
// Reconciliation complete - rely on event-driven reconciliation
// Kubernetes will automatically trigger reconcile when:
// - VirtualMCPServer spec changes
// - Referenced resources (MCPGroup, Secrets) change
// - Owned resources (Deployment, Service) status changes
// - vmcp pods emit events about backend health
return ctrl.Result{}, nil
}
// validateSpec validates the VirtualMCPServer spec and updates status on error.
// Returns an error if validation fails, which signals the caller to stop reconciliation.
func (r *VirtualMCPServerReconciler) validateSpec(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
if err := vmcp.Validate(); err != nil {
ctxLogger.Error(err, "VirtualMCPServer spec validation failed")
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetCondition("Valid", "ValidationFailed", err.Error(), metav1.ConditionFalse)
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after validation error")
}
return err
}
// Validation succeeded - set Valid=True condition
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetCondition("Valid", "ValidationSucceeded", "Spec validation passed", metav1.ConditionTrue)
return nil
}
// applyStatusUpdates applies all collected status changes in a single batch update.
// This implements the StatusCollector pattern to reduce API calls and prevent update conflicts.
func (r *VirtualMCPServerReconciler) applyStatusUpdates(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// Fetch the latest version to avoid conflicts
latest := &mcpv1alpha1.VirtualMCPServer{}
if err := r.Get(ctx, types.NamespacedName{
Name: vmcp.Name,
Namespace: vmcp.Namespace,
}, latest); err != nil {
return fmt.Errorf("failed to get latest VirtualMCPServer: %w", err)
}
// Apply collected changes to the latest status
hasUpdates := statusManager.UpdateStatus(ctx, &latest.Status)
// Only update if there are changes
if hasUpdates {
if err := r.Status().Update(ctx, latest); err != nil {
// Handle conflicts by returning error to trigger requeue
if errors.IsConflict(err) {
ctxLogger.V(1).Info("Conflict updating status, will requeue")
return err
}
return fmt.Errorf("failed to update VirtualMCPServer status: %w", err)
}
ctxLogger.V(1).Info("Successfully applied batched status updates")
}
return nil
}
// runValidations runs all pre-reconciliation validations (PodTemplateSpec, GroupRef,
// CompositeToolRefs, EmbeddingServerRef, AuthServerConfig).
// Returns (true, nil) to continue reconciliation.
// Returns (false, nil) for spec validation errors that should NOT trigger requeue
// (user must fix the spec; next reconciliation is triggered by spec changes).
// Returns (false, error) for transient errors that should trigger requeue.
func (r *VirtualMCPServerReconciler) runValidations(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) (bool, error) {
ctxLogger := log.FromContext(ctx)
// Validate spec configuration early (schema-level validation from types.go).
// Don't requeue on validation errors — user must fix spec.
if err := r.validateSpec(ctx, vmcp, statusManager); err != nil {
return false, nil
}
// Validate PodTemplateSpec early - before other validations.
// Don't requeue — user must fix the PodTemplateSpec.
if !r.validateAndUpdatePodTemplateStatus(ctx, vmcp, statusManager) {
if err := r.applyStatusUpdates(ctx, vmcp, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply status updates after PodTemplateSpec validation error")
}
return false, nil
}
// Validate GroupRef
if err := r.validateGroupRef(ctx, vmcp, statusManager); err != nil {
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after GroupRef validation error")
}
return false, err
}
// Validate CompositeToolRefs
if err := r.validateCompositeToolRefs(ctx, vmcp, statusManager); err != nil {
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after CompositeToolRefs validation error")
}
return false, err
}
// Validate EmbeddingServerRef (when using reference mode)
if vmcp.Spec.EmbeddingServerRef != nil {
if err := r.validateEmbeddingServerRef(ctx, vmcp, statusManager); err != nil {
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after EmbeddingServerRef validation error")
}
return false, err
}
}
// Validate inline AuthServerConfig (when specified).
if vmcp.Spec.AuthServerConfig != nil {
if err := r.validateAuthServerConfig(vmcp, statusManager); err != nil {
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after AuthServerConfig validation error")
}
return false, nil
}
} else {
// Remove stale condition if AuthServerConfig was previously set then removed.
statusManager.RemoveConditionsWithPrefix(mcpv1alpha1.ConditionTypeAuthServerConfigValidated, []string{})
}
// Advisory: warn when replicas > 1 but session storage is not Redis-backed.
r.validateSessionStorageForReplicas(vmcp, statusManager)
return true, nil
}
// validateSessionStorageForReplicas emits a SessionStorageWarning condition when
// replicas > 1 but session storage is not configured with a Redis backend.
// Reconciliation continues regardless; this is advisory only.
func (*VirtualMCPServerReconciler) validateSessionStorageForReplicas(
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) {
if vmcp.Spec.Replicas != nil && *vmcp.Spec.Replicas > 1 {
if vmcp.Spec.SessionStorage == nil || vmcp.Spec.SessionStorage.Provider != mcpv1alpha1.SessionStorageProviderRedis {
statusManager.SetCondition(
mcpv1alpha1.ConditionSessionStorageWarning,
mcpv1alpha1.ConditionReasonSessionStorageMissing,
"replicas > 1 but sessionStorage.provider is not redis; sessions are not shared across replicas",
metav1.ConditionTrue,
)
} else {
statusManager.SetCondition(
mcpv1alpha1.ConditionSessionStorageWarning,
mcpv1alpha1.ConditionReasonSessionStorageConfigured,
"Redis session storage is configured",
metav1.ConditionFalse,
)
}
} else {
statusManager.SetCondition(
mcpv1alpha1.ConditionSessionStorageWarning,
mcpv1alpha1.ConditionReasonSessionStorageNotApplicable,
"session storage warning is not active",
metav1.ConditionFalse,
)
}
}
// validateAuthServerConfig validates inline AuthServerConfig and sets the
// AuthServerConfigValidated condition. Returns an error when validation fails
// (caller should NOT requeue — user must fix the spec).
func (*VirtualMCPServerReconciler) validateAuthServerConfig(
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
cfg := vmcp.Spec.AuthServerConfig
if cfg.Issuer == "" {
message := "spec.authServerConfig.issuer is required"
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetAuthServerConfigValidatedCondition(
mcpv1alpha1.ConditionReasonAuthServerConfigInvalid,
message,
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return fmt.Errorf("%s", message)
}
if len(cfg.UpstreamProviders) == 0 {
message := "spec.authServerConfig.upstreamProviders is required"
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetAuthServerConfigValidatedCondition(
mcpv1alpha1.ConditionReasonAuthServerConfigInvalid,
message,
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return fmt.Errorf("%s", message)
}
// AuthServerConfig is valid
statusManager.SetAuthServerConfigValidatedCondition(
mcpv1alpha1.ConditionReasonAuthServerConfigValid,
"AuthServerConfig is valid",
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return nil
}
// handleSpecValidationError checks whether err is a SpecValidationError (user must fix the spec).
// If so, it applies the already-set status conditions and returns nil (no requeue).
// Otherwise it returns the original error unchanged for normal requeue handling.
func (r *VirtualMCPServerReconciler) handleSpecValidationError(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
err error,
) error {
var specErr *SpecValidationError
if !stderrors.As(err, &specErr) {
return err
}
ctxLogger := log.FromContext(ctx)
if applyErr := r.applyStatusUpdates(ctx, vmcp, statusManager); applyErr != nil {
ctxLogger.Error(applyErr, "Failed to apply status updates after spec validation error")
return applyErr
}
return nil
}
// validateGroupRef validates that the referenced MCPGroup exists and is ready
func (r *VirtualMCPServerReconciler) validateGroupRef(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// Validate GroupRef exists
mcpGroup := &mcpv1alpha1.MCPGroup{}
err := r.Get(ctx, types.NamespacedName{
Name: vmcp.Spec.Config.Group,
Namespace: vmcp.Namespace,
}, mcpGroup)
if errors.IsNotFound(err) {
message := fmt.Sprintf("Referenced MCPGroup %s not found", vmcp.Spec.Config.Group)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetGroupRefValidatedCondition(
mcpv1alpha1.ConditionReasonVirtualMCPServerGroupRefNotFound,
message,
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return err
} else if err != nil {
ctxLogger.Error(err, "Failed to get MCPGroup")
return err
}
// Check if MCPGroup is ready
if mcpGroup.Status.Phase != mcpv1alpha1.MCPGroupPhaseReady {
message := fmt.Sprintf("Referenced MCPGroup %s is not ready (phase: %s)",
vmcp.Spec.Config.Group, mcpGroup.Status.Phase)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhasePending)
statusManager.SetMessage(message)
statusManager.SetGroupRefValidatedCondition(
mcpv1alpha1.ConditionReasonVirtualMCPServerGroupRefNotReady,
message,
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
// Requeue to check again later
return fmt.Errorf("MCPGroup %s is not ready", vmcp.Spec.Config.Group)
}
// GroupRef is valid and ready
statusManager.SetGroupRefValidatedCondition(
mcpv1alpha1.ConditionReasonVirtualMCPServerGroupRefValid,
fmt.Sprintf("MCPGroup %s is valid and ready", vmcp.Spec.Config.Group),
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return nil
}
// validateCompositeToolRefs validates that all referenced VirtualMCPCompositeToolDefinition resources exist
func (r *VirtualMCPServerReconciler) validateCompositeToolRefs(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// If no composite tool refs, nothing to validate
if len(vmcp.Spec.Config.CompositeToolRefs) == 0 {
// Set condition to indicate validation passed (no refs to validate)
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefsValid,
"No composite tool references to validate",
metav1.ConditionTrue,
)
return nil
}
// Validate each referenced composite tool definition exists
for i := range vmcp.Spec.Config.CompositeToolRefs {
ref := &vmcp.Spec.Config.CompositeToolRefs[i]
compositeToolDef := &mcpv1alpha1.VirtualMCPCompositeToolDefinition{}
err := r.Get(ctx, types.NamespacedName{
Name: ref.Name,
Namespace: vmcp.Namespace,
}, compositeToolDef)
if errors.IsNotFound(err) {
message := fmt.Sprintf("Referenced VirtualMCPCompositeToolDefinition %s not found", ref.Name)
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefNotFound,
message,
metav1.ConditionFalse,
)
return err
} else if err != nil {
ctxLogger.Error(err, "Failed to get VirtualMCPCompositeToolDefinition", "name", ref.Name)
return err
}
// Check that the composite tool definition is validated and valid
if compositeToolDef.Status.ValidationStatus == mcpv1alpha1.ValidationStatusInvalid {
message := fmt.Sprintf("Referenced VirtualMCPCompositeToolDefinition %s is invalid", ref.Name)
if len(compositeToolDef.Status.ValidationErrors) > 0 {
message = fmt.Sprintf("%s: %s", message, strings.Join(compositeToolDef.Status.ValidationErrors, "; "))
}
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefInvalid,
message,
metav1.ConditionFalse,
)
return fmt.Errorf("referenced VirtualMCPCompositeToolDefinition %s is invalid", ref.Name)
}
// If ValidationStatus is Unknown, we still allow it (validation might be in progress)
// but log a warning
if compositeToolDef.Status.ValidationStatus == mcpv1alpha1.ValidationStatusUnknown {
ctxLogger.V(1).Info("Referenced composite tool definition validation status is Unknown, proceeding",
"name", ref.Name, "namespace", vmcp.Namespace)
}
}
// All composite tool refs are valid
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefsValid,
fmt.Sprintf("All %d composite tool references are valid", len(vmcp.Spec.Config.CompositeToolRefs)),
metav1.ConditionTrue,
)
return nil
}
// validateAndUpdatePodTemplateStatus validates the PodTemplateSpec and uses StatusManager to collect
// status changes. Returns true if validation passes, false otherwise.
// The caller is responsible for applying status updates via applyStatusUpdates().
func (r *VirtualMCPServerReconciler) validateAndUpdatePodTemplateStatus(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) bool {
ctxLogger := log.FromContext(ctx)
// Only validate if PodTemplateSpec is provided
if vmcp.Spec.PodTemplateSpec == nil || vmcp.Spec.PodTemplateSpec.Raw == nil {
// No PodTemplateSpec provided, validation passes
return true
}
_, err := ctrlutil.NewPodTemplateSpecBuilder(vmcp.Spec.PodTemplateSpec, "vmcp")
if err != nil {
// Record event for invalid PodTemplateSpec
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, nil, corev1.EventTypeWarning, "InvalidPodTemplateSpec", "ValidatePodTemplateSpec",
"Failed to parse PodTemplateSpec: %v. Deployment blocked until PodTemplateSpec is fixed.", err)
}
// Use StatusManager to collect status changes
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(fmt.Sprintf("Invalid PodTemplateSpec: %v", err))
statusManager.SetCondition(
mcpv1alpha1.ConditionTypeVirtualMCPServerPodTemplateSpecValid,
mcpv1alpha1.ConditionReasonVirtualMCPServerPodTemplateSpecInvalid,
fmt.Sprintf("Failed to parse PodTemplateSpec: %v. Deployment blocked until fixed.", err),
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
ctxLogger.Error(err, "PodTemplateSpec validation failed")
return false
}
// Use StatusManager to collect status changes for valid PodTemplateSpec
statusManager.SetCondition(
mcpv1alpha1.ConditionTypeVirtualMCPServerPodTemplateSpecValid,
mcpv1alpha1.ConditionReasonVirtualMCPServerPodTemplateSpecValid,
"PodTemplateSpec is valid",
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return true
}
// ensureAllResources ensures all Kubernetes resources for the VirtualMCPServer.
// Returns a ctrl.Result with RequeueAfter when the controller should retry later
// (e.g., waiting for EmbeddingServer readiness), and an error for failures.
func (r *VirtualMCPServerReconciler) ensureAllResources(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Validate secret references before creating resources.
// This catches configuration errors early, providing faster feedback than waiting for pod startup failures.
if err := r.ensureAuthSecretsValid(ctx, vmcp, statusManager); err != nil {
return ctrl.Result{}, err
}
// Check EmbeddingServer readiness before proceeding to Deployment.
// RequeueAfter provides a safety net in case the Watches() events
// are missed (e.g., EmbeddingServer controller not running).
esURL, err := r.isEmbeddingServerReady(ctx, vmcp)
if err != nil {
return ctrl.Result{}, err
}
// EmbeddingServer is configured but not yet ready — requeue
if esURL == nil && vmcp.Spec.EmbeddingServerRef != nil {
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhasePending)
statusManager.SetMessage("Waiting for EmbeddingServer to become ready")
statusManager.SetEmbeddingServerReadyCondition(
mcpv1alpha1.ConditionReasonEmbeddingServerNotReady,
"EmbeddingServer is not yet ready",
metav1.ConditionFalse,
)
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
// If an embedding server is configured and ready, set the condition
if esURL != nil {
statusManager.SetEmbeddingServerReadyCondition(
mcpv1alpha1.ConditionReasonEmbeddingServerReady,
"EmbeddingServer is ready",
metav1.ConditionTrue,
)
}
// List workloads once and pass to functions that need them
// This ensures consistency - all functions use the same workload list
// rather than listing at different times which could yield different results
workloadDiscoverer := workloads.NewK8SDiscovererWithClient(r.Client, vmcp.Namespace)
workloadNames, err := workloadDiscoverer.ListWorkloadsInGroup(ctx, vmcp.Spec.Config.Group)
if err != nil {
ctxLogger.Error(err, "Failed to list workloads in group")
return ctrl.Result{}, fmt.Errorf("failed to list workloads in group: %w", err)
}
// Ensure RBAC resources
if err := r.ensureRBACResources(ctx, vmcp); err != nil {
ctxLogger.Error(err, "Failed to ensure RBAC resources")
return ctrl.Result{}, err
}
// Ensure HMAC secret for session token binding (Session Management V2)
if err := r.ensureHMACSecret(ctx, vmcp); err != nil {
ctxLogger.Error(err, "Failed to ensure HMAC secret")
return ctrl.Result{}, err
}
// Ensure vmcp Config ConfigMap.
// handleSpecValidationError converts SpecValidationError to nil (no requeue)
// after applying status conditions, while passing through transient errors.
if specValidationErr := r.ensureVmcpConfigConfigMap(ctx, vmcp, workloadNames, statusManager); specValidationErr != nil {
if err := r.handleSpecValidationError(ctx, vmcp, statusManager, specValidationErr); err != nil {
ctxLogger.Error(err, "Failed to ensure vmcp Config ConfigMap")
return ctrl.Result{}, err
}
// SpecValidationError: status applied, stop reconciliation without requeue.
// Do not proceed to ensureDeployment — the ConfigMap was not created/updated.
return ctrl.Result{}, nil
}
// Ensure Deployment
if result, err := r.ensureDeployment(ctx, vmcp, workloadNames); err != nil {
return ctrl.Result{}, err
} else if result.RequeueAfter > 0 {
return result, nil
}
// Ensure Service
if result, err := r.ensureService(ctx, vmcp); err != nil {
return ctrl.Result{}, err
} else if result.RequeueAfter > 0 {
return result, nil
}
// Update service URL in status
r.ensureServiceURL(vmcp, statusManager)
return ctrl.Result{}, nil
}
// ensureAuthSecretsValid validates secret references and sets the AuthConfigured condition.
func (r *VirtualMCPServerReconciler) ensureAuthSecretsValid(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
if err := r.validateSecretReferences(ctx, vmcp); err != nil {
ctxLogger := log.FromContext(ctx)
ctxLogger.Error(err, "Secret validation failed")
statusManager.SetAuthConfiguredCondition(
mcpv1alpha1.ConditionReasonAuthInvalid,
fmt.Sprintf("Authentication configuration is invalid: %v", err),
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, nil, corev1.EventTypeWarning, "SecretValidationFailed", "ValidateSecrets",
"Secret validation failed: %v", err)
}
return err
}
statusManager.SetAuthConfiguredCondition(
mcpv1alpha1.ConditionReasonAuthValid,
"Authentication configuration is valid",
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return nil
}
// ensureRBACResources ensures RBAC resources for VirtualMCPServer.
// RBAC resources are created in all modes (discovered and inline) to support:
// - Backend discovery (discovered mode only)
// - Status reporting via K8sReporter (all modes)
//
// When a custom ServiceAccount is provided, RBAC creation is skipped.
//
// Uses the RBAC client (pkg/kubernetes/rbac) which creates or updates RBAC resources
// automatically during operator upgrades.
func (r *VirtualMCPServerReconciler) ensureRBACResources(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
) error {
// If a service account is specified, we don't need to create one
if vmcp.Spec.ServiceAccount != nil {
return nil
}
rbacClient := rbac.NewClient(r.Client, r.Scheme)
serviceAccountName := vmcpServiceAccountName(vmcp.Name)
// Select RBAC rules based on outgoing auth mode
// - inline mode: Minimal permissions (read own spec + update status)
// - discovered mode: Full permissions (read secrets, configmaps, MCP resources + update status)
rules := func() []rbacv1.PolicyRule {
if outgoingAuthSource(vmcp) == OutgoingAuthSourceInline {
// inline mode uses minimal permissions (no secret/configmap access)
return vmcpInlineRBACRules
}
// discovered mode (default)
return vmcpDiscoveredRBACRules
}()
// Ensure Role with appropriate permissions based on mode
_, err := rbacClient.EnsureRBACResources(ctx, rbac.EnsureRBACResourcesParams{
Name: serviceAccountName,
Namespace: vmcp.Namespace,
Rules: rules,
Owner: vmcp,
})
return err
}
// ensureHMACSecret ensures the HMAC secret exists for session token binding.
// This secret is required when Session Management V2 is enabled.
// The secret is automatically generated with a cryptographically secure random value.
//
// The secret follows this naming pattern: {vmcp-name}-hmac-secret
// and contains a single key: hmac-secret with a 32-byte base64-encoded random value.
func (r *VirtualMCPServerReconciler) ensureHMACSecret(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
) error {
ctxLogger := log.FromContext(ctx)
secretName := fmt.Sprintf("%s-hmac-secret", vmcp.Name)
secret := &corev1.Secret{}
err := r.Get(ctx, types.NamespacedName{Name: secretName, Namespace: vmcp.Namespace}, secret)
if errors.IsNotFound(err) {
// Generate a cryptographically secure 32-byte HMAC secret
hmacSecret, err := generateHMACSecret()
if err != nil {
ctxLogger.Error(err, "Failed to generate HMAC secret")
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, nil, corev1.EventTypeWarning, "HMACSecretGenerationFailed", "GenerateHMACSecret",
"Failed to generate HMAC secret: %v", err)
}
return fmt.Errorf("failed to generate HMAC secret: %w", err)
}
newSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: vmcp.Namespace,
Labels: map[string]string{
"app.kubernetes.io/name": "virtualmcpserver",
"app.kubernetes.io/instance": vmcp.Name,
"app.kubernetes.io/component": "session-security",
"app.kubernetes.io/managed-by": "toolhive-operator",
},
Annotations: map[string]string{
"toolhive.stacklok.dev/purpose": "hmac-secret-for-session-token-binding",
},
},
Type: corev1.SecretTypeOpaque,
Data: map[string][]byte{
"hmac-secret": []byte(hmacSecret),
},
}
// Set VirtualMCPServer as owner so secret is automatically deleted when VMCP is deleted
if err := controllerutil.SetControllerReference(vmcp, newSecret, r.Scheme); err != nil {
ctxLogger.Error(err, "Failed to set controller reference for HMAC secret")
return fmt.Errorf("failed to set controller reference: %w", err)
}
ctxLogger.Info("Creating HMAC secret for session token binding", "Secret.Name", secretName)
if err := r.Create(ctx, newSecret); err != nil {
ctxLogger.Error(err, "Failed to create HMAC secret")
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, nil, corev1.EventTypeWarning, "HMACSecretCreationFailed", "CreateHMACSecret",
"Failed to create HMAC secret: %v", err)
}
return fmt.Errorf("failed to create HMAC secret: %w", err)
}
// Record success event
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, nil, corev1.EventTypeNormal, "HMACSecretCreated", "CreateHMACSecret",
"HMAC secret created for session token binding")
}
return nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get HMAC secret")
return fmt.Errorf("failed to get HMAC secret: %w", err)
}
// Secret exists - validate ownership and structure before accepting it
if err := r.validateHMACSecret(ctx, vmcp, secret); err != nil {
ctxLogger.Error(err, "Existing HMAC secret is invalid", "Secret.Name", secretName)
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, nil, corev1.EventTypeWarning, "HMACSecretValidationFailed", "ValidateHMACSecret",
"Existing HMAC secret validation failed: %v", err)
}
return fmt.Errorf("existing HMAC secret validation failed: %w", err)
}
return nil
}
// validateHMACSecret validates that an existing HMAC secret has the correct ownership,
// structure, and content. This prevents accepting stale, malformed, or attacker-controlled
// secrets that could weaken session token signing or cause pod startup failures.
func (*VirtualMCPServerReconciler) validateHMACSecret(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
secret *corev1.Secret,
) error {
ctxLogger := log.FromContext(ctx)
// Verify the secret is owned by this VirtualMCPServer
// This prevents accepting secrets created by other actors
isOwned := false
for _, ownerRef := range secret.OwnerReferences {
if ownerRef.UID == vmcp.UID &&
ownerRef.Kind == "VirtualMCPServer" &&
ownerRef.Name == vmcp.Name {
isOwned = true
break
}
}
if !isOwned {
return fmt.Errorf("secret is not owned by VirtualMCPServer %s/%s", vmcp.Namespace, vmcp.Name)
}
// Verify the hmac-secret key exists
hmacSecretData, exists := secret.Data["hmac-secret"]
if !exists {
return fmt.Errorf("secret missing required 'hmac-secret' key")
}
// Verify it's valid base64 and decodes to exactly 32 bytes
hmacSecretBase64 := string(hmacSecretData)
if hmacSecretBase64 == "" {
return fmt.Errorf("hmac-secret is empty")
}
decoded, err := base64.StdEncoding.DecodeString(hmacSecretBase64)
if err != nil {
return fmt.Errorf("hmac-secret is not valid base64: %w", err)
}
if len(decoded) != 32 {
return fmt.Errorf("hmac-secret must be exactly 32 bytes, got %d bytes", len(decoded))
}
// Verify it's not all zeros (would indicate a weak/predictable key)
allZeros := true
for _, b := range decoded {
if b != 0 {
allZeros = false
break
}
}
if allZeros {
return fmt.Errorf("hmac-secret is all zeros (weak key)")
}
ctxLogger.V(1).Info("HMAC secret validation passed", "Secret.Name", secret.Name)
return nil
}
// getVmcpConfigChecksum fetches the vmcp Config ConfigMap checksum annotation.
// This is used to trigger deployment rollouts when the configuration changes.
//
// Note: VirtualMCPServer uses a custom ConfigMap naming pattern ("{name}-vmcp-config")
// instead of the standard "{name}-runconfig" pattern, so it cannot use the shared
// checksum.RunConfigChecksumFetcher. However, it follows the same validation logic
// and uses the same annotation constant for consistency.
func (r *VirtualMCPServerReconciler) getVmcpConfigChecksum(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
) (string, error) {
if vmcp == nil {
return "", fmt.Errorf("vmcp cannot be nil")
}
configMapName := vmcpConfigMapName(vmcp.Name)
configMap := &corev1.ConfigMap{}
err := r.Get(ctx, types.NamespacedName{
Name: configMapName,
Namespace: vmcp.Namespace,
}, configMap)