-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathmcpserver_controller.go
More file actions
2325 lines (2081 loc) · 90.5 KB
/
mcpserver_controller.go
File metadata and controls
2325 lines (2081 loc) · 90.5 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 MCPServer custom resource.
// It handles the creation, update, and deletion of MCP servers in Kubernetes.
package controllers
import (
"context"
"encoding/json"
goerr "errors"
"fmt"
"maps"
"os"
"strings"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
equality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"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/validation"
"github.com/stacklok/toolhive/pkg/container/kubernetes"
"github.com/stacklok/toolhive/pkg/transport"
)
// MCPServerReconciler reconciles a MCPServer object
type MCPServerReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder events.EventRecorder
PlatformDetector *ctrlutil.SharedPlatformDetector
ImageValidation validation.ImageValidation
}
// defaultRBACRules are the default RBAC rules that the
// ToolHive ProxyRunner and/or MCP server needs to have in order to run.
// These permissions are needed for MCPServer which deploys and manages MCP server containers.
var defaultRBACRules = []rbacv1.PolicyRule{
{
APIGroups: []string{"apps"},
Resources: []string{"statefulsets"},
Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"},
},
{
APIGroups: []string{""},
Resources: []string{"services"},
Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"},
},
{
APIGroups: []string{""},
Resources: []string{"pods"},
Verbs: []string{"get", "list", "watch"},
},
{
APIGroups: []string{""},
Resources: []string{"pods/log"},
Verbs: []string{"get"},
},
{
APIGroups: []string{""},
Resources: []string{"pods/attach"},
Verbs: []string{"create", "get"},
},
{
APIGroups: []string{""},
Resources: []string{"configmaps"},
Verbs: []string{"get", "list", "watch"},
},
}
// remoteProxyRBACRules defines minimal RBAC permissions for MCPRemoteProxy.
// Remote proxies only connect to external MCP servers and do not deploy containers,
// so they only need read access to ConfigMaps and Secrets (for OIDC/token exchange).
var remoteProxyRBACRules = []rbacv1.PolicyRule{
{
APIGroups: []string{""},
Resources: []string{"configmaps"},
Verbs: []string{"get", "list", "watch"},
},
{
APIGroups: []string{""},
Resources: []string{"secrets"},
Verbs: []string{"get", "list", "watch"},
},
}
// mcpContainerName is the name of the mcp container used in pod templates
const mcpContainerName = "mcp"
// Restart annotation keys for triggering pod restart
const (
RestartedAtAnnotationKey = "mcpserver.toolhive.stacklok.dev/restarted-at"
RestartStrategyAnnotationKey = "mcpserver.toolhive.stacklok.dev/restart-strategy"
LastProcessedRestartAnnotationKey = "mcpserver.toolhive.stacklok.dev/last-processed-restart"
)
// Restart strategy constants
const (
RestartStrategyRolling = "rolling"
RestartStrategyImmediate = "immediate"
)
// Authorization ConfigMap label constants
const (
// authzLabelKey is the label key for authorization configuration type
authzLabelKey = "toolhive.stacklok.io/authz"
// authzLabelValueInline is the label value for inline authorization configuration
authzLabelValueInline = "inline"
)
const defaultTerminationGracePeriodSeconds = int64(30)
const stdioTransport = "stdio"
// detectPlatform detects the Kubernetes platform type (Kubernetes vs OpenShift)
// It uses the shared platform detector to ensure detection is only performed once and cached
func (r *MCPServerReconciler) detectPlatform(ctx context.Context) (kubernetes.Platform, error) {
return r.PlatformDetector.DetectPlatform(ctx)
}
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpservers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpservers/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpservers/finalizers,verbs=update
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcptoolconfigs,verbs=get;list;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=mcptelemetryconfigs,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=pods,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=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=apps,resources=statefulsets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=pods/attach,verbs=create;get
// +kubebuilder:rbac:groups="",resources=pods/log,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.
//
//nolint:gocyclo
func (r *MCPServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Fetch the MCPServer instance
mcpServer := &mcpv1alpha1.MCPServer{}
err := r.Get(ctx, req.NamespacedName, mcpServer)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Return and don't requeue
ctxLogger.Info("MCPServer resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
ctxLogger.Error(err, "Failed to get MCPServer")
return ctrl.Result{}, err
}
// Check if the restart annotation has been updated and trigger a rolling restart if needed
if shouldTriggerRestart, err := r.handleRestartAnnotation(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to handle restart annotation")
return ctrl.Result{}, err
} else if shouldTriggerRestart {
// Return and requeue to avoid double-processing after triggering restart
return ctrl.Result{Requeue: true}, nil
}
// Check if the GroupRef is valid if specified
r.validateGroupRef(ctx, mcpServer)
// Validate CABundleRef if specified
r.validateCABundleRef(ctx, mcpServer)
// Validate stdio replica cap and session storage requirements
r.validateStdioReplicaCap(ctx, mcpServer)
r.validateSessionStorageForReplicas(ctx, mcpServer)
// Validate PodTemplateSpec early - before other validations
// This ensures we fail fast if the spec is invalid
if !r.validateAndUpdatePodTemplateStatus(ctx, mcpServer) {
// Invalid PodTemplateSpec - return without error to avoid infinite retries
// The user must fix the spec and the next reconciliation will retry
return ctrl.Result{}, nil
}
// Check if MCPToolConfig is referenced and handle it
if err := r.handleToolConfig(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to handle MCPToolConfig")
// Update status to reflect the error
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, err.Error())
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPToolConfig error")
}
return ctrl.Result{}, err
}
// Check if MCPTelemetryConfig is referenced and handle it
if err := r.handleTelemetryConfig(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to handle MCPTelemetryConfig")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, err.Error())
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPTelemetryConfig error")
}
return ctrl.Result{}, err
}
// Check if MCPExternalAuthConfig is referenced and handle it
if err := r.handleExternalAuthConfig(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig")
// Update status to reflect the error
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, err.Error())
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPExternalAuthConfig error")
}
return ctrl.Result{}, err
}
// Check if MCPOIDCConfig is referenced and handle it
if err := r.handleOIDCConfig(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to handle MCPOIDCConfig")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, err.Error())
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPOIDCConfig error")
}
return ctrl.Result{}, err
}
// Validate MCPServer image against enforcing registries
imageValidator := validation.NewImageValidator(r.Client, mcpServer.Namespace, r.ImageValidation)
err = imageValidator.ValidateImage(ctx, mcpServer.Spec.Image, mcpServer.ObjectMeta)
if goerr.Is(err, validation.ErrImageNotChecked) {
ctxLogger.Info("Image validation skipped - no enforcement configured")
// Set condition to indicate validation was skipped
setImageValidationCondition(mcpServer, metav1.ConditionTrue,
mcpv1alpha1.ConditionReasonImageValidationSkipped,
"Image validation was not performed (no enforcement configured)")
// Update status to persist the condition
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after image validation")
}
} else if goerr.Is(err, validation.ErrImageInvalid) {
ctxLogger.Error(err, "MCPServer image validation failed", "image", mcpServer.Spec.Image)
// Update status to reflect validation failure
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = err.Error() // Gets the specific validation failure reason
setImageValidationCondition(mcpServer, metav1.ConditionFalse,
mcpv1alpha1.ConditionReasonImageValidationFailed,
err.Error()) // This will include the wrapped error context with specific reason
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, err.Error())
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after validation error")
}
// Requeue after 5 minutes to retry validation
return ctrl.Result{RequeueAfter: 5 * time.Minute}, nil
} else if err != nil {
// Other system/infrastructure errors
ctxLogger.Error(err, "MCPServer image validation system error", "image", mcpServer.Spec.Image)
setImageValidationCondition(mcpServer, metav1.ConditionFalse,
mcpv1alpha1.ConditionReasonImageValidationError,
fmt.Sprintf("Error checking image validity: %v", err))
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady,
fmt.Sprintf("Error checking image validity: %v", err))
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after validation error")
}
// Requeue after 5 minutes to retry validation
return ctrl.Result{RequeueAfter: 5 * time.Minute}, nil
} else {
// Validation passed
ctxLogger.Info("Image validation passed", "image", mcpServer.Spec.Image)
setImageValidationCondition(mcpServer, metav1.ConditionTrue,
mcpv1alpha1.ConditionReasonImageValidationSuccess,
"Image validation passed - image found in enforced registries")
// Update status to persist the condition
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after image validation")
}
}
// Check if the MCPServer instance is marked to be deleted
if mcpServer.GetDeletionTimestamp() != nil {
// The object is being deleted
if controllerutil.ContainsFinalizer(mcpServer, "mcpserver.toolhive.stacklok.dev/finalizer") {
// Run finalization logic. If the finalization logic fails,
// don't remove the finalizer so that we can retry during the next reconciliation.
if err := r.finalizeMCPServer(ctx, mcpServer); err != nil {
return ctrl.Result{}, err
}
// Remove the finalizer. Once all finalizers have been removed, the object will be deleted.
controllerutil.RemoveFinalizer(mcpServer, "mcpserver.toolhive.stacklok.dev/finalizer")
err := r.Update(ctx, mcpServer)
if err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
// Add finalizer for this CR
if !controllerutil.ContainsFinalizer(mcpServer, "mcpserver.toolhive.stacklok.dev/finalizer") {
controllerutil.AddFinalizer(mcpServer, "mcpserver.toolhive.stacklok.dev/finalizer")
err = r.Update(ctx, mcpServer)
if err != nil {
return ctrl.Result{}, err
}
}
// Update the MCPServer status with the pod status
if err := r.updateMCPServerStatus(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to update MCPServer status")
return ctrl.Result{}, err
}
// check if the RBAC resources are in place for the MCP server
if err := r.ensureRBACResources(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to ensure RBAC resources")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = fmt.Sprintf("Failed to ensure RBAC resources: %s", err.Error())
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, mcpServer.Status.Message)
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after RBAC error")
}
return ctrl.Result{}, err
}
// Ensure authorization ConfigMap for inline configuration
if err := r.ensureAuthzConfigMap(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to ensure authorization ConfigMap")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = fmt.Sprintf("Failed to ensure authorization ConfigMap: %s", err.Error())
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, mcpServer.Status.Message)
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after authz ConfigMap error")
}
return ctrl.Result{}, err
}
// Ensure RunConfig ConfigMap exists and is up to date
if err := r.ensureRunConfigConfigMap(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to ensure RunConfig ConfigMap")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = fmt.Sprintf("Failed to build configuration: %s", err.Error())
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, mcpServer.Status.Message)
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after RunConfig error")
}
return ctrl.Result{}, err
}
// Fetch RunConfig ConfigMap checksum to include in pod template annotations
runConfigChecksum, err := r.getRunConfigChecksum(ctx, mcpServer)
if err != nil {
if errors.IsNotFound(err) {
// ConfigMap doesn't exist yet - requeue with a short delay to allow
// API server propagation.
ctxLogger.Info("RunConfig ConfigMap not found yet, will retry",
"server", mcpServer.Name, "namespace", mcpServer.Namespace)
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
ctxLogger.Error(err, "Failed to get RunConfig checksum")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = fmt.Sprintf("Failed to build configuration: %s", err.Error())
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, mcpServer.Status.Message)
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after RunConfig checksum error")
}
return ctrl.Result{}, err
}
// Check if the deployment already exists, if not create a new one
deployment := &appsv1.Deployment{}
err = r.Get(ctx, types.NamespacedName{Name: mcpServer.Name, Namespace: mcpServer.Namespace}, deployment)
if err != nil && errors.IsNotFound(err) {
// Define a new deployment
dep := r.deploymentForMCPServer(ctx, mcpServer, runConfigChecksum)
if dep == nil {
ctxLogger.Error(nil, "Failed to create Deployment object")
deploymentErr := fmt.Errorf("failed to create Deployment object")
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = deploymentErr.Error()
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, mcpServer.Status.Message)
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after Deployment build failure")
}
return ctrl.Result{}, deploymentErr
}
ctxLogger.Info("Creating a new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
err = r.Create(ctx, dep)
if err != nil {
ctxLogger.Error(err, "Failed to create new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = fmt.Sprintf("Failed to create Deployment: %s", err.Error())
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady, mcpServer.Status.Message)
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status after Deployment creation failure")
}
return ctrl.Result{}, err
}
// Deployment created successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get Deployment")
return ctrl.Result{}, err
}
// Enforce stdio transport replica cap: stdio requires 1:1 proxy-to-backend
// connections and cannot scale beyond 1. Other transports are hands-off
// to allow HPAs, KEDA, or manual kubectl scale to manage replicas freely.
if mcpServer.Spec.Transport == stdioTransport &&
deployment.Spec.Replicas != nil && *deployment.Spec.Replicas > 1 {
deployment.Spec.Replicas = int32Ptr(1)
err = r.Update(ctx, deployment)
if err != nil {
ctxLogger.Error(err, "Failed to cap stdio deployment replicas",
"Deployment.Namespace", deployment.Namespace,
"Deployment.Name", deployment.Name)
return ctrl.Result{}, err
}
// Spec updated - return and requeue
return ctrl.Result{Requeue: true}, nil
}
// Check if the Service already exists, if not create a new one
serviceName := ctrlutil.CreateProxyServiceName(mcpServer.Name)
service := &corev1.Service{}
err = r.Get(ctx, types.NamespacedName{Name: serviceName, Namespace: mcpServer.Namespace}, service)
if err != nil && errors.IsNotFound(err) {
// Define a new service
svc := r.serviceForMCPServer(ctx, mcpServer)
if svc == nil {
ctxLogger.Error(nil, "Failed to create Service object")
return ctrl.Result{}, fmt.Errorf("failed to create Service object")
}
ctxLogger.Info("Creating a new Service", "Service.Namespace", svc.Namespace, "Service.Name", svc.Name)
err = r.Create(ctx, svc)
if err != nil {
ctxLogger.Error(err, "Failed to create new Service", "Service.Namespace", svc.Namespace, "Service.Name", svc.Name)
return ctrl.Result{}, err
}
// Service created successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get Service")
return ctrl.Result{}, err
}
// Update the MCPServer status with the service URL including transport-specific path
if mcpServer.Status.URL == "" {
host := fmt.Sprintf("%s.%s.svc.cluster.local", serviceName, mcpServer.Namespace)
mcpServer.Status.URL = transport.GenerateMCPServerURL(
mcpServer.Spec.Transport,
mcpServer.Spec.ProxyMode,
host,
int(mcpServer.GetProxyPort()),
mcpServer.Name,
"", // empty remoteURL for MCPServer (not remote proxy)
)
err = r.Status().Update(ctx, mcpServer)
if err != nil {
ctxLogger.Error(err, "Failed to update MCPServer status")
return ctrl.Result{}, err
}
}
// Check if the deployment spec changed
if r.deploymentNeedsUpdate(ctx, deployment, mcpServer, runConfigChecksum) {
// Update template and metadata. Also sync Spec.Replicas when spec.replicas is
// explicitly set — this makes the operator authoritative for spec-driven scaling.
// When spec.replicas is nil, preserve the live count so HPAs, KEDA, and manual
// kubectl scale remain in control.
newDeployment := r.deploymentForMCPServer(ctx, mcpServer, runConfigChecksum)
deployment.Spec.Template = newDeployment.Spec.Template
deployment.Spec.Selector = newDeployment.Spec.Selector
deployment.Labels = newDeployment.Labels
deployment.Annotations = ctrlutil.MergeAnnotations(newDeployment.Annotations, deployment.Annotations)
if newDeployment.Spec.Replicas != nil {
deployment.Spec.Replicas = newDeployment.Spec.Replicas
}
err = r.Update(ctx, deployment)
if err != nil {
ctxLogger.Error(err, "Failed to update Deployment",
"Deployment.Namespace", deployment.Namespace,
"Deployment.Name", deployment.Name)
return ctrl.Result{}, err
}
// Spec updated - return and requeue
return ctrl.Result{Requeue: true}, nil
}
// Check if the service spec changed
if serviceNeedsUpdate(service, mcpServer) {
// Update the service
newService := r.serviceForMCPServer(ctx, mcpServer)
service.Spec.Ports = newService.Spec.Ports
service.Spec.SessionAffinity = newService.Spec.SessionAffinity
service.Labels = newService.Labels
service.Annotations = newService.Annotations
err = r.Update(ctx, service)
if err != nil {
ctxLogger.Error(err, "Failed to update Service", "Service.Namespace", service.Namespace, "Service.Name", service.Name)
return ctrl.Result{}, err
}
// Spec updated - return and requeue
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
func (r *MCPServerReconciler) validateGroupRef(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) {
if mcpServer.Spec.GroupRef == "" {
// No group reference, nothing to validate
return
}
ctxLogger := log.FromContext(ctx)
// Find the referenced MCPGroup
group := &mcpv1alpha1.MCPGroup{}
if err := r.Get(ctx, types.NamespacedName{Namespace: mcpServer.Namespace, Name: mcpServer.Spec.GroupRef}, group); err != nil {
ctxLogger.Error(err, "Failed to validate GroupRef")
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionGroupRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1alpha1.ConditionReasonGroupRefNotFound,
Message: fmt.Sprintf("MCPGroup '%s' not found in namespace '%s'", mcpServer.Spec.GroupRef, mcpServer.Namespace),
ObservedGeneration: mcpServer.Generation,
})
} else if group.Status.Phase != mcpv1alpha1.MCPGroupPhaseReady {
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionGroupRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1alpha1.ConditionReasonGroupRefNotReady,
Message: fmt.Sprintf("MCPGroup '%s' is not ready (current phase: %s)", mcpServer.Spec.GroupRef, group.Status.Phase),
ObservedGeneration: mcpServer.Generation,
})
} else {
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionGroupRefValidated,
Status: metav1.ConditionTrue,
Reason: mcpv1alpha1.ConditionReasonGroupRefValidated,
Message: fmt.Sprintf("MCPGroup '%s' is valid and ready", mcpServer.Spec.GroupRef),
ObservedGeneration: mcpServer.Generation,
})
}
if err := r.Status().Update(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to update MCPServer status after GroupRef validation")
}
}
// getCABundleRef extracts the CABundleRef from the OIDC configuration based on type
func getCABundleRef(oidcConfig *mcpv1alpha1.OIDCConfigRef) *mcpv1alpha1.CABundleSource {
if oidcConfig == nil {
return nil
}
switch oidcConfig.Type {
case mcpv1alpha1.OIDCConfigTypeInline:
if oidcConfig.Inline != nil {
return oidcConfig.Inline.CABundleRef
}
case mcpv1alpha1.OIDCConfigTypeConfigMap:
if oidcConfig.ConfigMap != nil {
return oidcConfig.ConfigMap.CABundleRef
}
}
return nil
}
// setCABundleRefCondition sets the CA bundle validation status condition
func setCABundleRefCondition(mcpServer *mcpv1alpha1.MCPServer, status metav1.ConditionStatus, reason, message string) {
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionCABundleRefValidated,
Status: status,
Reason: reason,
Message: message,
ObservedGeneration: mcpServer.Generation,
})
}
// validateCABundleRef validates the CABundleRef ConfigMap reference if specified.
// Checks both the legacy OIDCConfig path and the new MCPOIDCConfig path.
func (r *MCPServerReconciler) validateCABundleRef(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) {
caBundleRef := getCABundleRef(mcpServer.Spec.OIDCConfig)
// Also check MCPOIDCConfig inline CA bundle if using the new reference path
if caBundleRef == nil && mcpServer.Spec.OIDCConfigRef != nil {
oidcCfg, err := ctrlutil.GetOIDCConfigForServer(ctx, r.Client, mcpServer.Namespace, mcpServer.Spec.OIDCConfigRef)
if err == nil && oidcCfg != nil &&
oidcCfg.Spec.Type == mcpv1alpha1.MCPOIDCConfigTypeInline &&
oidcCfg.Spec.Inline != nil {
caBundleRef = oidcCfg.Spec.Inline.CABundleRef
}
}
if caBundleRef == nil || caBundleRef.ConfigMapRef == nil {
return
}
ctxLogger := log.FromContext(ctx)
// Validate the CABundleRef configuration
if err := validation.ValidateCABundleSource(caBundleRef); err != nil {
ctxLogger.Error(err, "Invalid CABundleRef configuration")
setCABundleRefCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonCABundleRefInvalid, err.Error())
r.updateCABundleStatus(ctx, mcpServer)
return
}
// Check if the referenced ConfigMap exists
cmName := caBundleRef.ConfigMapRef.Name
configMap := &corev1.ConfigMap{}
if err := r.Get(ctx, types.NamespacedName{Namespace: mcpServer.Namespace, Name: cmName}, configMap); err != nil {
ctxLogger.Error(err, "Failed to find CA bundle ConfigMap", "configMap", cmName)
setCABundleRefCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonCABundleRefNotFound,
fmt.Sprintf("CA bundle ConfigMap '%s' not found in namespace '%s'", cmName, mcpServer.Namespace))
r.updateCABundleStatus(ctx, mcpServer)
return
}
// Verify the key exists in the ConfigMap
key := caBundleRef.ConfigMapRef.Key
if key == "" {
key = validation.OIDCCABundleDefaultKey
}
if _, exists := configMap.Data[key]; !exists {
ctxLogger.Error(nil, "CA bundle key not found in ConfigMap", "configMap", cmName, "key", key)
setCABundleRefCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonCABundleRefInvalid,
fmt.Sprintf("Key '%s' not found in ConfigMap '%s'", key, cmName))
r.updateCABundleStatus(ctx, mcpServer)
return
}
// Validation passed
setCABundleRefCondition(mcpServer, metav1.ConditionTrue, mcpv1alpha1.ConditionReasonCABundleRefValid,
fmt.Sprintf("CA bundle ConfigMap '%s' is valid (key: %s)", cmName, key))
r.updateCABundleStatus(ctx, mcpServer)
}
// updateCABundleStatus updates the MCPServer status after CA bundle validation
func (r *MCPServerReconciler) updateCABundleStatus(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) {
ctxLogger := log.FromContext(ctx)
if err := r.Status().Update(ctx, mcpServer); err != nil {
ctxLogger.Error(err, "Failed to update MCPServer status after CABundleRef validation")
}
}
// setImageValidationCondition is a helper function to set the image validation status condition
// This reduces code duplication in the image validation logic
func setImageValidationCondition(mcpServer *mcpv1alpha1.MCPServer, status metav1.ConditionStatus, reason, message string) {
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionImageValidated,
Status: status,
Reason: reason,
Message: message,
})
}
// setReadyCondition sets the top-level Ready status condition.
func setReadyCondition(mcpServer *mcpv1alpha1.MCPServer, status metav1.ConditionStatus, reason, message string) {
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionTypeReady,
Status: status,
Reason: reason,
Message: message,
ObservedGeneration: mcpServer.Generation,
})
}
// validateAndUpdatePodTemplateStatus validates the PodTemplateSpec and updates the MCPServer status
// with appropriate conditions and events
func (r *MCPServerReconciler) validateAndUpdatePodTemplateStatus(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) bool {
ctxLogger := log.FromContext(ctx)
// Only validate if PodTemplateSpec is provided
if mcpServer.Spec.PodTemplateSpec == nil || mcpServer.Spec.PodTemplateSpec.Raw == nil {
// No PodTemplateSpec provided, validation passes
return true
}
_, err := ctrlutil.NewPodTemplateSpecBuilder(mcpServer.Spec.PodTemplateSpec, mcpContainerName)
if err != nil {
// Record event for invalid PodTemplateSpec
if r.Recorder != nil {
r.Recorder.Eventf(mcpServer, nil, corev1.EventTypeWarning, "InvalidPodTemplateSpec", "ValidatePodTemplateSpec",
"Failed to parse PodTemplateSpec: %v. Deployment blocked until PodTemplateSpec is fixed.", err)
}
// Set phase and message
mcpServer.Status.Phase = mcpv1alpha1.MCPServerPhaseFailed
mcpServer.Status.Message = fmt.Sprintf("Invalid PodTemplateSpec: %v", err)
// Set condition for invalid PodTemplateSpec
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionPodTemplateValid,
Status: metav1.ConditionFalse,
ObservedGeneration: mcpServer.Generation,
Reason: mcpv1alpha1.ConditionReasonPodTemplateInvalid,
Message: fmt.Sprintf("Failed to parse PodTemplateSpec: %v. Deployment blocked until fixed.", err),
})
setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1alpha1.ConditionReasonNotReady,
fmt.Sprintf("Invalid PodTemplateSpec: %v", err))
// Update status with the condition
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status with PodTemplateSpec validation")
return false
}
ctxLogger.Error(err, "PodTemplateSpec validation failed")
return false
}
// Set condition for valid PodTemplateSpec
meta.SetStatusCondition(&mcpServer.Status.Conditions, metav1.Condition{
Type: mcpv1alpha1.ConditionPodTemplateValid,
Status: metav1.ConditionTrue,
ObservedGeneration: mcpServer.Generation,
Reason: mcpv1alpha1.ConditionReasonPodTemplateValid,
Message: "PodTemplateSpec is valid",
})
// Update status with the condition
if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPServer status with PodTemplateSpec validation")
}
return true
}
// handleRestartAnnotation checks if the restart annotation has been updated and triggers a restart if needed
// Returns true if a restart was triggered and the reconciliation should be requeued
func (r *MCPServerReconciler) handleRestartAnnotation(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) (bool, error) {
ctxLogger := log.FromContext(ctx)
// Get the current restarted-at annotation value from the CR
currentRestartedAt := ""
if mcpServer.Annotations != nil {
currentRestartedAt = mcpServer.Annotations[RestartedAtAnnotationKey]
}
// Skip if no restart annotation is present
if currentRestartedAt == "" {
return false, nil
}
// Parse the timestamp from the annotation
requestTime, err := time.Parse(time.RFC3339, currentRestartedAt)
if err != nil {
ctxLogger.Error(err, "Invalid timestamp format in restart annotation",
"annotation", RestartedAtAnnotationKey,
"value", currentRestartedAt)
return false, nil
}
// Check if we've already processed this restart request
lastProcessedRestart := ""
if mcpServer.Annotations != nil {
lastProcessedRestart = mcpServer.Annotations[LastProcessedRestartAnnotationKey]
}
if lastProcessedRestart != "" {
lastProcessedTime, err := time.Parse(time.RFC3339, lastProcessedRestart)
if err == nil && !requestTime.After(lastProcessedTime) {
// This request has already been processed
return false, nil
}
}
// Get restart strategy (default to rolling)
strategy := RestartStrategyRolling
if mcpServer.Annotations != nil {
if strategyValue, exists := mcpServer.Annotations[RestartStrategyAnnotationKey]; exists {
strategy = strategyValue
}
}
ctxLogger.Info("Processing restart request",
"annotation", RestartedAtAnnotationKey,
"timestamp", currentRestartedAt,
"strategy", strategy)
// Perform the restart based on strategy
err = r.performRestart(ctx, mcpServer, strategy)
if err != nil {
return false, fmt.Errorf("failed to perform restart: %w", err)
}
// Update the last processed restart timestamp in annotations
if mcpServer.Annotations == nil {
mcpServer.Annotations = make(map[string]string)
}
mcpServer.Annotations[LastProcessedRestartAnnotationKey] = currentRestartedAt
err = r.Update(ctx, mcpServer)
if err != nil {
return false, fmt.Errorf("failed to update MCPServer with last processed restart annotation: %w", err)
}
return true, nil
}
// performRestart executes the restart based on the specified strategy
func (r *MCPServerReconciler) performRestart(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer, strategy string) error {
switch strategy {
case RestartStrategyRolling:
return r.performRollingRestart(ctx, mcpServer)
case RestartStrategyImmediate:
return r.performImmediateRestart(ctx, mcpServer)
default:
ctxLogger := log.FromContext(ctx)
ctxLogger.Info("Unknown restart strategy, defaulting to rolling", "strategy", strategy)
return r.performRollingRestart(ctx, mcpServer)
}
}
// getRunConfigChecksum fetches the RunConfig ConfigMap checksum annotation for this server.
// Uses the shared RunConfigChecksumFetcher to maintain consistency with MCPRemoteProxy.
func (r *MCPServerReconciler) getRunConfigChecksum(
ctx context.Context, mcpServer *mcpv1alpha1.MCPServer,
) (string, error) {
if mcpServer == nil {
return "", fmt.Errorf("mcpServer cannot be nil")
}
fetcher := checksum.NewRunConfigChecksumFetcher(r.Client)
return fetcher.GetRunConfigChecksum(ctx, mcpServer.Namespace, mcpServer.Name)
}
// performRollingRestart triggers a rolling restart by updating the deployment's pod template annotation
func (r *MCPServerReconciler) performRollingRestart(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) error {
ctxLogger := log.FromContext(ctx)
deployment := &appsv1.Deployment{}
err := r.Get(ctx, types.NamespacedName{Name: mcpServer.Name, Namespace: mcpServer.Namespace}, deployment)
if err != nil {
if errors.IsNotFound(err) {
ctxLogger.Info("Deployment not found, skipping rolling restart")
return nil
}
return fmt.Errorf("failed to get deployment for rolling restart: %w", err)
}
// Update the deployment's pod template annotation to trigger a rolling restart
if deployment.Spec.Template.Annotations == nil {
deployment.Spec.Template.Annotations = map[string]string{}
}
deployment.Spec.Template.Annotations[RestartedAtAnnotationKey] = time.Now().Format(time.RFC3339)
err = r.Update(ctx, deployment)
if err != nil {
return fmt.Errorf("failed to update deployment for rolling restart: %w", err)
}
ctxLogger.Info("Successfully triggered rolling restart of deployment", "deployment", deployment.Name)
return nil
}
// performImmediateRestart triggers an immediate restart by deleting the pods directly
func (r *MCPServerReconciler) performImmediateRestart(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) error {
ctxLogger := log.FromContext(ctx)
// List pods belonging to this MCPServer
podList := &corev1.PodList{}
listOpts := []client.ListOption{
client.InNamespace(mcpServer.Namespace),
client.MatchingLabels(labelsForMCPServer(mcpServer.Name)),
}
err := r.List(ctx, podList, listOpts...)
if err != nil {
return fmt.Errorf("failed to list pods for immediate restart: %w", err)
}
// Delete each pod to trigger immediate restart
for _, pod := range podList.Items {
ctxLogger.Info("Deleting pod for immediate restart", "pod", pod.Name)
err = r.Delete(ctx, &pod)
if err != nil && !errors.IsNotFound(err) {
return fmt.Errorf("failed to delete pod %s for immediate restart: %w", pod.Name, err)
}
}
ctxLogger.Info("Successfully triggered immediate restart", "podsDeleted", len(podList.Items))
return nil
}
// handleToolConfig handles MCPToolConfig reference for an MCPServer
func (r *MCPServerReconciler) handleToolConfig(ctx context.Context, m *mcpv1alpha1.MCPServer) error {
ctxLogger := log.FromContext(ctx)
if m.Spec.ToolConfigRef == nil {
// No MCPToolConfig referenced, clear any stored hash
if m.Status.ToolConfigHash != "" {
m.Status.ToolConfigHash = ""
if err := r.Status().Update(ctx, m); err != nil {
return fmt.Errorf("failed to clear MCPToolConfig hash from status: %w", err)
}
}
return nil
}
// Get the referenced MCPToolConfig
toolConfig, err := ctrlutil.GetToolConfigForMCPServer(ctx, r.Client, m)
if err != nil {
return err
}
if toolConfig == nil {
return fmt.Errorf("MCPToolConfig %s not found", m.Spec.ToolConfigRef.Name)
}
// Check if the MCPToolConfig hash has changed
if m.Status.ToolConfigHash != toolConfig.Status.ConfigHash {
ctxLogger.Info("MCPToolConfig has changed, updating MCPServer",
"mcpserver", m.Name,
"toolconfig", toolConfig.Name,
"oldHash", m.Status.ToolConfigHash,
"newHash", toolConfig.Status.ConfigHash)
// Update the stored hash
m.Status.ToolConfigHash = toolConfig.Status.ConfigHash
if err := r.Status().Update(ctx, m); err != nil {
return fmt.Errorf("failed to update MCPToolConfig hash in status: %w", err)
}
// The change in hash will trigger a reconciliation of the RunConfig
// which will pick up the new tool configuration
}
return nil
}
func (r *MCPServerReconciler) ensureRBACResources(ctx context.Context, mcpServer *mcpv1alpha1.MCPServer) error {
rbacClient := rbac.NewClient(r.Client, r.Scheme)
proxyRunnerNameForRBAC := ctrlutil.ProxyRunnerServiceAccountName(mcpServer.Name)
// Extract ImagePullSecrets from ResourceOverrides if present
var imagePullSecrets []corev1.LocalObjectReference
if mcpServer.Spec.ResourceOverrides != nil &&
mcpServer.Spec.ResourceOverrides.ProxyDeployment != nil {
imagePullSecrets = mcpServer.Spec.ResourceOverrides.ProxyDeployment.ImagePullSecrets
}
// Ensure RBAC resources for proxy runner
if _, err := rbacClient.EnsureRBACResources(ctx, rbac.EnsureRBACResourcesParams{
Name: proxyRunnerNameForRBAC,
Namespace: mcpServer.Namespace,
Rules: defaultRBACRules,
Owner: mcpServer,
ImagePullSecrets: imagePullSecrets,
}); err != nil {
return err
}
// If a service account is specified, we don't need to create one
if mcpServer.Spec.ServiceAccount != nil {
return nil
}
// Otherwise, create a service account for the MCP server
mcpServerSAName := mcpServerServiceAccountName(mcpServer.Name)
mcpServerSA := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: mcpServerSAName,
Namespace: mcpServer.Namespace,
},
ImagePullSecrets: imagePullSecrets,
}
_, err := rbacClient.UpsertServiceAccountWithOwnerReference(ctx, mcpServerSA, mcpServer)
return err
}