-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathmcpserver_controller.go
More file actions
392 lines (351 loc) · 12.7 KB
/
Copy pathmcpserver_controller.go
File metadata and controls
392 lines (351 loc) · 12.7 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
/*
Copyright 2025.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
"fmt"
"time"
"github.com/kagent-dev/kmcp/pkg/controller/transportadapter"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
kagentdevv1alpha1 "github.com/kagent-dev/kmcp/api/v1alpha1"
)
// MCPServerReconciler reconciles a MCPServer object
type MCPServerReconciler struct {
client.Client
Scheme *runtime.Scheme
Plugins []transportadapter.TranslatorPlugin
}
// +kubebuilder:rbac:groups=kagent.dev,resources=mcpservers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=kagent.dev,resources=mcpservers/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=kagent.dev,resources=mcpservers/finalizers,verbs=update
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the MCPServer object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.20.0/pkg/reconcile
func (r *MCPServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
// Fetch the MCPServer instance
mcpServer := &kagentdevv1alpha1.MCPServer{}
if err := r.Get(ctx, req.NamespacedName, mcpServer); err != nil {
// If the resource is not found, we can ignore the error since it will be requeued later
return ctrl.Result{}, client.IgnoreNotFound(err)
}
t := transportadapter.NewTransportAdapterTranslator(r.Scheme, r.Plugins)
outputs, err := t.TranslateTransportAdapterOutputs(ctx, mcpServer)
if err != nil {
log.FromContext(ctx).Error(err, "Failed to translate MCPServer outputs")
r.reconcileStatus(ctx, mcpServer, err)
return ctrl.Result{}, err
}
err = r.reconcileOutputs(ctx, outputs)
if err != nil {
log.FromContext(ctx).Error(err, "Failed to reconcile outputs")
r.reconcileStatus(ctx, mcpServer, err)
return ctrl.Result{}, err
}
r.reconcileStatus(ctx, mcpServer, nil)
// If the deployment is not ready, requeue after a short interval to check again
deployment := &appsv1.Deployment{}
deploymentName := mcpServer.Name
if err := r.Get(ctx, client.ObjectKey{Name: deploymentName, Namespace: mcpServer.Namespace}, deployment); err == nil {
if deployment.Status.AvailableReplicas == 0 || deployment.Status.AvailableReplicas < deployment.Status.Replicas {
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *MCPServerReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&kagentdevv1alpha1.MCPServer{}, builder.WithPredicates(
predicate.Or(
predicate.GenerationChangedPredicate{},
predicate.LabelChangedPredicate{},
),
)).
Owns(&appsv1.Deployment{}, builder.WithPredicates(predicate.ResourceVersionChangedPredicate{})).
Owns(&corev1.Service{}, builder.WithPredicates(predicate.ResourceVersionChangedPredicate{})).
Owns(&corev1.ConfigMap{}, builder.WithPredicates(predicate.ResourceVersionChangedPredicate{})).
Named("mcpserver").
Complete(r)
}
func (r *MCPServerReconciler) reconcileOutputs(ctx context.Context, outputs []client.Object) error {
// upsert the outputs to the cluster
for _, output := range outputs {
if err := upsertOutput(ctx, r.Client, output); err != nil {
return err
}
}
return nil
}
func (r *MCPServerReconciler) reconcileStatus(
ctx context.Context,
server *kagentdevv1alpha1.MCPServer,
reconcileErr error,
) {
// Update ObservedGeneration
server.Status.ObservedGeneration = server.Generation
// Set Accepted condition based on validation
if err := r.validateMCPServer(server); err != nil {
setAcceptedCondition(server, false, kagentdevv1alpha1.MCPServerReasonInvalidConfig, err.Error())
// If validation fails, set other conditions as unknown/false
setResolvedRefsCondition(
server,
false,
kagentdevv1alpha1.MCPServerReasonImageNotFound,
"Configuration validation failed",
)
setProgrammedCondition(
server,
false,
kagentdevv1alpha1.MCPServerReasonDeploymentFailed,
"Configuration validation failed",
)
setReadyCondition(
server,
false,
kagentdevv1alpha1.MCPServerReasonPodsNotReady,
"Configuration validation failed",
)
} else {
setAcceptedCondition(
server,
true,
kagentdevv1alpha1.MCPServerReasonAccepted,
"MCPServer configuration is valid",
)
// Set ResolvedRefs condition (for now, assume image exists - could be enhanced later)
setResolvedRefsCondition(
server,
true,
kagentdevv1alpha1.MCPServerReasonResolvedRefs,
"All references resolved successfully",
)
// Set Programmed condition based on reconcile result
if reconcileErr != nil {
setProgrammedCondition(
server,
false,
kagentdevv1alpha1.MCPServerReasonDeploymentFailed,
reconcileErr.Error(),
)
setReadyCondition(server,
false,
kagentdevv1alpha1.MCPServerReasonPodsNotReady,
"Resources failed to be created",
)
} else {
setProgrammedCondition(server,
true,
kagentdevv1alpha1.MCPServerReasonProgrammed,
"All resources created successfully",
)
// Check Ready condition by examining deployment status
r.checkReadyCondition(ctx, server)
}
}
// Set human-readable DisplayStatus based on deletion timestamp and Ready condition
if !server.DeletionTimestamp.IsZero() {
server.Status.DisplayStatus = "Deleting"
} else {
readyCondition := false
for _, condition := range server.Status.Conditions {
if condition.Type == string(kagentdevv1alpha1.MCPServerConditionReady) &&
condition.Status == metav1.ConditionTrue {
readyCondition = true
break
}
}
if readyCondition {
server.Status.DisplayStatus = "Ready"
} else {
server.Status.DisplayStatus = "Not Ready"
}
}
// Update the status
if err := r.Status().Update(ctx, server); err != nil {
log.FromContext(ctx).Error(err, "Failed to update MCPServer status")
}
}
// validateMCPServer validates the MCPServer configuration
func (r *MCPServerReconciler) validateMCPServer(server *kagentdevv1alpha1.MCPServer) error {
// Check if transport type is supported
if server.Spec.TransportType != kagentdevv1alpha1.TransportTypeStdio &&
server.Spec.TransportType != kagentdevv1alpha1.TransportTypeHTTP {
return fmt.Errorf("unsupported transport type: %s", server.Spec.TransportType)
}
// Check if required fields are present
// Allow empty image if command is npx or uvx (default images will be injected)
if server.Spec.Deployment.Image == "" {
if server.Spec.Deployment.Cmd != "npx" && server.Spec.Deployment.Cmd != "uvx" {
return fmt.Errorf("deployment.image is required when command is not 'npx' or 'uvx'")
}
}
// Additional validation could be added here
return nil
}
// checkReadyCondition checks if the MCPServer is ready by examining the deployment status
func (r *MCPServerReconciler) checkReadyCondition(ctx context.Context, server *kagentdevv1alpha1.MCPServer) {
// Get the deployment
deployment := &appsv1.Deployment{}
deploymentName := server.Name
if err := r.Get(ctx, client.ObjectKey{Name: deploymentName, Namespace: server.Namespace}, deployment); err != nil {
if client.IgnoreNotFound(err) == nil {
setReadyCondition(server, false, kagentdevv1alpha1.MCPServerReasonPodsNotReady, "Deployment not found")
} else {
setReadyCondition(
server,
false,
kagentdevv1alpha1.MCPServerReasonPodsNotReady,
fmt.Sprintf("Error getting deployment: %s", err.Error()),
)
}
return
}
// Check if deployment is available
// A deployment is considered ready when it has the desired number of available replicas
if deployment.Status.AvailableReplicas > 0 && deployment.Status.AvailableReplicas == deployment.Status.Replicas {
setReadyCondition(
server,
true,
kagentdevv1alpha1.MCPServerReasonAvailable,
"Deployment is ready and all pods are running",
)
} else {
message := fmt.Sprintf("Deployment not ready: %d/%d replicas available",
deployment.Status.AvailableReplicas, deployment.Status.Replicas)
setReadyCondition(server, false, kagentdevv1alpha1.MCPServerReasonNotAvailable, message)
}
}
// setCondition sets the given condition on the MCPServer status.
func setCondition(
server *kagentdevv1alpha1.MCPServer,
conditionType kagentdevv1alpha1.MCPServerConditionType,
status metav1.ConditionStatus,
reason kagentdevv1alpha1.MCPServerConditionReason,
message string,
) {
now := metav1.Now()
condition := metav1.Condition{
Type: string(conditionType),
Status: status,
LastTransitionTime: now,
Reason: string(reason),
Message: message,
ObservedGeneration: server.Generation,
}
// Find existing condition
for i, existingCondition := range server.Status.Conditions {
if existingCondition.Type == string(conditionType) {
// Only update LastTransitionTime if status changed
if existingCondition.Status != status {
server.Status.Conditions[i] = condition
} else {
// Update other fields but keep the original LastTransitionTime
condition.LastTransitionTime = existingCondition.LastTransitionTime
server.Status.Conditions[i] = condition
}
return
}
}
// Add new condition
server.Status.Conditions = append(server.Status.Conditions, condition)
}
// setAcceptedCondition sets the Accepted condition on the MCPServer.
func setAcceptedCondition(
server *kagentdevv1alpha1.MCPServer,
accepted bool,
reason kagentdevv1alpha1.MCPServerConditionReason,
message string,
) {
status := metav1.ConditionTrue
if !accepted {
status = metav1.ConditionFalse
}
setCondition(server, kagentdevv1alpha1.MCPServerConditionAccepted, status, reason, message)
}
// setResolvedRefsCondition sets the ResolvedRefs condition on the MCPServer.
func setResolvedRefsCondition(
server *kagentdevv1alpha1.MCPServer,
resolved bool,
reason kagentdevv1alpha1.MCPServerConditionReason,
message string,
) {
status := metav1.ConditionTrue
if !resolved {
status = metav1.ConditionFalse
}
setCondition(server, kagentdevv1alpha1.MCPServerConditionResolvedRefs, status, reason, message)
}
// setProgrammedCondition sets the Programmed condition on the MCPServer.
func setProgrammedCondition(
server *kagentdevv1alpha1.MCPServer,
programmed bool,
reason kagentdevv1alpha1.MCPServerConditionReason,
message string,
) {
status := metav1.ConditionTrue
if !programmed {
status = metav1.ConditionFalse
}
setCondition(server, kagentdevv1alpha1.MCPServerConditionProgrammed, status, reason, message)
}
// setReadyCondition sets the Ready condition on the MCPServer.
func setReadyCondition(
server *kagentdevv1alpha1.MCPServer,
ready bool,
reason kagentdevv1alpha1.MCPServerConditionReason,
message string,
) {
status := metav1.ConditionTrue
if !ready {
status = metav1.ConditionFalse
}
setCondition(server, kagentdevv1alpha1.MCPServerConditionReady, status, reason, message)
}
func upsertOutput(ctx context.Context, kube client.Client, output client.Object) error {
existing := output.DeepCopyObject().(client.Object)
if err := kube.Get(ctx, client.ObjectKeyFromObject(existing), existing); err != nil {
if client.IgnoreNotFound(err) != nil {
return err
}
// If not found, create it
if err := kube.Create(ctx, output); err != nil {
return err
}
} else {
// If found, update it
output.SetResourceVersion(existing.GetResourceVersion())
if err := kube.Update(ctx, output); err != nil {
return err
}
}
return nil
}