Skip to content

Commit d1cac85

Browse files
committed
feat(code): add evaluate_script tool for JavaScript script execution
Add a new MCP tool that enables LLMs to execute JavaScript scripts with direct access to Kubernetes clients. This allows complex operations that require multiple API calls, data transformation, filtering, or aggregation to be performed efficiently in a single tool call. Key features: - JavaScript execution via Goja (pure Go ES5.1+ engine) - Access to typed Kubernetes clients (CoreV1, AppsV1, BatchV1, etc.) - Transparent metadata flattening for standard K8s YAML/JSON structure - Case-insensitive method resolution (CoreV1/coreV1, Pods/pods, List/list) - SDK introspection support for API discovery - Configurable execution timeout (default 30s, max 5min) - Sandboxed environment with no file system or network access The tool is designed to be lenient and model-friendly: - Models can use familiar Kubernetes structure with metadata wrapper - Both uppercase and lowercase method names are supported - Automatic conversion handles the Go struct format requirements Signed-off-by: Marc Nuri <marc@marcnuri.com>
1 parent ceb360b commit d1cac85

21 files changed

Lines changed: 3942 additions & 3 deletions

README.md

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,7 @@ The following sets of tools are available (toolsets marked with ✓ in the Defau
400400

401401
| Toolset | Description | Default |
402402
|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
403+
| code | Execute JavaScript code with access to Kubernetes clients for advanced operations and data transformation (opt-in, security-sensitive) | |
403404
| config | View and manage the current local Kubernetes configuration (kubeconfig) ||
404405
| core | Most common tools for Kubernetes management (Pods, Generic Resources, Events, etc.) ||
405406
| kcp | Manage kcp workspaces and multi-tenancy features | |
@@ -417,6 +418,116 @@ In case multi-cluster support is enabled (default) and you have access to multip
417418

418419
<details>
419420

421+
<summary>code</summary>
422+
423+
- **evaluate_script** - Execute a JavaScript script with access to Kubernetes clients. Use this tool for complex operations that require multiple API calls, data transformation, filtering, or aggregation that would be inefficient with individual tool calls. The script runs in a sandboxed environment with access only to Kubernetes clients - no file system or network access.
424+
425+
426+
## JavaScript SDK
427+
428+
**Note:** Full ES5.1 syntax support, partial ES6. Synchronous execution only (no async/await or Promises).
429+
430+
### Globals
431+
- **k8s** - Kubernetes client (case-insensitive: coreV1, CoreV1, COREV1 all work)
432+
- **ctx** - Request context for cancellation
433+
- **namespace** - Default namespace
434+
435+
### k8s API Clients
436+
- k8s.coreV1() - pods, services, configMaps, secrets, namespaces, nodes, etc.
437+
- k8s.appsV1() - deployments, statefulSets, daemonSets, replicaSets
438+
- k8s.batchV1() - jobs, cronJobs
439+
- k8s.networkingV1() - ingresses, networkPolicies
440+
- k8s.rbacV1() - roles, roleBindings, clusterRoles, clusterRoleBindings
441+
- k8s.metricsV1beta1Client() - pod and node metrics (CPU/memory usage)
442+
- k8s.dynamicClient() - any resource by GVR
443+
- k8s.discoveryClient() - API discovery
444+
445+
### Examples
446+
447+
#### Combine multiple API calls with JavaScript
448+
```javascript
449+
// Get all deployments and their pod counts across namespaces
450+
const deps = k8s.appsV1().deployments("").list(ctx, {});
451+
const result = deps.items.flatMap(d => {
452+
const pods = k8s.coreV1().pods(d.metadata.namespace).list(ctx, {
453+
labelSelector: Object.entries(d.spec.selector.matchLabels || {})
454+
.map(([k,v]) => k+"="+v).join(",")
455+
});
456+
return [{
457+
deployment: d.metadata.name,
458+
namespace: d.metadata.namespace,
459+
replicas: d.status.readyReplicas + "/" + d.status.replicas,
460+
pods: pods.items.map(p => p.metadata.name)
461+
}];
462+
});
463+
JSON.stringify(result);
464+
```
465+
466+
#### Filter and aggregate
467+
```javascript
468+
const pods = k8s.coreV1().pods("").list(ctx, {});
469+
const unhealthy = pods.items.filter(p =>
470+
p.status.containerStatuses?.some(c => c.restartCount > 5)
471+
).map(p => ({
472+
name: p.metadata.name,
473+
ns: p.metadata.namespace,
474+
restarts: p.status.containerStatuses.reduce((s,c) => s + c.restartCount, 0)
475+
}));
476+
JSON.stringify(unhealthy);
477+
```
478+
479+
#### Create resources (using standard Kubernetes YAML/JSON structure)
480+
```javascript
481+
const pod = {
482+
apiVersion: "v1", kind: "Pod",
483+
metadata: { name: "my-pod", namespace: namespace },
484+
spec: { containers: [{ name: "nginx", image: "nginx:latest" }] }
485+
};
486+
k8s.coreV1().pods(namespace).create(ctx, pod, {}).metadata.name;
487+
```
488+
489+
#### API introspection
490+
```javascript
491+
// Discover available resources on coreV1
492+
const resources = []; for (const k in k8s.coreV1()) if (typeof k8s.coreV1()[k]==='function') resources.push(k);
493+
// resources: ["configMaps","namespaces","pods","secrets","services",...]
494+
495+
// Discover available operations on pods
496+
const ops = []; for (const k in k8s.coreV1().pods(namespace)) if (typeof k8s.coreV1().pods(namespace)[k]==='function') ops.push(k);
497+
// ops: ["create","delete","get","list","update","watch",...]
498+
```
499+
500+
#### Get pod metrics with resource quantities
501+
```javascript
502+
const metrics = k8s.metricsV1beta1Client();
503+
const podMetrics = metrics.podMetricses("").list(ctx, {});
504+
const result = podMetrics.items.map(function(pm) {
505+
return {
506+
name: pm.metadata.name,
507+
cpu: pm.containers[0].usage.cpu, // "100m"
508+
memory: pm.containers[0].usage.memory // "128Mi"
509+
};
510+
});
511+
JSON.stringify(result);
512+
```
513+
514+
#### Get pod logs
515+
```javascript
516+
const logBytes = k8s.coreV1().pods(namespace).getLogs("my-pod", {container: "main", tailLines: 100}).doRaw(ctx);
517+
var logs = ""; for (var i = 0; i < logBytes.length; i++) logs += String.fromCharCode(logBytes[i]);
518+
logs;
519+
```
520+
521+
### Return Value
522+
Last expression is returned. Use JSON.stringify() for objects.
523+
524+
- `script` (`string`) **(required)** - JavaScript code to execute. The last expression is returned as the result.
525+
- `timeout` (`integer`) - Execution timeout in milliseconds (default: 30000, max: 300000)
526+
527+
</details>
528+
529+
<details>
530+
420531
<summary>config</summary>
421532
422533
- **configuration_contexts_list** - List all available context names and associated server urls from the kubeconfig file
@@ -687,4 +798,4 @@ npx @modelcontextprotocol/inspector@latest $(pwd)/kubernetes-mcp-server
687798
688799
---
689800
690-
mcp-name: io.github.containers/kubernetes-mcp-server
801+
mcp-name: io.github.containers/kubernetes-mcp-server

go.mod

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.25.0
55
require (
66
github.com/BurntSushi/toml v1.6.0
77
github.com/coreos/go-oidc/v3 v3.17.0
8+
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3
89
github.com/fsnotify/fsnotify v1.9.0
910
github.com/go-jose/go-jose/v4 v4.1.3
1011
github.com/go-logr/logr v1.4.3
@@ -66,6 +67,7 @@ require (
6667
github.com/containerd/platforms v0.2.1 // indirect
6768
github.com/cyphar/filepath-securejoin v0.6.1 // indirect
6869
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
70+
github.com/dlclark/regexp2 v1.11.4 // indirect
6971
github.com/emicklei/go-restful/v3 v3.12.2 // indirect
7072
github.com/evanphx/json-patch v5.9.11+incompatible // indirect
7173
github.com/evanphx/json-patch/v5 v5.9.11 // indirect
@@ -78,10 +80,12 @@ require (
7880
github.com/go-openapi/jsonpointer v0.21.1 // indirect
7981
github.com/go-openapi/jsonreference v0.21.0 // indirect
8082
github.com/go-openapi/swag v0.23.1 // indirect
83+
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
8184
github.com/gobwas/glob v0.2.3 // indirect
8285
github.com/google/btree v1.1.3 // indirect
8386
github.com/google/gnostic-models v0.7.0 // indirect
8487
github.com/google/go-cmp v0.7.0 // indirect
88+
github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 // indirect
8589
github.com/google/uuid v1.6.0 // indirect
8690
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
8791
github.com/gosuri/uitable v0.0.4 // indirect

go.sum

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,16 @@ github.com/distribution/distribution/v3 v3.0.0 h1:q4R8wemdRQDClzoNNStftB2ZAfqOiN
6969
github.com/distribution/distribution/v3 v3.0.0/go.mod h1:tRNuFoZsUdyRVegq8xGNeds4KLjwLCRin/tTo6i1DhU=
7070
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
7171
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
72-
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
73-
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
72+
github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=
73+
github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
7474
github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo=
7575
github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M=
7676
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8=
7777
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=
7878
github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8=
7979
github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw=
80+
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3 h1:bVp3yUzvSAJzu9GqID+Z96P+eu5TKnIMJSV4QaZMauM=
81+
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
8082
github.com/emicklei/go-restful/v3 v3.12.2 h1:DhwDP0vY3k8ZzE0RunuJy8GhNpPL6zqLkDf9B/a0/xU=
8183
github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
8284
github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8=
@@ -116,6 +118,8 @@ github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF
116118
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
117119
github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU=
118120
github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0=
121+
github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU=
122+
github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
119123
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
120124
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
121125
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=

internal/tools/update-readme/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/containers/kubernetes-mcp-server/pkg/config"
1414
"github.com/containers/kubernetes-mcp-server/pkg/toolsets"
1515

16+
_ "github.com/containers/kubernetes-mcp-server/pkg/toolsets/code"
1617
_ "github.com/containers/kubernetes-mcp-server/pkg/toolsets/config"
1718
_ "github.com/containers/kubernetes-mcp-server/pkg/toolsets/core"
1819
_ "github.com/containers/kubernetes-mcp-server/pkg/toolsets/helm"

0 commit comments

Comments
 (0)