|
| 1 | +package mcp |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "github.com/mark3labs/mcp-go/mcp" |
| 6 | + "io" |
| 7 | + v1 "k8s.io/api/core/v1" |
| 8 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + "testing" |
| 12 | +) |
| 13 | + |
| 14 | +func TestPodsExec(t *testing.T) { |
| 15 | + testCase(t, func(c *mcpContext) { |
| 16 | + mockServer := NewMockServer() |
| 17 | + defer mockServer.Close() |
| 18 | + c.withKubeConfig(mockServer.config) |
| 19 | + mockServer.Handle(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 20 | + if req.URL.Path != "/api/v1/namespaces/default/pods/pod-to-exec/exec" { |
| 21 | + return |
| 22 | + } |
| 23 | + var stdin, stdout bytes.Buffer |
| 24 | + ctx, err := createHTTPStreams(w, req, &StreamOptions{ |
| 25 | + Stdin: &stdin, |
| 26 | + Stdout: &stdout, |
| 27 | + }) |
| 28 | + if err != nil { |
| 29 | + w.WriteHeader(http.StatusInternalServerError) |
| 30 | + _, _ = w.Write([]byte(err.Error())) |
| 31 | + return |
| 32 | + } |
| 33 | + defer ctx.conn.Close() |
| 34 | + _, _ = io.WriteString(ctx.stdoutStream, strings.Join(req.URL.Query()["command"], " ")) |
| 35 | + _, _ = io.WriteString(ctx.stdoutStream, "\ntotal 0\n") |
| 36 | + })) |
| 37 | + mockServer.Handle(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 38 | + if req.URL.Path != "/api/v1/namespaces/default/pods/pod-to-exec" { |
| 39 | + return |
| 40 | + } |
| 41 | + writeObject(w, &v1.Pod{ |
| 42 | + ObjectMeta: metav1.ObjectMeta{ |
| 43 | + Namespace: "default", |
| 44 | + Name: "pod-to-exec", |
| 45 | + }, |
| 46 | + Spec: v1.PodSpec{Containers: []v1.Container{{Name: "container-to-exec"}}}, |
| 47 | + }) |
| 48 | + })) |
| 49 | + toolResult, err := c.callTool("pods_exec", map[string]interface{}{ |
| 50 | + "namespace": "default", |
| 51 | + "name": "pod-to-exec", |
| 52 | + "command": []interface{}{"ls", "-l"}, |
| 53 | + }) |
| 54 | + t.Run("pods_exec returns command output", func(t *testing.T) { |
| 55 | + if err != nil { |
| 56 | + t.Fatalf("call tool failed %v", err) |
| 57 | + } |
| 58 | + if toolResult.IsError { |
| 59 | + t.Fatalf("call tool failed") |
| 60 | + } |
| 61 | + if toolResult.Content[0].(mcp.TextContent).Text != "ls -l\ntotal 0\n" { |
| 62 | + t.Errorf("unexpected result %v", toolResult.Content[0].(mcp.TextContent).Text) |
| 63 | + } |
| 64 | + }) |
| 65 | + |
| 66 | + }) |
| 67 | +} |
0 commit comments