-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathserver.go
More file actions
226 lines (196 loc) · 6.68 KB
/
server.go
File metadata and controls
226 lines (196 loc) · 6.68 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
package mcp
import (
"context"
"fmt"
"strings"
"kubernetes-mcp-server/internal/config"
"kubernetes-mcp-server/internal/logging"
"kubernetes-mcp-server/pkg/k8s"
"kubernetes-mcp-server/pkg/types"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
// Server represents the MCP server
type Server struct {
config *config.Config
k8sClient *k8s.Client
logger *logging.Logger
mcpServer *server.MCPServer
formatter *ResourceFormatter
}
// NewServer creates a new MCP server instance with proper MCP protocol implementation
func NewServer(cfg *config.Config, k8sClient *k8s.Client) *Server {
logger := logging.NewLogger("info", "text")
// Create MCP server
mcpServer := server.NewMCPServer("k8s-mcp-server", "1.0.0", server.WithResourceCapabilities(true, true))
s := &Server{
config: cfg,
k8sClient: k8sClient,
logger: logger,
mcpServer: mcpServer,
formatter: NewResourceFormatter(),
}
// Register MCP resources
s.registerResources()
return s
}
// registerResources discovers and registers actual Kubernetes resources
func (s *Server) registerResources() {
// For now, we'll register a few sample resources from common namespaces
// In a production implementation, this could be made more dynamic
ctx := context.Background()
// Get some actual pods and register them
pods, err := s.k8sClient.ListPods(ctx, "")
if err != nil {
s.logger.Errorf("Failed to list pods for registration: %v", err)
} else {
// Register first few pods as examples (limit to avoid too many resources)
count := 0
for _, pod := range pods {
if count >= 5 { // Limit to first 5 pods
break
}
resource := mcp.Resource{
URI: fmt.Sprintf("k8s://pod/%s/%s", pod.Namespace, pod.Name),
Name: fmt.Sprintf("Pod: %s/%s", pod.Namespace, pod.Name),
Description: fmt.Sprintf("Kubernetes Pod in namespace %s (Status: %s)", pod.Namespace, pod.Status),
MIMEType: "application/json",
}
s.mcpServer.AddResource(resource, s.handleResourceRead)
count++
}
}
// Get some actual services and register them
services, err := s.k8sClient.ListServices(ctx, "")
if err != nil {
s.logger.Errorf("Failed to list services for registration: %v", err)
} else {
// Register first few services as examples
count := 0
for _, service := range services {
if count >= 5 { // Limit to first 5 services
break
}
resource := mcp.Resource{
URI: fmt.Sprintf("k8s://service/%s/%s", service.Namespace, service.Name),
Name: fmt.Sprintf("Service: %s/%s", service.Namespace, service.Name),
Description: fmt.Sprintf("Kubernetes Service in namespace %s (Type: %s)", service.Namespace, service.Type),
MIMEType: "application/json",
}
s.mcpServer.AddResource(resource, s.handleResourceRead)
count++
}
}
// Get some actual deployments and register them
deployments, err := s.k8sClient.ListDeployments(ctx, "")
if err != nil {
s.logger.Errorf("Failed to list deployments for registration: %v", err)
} else {
// Register first few deployments as examples
count := 0
for _, deployment := range deployments {
if count >= 5 { // Limit to first 5 deployments
break
}
resource := mcp.Resource{
URI: fmt.Sprintf("k8s://deployment/%s/%s", deployment.Namespace, deployment.Name),
Name: fmt.Sprintf("Deployment: %s/%s", deployment.Namespace, deployment.Name),
Description: fmt.Sprintf("Kubernetes Deployment in namespace %s (%d/%d replicas ready)", deployment.Namespace, deployment.ReadyReplicas, deployment.TotalReplicas),
MIMEType: "application/json",
}
s.mcpServer.AddResource(resource, s.handleResourceRead)
count++
}
}
}
// Start starts the MCP server with stdio transport
func (s *Server) Start(ctx context.Context) error {
s.logger.Info("Starting Kubernetes MCP Server")
// Use the convenient ServeStdio function
if err := server.ServeStdio(s.mcpServer); err != nil {
s.logger.Errorf("MCP server error: %v", err)
return fmt.Errorf("MCP server failed: %w", err)
}
s.logger.Info("MCP Server stopped")
return nil
}
// handleResourceRead handles resource read requests
func (s *Server) handleResourceRead(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
uri := request.Params.URI
s.logger.Infof("Handling read_resource request for URI: %s", uri)
if !strings.HasPrefix(uri, "k8s://") {
return nil, fmt.Errorf("invalid URI format. Expected k8s://<resource-type>/<namespace>/<name>, got: %s", uri)
}
// Parse URI: k8s://<resource-type>/<namespace>/<name>
parts := strings.Split(strings.TrimPrefix(uri, "k8s://"), "/")
if len(parts) != 3 {
return nil, fmt.Errorf("invalid URI format. Expected k8s://<resource-type>/<namespace>/<name>, got %d parts", len(parts))
}
resourceType, namespace, name := parts[0], parts[1], parts[2]
var resourceTypeEnum types.K8sResourceType
switch resourceType {
case "pod":
resourceTypeEnum = types.ResourceTypePod
case "service":
resourceTypeEnum = types.ResourceTypeService
case "deployment":
resourceTypeEnum = types.ResourceTypeDeployment
default:
return nil, fmt.Errorf("unsupported resource type: %s. Supported types: pod, service, deployment", resourceType)
}
content, err := s.k8sClient.GetResource(ctx, &types.ResourceIdentifier{
Type: resourceTypeEnum,
Namespace: namespace,
Name: name,
})
if err != nil {
return nil, fmt.Errorf("failed to get resource %s: %w", uri, err)
}
// Format the content using AI-optimized formatters
var formattedContent string
var mimeType string
switch resourceType {
case "pod":
formattedContent, err = s.formatter.FormatPodForAI(content)
if err != nil {
s.logger.Errorf("Failed to format pod data: %v", err)
// Fall back to raw JSON
formattedContent = content
mimeType = "application/json"
} else {
mimeType = "text/markdown"
}
case "service":
formattedContent, err = s.formatter.FormatServiceForAI(content)
if err != nil {
s.logger.Errorf("Failed to format service data: %v", err)
// Fall back to raw JSON
formattedContent = content
mimeType = "application/json"
} else {
mimeType = "text/markdown"
}
case "deployment":
formattedContent, err = s.formatter.FormatDeploymentForAI(content)
if err != nil {
s.logger.Errorf("Failed to format deployment data: %v", err)
// Fall back to raw JSON
formattedContent = content
mimeType = "application/json"
} else {
mimeType = "text/markdown"
}
default:
// For unsupported types, return raw JSON
formattedContent = content
mimeType = "application/json"
}
// Return the formatted resource contents
return []mcp.ResourceContents{
&mcp.TextResourceContents{
URI: uri,
MIMEType: mimeType,
Text: formattedContent,
},
}, nil
}