K8s.pm

filter: Statementstmt 91.6% 405 / 442 Branchbran 65.9% 178 / 270 Conditioncond 53.0% 106 / 200 MC/DCmcdc 29.2% 36 / 123 Subroutinesub 95.2% 40 / 42 Podpod 66.6% 2 / 3 totaltotal 71.0% 767 / 1080 CC 218 SCAR 35.8
CC
218
Cov
76%
_build_namespaces
182.0
_format_resource_summary
90.5
_discover_resource_plurals
35.1
CRAP 35.8
↑ Summary K8s/Permissions.pm »
1 package MCP::K8s;
2 # ABSTRACT: MCP Server for Kubernetes with RBAC-aware dynamic tools
3 10 our $VERSION = '0.003';
4 10 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use MCP::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 extends 'MCP::Server';
7 10 ▶use MCP::K8s::Permissions;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use Kubernetes::REST;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use Kubernetes::REST::Kubeconfig;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14  
15 # Map common resource short names to their plural form for RBAC checking.
16 # This is necessary because RBAC rules use plural resource names (e.g. "pods")
17 # while the Kubernetes::REST API accepts singular Kind names (e.g. "Pod").
18 10 my %RESOURCE_PLURALS = (
19 Pod => 'pods',
20 Service => 'services',
21 Deployment => 'deployments',
22 ReplicaSet => 'replicasets',
23 StatefulSet => 'statefulsets',
24 DaemonSet => 'daemonsets',
25 Job => 'jobs',
26 CronJob => 'cronjobs',
27 ConfigMap => 'configmaps',
28 Secret => 'secrets',
29 Namespace => 'namespaces',
30 Node => 'nodes',
31 PersistentVolume => 'persistentvolumes',
32 PersistentVolumeClaim => 'persistentvolumeclaims',
33 ServiceAccount => 'serviceaccounts',
34 Role => 'roles',
35 RoleBinding => 'rolebindings',
36 ClusterRole => 'clusterroles',
37 ClusterRoleBinding => 'clusterrolebindings',
38 Ingress => 'ingresses',
39 NetworkPolicy => 'networkpolicies',
40 HorizontalPodAutoscaler => 'horizontalpodautoscalers',
41 Event => 'events',
42 Endpoints => 'endpoints',
43 LimitRange => 'limitranges',
44 ResourceQuota => 'resourcequotas',
45 );
46  
47 has context_name => (
48 is => 'ro',
49 lazy => 1,
50 16 ▶ default => sub { $ENV{MCP_K8S_CONTEXT} },
Subroutine __ANON__: called CC=1 SCAR=0.0
51 10 predicate => 1,
52 );
53  
54  
55 10 has kubeconfig_path => (
56 is => 'ro',
57 predicate => 1,
58 );
59  
60  
61 has token => (
62 is => 'ro',
63 lazy => 1,
64 27 ▶ default => sub { $ENV{MCP_K8S_TOKEN} },
Subroutine __ANON__: called CC=1 SCAR=0.0
65 10 predicate => 1,
66 );
67  
68  
69 has server_endpoint => (
70 is => 'ro',
71 lazy => 1,
72 9 ▶ default => sub { $ENV{MCP_K8S_SERVER} },
Subroutine __ANON__: called CC=1 SCAR=0.0
73 10 predicate => 1,
74 );
75  
76  
77 10 has namespaces => (
78 is => 'ro',
79 lazy => 1,
80 builder => '_build_namespaces',
81 );
82  
83  
84 10 has api => (
85 is => 'ro',
86 lazy => 1,
87 builder => '_build_api',
88 );
89  
90  
91 10 has permissions => (
92 is => 'ro',
93 lazy => 1,
94 builder => '_build_permissions',
95 );
96  
97  
98 has _resource_plurals_cache => (
99 is => 'rw',
100 46 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
101 10 );
102  
103 # Stores [tool_ref, base_desc, verb] tuples for lazy description updates
104 has _tool_desc_map => (
105 is => 'rw',
106 46 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
107 10 );
108  
109 10 has _descriptions_updated => (
110 is => 'rw',
111 default => 0,
112 );
113  
114 has json => (
115 is => 'ro',
116 lazy => 1,
117 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
118 5 JSON::MaybeXS->new(utf8 => 1, pretty => 1, canonical => 1, convert_blessed => 1);
119 },
120 10 );
121  
122  
123  
124 40 ▶sub server { $_[0] }
Subroutine server: called CC=1 SCAR=0.0
Pod documented
125  
126 46 ▶sub BUILD {
Subroutine BUILD: called CC=4 SCAR=14.9
Pod undocumented
127 46 my ($self) = @_;
128 46 ▶ $self->name('MCP-K8s') if $self->name eq 'PerlServer';
Branch: 1 branch
BranchTrueFalseTotal
if $self->name eq "PerlServer" 46 0 46
129 46 ▶ $self->version($MCP::K8s::VERSION || 'dev') if $self->version eq '1.0.0';
Branch: 1 branch
BranchTrueFalseTotal
if $self->version eq "1.0.0" 46 0 46
Condition50%1/2
$MCP::K8s::VERSION || 'dev'
l!l
460
MC/DC0%0/1
$MCP::K8s::VERSION || 'dev'
$MCP::K8s::VERSION
Truth table50%1/2
A
A= $MCP::K8s::VERSION
Aresult
11
00
130 46 $self->_register_tools;
131 }
132  
133 10 my $IN_CLUSTER_TOKEN_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/token';
134 10 my $IN_CLUSTER_CA_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt';
135 10 my $IN_CLUSTER_NS_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/namespace';
136 10 my $IN_CLUSTER_DEFAULT_SERVER = 'https://kubernetes.default.svc.cluster.local';
137  
138 2 ▶sub _read_file {
Subroutine _read_file: called CC=3 SCAR=11.0
139 2 my ($self, $path) = @_;
140 2 ▶ open my $fh, '<', $path or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or return undef 1 1 2
141 1 my $content = do { local $/; <$fh> };
142 1 close $fh;
143 1 ▶ chomp $content if defined $content;
Branch: 1 branch
BranchTrueFalseTotal
if defined $content 1 0 1
144 1 return $content;
145 }
146  
147 26 ▶sub _build_api {
Subroutine _build_api: called CC=16 SCAR=33.2
148 26 my ($self) = @_;
149  
150 # Materialize the env-backed attributes up-front. The lazy `default`
151 # subs read $ENV{MCP_K8S_TOKEN} / $ENV{MCP_K8S_SERVER}, but `has_token`
152 # and `has_server_endpoint` are still false until the reader is called
153 # once. Gating Tier 1 on the predicates silently skipped Tier 1 when the
154 # token came purely from the environment — see Issue #1.
155 26 my $token = $self->token;
156  
157 # Tier 1: Direct token from MCP_K8S_TOKEN
158 26 ▶ if (defined $token && length $token) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $token and length $token) 7 19 26
Condition100%3/3
defined $token and length $token
!ll&&!rl&&r
1727
MC/DC100%2/2
defined $token and length $token
defined $token length $token
Truth table100%3/3
A and B
A= defined $tokenB= length $token
ABresult
0X0
100
111
159 7 my $endpoint = $self->server_endpoint;
160 7 ▶ $endpoint = $IN_CLUSTER_DEFAULT_SERVER
Branch: 1 branch
BranchTrueFalseTotal
unless defined $endpoint and length $endpoint 4 3 7
Condition100%3/3
defined $endpoint and length $endpoint
!ll&&!rl&&r
313
MC/DC100%2/2
defined $endpoint and length $endpoint
defined $endpoint length $endpoint
Truth table100%3/3
A and B
A= defined $endpointB= length $endpoint
ABresult
0X0
100
111
161 unless defined $endpoint && length $endpoint;
162 7 my %server = (endpoint => $endpoint);
163 7 ▶ $server{ssl_ca_file} = $IN_CLUSTER_CA_PATH if -f $IN_CLUSTER_CA_PATH;
Branch: 1 branch
BranchTrueFalseTotal
if -f $IN_CLUSTER_CA_PATH 0 7 7
164 7 return Kubernetes::REST->new(
165 server => \%server,
166 credentials => { token => $token },
167 );
168 }
169  
170 # Tier 2: In-cluster service account token
171 19 ▶ if (-f $IN_CLUSTER_TOKEN_PATH) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $IN_CLUSTER_TOKEN_PATH) 0 19 19
172 0 my $sa_token = $self->_read_file($IN_CLUSTER_TOKEN_PATH);
173 0 ▶ if (defined $sa_token && length $sa_token) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sa_token and length $sa_token) 0 0 0
Condition0%0/3
defined $sa_token and length $sa_token
!ll&&!rl&&r
000
MC/DC0%0/2
defined $sa_token and length $sa_token
defined $sa_token length $sa_token
Truth table0%0/3
A and B
A= defined $sa_tokenB= length $sa_token
ABresult
0X0
100
111
174 0 my $endpoint = $self->server_endpoint;
175 0 ▶ $endpoint = $IN_CLUSTER_DEFAULT_SERVER
Branch: 1 branch
BranchTrueFalseTotal
unless defined $endpoint and length $endpoint 0 0 0
Condition0%0/3
defined $endpoint and length $endpoint
!ll&&!rl&&r
000
MC/DC0%0/2
defined $endpoint and length $endpoint
defined $endpoint length $endpoint
Truth table0%0/3
A and B
A= defined $endpointB= length $endpoint
ABresult
0X0
100
111
176 unless defined $endpoint && length $endpoint;
177 0 my %server = (endpoint => $endpoint);
178 0 ▶ $server{ssl_ca_file} = $IN_CLUSTER_CA_PATH if -f $IN_CLUSTER_CA_PATH;
Branch: 1 branch
BranchTrueFalseTotal
if -f $IN_CLUSTER_CA_PATH 0 0 0
179 0 return Kubernetes::REST->new(
180 server => \%server,
181 credentials => { token => $sa_token },
182 );
183 }
184 }
185  
186 # Tier 3: Kubeconfig. Same predicate-with-lazy-default trap as Tier 1:
187 # `has_context_name` stays false until the reader fires, so an env-only
188 # MCP_K8S_CONTEXT would be silently dropped. Pass the materialized value
189 # through, dropping empty/undef so Kubeconfig keeps its current-context
190 # fallback when nothing is set. kubeconfig_path has no env default, but
191 # the same gate applies: Kubeconfig's own kubeconfig_path default is a
192 # plain (non-lazy) default, so an explicit undef or '' would override
193 # its KUBECONFIG / ~/.kube/config lookup instead of leaving it alone.
194 19 my $context_name = $self->context_name;
195 19 my $kubeconfig_path = $self->kubeconfig_path;
196 19 my %kc_args;
197 19 ▶ $kc_args{context_name} = $context_name
Branch: 1 branch
BranchTrueFalseTotal
if defined $context_name and length $context_name 6 13 19
Condition100%3/3
defined $context_name and length $context_name
!ll&&!rl&&r
1126
MC/DC100%2/2
defined $context_name and length $context_name
defined $context_name length $context_name
Truth table100%3/3
A and B
A= defined $context_nameB= length $context_name
ABresult
0X0
100
111
198 if defined $context_name && length $context_name;
199 19 ▶ $kc_args{kubeconfig_path} = $kubeconfig_path
Branch: 1 branch
BranchTrueFalseTotal
if defined $kubeconfig_path and length $kubeconfig_path 3 16 19
Condition100%3/3
defined $kubeconfig_path and length $kubeconfig_path
!ll&&!rl&&r
1513
MC/DC100%2/2
defined $kubeconfig_path and length $kubeconfig_path
defined $kubeconfig_path length $kubeconfig_path
Truth table100%3/3
A and B
A= defined $kubeconfig_pathB= length $kubeconfig_path
ABresult
0X0
100
111
200 if defined $kubeconfig_path && length $kubeconfig_path;
201 19 my $kc = Kubernetes::REST::Kubeconfig->new(%kc_args);
202 19 return $kc->api;
203 }
204  
205 0 ▶sub _build_namespaces {
Subroutine _build_namespaces: not called CC=13 SCAR=52.0
206 0 my ($self) = @_;
207  
208 # From environment variable
209 0 ▶ if (my $env = $ENV{MCP_K8S_NAMESPACES}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $env = $ENV{"MCP_K8S_NAMESPACES"}) 0 0 0
210 0 return [ split /,/, $env ];
211 }
212  
213 # In-cluster: read mounted namespace as default
214 0 ▶ if (-f $IN_CLUSTER_NS_PATH) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $IN_CLUSTER_NS_PATH) 0 0 0
215 0 my $ns = $self->_read_file($IN_CLUSTER_NS_PATH);
216 0 ▶ if (defined $ns && length $ns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ns and length $ns) 0 0 0
Condition0%0/3
defined $ns and length $ns
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ns and length $ns
defined $ns length $ns
Truth table0%0/3
A and B
A= defined $nsB= length $ns
ABresult
0X0
100
111
217 # Try to discover more, but use in-cluster namespace as fallback
218 0 my $list = eval { $self->api->list('Namespace') };
219 0 ▶ if (!$@ && $list) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and $list) 0 0 0
Condition0%0/3
not $@ and $list
!ll&&!rl&&r
000
MC/DC0%0/2
not $@ and $list
not $@ $list
Truth table0%0/3
not(A) and B
A= not $@B= $list
ABresult
0X0
100
111
220 0 ▶ my @ns = map { $_->metadata->name } @{ $list->items // [] };
Condition0%0/2
$list->items // []
l!l
00
MC/DC0%0/1
$list->items // []
$list->items
Truth table0%0/2
A
A= $list->items
Aresult
11
00
221 0 ▶ return \@ns if @ns;
Branch: 1 branch
BranchTrueFalseTotal
if @ns 0 0 0
222 }
223 0 return [$ns];
224 }
225 }
226  
227 # Auto-discover from cluster
228 0 my $list = eval { $self->api->list('Namespace') };
229 0 ▶ if ($@ || !$list) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $list) 0 0 0
Condition0%0/3
$@ or not $list
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not $list
$@ not $list
Truth table0%0/3
A or not(B)
A= $@B= not $list
ABresult
1X1
011
000
230 0 return ['default'];
231 }
232  
233 0 ▶ my @ns = map { $_->metadata->name } @{ $list->items // [] };
Condition0%0/2
$list->items // []
l!l
00
MC/DC0%0/1
$list->items // []
$list->items
Truth table0%0/2
A
A= $list->items
Aresult
11
00
234 0 ▶ return @ns ? \@ns : ['default'];
Branch: 1 branch
BranchTrueFalseTotal
@ns ? : 0 0 0
235 }
236  
237 8 ▶sub _build_permissions {
Subroutine _build_permissions: called CC=1 SCAR=0.0
238 8 my ($self) = @_;
239 8 return MCP::K8s::Permissions->new(
240 api => $self->api,
241 namespaces => $self->namespaces,
242 );
243 }
244  
245 19 ▶sub _to_json {
Subroutine _to_json: called CC=1 SCAR=0.0
246 19 my ($self, $data) = @_;
247 19 return $self->json->encode($data);
248 }
249  
250 85 ▶sub _resource_plural {
Subroutine _resource_plural: called CC=9 SCAR=22.0
251 85 my ($self, $resource) = @_;
252  
253  
254 # Tier 1: Static map (fast path)
255 85 ▶ return $RESOURCE_PLURALS{$resource} if $RESOURCE_PLURALS{$resource};
Branch: 1 branch
BranchTrueFalseTotal
if $RESOURCE_PLURALS{$resource} 60 25 85
256  
257 # Tier 2: resource_plural() on the IO::K8s class the Kind resolves to.
258 # Built-in Kinds resolve from the client's built-in map without a request;
259 # an unknown Kind costs the client's aggregated discovery (GET /api, /apis),
260 # which the tool's own API call right after would trigger anyway. A Kind
261 # nothing ships resolves to a fabricated name or IO::K8s::Unstructured,
262 # neither of which can resource_plural, so it falls through to tier 3.
263 25 my $class = eval { $self->api->expand_class($resource) };
264 25 ▶ if ($class && $class->can('resource_plural')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class and $class->can("resource_plural")) 8 17 25
Condition100%3/3
$class and $class->can("resource_plural")
!ll&&!rl&&r
1078
MC/DC100%2/2
$class and $class->can("resource_plural")
$class $class->can("resource_plural")
Truth table100%3/3
A and B
A= $classB= $class->can("resource_plural")
ABresult
0X0
100
111
265 8 my $plural = eval { $class->resource_plural };
266 8 ▶ return $plural if defined $plural && length $plural;
Branch: 1 branch
BranchTrueFalseTotal
if defined $plural and length $plural 8 0 8
Condition33%1/3
defined $plural and length $plural
!ll&&!rl&&r
008
MC/DC0%0/2
defined $plural and length $plural
defined $plural length $plural
Truth table33%1/3
A and B
A= defined $pluralB= length $plural
ABresult
0X0
100
111
267 }
268  
269 # Tier 3: API server discovery (cached)
270 17 my $cache = $self->_resource_plurals_cache;
271 17 ▶ unless (%$cache) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%$cache) 11 6 17
272 11 $self->_discover_resource_plurals;
273 11 $cache = $self->_resource_plurals_cache;
274 }
275 17 ▶ return $cache->{$resource} if $cache->{$resource};
Branch: 1 branch
BranchTrueFalseTotal
if $$cache{$resource} 6 11 17
276  
277 # Tier 4: Heuristic fallback
278 11 my $plural = lc($resource);
279 11 ▶ $plural .= 's' unless $plural =~ /s$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $plural =~ /s$/ 10 1 11
280 11 $plural =~ s/ys$/ies/;
281 11 return $plural;
282 }
283  
284 11 ▶sub _discover_resource_plurals {
Subroutine _discover_resource_plurals: called CC=25 SCAR=35.6
285 11 my ($self) = @_;
286  
287  
288 11 my %cache;
289  
290 # Query /api/v1 for core resources
291 11 my $core = eval {
292 11 my $resp = $self->api->_request('GET', '/api/v1');
293 6 ▶ return undef if !$resp || $resp->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if not $resp or $resp->status >= 400 4 2 6
Condition66%2/3
not $resp or $resp->status >= 400
l!l&&r!l&&!r
042
MC/DC50%1/2
not $resp or $resp->status >= 400
not $resp $resp->status >= 400
Truth table66%2/3
not(A) or B
A= not $respB= $resp->status >= 400
ABresult
1X1
011
000
294 2 JSON::MaybeXS->new->decode($resp->content);
295 };
296 11 ▶ if ($core && $core->{resources}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($core and $$core{"resources"}) 2 9 11
Condition66%2/3
$core and $$core{"resources"}
!ll&&!rl&&r
902
MC/DC50%1/2
$core and $$core{"resources"}
$core $$core{"resources"}
Truth table66%2/3
A and B
A= $coreB= $$core{"resources"}
ABresult
0X0
100
111
297 2 for my $r (@{ $core->{resources} }) {
298 10 ▶ next if ($r->{name} // '') =~ m{/}; # skip subresources
Branch: 1 branch
BranchTrueFalseTotal
if ($$r{"name"} // "") =~ m[/] 2 8 10
Condition50%1/2
$$r{"name"} // ""
l!l
100
MC/DC0%0/1
$$r{"name"} // ""
$$r{"name"}
Truth table50%1/2
A
A= $$r{"name"}
Aresult
11
00
299 8 ▶ $cache{ $r->{kind} } = $r->{name} if $r->{kind} && $r->{name};
Branch: 1 branch
BranchTrueFalseTotal
if $$r{"kind"} and $$r{"name"} 8 0 8
Condition33%1/3
$$r{"kind"} and $$r{"name"}
!ll&&!rl&&r
008
MC/DC0%0/2
$$r{"kind"} and $$r{"name"}
$$r{"kind"} $$r{"name"}
Truth table33%1/3
A and B
A= $$r{"kind"}B= $$r{"name"}
ABresult
0X0
100
111
300 }
301 }
302  
303 # Query /apis for API groups
304 11 my $groups = eval {
305 11 my $resp = $self->api->_request('GET', '/apis');
306 6 ▶ return undef if !$resp || $resp->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if not $resp or $resp->status >= 400 4 2 6
Condition66%2/3
not $resp or $resp->status >= 400
l!l&&r!l&&!r
042
MC/DC50%1/2
not $resp or $resp->status >= 400
not $resp $resp->status >= 400
Truth table66%2/3
not(A) or B
A= not $respB= $resp->status >= 400
ABresult
1X1
011
000
307 2 JSON::MaybeXS->new->decode($resp->content);
308 };
309 11 ▶ if ($groups && $groups->{groups}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($groups and $$groups{"groups"}) 2 9 11
Condition66%2/3
$groups and $$groups{"groups"}
!ll&&!rl&&r
902
MC/DC50%1/2
$groups and $$groups{"groups"}
$groups $$groups{"groups"}
Truth table66%2/3
A and B
A= $groupsB= $$groups{"groups"}
ABresult
0X0
100
111
310 2 for my $group (@{ $groups->{groups} }) {
311 2 ▶ my $pv = $group->{preferredVersion}{groupVersion} // next;
Condition50%1/2
$$group{"preferredVersion"}{"groupVersion"} // (next)
l!l
20
MC/DC0%0/1
$$group{"preferredVersion"}{"groupVersion"} // (next)
$$group{"preferredVersion"}{"groupVersion"}
Truth table50%1/2
A
A= $$group{"preferredVersion"}{"groupVersion"}
Aresult
11
00
312 2 my $group_resources = eval {
313 2 my $resp = $self->api->_request('GET', "/apis/$pv");
314 2 ▶ return undef if !$resp || $resp->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if not $resp or $resp->status >= 400 0 2 2
Condition33%1/3
not $resp or $resp->status >= 400
l!l&&r!l&&!r
002
MC/DC0%0/2
not $resp or $resp->status >= 400
not $resp $resp->status >= 400
Truth table33%1/3
not(A) or B
A= not $respB= $resp->status >= 400
ABresult
1X1
011
000
315 2 JSON::MaybeXS->new->decode($resp->content);
316 };
317 2 ▶ if ($group_resources && $group_resources->{resources}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($group_resources and $$group_resources{"resources"}) 2 0 2
Condition33%1/3
$group_resources and $$group_resources{"resources"}
!ll&&!rl&&r
002
MC/DC0%0/2
$group_resources and $$group_resources{"resources"}
$group_resources $$group_resources{"resources"}
Truth table33%1/3
A and B
A= $group_resourcesB= $$group_resources{"resources"}
ABresult
0X0
100
111
318 2 for my $r (@{ $group_resources->{resources} }) {
319 4 ▶ next if ($r->{name} // '') =~ m{/};
Branch: 1 branch
BranchTrueFalseTotal
if ($$r{"name"} // "") =~ m[/] 0 4 4
Condition50%1/2
$$r{"name"} // ""
l!l
40
MC/DC0%0/1
$$r{"name"} // ""
$$r{"name"}
Truth table50%1/2
A
A= $$r{"name"}
Aresult
11
00
320 4 ▶ $cache{ $r->{kind} } = $r->{name} if $r->{kind} && $r->{name};
Branch: 1 branch
BranchTrueFalseTotal
if $$r{"kind"} and $$r{"name"} 4 0 4
Condition33%1/3
$$r{"kind"} and $$r{"name"}
!ll&&!rl&&r
004
MC/DC0%0/2
$$r{"kind"} and $$r{"name"}
$$r{"kind"} $$r{"name"}
Truth table33%1/3
A and B
A= $$r{"kind"}B= $$r{"name"}
ABresult
0X0
100
111
321 }
322 }
323 }
324 }
325  
326 11 $self->_resource_plurals_cache(\%cache);
327 }
328  
329 46 ▶sub _resolve_namespace {
Subroutine _resolve_namespace: called CC=4 SCAR=13.9
330 46 my ($self, $args) = @_;
331  
332  
333 46 my $ns = $args->{namespace};
334 46 ▶ return $ns if defined $ns && length $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns and length $ns 38 8 46
Condition100%3/3
defined $ns and length $ns
!ll&&!rl&&r
7138
MC/DC100%2/2
defined $ns and length $ns
defined $ns length $ns
Truth table100%3/3
A and B
A= defined $nsB= length $ns
ABresult
0X0
100
111
335  
336 # Auto-fill if only one namespace accessible
337 8 my @allowed = $self->permissions->allowed_namespaces;
338 8 ▶ return $allowed[0] if @allowed == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @allowed == 1 5 3 8
339  
340 3 return undef;
341 }
342  
343 8 ▶sub _is_conflict_error {
Subroutine _is_conflict_error: called CC=3 SCAR=11.0
344 8 my ($self, $err) = @_;
345  
346  
347 8 ▶ return 0 unless defined $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err 1 7 8
348 7 ▶ return $err =~ /409|AlreadyExists/i ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$err =~ /409|AlreadyExists/i ? : 4 3 7
349 }
350  
351 18 ▶sub _format_resource_summary {
Subroutine _format_resource_summary: called CC=41 SCAR=45.1
352 18 my ($self, $obj) = @_;
353  
354  
355 18 my %summary;
356  
357 18 ▶ if ($obj->can('metadata') && $obj->metadata) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->can("metadata") and $obj->metadata) 18 0 18
Condition33%1/3
$obj->can("metadata") and $obj->metadata
!ll&&!rl&&r
0018
MC/DC0%0/2
$obj->can("metadata") and $obj->metadata
$obj->can("metadata") $obj->metadata
Truth table33%1/3
A and B
A= $obj->can("metadata")B= $obj->metadata
ABresult
0X0
100
111
358 18 my $meta = $obj->metadata;
359 18 ▶ $summary{name} = $meta->name if $meta->can('name');
Branch: 1 branch
BranchTrueFalseTotal
if $meta->can("name") 18 0 18
360 18 ▶ $summary{namespace} = $meta->namespace if $meta->can('namespace') && $meta->namespace;
Branch: 1 branch
BranchTrueFalseTotal
if $meta->can("namespace") and $meta->namespace 17 1 18
Condition66%2/3
$meta->can("namespace") and $meta->namespace
!ll&&!rl&&r
1017
MC/DC50%1/2
$meta->can("namespace") and $meta->namespace
$meta->can("namespace") $meta->namespace
Truth table66%2/3
A and B
A= $meta->can("namespace")B= $meta->namespace
ABresult
0X0
100
111
361 18 ▶ $summary{labels} = $meta->labels if $meta->can('labels') && $meta->labels;
Branch: 1 branch
BranchTrueFalseTotal
if $meta->can("labels") and $meta->labels 4 14 18
Condition100%3/3
$meta->can("labels") and $meta->labels
!ll&&!rl&&r
594
MC/DC100%2/2
$meta->can("labels") and $meta->labels
$meta->can("labels") $meta->labels
Truth table100%3/3
A and B
A= $meta->can("labels")B= $meta->labels
ABresult
0X0
100
111
362 18 ▶ $summary{creationTimestamp} = $meta->creationTimestamp if $meta->can('creationTimestamp') && $meta->creationTimestamp;
Branch: 1 branch
BranchTrueFalseTotal
if $meta->can("creationTimestamp") and $meta->creationTimestamp 1 17 18
Condition100%3/3
$meta->can("creationTimestamp") and $meta->creationTimestamp
!ll&&!rl&&r
5121
MC/DC100%2/2
$meta->can("creationTimestamp") and $meta->creationTimestamp
$meta->can("creationTimestamp") $meta->creationTimestamp
Truth table100%3/3
A and B
A= $meta->can("creationTimestamp")B= $meta->creationTimestamp
ABresult
0X0
100
111
363 }
364  
365 18 ▶ if ($obj->can('kind') && $obj->kind) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->can("kind") and $obj->kind) 18 0 18
Condition33%1/3
$obj->can("kind") and $obj->kind
!ll&&!rl&&r
0018
MC/DC0%0/2
$obj->can("kind") and $obj->kind
$obj->can("kind") $obj->kind
Truth table33%1/3
A and B
A= $obj->can("kind")B= $obj->kind
ABresult
0X0
100
111
366 18 $summary{kind} = $obj->kind;
367 }
368  
369 18 ▶ if ($obj->can('status') && $obj->status) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->can("status") and $obj->status) 13 5 18
Condition66%2/3
$obj->can("status") and $obj->status
!ll&&!rl&&r
5013
MC/DC50%1/2
$obj->can("status") and $obj->status
$obj->can("status") $obj->status
Truth table66%2/3
A and B
A= $obj->can("status")B= $obj->status
ABresult
0X0
100
111
370 13 my $status = $obj->status;
371 13 ▶ $summary{phase} = $status->phase if $status->can('phase') && $status->phase;
Branch: 1 branch
BranchTrueFalseTotal
if $status->can("phase") and $status->phase 13 0 13
Condition33%1/3
$status->can("phase") and $status->phase
!ll&&!rl&&r
0013
MC/DC0%0/2
$status->can("phase") and $status->phase
$status->can("phase") $status->phase
Truth table33%1/3
A and B
A= $status->can("phase")B= $status->phase
ABresult
0X0
100
111
372 13 ▶ $summary{replicas} = $status->replicas if $status->can('replicas') && defined $status->replicas;
Branch: 1 branch
BranchTrueFalseTotal
if $status->can("replicas") and defined $status->replicas 0 13 13
Condition33%1/3
$status->can("replicas") and defined $status->replicas
!ll&&!rl&&r
1300
MC/DC0%0/2
$status->can("replicas") and defined $status->replicas
$status->can("replicas") defined $status->replicas
Truth table33%1/3
A and B
A= $status->can("replicas")B= defined $status->replicas
ABresult
0X0
100
111
373 13 ▶ $summary{readyReplicas} = $status->readyReplicas if $status->can('readyReplicas') && defined $status->readyReplicas;
Branch: 1 branch
BranchTrueFalseTotal
if $status->can("readyReplicas") and defined $status->readyReplicas 0 13 13
Condition33%1/3
$status->can("readyReplicas") and defined $status->readyReplicas
!ll&&!rl&&r
1300
MC/DC0%0/2
$status->can("readyReplicas") and defined $status->readyReplicas
$status->can("readyReplicas") defined $status->readyReplicas
Truth table33%1/3
A and B
A= $status->can("readyReplicas")B= defined $status->readyReplicas
ABresult
0X0
100
111
374 13 ▶ $summary{availableReplicas} = $status->availableReplicas if $status->can('availableReplicas') && defined $status->availableReplicas;
Branch: 1 branch
BranchTrueFalseTotal
if $status->can("availableReplicas") and defined $status->availableReplicas 0 13 13
Condition33%1/3
$status->can("availableReplicas") and defined $status->availableReplicas
!ll&&!rl&&r
1300
MC/DC0%0/2
$status->can("availableReplicas") and defined $status->availableReplicas
$status->can("availableReplicas") defined $status->availableReplicas
Truth table33%1/3
A and B
A= $status->can("availableReplicas")B= defined $status->availableReplicas
ABresult
0X0
100
111
375 13 ▶ $summary{conditions} = $status->conditions if $status->can('conditions') && $status->conditions;
Branch: 1 branch
BranchTrueFalseTotal
if $status->can("conditions") and $status->conditions 0 13 13
Condition33%1/3
$status->can("conditions") and $status->conditions
!ll&&!rl&&r
1300
MC/DC0%0/2
$status->can("conditions") and $status->conditions
$status->can("conditions") $status->conditions
Truth table33%1/3
A and B
A= $status->can("conditions")B= $status->conditions
ABresult
0X0
100
111
376 }
377  
378 18 ▶ if ($obj->can('spec') && $obj->spec) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->can("spec") and $obj->spec) 2 16 18
Condition100%3/3
$obj->can("spec") and $obj->spec
!ll&&!rl&&r
792
MC/DC100%2/2
$obj->can("spec") and $obj->spec
$obj->can("spec") $obj->spec
Truth table100%3/3
A and B
A= $obj->can("spec")B= $obj->spec
ABresult
0X0
100
111
379 2 my $spec = $obj->spec;
380 2 ▶ $summary{replicas} //= $spec->replicas if $spec->can('replicas') && defined $spec->replicas;
Branch: 1 branch
BranchTrueFalseTotal
if $spec->can("replicas") and defined $spec->replicas 0 2 2
Condition16%1/6
$spec->can("replicas") and defined $spec->replicas
!ll&&!rl&&r
200
$summary{"replicas"} //= $spec->replicas
l!l&&r!l&&!r
000
MC/DC0%0/2
$spec->can("replicas") and defined $spec->replicas
$spec->can("replicas") defined $spec->replicas
MC/DC0%0/2
$summary{"replicas"} //= $spec->replicas
$summary{"replicas"} $spec->replicas
Truth table33%1/3
A and B
A= $spec->can("replicas")B= defined $spec->replicas
ABresult
0X0
100
111
Truth table0%0/3
A //= B
A= $summary{"replicas"}B= $spec->replicas
ABresult
1X1
011
000
381 2 ▶ if ($spec->can('containers') && $spec->containers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->can("containers") and $spec->containers) 1 1 2
Condition66%2/3
$spec->can("containers") and $spec->containers
!ll&&!rl&&r
101
MC/DC50%1/2
$spec->can("containers") and $spec->containers
$spec->can("containers") $spec->containers
Truth table66%2/3
A and B
A= $spec->can("containers")B= $spec->containers
ABresult
0X0
100
111
382 1 $summary{containers} = [ map { $_->name } @{ $spec->containers } ];
383 }
384 2 ▶ if ($spec->can('type') && $spec->type) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->can("type") and $spec->type) 1 1 2
Condition66%2/3
$spec->can("type") and $spec->type
!ll&&!rl&&r
101
MC/DC50%1/2
$spec->can("type") and $spec->type
$spec->can("type") $spec->type
Truth table66%2/3
A and B
A= $spec->can("type")B= $spec->type
ABresult
0X0
100
111
385 1 $summary{type} = $spec->type;
386 }
387 2 ▶ if ($spec->can('ports') && $spec->ports) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->can("ports") and $spec->ports) 1 1 2
Condition66%2/3
$spec->can("ports") and $spec->ports
!ll&&!rl&&r
101
MC/DC50%1/2
$spec->can("ports") and $spec->ports
$spec->can("ports") $spec->ports
Truth table66%2/3
A and B
A= $spec->can("ports")B= $spec->ports
ABresult
0X0
100
111
388 $summary{ports} = [ map {
389 2 my $p = $_;
390 2 my %port;
391 2 ▶ $port{port} = $p->port if $p->can('port') && defined $p->port;
Branch: 1 branch
BranchTrueFalseTotal
if $p->can("port") and defined $p->port 2 0 2
Condition33%1/3
$p->can("port") and defined $p->port
!ll&&!rl&&r
002
MC/DC0%0/2
$p->can("port") and defined $p->port
$p->can("port") defined $p->port
Truth table33%1/3
A and B
A= $p->can("port")B= defined $p->port
ABresult
0X0
100
111
392 2 ▶ $port{targetPort} = $p->targetPort if $p->can('targetPort') && defined $p->targetPort;
Branch: 1 branch
BranchTrueFalseTotal
if $p->can("targetPort") and defined $p->targetPort 2 0 2
Condition33%1/3
$p->can("targetPort") and defined $p->targetPort
!ll&&!rl&&r
002
MC/DC0%0/2
$p->can("targetPort") and defined $p->targetPort
$p->can("targetPort") defined $p->targetPort
Truth table33%1/3
A and B
A= $p->can("targetPort")B= defined $p->targetPort
ABresult
0X0
100
111
393 2 ▶ $port{protocol} = $p->protocol if $p->can('protocol') && $p->protocol;
Branch: 1 branch
BranchTrueFalseTotal
if $p->can("protocol") and $p->protocol 2 0 2
Condition33%1/3
$p->can("protocol") and $p->protocol
!ll&&!rl&&r
002
MC/DC0%0/2
$p->can("protocol") and $p->protocol
$p->can("protocol") $p->protocol
Truth table33%1/3
A and B
A= $p->can("protocol")B= $p->protocol
ABresult
0X0
100
111
394 2 \%port;
395 1 } @{ $spec->ports } ];
396 }
397 }
398  
399 18 return \%summary;
400 }
401  
402 8 ▶sub _format_list {
Subroutine _format_list: called CC=3 SCAR=11.0
403 8 my ($self, $items) = @_;
404  
405  
406 8 my @summaries;
407 8 ▶ for my $item (@{ $items // [] }) {
Condition100%2/2
$items // []
l!l
71
MC/DC100%1/1
$items // []
$items
Truth table100%2/2
A
A= $items
Aresult
11
00
408 13 push @summaries, $self->_format_resource_summary($item);
409 }
410 8 return \@summaries;
411 }
412  
413 16 ▶sub _available_resources_desc {
Subroutine _available_resources_desc: called CC=6 SCAR=19.2
414 16 my ($self, $verb) = @_;
415 16 my @parts;
416 16 for my $ns ($self->permissions->allowed_namespaces) {
417 16 my @resources = $self->permissions->allowed_resources($verb, $ns);
418 16 ▶ if (@resources) {
Branch: 1 branch
BranchTrueFalseTotal
if (@resources) 16 0 16
419 16 my @display = grep { $_ ne '*' } @resources;
420 16 ▶ if (grep { $_ eq '*' } @resources) {
Branch: 2 branches
BranchTrueFalseTotal
if (grep {$_ eq '*';} @resources) { } 0 16 16
elsif (@display > 10) { } 0 16 16
421 0 push @parts, "$ns: all resources";
422 } elsif (@display > 10) {
423 0 push @parts, "$ns: " . join(', ', @display[0..9]) . ", ...";
424 } else {
425 16 push @parts, "$ns: " . join(', ', @display);
426 }
427 }
428 }
429 16 ▶ return join('; ', @parts) || 'none discovered';
Condition50%1/2
join('; ', @parts) || 'none discovered'
l!l
160
MC/DC0%0/1
join('; ', @parts) || 'none discovered'
join('; ', @parts)
Truth table50%1/2
A
A= join('; ', @parts)
Aresult
11
00
430 }
431  
432 2 ▶sub _update_tool_descriptions {
Subroutine _update_tool_descriptions: called CC=5 SCAR=16.2
433 2 my ($self) = @_;
434 2 ▶ return if $self->_descriptions_updated;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_descriptions_updated 0 2 2
435 2 $self->permissions->ensure_discovered;
436  
437 2 for my $entry (@{ $self->_tool_desc_map }) {
438 18 my ($tool, $base, $verb) = @$entry;
439 18 ▶ if ($verb eq '_logs') {
Branch: 1 branch
BranchTrueFalseTotal
if ($verb eq '_logs') { } 2 16 18
440 my @log_ns = grep {
441 2 $self->permissions->can_read_logs($_)
442 } $self->permissions->allowed_namespaces;
443 2 ▶ $tool->description($base . (join(', ', @log_ns) || 'none'));
Condition50%1/2
join(', ', @log_ns) || 'none'
l!l
20
MC/DC0%0/1
join(', ', @log_ns) || 'none'
join(', ', @log_ns)
Truth table50%1/2
A
A= join(', ', @log_ns)
Aresult
11
00
444 } else {
445 16 $tool->description($base . $self->_available_resources_desc($verb));
446 }
447 }
448 2 $self->_descriptions_updated(1);
449 }
450  
451 1 ▶sub _tools {
Subroutine _tools: called CC=1 SCAR=0.0
452 1 my ($self, $context) = @_;
453  
454  
455 1 $self->_update_tool_descriptions;
456 1 return $self->SUPER::_tools($context);
457 }
458  
459  
460 46 ▶sub _register_tools {
Subroutine _register_tools: called CC=1 SCAR=0.1
461 46 my ($self) = @_;
462  
463 46 my @desc_map;
464  
465 # ---- Tool 1: k8s_permissions ----
466 $self->tool(
467 name => 'k8s_permissions',
468 description => 'Show what this Kubernetes service account is allowed to do (RBAC permissions). Call this first to understand available capabilities.',
469 input_schema => {
470 type => 'object',
471 properties => {},
472 },
473 1 ▶ code => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
474 1 my ($tool, $args) = @_;
475 1 return $self->permissions->summary;
476 },
477 46 );
478  
479 # ---- Tool 2: k8s_list ----
480 46 my $list_desc = 'List Kubernetes resources.';
481 push @desc_map, [$self->tool(
482 name => 'k8s_list',
483 description => $list_desc,
484 input_schema => {
485 type => 'object',
486 properties => {
487 resource => {
488 type => 'string',
489 description => 'Resource type (e.g. Pod, Deployment, Service, ConfigMap)',
490 },
491 namespace => {
492 type => 'string',
493 description => 'Namespace (auto-detected if only one available)',
494 },
495 label_selector => {
496 type => 'string',
497 description => 'Label selector filter (e.g. app=web)',
498 },
499 field_selector => {
500 type => 'string',
501 description => 'Field selector filter (e.g. status.phase=Running)',
502 },
503 },
504 required => ['resource'],
505 },
506 4 ▶ code => sub {
Subroutine __ANON__: called CC=10 SCAR=24.2
507 4 my ($tool, $args) = @_;
508  
509 4 my $resource = $args->{resource};
510 4 my $ns = $self->_resolve_namespace($args);
511 4 my $plural = $self->_resource_plural($resource);
512  
513 4 ▶ unless ($self->permissions->can_do('list', $plural, $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("list", $plural, $ns // "")) 1 3 4
Condition50%1/2
$ns // ""
l!l
40
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
514 1 ▶ return "Permission denied: cannot list $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
515 }
516  
517 3 my %api_args;
518 3 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 3 0 3
519 3 ▶ $api_args{labelSelector} = $args->{label_selector} if $args->{label_selector};
Branch: 1 branch
BranchTrueFalseTotal
if $$args{"label_selector"} 0 3 3
520 3 ▶ $api_args{fieldSelector} = $args->{field_selector} if $args->{field_selector};
Branch: 1 branch
BranchTrueFalseTotal
if $$args{"field_selector"} 0 3 3
521  
522 3 my $list = eval { $self->api->list($resource, %api_args) };
523 3 ▶ return "Failed to list $resource: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
524  
525 3 ▶ my $items = $list->items // [];
Condition50%1/2
$list->items // []
l!l
30
MC/DC0%0/1
$list->items // []
$list->items
Truth table50%1/2
A
A= $list->items
Aresult
11
00
526 3 ▶ return "No $resource resources found" unless @$items;
Branch: 1 branch
BranchTrueFalseTotal
unless @$items 0 3 3
527  
528 3 my $summaries = $self->_format_list($items);
529 3 return $self->_to_json({
530 count => scalar @$items,
531 items => $summaries,
532 });
533 },
534 46 ), 'List Kubernetes resources. Available: ', 'list'];
535  
536 # ---- Tool 3: k8s_get ----
537 46 my $get_desc = 'Get a single Kubernetes resource.';
538 push @desc_map, [$self->tool(
539 name => 'k8s_get',
540 description => $get_desc,
541 input_schema => {
542 type => 'object',
543 properties => {
544 resource => {
545 type => 'string',
546 description => 'Resource type (e.g. Pod, Deployment, Service)',
547 },
548 name => {
549 type => 'string',
550 description => 'Resource name',
551 },
552 namespace => {
553 type => 'string',
554 description => 'Namespace (auto-detected if only one available)',
555 },
556 output => {
557 type => 'string',
558 description => 'Output format: summary (default), json, yaml',
559 enum => ['summary', 'json', 'yaml'],
560 },
561 },
562 required => ['resource', 'name'],
563 },
564 8 ▶ code => sub {
Subroutine __ANON__: called CC=10 SCAR=23.2
565 8 my ($tool, $args) = @_;
566  
567 8 my $resource = $args->{resource};
568 8 my $name = $args->{name};
569 8 my $ns = $self->_resolve_namespace($args);
570 8 ▶ my $output = $args->{output} // 'summary';
Condition100%2/2
$$args{"output"} // "summary"
l!l
53
MC/DC100%1/1
$$args{"output"} // "summary"
$$args{"output"}
Truth table100%2/2
A
A= $$args{"output"}
Aresult
11
00
571 8 my $plural = $self->_resource_plural($resource);
572  
573 8 ▶ unless ($self->permissions->can_do('get', $plural, $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("get", $plural, $ns // "")) 1 7 8
Condition50%1/2
$ns // ""
l!l
80
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
574 1 ▶ return "Permission denied: cannot get $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
575 }
576  
577 7 my %api_args = (name => $name);
578 7 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 7 0 7
579  
580 7 my $obj = eval { $self->api->get($resource, %api_args) };
581 7 ▶ return "Failed to get $resource/$name: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
582  
583 7 ▶ if ($output eq 'json') {
Branch: 2 branches
BranchTrueFalseTotal
if ($output eq 'json') { } 2 5 7
elsif ($output eq 'yaml') { } 3 2 5
584 2 return $self->_to_json($obj->TO_JSON);
585 } elsif ($output eq 'yaml') {
586 # IO::K8s::Role::APIObject::to_yaml, not a YAML dump of TO_JSON.
587 # TO_JSON hands out JSON::PP::Boolean objects for every boolean field,
588 # and a generic dumper serialises those as Perl internals —
589 # "hostNetwork: !!perl/scalar:JSON::PP::Boolean 1" instead of
590 # "hostNetwork: true", which kubectl apply rejects. to_yaml runs
591 # YAML::PP with the JSON schema and boolean => 'JSON::PP', which is
592 # what makes the output a manifest.
593 3 ▶ unless ($obj->can('to_yaml')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($obj->can("to_yaml")) 1 2 3
594 1 return "Cannot render $resource/$name as YAML: " . ref($obj)
595 . " does not implement to_yaml (not a top-level Kubernetes API"
596 . " object). Retry with output 'json'.";
597 }
598 2 return $obj->to_yaml;
599 } else {
600 2 return $self->_to_json($self->_format_resource_summary($obj));
601 }
602 },
603 46 ), 'Get a single Kubernetes resource. Available: ', 'get'];
604  
605 # ---- Tool 4: k8s_create ----
606 46 my $create_desc = 'Create a Kubernetes resource.';
607 push @desc_map, [$self->tool(
608 name => 'k8s_create',
609 description => $create_desc,
610 input_schema => {
611 type => 'object',
612 properties => {
613 resource => {
614 type => 'string',
615 description => 'Resource type (e.g. Pod, Deployment, ConfigMap)',
616 },
617 namespace => {
618 type => 'string',
619 description => 'Namespace for the resource',
620 },
621 manifest => {
622 type => 'object',
623 description => 'Resource manifest (apiVersion/kind auto-populated from resource type)',
624 },
625 },
626 required => ['resource', 'manifest'],
627 },
628 2 ▶ code => sub {
Subroutine __ANON__: called CC=11 SCAR=25.6
629 2 my ($tool, $args) = @_;
630  
631 2 my $resource = $args->{resource};
632 2 my $ns = $self->_resolve_namespace($args);
633 2 my $manifest = $args->{manifest};
634 2 my $plural = $self->_resource_plural($resource);
635  
636 2 ▶ unless ($self->permissions->can_do('create', $plural, $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("create", $plural, $ns // "")) 1 1 2
Condition50%1/2
$ns // ""
l!l
20
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
637 1 ▶ return "Permission denied: cannot create $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
638 }
639  
640 # Auto-populate namespace in metadata
641 1 ▶ if (defined $ns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ns) 1 0 1
642 1 ▶ $manifest->{metadata} //= {};
Condition50%1/2
$$manifest{"metadata"} //= {}
l!l
10
MC/DC0%0/1
$$manifest{"metadata"} //= {}
$$manifest{"metadata"}
Truth table50%1/2
A
A= $$manifest{"metadata"}
Aresult
11
00
643 1 ▶ $manifest->{metadata}{namespace} //= $ns;
Condition33%1/3
$$manifest{"metadata"}{"namespace"} //= $ns
l!l&&r!l&&!r
010
MC/DC0%0/2
$$manifest{"metadata"}{"namespace"} //= $ns
$$manifest{"metadata"}{"namespace"} $ns
Truth table33%1/3
A //= B
A= $$manifest{"metadata"}{"namespace"}B= $ns
ABresult
1X1
011
000
644 }
645  
646 1 my $obj = eval { $self->api->new_object($resource, $manifest) };
647 1 ▶ return "Failed to build $resource object: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
648  
649 1 my $created = eval { $self->api->create($obj) };
650 1 ▶ return "Failed to create $resource: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
651  
652 1 ▶ my $created_name = eval { $created->metadata->name } // 'unknown';
Condition50%1/2
eval { // "unknown"
l!l
10
MC/DC0%0/1
eval { do { $created->metadata->name } } // "unknown"
eval { do { $created->metadata->name } }
Truth table50%1/2
A
A= eval { do { $created->metadata->name } }
Aresult
11
00
653 1 ▶ return $self->_to_json({
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
654 status => 'created',
655 kind => $resource,
656 name => $created_name,
657 ($ns ? (namespace => $ns) : ()),
658 });
659 },
660 46 ), 'Create a Kubernetes resource. Available: ', 'create'];
661  
662 # ---- Tool 5: k8s_patch ----
663 46 my $patch_desc = 'Patch (partial update) a Kubernetes resource.';
664 push @desc_map, [$self->tool(
665 name => 'k8s_patch',
666 description => $patch_desc,
667 input_schema => {
668 type => 'object',
669 properties => {
670 resource => {
671 type => 'string',
672 description => 'Resource type (e.g. Deployment, Service)',
673 },
674 name => {
675 type => 'string',
676 description => 'Resource name',
677 },
678 namespace => {
679 type => 'string',
680 description => 'Namespace',
681 },
682 patch => {
683 type => 'object',
684 description => 'Patch body (fields to change)',
685 },
686 patch_type => {
687 type => 'string',
688 description => 'Patch strategy: strategic (default, merge for status), merge, json',
689 enum => ['strategic', 'merge', 'json'],
690 },
691 subresource => {
692 type => 'string',
693 description => 'Write to a subresource instead of the main endpoint. '
694 . 'Use "status" for status fields: the API server strips status '
695 . 'from writes to the main endpoint and still answers 2xx.',
696 enum => ['status'],
697 },
698 },
699 required => ['resource', 'name', 'patch'],
700 },
701 7 ▶ code => sub {
Subroutine __ANON__: called CC=16 SCAR=28.1
702 7 my ($tool, $args) = @_;
703  
704 7 my $resource = $args->{resource};
705 7 my $name = $args->{name};
706 7 my $ns = $self->_resolve_namespace($args);
707 7 my $patch = $args->{patch};
708 7 my $subresource = $args->{subresource};
709 7 my $plural = $self->_resource_plural($resource);
710  
711 7 ▶ if (defined $subresource && $subresource ne 'status') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subresource and $subresource ne "status") 1 6 7
Condition100%3/3
defined $subresource and $subresource ne "status"
!ll&&!rl&&r
241
MC/DC100%2/2
defined $subresource and $subresource ne "status"
defined $subresource $subresource ne "status"
Truth table100%3/3
A and B
A= defined $subresourceB= $subresource ne "status"
ABresult
0X0
100
111
712 1 return "Unsupported subresource '$subresource': only 'status' is supported";
713 }
714 6 ▶ my $to_status = defined $subresource && $subresource eq 'status';
Condition66%2/3
defined $subresource && $subresource eq 'status'
!ll&&!rl&&r
204
MC/DC50%1/2
defined $subresource && $subresource eq 'status'
defined $subresource $subresource eq 'status'
Truth table66%2/3
A && B
A= defined $subresourceB= $subresource eq 'status'
ABresult
0X0
100
111
715  
716 # The status subresource is its own RBAC resource: patch on <plural>
717 # does not grant patch on <plural>/status. The plural cache cannot help
718 # here — _discover_resource_plurals skips names containing '/' — so the
719 # subresource is appended to the base plural.
720 6 ▶ my $rbac_resource = $to_status ? "$plural/status" : $plural;
Branch: 1 branch
BranchTrueFalseTotal
$to_status ? : 4 2 6
721  
722 6 ▶ unless ($self->permissions->can_do('patch', $rbac_resource, $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("patch", $rbac_resource, $ns // "")) 2 4 6
Condition50%1/2
$ns // ""
l!l
60
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
723 2 ▶ return "Permission denied: cannot patch "
Branch: 2 branches
BranchTrueFalseTotal
$to_status ? : 1 1 2
$ns ? : 2 0 2
724 . ($to_status ? "$resource status" : $resource)
725 . ($ns ? " in namespace $ns" : "");
726 }
727  
728 # Status writes default to a merge patch: custom resources answer 415 to
729 # a strategic merge patch. An explicit patch_type still wins.
730 my $patch_type = $args->{patch_type}
731 4 ▶ // ($to_status ? 'merge' : 'strategic');
Branch: 1 branch
BranchTrueFalseTotal
$to_status ? : 2 1 3
Condition66%2/3
$$args{"patch_type"} // ($to_status ? "merge" : "strategic")
l!l&&r!l&&!r
130
MC/DC0%0/2
$$args{"patch_type"} // ($to_status ? "merge" : "strategic")
$$args{"patch_type"} ($to_status ? "merge" : "strategic")
Truth table66%2/3
A // B
A= $$args{"patch_type"}B= ($to_status ? "merge" : "strategic")
ABresult
1X1
011
000
732  
733 4 my %api_args = (
734 patch => $patch,
735 type => $patch_type,
736 );
737 4 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 4 0 4
738  
739 # patch() writes the main endpoint, which silently drops a status stanza
740 # for every resource that has a status subresource.
741 4 ▶ my $method = $to_status ? 'patch_status' : 'patch';
Branch: 1 branch
BranchTrueFalseTotal
$to_status ? : 3 1 4
742 4 my $patched = eval { $self->api->$method($resource, $name, %api_args) };
743 4 ▶ return "Failed to patch $resource/$name: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
744  
745 4 ▶ return $self->_to_json({
Branch: 2 branches
BranchTrueFalseTotal
$to_status ? : 3 1 4
$ns ? : 4 0 4
746 status => 'patched',
747 kind => $resource,
748 name => $name,
749 ($to_status ? (subresource => 'status') : ()),
750 ($ns ? (namespace => $ns) : ()),
751 });
752 },
753 46 ), 'Patch (partial update) a Kubernetes resource. Available: ', 'patch'];
754  
755 # ---- Tool 6: k8s_delete ----
756 46 my $delete_desc = 'Delete a Kubernetes resource.';
757 push @desc_map, [$self->tool(
758 name => 'k8s_delete',
759 description => $delete_desc,
760 input_schema => {
761 type => 'object',
762 properties => {
763 resource => {
764 type => 'string',
765 description => 'Resource type (e.g. Pod, Deployment)',
766 },
767 name => {
768 type => 'string',
769 description => 'Resource name',
770 },
771 namespace => {
772 type => 'string',
773 description => 'Namespace',
774 },
775 },
776 required => ['resource', 'name'],
777 },
778 2 ▶ code => sub {
Subroutine __ANON__: called CC=7 SCAR=20.0
779 2 my ($tool, $args) = @_;
780  
781 2 my $resource = $args->{resource};
782 2 my $name = $args->{name};
783 2 my $ns = $self->_resolve_namespace($args);
784 2 my $plural = $self->_resource_plural($resource);
785  
786 2 ▶ unless ($self->permissions->can_do('delete', $plural, $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("delete", $plural, $ns // "")) 1 1 2
Condition50%1/2
$ns // ""
l!l
20
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
787 1 ▶ return "Permission denied: cannot delete $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
788 }
789  
790 1 my %api_args = (name => $name);
791 1 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 1 0 1
792  
793 1 eval { $self->api->delete($resource, %api_args) };
794 1 ▶ return "Failed to delete $resource/$name: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
795  
796 1 ▶ return $self->_to_json({
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
797 status => 'deleted',
798 kind => $resource,
799 name => $name,
800 ($ns ? (namespace => $ns) : ()),
801 });
802 },
803 46 ), 'Delete a Kubernetes resource. Available: ', 'delete'];
804  
805 # ---- Tool 7: k8s_logs ----
806 46 my $logs_desc = 'Get pod logs from Kubernetes pods.';
807 push @desc_map, [$self->tool(
808 name => 'k8s_logs',
809 description => $logs_desc,
810 input_schema => {
811 type => 'object',
812 properties => {
813 name => {
814 type => 'string',
815 description => 'Pod name',
816 },
817 namespace => {
818 type => 'string',
819 description => 'Namespace (auto-detected if only one available)',
820 },
821 container => {
822 type => 'string',
823 description => 'Container name (required for multi-container pods)',
824 },
825 tail_lines => {
826 type => 'integer',
827 description => 'Number of lines from end (default: 100)',
828 },
829 previous => {
830 type => 'boolean',
831 description => 'Get logs from previous container instance',
832 },
833 },
834 required => ['name'],
835 },
836 6 ▶ code => sub {
Subroutine __ANON__: called CC=11 SCAR=24.0
837 6 my ($tool, $args) = @_;
838  
839 6 my $name = $args->{name};
840 6 my $ns = $self->_resolve_namespace($args);
841 6 my $container = $args->{container};
842 6 ▶ my $tail_lines = $args->{tail_lines} // 100;
Condition100%2/2
$$args{"tail_lines"} // 100
l!l
15
MC/DC100%1/1
$$args{"tail_lines"} // 100
$$args{"tail_lines"}
Truth table100%2/2
A
A= $$args{"tail_lines"}
Aresult
11
00
843 6 ▶ my $previous = $args->{previous} // 0;
Condition100%2/2
$$args{"previous"} // 0
l!l
15
MC/DC100%1/1
$$args{"previous"} // 0
$$args{"previous"}
Truth table100%2/2
A
A= $$args{"previous"}
Aresult
11
00
844  
845 6 ▶ unless ($ns) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ns) 1 5 6
846 1 return "Namespace required for pod logs";
847 }
848  
849 5 ▶ unless ($self->permissions->can_read_logs($ns)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_read_logs($ns)) 1 4 5
850 1 return "Permission denied: cannot read pod logs in namespace $ns";
851 }
852  
853 # Kubernetes::REST's log() builds /api/v1/namespaces/$ns/pods/$name/log
854 # and the query parameters itself. It raises API errors (404, 403, ...)
855 # instead of handing back the response, so the status check lives in the
856 # eval now.
857 4 my %log_args = (name => $name, namespace => $ns);
858 4 ▶ $log_args{tailLines} = $tail_lines if $tail_lines;
Branch: 1 branch
BranchTrueFalseTotal
if $tail_lines 4 0 4
859 4 ▶ $log_args{container} = $container if $container;
Branch: 1 branch
BranchTrueFalseTotal
if $container 1 3 4
860 4 ▶ $log_args{previous} = 1 if $previous;
Branch: 1 branch
BranchTrueFalseTotal
if $previous 1 3 4
861  
862 4 my $content = eval { $self->api->log('Pod', %log_args) };
863 4 ▶ return "Failed to get logs for pod/$name: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 3 4
864  
865 3 ▶ return ($content // '') || "(no log output)";
Condition75%3/4
($content // '') || '(no log output)'
l!l
21
$content // ""
l!l
30
MC/DC0%0/1
($content // '') || '(no log output)'
$content
Truth table50%1/2
A
A= $content
Aresult
11
00
866 },
867 46 ), 'Get pod logs. Available in namespaces: ', '_logs'];
868  
869 # ---- Tool 8: k8s_events ----
870 46 my $events_desc = 'Get Kubernetes events for debugging.';
871 push @desc_map, [$self->tool(
872 name => 'k8s_events',
873 description => $events_desc,
874 input_schema => {
875 type => 'object',
876 properties => {
877 namespace => {
878 type => 'string',
879 description => 'Namespace (auto-detected if only one available)',
880 },
881 involved_object => {
882 type => 'string',
883 description => 'Filter events by involved object name (e.g. a pod name)',
884 },
885 field_selector => {
886 type => 'string',
887 description => 'Field selector filter (e.g. reason=BackOff)',
888 },
889 },
890 },
891 3 ▶ code => sub {
Subroutine __ANON__: called CC=11 SCAR=24.9
892 3 my ($tool, $args) = @_;
893  
894 3 my $ns = $self->_resolve_namespace($args);
895  
896 3 ▶ unless ($self->permissions->can_do('list', 'events', $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("list", "events", $ns // "")) 1 2 3
Condition50%1/2
$ns // ""
l!l
30
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
897 1 ▶ return "Permission denied: cannot list events" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
898 }
899  
900 2 my %api_args;
901 2 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 2 0 2
902  
903 2 my @selectors;
904 2 ▶ if (my $obj = $args->{involved_object}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $obj = $$args{"involved_object"}) 1 1 2
905 1 push @selectors, "involvedObject.name=$obj";
906 }
907 2 ▶ if (my $fs = $args->{field_selector}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fs = $$args{"field_selector"}) 0 2 2
908 0 push @selectors, $fs;
909 }
910 2 ▶ $api_args{fieldSelector} = join(',', @selectors) if @selectors;
Branch: 1 branch
BranchTrueFalseTotal
if @selectors 1 1 2
911  
912 2 my $list = eval { $self->api->list('Event', %api_args) };
913 2 ▶ return "Failed to list events: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
914  
915 2 ▶ my $items = $list->items // [];
Condition50%1/2
$list->items // []
l!l
20
MC/DC0%0/1
$list->items // []
$list->items
Truth table50%1/2
A
A= $list->items
Aresult
11
00
916 2 ▶ return "No events found" unless @$items;
Branch: 1 branch
BranchTrueFalseTotal
unless @$items 0 2 2
917  
918 2 my $summaries = $self->_format_list($items);
919 2 return $self->_to_json({
920 count => scalar @$items,
921 items => $summaries,
922 });
923 },
924 46 ), 'Get Kubernetes events for debugging. Available in: ', 'list'];
925  
926 # ---- Tool 9: k8s_rollout_restart ----
927 46 my $restart_desc = 'Trigger rolling restart of a Deployment, StatefulSet, or DaemonSet.';
928 push @desc_map, [$self->tool(
929 name => 'k8s_rollout_restart',
930 description => $restart_desc,
931 input_schema => {
932 type => 'object',
933 properties => {
934 resource => {
935 type => 'string',
936 description => 'Resource type: Deployment, StatefulSet, or DaemonSet',
937 enum => ['Deployment', 'StatefulSet', 'DaemonSet'],
938 },
939 name => {
940 type => 'string',
941 description => 'Resource name',
942 },
943 namespace => {
944 type => 'string',
945 description => 'Namespace',
946 },
947 },
948 required => ['resource', 'name'],
949 },
950 2 ▶ code => sub {
Subroutine __ANON__: called CC=7 SCAR=19.8
951 2 my ($tool, $args) = @_;
952  
953 2 my $resource = $args->{resource};
954 2 my $name = $args->{name};
955 2 my $ns = $self->_resolve_namespace($args);
956 2 my $plural = $self->_resource_plural($resource);
957  
958 2 ▶ unless ($self->permissions->can_do('patch', $plural, $ns // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->permissions->can_do("patch", $plural, $ns // "")) 1 1 2
Condition50%1/2
$ns // ""
l!l
20
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
959 1 ▶ return "Permission denied: cannot patch $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
960 }
961  
962 # Generate ISO 8601 timestamp without POSIX dependency
963 1 my @t = gmtime;
964 1 my $timestamp = sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',
965 $t[5] + 1900, $t[4] + 1, $t[3], $t[2], $t[1], $t[0]);
966  
967 1 my $patch = {
968 spec => {
969 template => {
970 metadata => {
971 annotations => {
972 'kubectl.kubernetes.io/restartedAt' => $timestamp,
973 },
974 },
975 },
976 },
977 };
978  
979 1 my %api_args = (
980 patch => $patch,
981 type => 'strategic',
982 );
983 1 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 1 0 1
984  
985 1 my $patched = eval { $self->api->patch($resource, $name, %api_args) };
986 1 ▶ return "Failed to restart $resource/$name: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
987  
988 1 ▶ return $self->_to_json({
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
989 status => 'restarting',
990 kind => $resource,
991 name => $name,
992 restartAt => $timestamp,
993 ($ns ? (namespace => $ns) : ()),
994 });
995 },
996 46 ), 'Trigger rolling restart of a Deployment, StatefulSet, or DaemonSet. Available: ', 'patch'];
997  
998 # ---- Tool 10: k8s_apply ----
999 46 my $apply_desc = 'Create or update a Kubernetes resource (like kubectl apply).';
1000 push @desc_map, [$self->tool(
1001 name => 'k8s_apply',
1002 description => $apply_desc,
1003 input_schema => {
1004 type => 'object',
1005 properties => {
1006 resource => {
1007 type => 'string',
1008 description => 'Resource type (e.g. Deployment, ConfigMap)',
1009 },
1010 namespace => {
1011 type => 'string',
1012 description => 'Namespace for the resource',
1013 },
1014 manifest => {
1015 type => 'object',
1016 description => 'Resource manifest (must include metadata.name)',
1017 },
1018 },
1019 required => ['resource', 'manifest'],
1020 },
1021 5 ▶ code => sub {
Subroutine __ANON__: called CC=22 SCAR=34.1
1022 5 my ($tool, $args) = @_;
1023  
1024 5 my $resource = $args->{resource};
1025 5 my $ns = $self->_resolve_namespace($args);
1026 5 my $manifest = $args->{manifest};
1027 5 my $plural = $self->_resource_plural($resource);
1028  
1029 5 ▶ my $can_create = $self->permissions->can_do('create', $plural, $ns // '');
Condition50%1/2
$ns // ""
l!l
50
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
1030 5 ▶ my $can_patch = $self->permissions->can_do('patch', $plural, $ns // '');
Condition50%1/2
$ns // ""
l!l
50
MC/DC0%0/1
$ns // ""
$ns
Truth table50%1/2
A
A= $ns
Aresult
11
00
1031  
1032 5 ▶ unless ($can_create || $can_patch) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($can_create or $can_patch) 1 4 5
Condition66%2/3
$can_create or $can_patch
l!l&&r!l&&!r
401
MC/DC50%1/2
$can_create or $can_patch
$can_create $can_patch
Truth table66%2/3
A or B
A= $can_createB= $can_patch
ABresult
1X1
011
000
1033 1 ▶ return "Permission denied: cannot create or patch $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
1034 }
1035  
1036 4 my $res_name = eval { $manifest->{metadata}{name} };
1037 4 ▶ return "manifest must include metadata.name" unless defined $res_name && length $res_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $res_name and length $res_name 1 3 4
Condition66%2/3
defined $res_name and length $res_name
!ll&&!rl&&r
103
MC/DC50%1/2
defined $res_name and length $res_name
defined $res_name length $res_name
Truth table66%2/3
A and B
A= defined $res_nameB= length $res_name
ABresult
0X0
100
111
1038  
1039 # Auto-populate namespace in metadata
1040 3 ▶ if (defined $ns) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ns) 3 0 3
1041 3 ▶ $manifest->{metadata} //= {};
Condition50%1/2
$$manifest{"metadata"} //= {}
l!l
30
MC/DC0%0/1
$$manifest{"metadata"} //= {}
$$manifest{"metadata"}
Truth table50%1/2
A
A= $$manifest{"metadata"}
Aresult
11
00
1042 3 ▶ $manifest->{metadata}{namespace} //= $ns;
Condition33%1/3
$$manifest{"metadata"}{"namespace"} //= $ns
l!l&&r!l&&!r
030
MC/DC0%0/2
$$manifest{"metadata"}{"namespace"} //= $ns
$$manifest{"metadata"}{"namespace"} $ns
Truth table33%1/3
A //= B
A= $$manifest{"metadata"}{"namespace"}B= $ns
ABresult
1X1
011
000
1043 }
1044  
1045 # Try create first
1046 3 ▶ if ($can_create) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_create) 3 0 3
1047 3 my $obj = eval { $self->api->new_object($resource, $manifest) };
1048 3 ▶ return "Failed to build $resource object: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
1049  
1050 3 my $created = eval { $self->api->create($obj) };
1051 3 ▶ if (!$@) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@) 1 2 3
1052 1 ▶ my $created_name = eval { $created->metadata->name } // $res_name;
Condition33%1/3
eval { // $res_name
l!l&&r!l&&!r
100
MC/DC0%0/2
eval { do { $created->metadata->name } } // $res_name
eval { do { $created->metadata->name } } $res_name
Truth table33%1/3
A // B
A= eval { do { $created->metadata->name } }B= $res_name
ABresult
1X1
011
000
1053 1 ▶ return $self->_to_json({
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
1054 status => 'created',
1055 kind => $resource,
1056 name => $created_name,
1057 ($ns ? (namespace => $ns) : ()),
1058 });
1059 }
1060  
1061 # If 409 Conflict / AlreadyExists, fall through to patch
1062 2 my $err = "$@";
1063 2 ▶ unless ($self->_is_conflict_error($err)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_is_conflict_error($err)) 1 1 2
1064 1 return "Failed to create $resource: $err";
1065 }
1066 }
1067  
1068 # Fall back to strategic merge patch
1069 1 ▶ unless ($can_patch) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($can_patch) 0 1 1
1070 0 ▶ return "Resource already exists and cannot patch $resource" . ($ns ? " in namespace $ns" : "");
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 0 0 0
1071 }
1072  
1073 1 my %api_args = (
1074 patch => $manifest,
1075 type => 'strategic',
1076 );
1077 1 ▶ $api_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 1 0 1
1078  
1079 1 my $patched = eval { $self->api->patch($resource, $res_name, %api_args) };
1080 1 ▶ return "Failed to update $resource/$res_name: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
1081  
1082 1 ▶ return $self->_to_json({
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 1 0 1
1083 status => 'updated',
1084 kind => $resource,
1085 name => $res_name,
1086 ($ns ? (namespace => $ns) : ()),
1087 });
1088 },
1089 46 ), 'Create or update a Kubernetes resource (like kubectl apply). Available: ', 'create'];
1090  
1091 46 $self->_tool_desc_map(\@desc_map);
1092 }
1093  
1094 0 ▶sub run_stdio {
Subroutine run_stdio: not called CC=2 SCAR=17.9
Pod documented
1095 0 my ($self) = @_;
1096  
1097  
1098 0 ▶ $self = $self->new unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 0 0
1099 # Not redundant with the _tools override: fails fast before to_stdio.
1100 0 $self->_update_tool_descriptions;
1101 0 $self->to_stdio;
1102 }
1103  
1104 10 1;
1105  
1106 __END__
1107  
1108 =pod
1109  
1110 =encoding UTF-8
1111  
1112 =head1 NAME
1113  
1114 MCP::K8s - MCP Server for Kubernetes with RBAC-aware dynamic tools
1115  
1116 =head1 VERSION
1117  
1118 version 0.003
1119  
1120 =head1 SYNOPSIS
1121  
1122 # Start the MCP server on stdio (for Claude Desktop, Claude Code, etc.)
1123 use MCP::K8s;
1124 MCP::K8s->run_stdio;
1125  
1126 # Or use the included script:
1127 $ mcp-k8s
1128  
1129 # Configure via environment variables:
1130 $ export MCP_K8S_CONTEXT="my-cluster"
1131 $ export MCP_K8S_NAMESPACES="default,production"
1132 $ mcp-k8s
1133  
1134 # Direct token authentication:
1135 $ export MCP_K8S_TOKEN="eyJhbGci..."
1136 $ export MCP_K8S_SERVER="https://my-cluster:6443"
1137 $ mcp-k8s
1138  
1139 # In-cluster: auto-detects when running as a Kubernetes pod
1140  
1141 # Programmatic usage with custom API:
1142 use MCP::K8s;
1143 my $k8s = MCP::K8s->new(
1144 api => $my_kubernetes_rest_instance,
1145 namespaces => ['default', 'staging'],
1146 );
1147 $k8s->to_stdio;
1148  
1149 # Embedded, with a kubeconfig outside the default location:
1150 my $k8s = MCP::K8s->new(
1151 kubeconfig_path => '/etc/myapp/clusters/prod/kubeconfig',
1152 context_name => 'prod',
1153 );
1154  
1155 =head1 DESCRIPTION
1156  
1157 MCP::K8s provides an MCP (Model Context Protocol) server that gives AI
1158 assistants like Claude access to Kubernetes clusters.
1159  
1160 The key innovation: B<the server dynamically discovers what the connected
1161 service account can do via RBAC> and only exposes those capabilities as
1162 MCP tools. A read-only service account gets read-only tools; a cluster-admin
1163 gets everything. Tool descriptions include the specific resources and
1164 namespaces available, so the LLM always knows exactly what it can do.
1165  
1166 =head2 How it works
1167  
1168 =over 4
1169  
1170 =item 1. B<Register> — Registers the MCP tools at construction; no cluster connection needed yet
1171  
1172 =item 2. B<Connect> — On the first request, authenticates via direct token, in-cluster service account, or kubeconfig
1173  
1174 =item 3. B<Discover> — Submits C<SelfSubjectRulesReview> requests to discover RBAC permissions per namespace, then rewrites the tool descriptions to reflect them
1175  
1176 =item 4. B<Serve> — Answers MCP requests over any transport (stdio, HTTP, embedded via L<Net::Async::MCP>), checking permissions on every tool call
1177  
1178 =back
1179  
1180 =head2 Why generic tools?
1181  
1182 Kubernetes has 50+ built-in resource types plus unlimited Custom Resources.
1183 Instead of creating hundreds of specific tools (C<list_pods>, C<get_deployment>,
1184 C<delete_configmap>...), MCP::K8s uses 10 generic tools with a C<resource>
1185 parameter — the same pattern as C<kubectl get>, C<kubectl delete>, etc.
1186 This keeps the tool count manageable for MCP clients while supporting
1187 every resource type including CRDs.
1188  
1189 Built on top of L<Kubernetes::REST> (API client), L<IO::K8s> (typed objects),
1190 and L<MCP::Server> (protocol implementation).
1191  
1192 =head2 context_name
1193  
1194 Optional. Kubeconfig context name to use. Read from C<$ENV{MCP_K8S_CONTEXT}>
1195 by default. If not set, the kubeconfig's C<current-context> is used.
1196  
1197 =head2 kubeconfig_path
1198  
1199 Optional. Path to the kubeconfig file used by the kubeconfig auth tier,
1200 passed through to L<Kubernetes::REST::Kubeconfig/kubeconfig_path>. For an
1201 embedder that keeps its kubeconfigs outside the default location: with a
1202 same-named context in C<~/.kube/config>, only the explicit path tells the
1203 two apart. Accepts whatever Kubeconfig accepts there — a single path, a
1204 C<KUBECONFIG>-style path list, or an arrayref. Not read from the
1205 environment; if not set, Kubeconfig does its own lookup
1206 (C<$ENV{KUBECONFIG}>, then C<~/.kube/config>). Has no effect when
1207 L</token> or the in-cluster service account engages an earlier tier.
1208  
1209 =head2 token
1210  
1211 Optional. Bearer token for direct authentication. Read from
1212 C<$ENV{MCP_K8S_TOKEN}> by default. When set, bypasses kubeconfig
1213 entirely and connects using this token directly.
1214  
1215 =head2 server_endpoint
1216  
1217 Optional. Kubernetes API server URL. Read from C<$ENV{MCP_K8S_SERVER}>
1218 by default. Used with L</token> for direct authentication, or with
1219 in-cluster auth. Defaults to C<https://kubernetes.default.svc.cluster.local>
1220 when running in-cluster.
1221  
1222 =head2 namespaces
1223  
1224 ArrayRef of namespace names to operate on. Configured via:
1225  
1226 =over 4
1227  
1228 =item * C<$ENV{MCP_K8S_NAMESPACES}> — comma-separated list (e.g. C<"default,production">)
1229  
1230 =item * Auto-discovery — lists all namespaces from the cluster
1231  
1232 =item * In-cluster fallback — the service account's mounted namespace, if listing fails
1233  
1234 =item * Fallback — C<['default']> if discovery fails outside a cluster
1235  
1236 =back
1237  
1238 =head2 api
1239  
1240 L<Kubernetes::REST> instance for cluster communication. Built automatically
1241 from kubeconfig using L<Kubernetes::REST::Kubeconfig>. Can be provided
1242 directly for testing or custom configurations.
1243  
1244 =head2 permissions
1245  
1246 L<MCP::K8s::Permissions> instance holding the discovered RBAC permissions.
1247 Built and populated automatically on first access via C<SelfSubjectRulesReview>.
1248  
1249 =head2 json
1250  
1251 L<JSON::MaybeXS> encoder instance. Configured with C<utf8>, C<pretty>,
1252 C<canonical>, and C<convert_blessed> for consistent, readable output.
1253  
1254 =head2 server
1255  
1256 Returns C<$self> for backward compatibility. Since MCP::K8s now inherits
1257 from L<MCP::Server>, the object itself is the server.
1258  
1259 =head2 _resource_plural
1260  
1261 my $plural = $self->_resource_plural('Pod'); # => 'pods'
1262 my $plural = $self->_resource_plural('Ingress'); # => 'ingresses'
1263  
1264 Convert a Kubernetes Kind name (e.g. C<Pod>, C<Deployment>) to its plural
1265 form used in RBAC rules (e.g. C<pods>, C<deployments>). Uses a 4-tier
1266 lookup:
1267  
1268 =over 4
1269  
1270 =item 1. Static C<%RESOURCE_PLURALS> map (fast, zero-cost)
1271  
1272 =item 2. C<resource_plural()> on the L<IO::K8s> class the Kind resolves to
1273 via the client's C<expand_class>
1274  
1275 =item 3. API server discovery cache (lazy, one-time query)
1276  
1277 =item 4. Heuristic fallback (lowercase + simple pluralization)
1278  
1279 =back
1280  
1281 Tier 2 answers every built-in Kind: L<IO::K8s> carries the upstream plurals
1282 on its classes, and L<Kubernetes::REST>'s C<expand_class> resolves a name its
1283 built-in map knows without a request, even when C<resource_map_from_cluster>
1284 is set. It also answers for a CRD provider's class registered with the
1285 client, which brings its own C<resource_plural()>.
1286  
1287 For a Kind nothing ships, C<expand_class> consults the client's aggregated
1288 discovery (C<GET /api>, C<GET /apis>) — the same resolution the tool's own
1289 API call does right after, so this tier moves that cost rather than adding
1290 it. Such a Kind resolves to L<IO::K8s::Unstructured> or to a class name that
1291 does not load; neither has C<resource_plural()>, so the lookup falls through.
1292  
1293 Tier 3 is therefore the source for CRDs without a class: it asks C</api/v1>
1294 and C</apis> and gets back the plurals the API server itself uses.
1295  
1296 =head2 _discover_resource_plurals
1297  
1298 $self->_discover_resource_plurals;
1299  
1300 Query the API server's discovery endpoints (C</api/v1> and C</apis>) to
1301 build a Kind-to-plural mapping. Results are cached in
1302 C<_resource_plurals_cache>. Failures are silently ignored — the cache
1303 simply remains empty and callers fall through to heuristic pluralization.
1304  
1305 =head2 _resolve_namespace
1306  
1307 my $ns = $self->_resolve_namespace($args);
1308  
1309 Resolve the namespace for a tool call. If C<< $args->{namespace} >> is
1310 provided, uses that. Otherwise, if only one namespace is accessible,
1311 auto-fills it. Returns C<undef> if the namespace cannot be determined
1312 (the tool should handle this case).
1313  
1314 =head2 _is_conflict_error
1315  
1316 if ($self->_is_conflict_error("$@")) { ... }
1317  
1318 Decide whether a failed C<create> failed because the resource already
1319 exists (HTTP 409 / C<AlreadyExists>), which is the signal for
1320 L</k8s_apply> to fall back to a patch.
1321  
1322 This is a string match, deliberately. L<Kubernetes::REST> 1.108 does not
1323 raise a typed exception for API errors: C<create> runs the response
1324 through C<_check_response>, which C<croak>s with
1325  
1326 Kubernetes API error (create <class>): <status> <body>
1327  
1328 C<Kubernetes::REST::Error> and C<Kubernetes::REST::RemoteError> still
1329 exist, but only as compatibility helpers for the deprecated v0 API — no
1330 code path in 1.108 throws them, so there is no C<< ->code >> to check.
1331 The match stays wide (status code B<or> C<reason>) so that it survives a
1332 reworded error as long as either token is still in it; narrowing it to
1333 the exact croak format above would trade one fragility for a worse one.
1334  
1335 Revisit when the client grows typed errors.
1336  
1337 =head2 _format_resource_summary
1338  
1339 my $summary = $self->_format_resource_summary($io_k8s_object);
1340  
1341 Extract a concise summary hashref from an L<IO::K8s> object, suitable for
1342 LLM consumption. Includes metadata (name, namespace, labels, creation time),
1343 kind, status fields (phase, replicas, conditions), and key spec fields
1344 (containers, ports, type).
1345  
1346 The summary is intentionally compact — for full details, the C<k8s_get>
1347 tool with C<output =E<gt> 'json'> should be used.
1348  
1349 =head2 _format_list
1350  
1351 my $summaries = $self->_format_list($list->items);
1352  
1353 Format an arrayref of L<IO::K8s> objects into an arrayref of summary
1354 hashrefs using L</_format_resource_summary>.
1355  
1356 =head2 _tools
1357  
1358 Override of L<MCP::Server/_tools>. Enriches the tool descriptions with the
1359 discovered RBAC permissions before handing the list to the caller, then
1360 defers to the parent implementation.
1361  
1362 C<_tools> is the single funnel every transport passes through for
1363 C<tools/list> (and C<tools/call>), so this is the one place that covers
1364 stdio, the inherited HTTP transport, and an embedded server driven through
1365 L<Net::Async::MCP> alike. Hooking anywhere else — as C<run_stdio> alone
1366 used to — leaves every other path serving the static descriptions, and the
1367 descriptions are what tell the LLM which resources exist per namespace.
1368  
1369 Discovery stays lazy: the first C<< ->api >> access happens here, on the first
1370 request, not in C<BUILD>. C<_update_tool_descriptions> is idempotent via
1371 its own guard, so the per-request cost after the first one is a boolean.
1372  
1373 =head1 MCP TOOLS
1374  
1375 All tools are registered on the L</server> during construction. Each tool
1376 checks RBAC permissions before executing and returns clear error messages
1377 on denial. Tool descriptions dynamically include which resources and
1378 namespaces are available.
1379  
1380 =head2 k8s_permissions
1381  
1382 Show what the current Kubernetes service account is allowed to do. Returns
1383 a Markdown-formatted RBAC summary. B<The LLM should call this first> to
1384 understand its capabilities.
1385  
1386 No parameters required.
1387  
1388 =head2 k8s_list
1389  
1390 List Kubernetes resources with optional filtering.
1391  
1392 B<Parameters:>
1393  
1394 =over 4
1395  
1396 =item C<resource> (string, B<required>) — Resource type: C<Pod>, C<Deployment>, C<Service>, C<ConfigMap>, etc.
1397  
1398 =item C<namespace> (string) — Target namespace. Auto-detected if only one is accessible.
1399  
1400 =item C<label_selector> (string) — Label filter, e.g. C<app=web,env=prod>
1401  
1402 =item C<field_selector> (string) — Field filter, e.g. C<status.phase=Running>
1403  
1404 =back
1405  
1406 Returns JSON with C<count> and C<items> (array of resource summaries).
1407  
1408 =head2 k8s_get
1409  
1410 Get a single Kubernetes resource by name.
1411  
1412 B<Parameters:>
1413  
1414 =over 4
1415  
1416 =item C<resource> (string, B<required>) — Resource type
1417  
1418 =item C<name> (string, B<required>) — Resource name
1419  
1420 =item C<namespace> (string) — Target namespace
1421  
1422 =item C<output> (string) — Format: C<summary> (default), C<json>, or C<yaml>
1423  
1424 =back
1425  
1426 =head2 k8s_create
1427  
1428 Create a Kubernetes resource from a manifest. The C<apiVersion> and C<kind>
1429 fields are auto-populated from the resource type via L<IO::K8s>.
1430  
1431 B<Parameters:>
1432  
1433 =over 4
1434  
1435 =item C<resource> (string, B<required>) — Resource type
1436  
1437 =item C<manifest> (object, B<required>) — Resource manifest (metadata, spec, etc.)
1438  
1439 =item C<namespace> (string) — Target namespace (also auto-populated in metadata)
1440  
1441 =back
1442  
1443 Returns JSON confirmation with the created resource name.
1444  
1445 =head2 k8s_patch
1446  
1447 Partially update a Kubernetes resource.
1448  
1449 B<Parameters:>
1450  
1451 =over 4
1452  
1453 =item C<resource> (string, B<required>) — Resource type
1454  
1455 =item C<name> (string, B<required>) — Resource name
1456  
1457 =item C<patch> (object, B<required>) — Fields to change
1458  
1459 =item C<namespace> (string) — Target namespace
1460  
1461 =item C<patch_type> (string) — Strategy: C<strategic> (default; C<merge> with C<subresource>), C<merge>, or C<json>
1462  
1463 =item C<subresource> (string) — C<status> to write the status subresource
1464  
1465 =back
1466  
1467 See L<Kubernetes::REST/patch> for details on patch strategies.
1468  
1469 B<Status writes need C<< subresource => 'status' >>.> Once a resource has a
1470 status subresource — every CRD declaring one, plus the built-ins that always
1471 had one — the API server strips C<status> from any write to the main endpoint
1472 and still answers 2xx. Without this parameter the patch reports success and
1473 stores nothing. With it, the call goes to L<Kubernetes::REST/patch_status>,
1474 which addresses C</status>, and the patch type defaults to C<merge> rather
1475 than C<strategic>, because custom resources answer a strategic merge patch
1476 with 415. An explicit C<patch_type> still wins.
1477  
1478 The status subresource is a separate resource in RBAC as well: this path
1479 requires C<patch> on C<< <plural>/status >>, not on C<< <plural> >>.
1480  
1481 =head2 k8s_delete
1482  
1483 Delete a Kubernetes resource by name.
1484  
1485 B<Parameters:>
1486  
1487 =over 4
1488  
1489 =item C<resource> (string, B<required>) — Resource type
1490  
1491 =item C<name> (string, B<required>) — Resource name
1492  
1493 =item C<namespace> (string) — Target namespace
1494  
1495 =back
1496  
1497 =head2 k8s_logs
1498  
1499 Get container logs from a pod. Essential for debugging. Reads the pod's
1500 C<log> subresource through L<Kubernetes::REST>'s C<log()>.
1501  
1502 B<Parameters:>
1503  
1504 =over 4
1505  
1506 =item C<name> (string, B<required>) — Pod name
1507  
1508 =item C<namespace> (string) — Target namespace (B<required> for logs)
1509  
1510 =item C<container> (string) — Container name (required for multi-container pods)
1511  
1512 =item C<tail_lines> (integer) — Number of lines from end (default: 100)
1513  
1514 =item C<previous> (boolean) — Get logs from previous container instance
1515  
1516 =back
1517  
1518 =head2 k8s_events
1519  
1520 Get Kubernetes events for debugging. Supports filtering by involved object
1521 name and arbitrary field selectors.
1522  
1523 B<Parameters:>
1524  
1525 =over 4
1526  
1527 =item C<namespace> (string) — Target namespace
1528  
1529 =item C<involved_object> (string) — Filter events by object name (e.g. pod name)
1530  
1531 =item C<field_selector> (string) — Field selector filter (e.g. C<reason=BackOff>)
1532  
1533 =back
1534  
1535 Returns JSON with C<count> and C<items> (array of event summaries).
1536  
1537 =head2 k8s_rollout_restart
1538  
1539 Trigger a rolling restart of a Deployment, StatefulSet, or DaemonSet.
1540 Works by patching the pod template annotation C<kubectl.kubernetes.io/restartedAt>
1541 with the current timestamp — the same mechanism as C<kubectl rollout restart>.
1542  
1543 B<Parameters:>
1544  
1545 =over 4
1546  
1547 =item C<resource> (string, B<required>) — One of C<Deployment>, C<StatefulSet>, C<DaemonSet>
1548  
1549 =item C<name> (string, B<required>) — Resource name
1550  
1551 =item C<namespace> (string) — Target namespace
1552  
1553 =back
1554  
1555 =head2 k8s_apply
1556  
1557 Create or update a Kubernetes resource (like C<kubectl apply>). Tries to
1558 create the resource first; if it already exists (409 Conflict), falls back
1559 to a strategic merge patch.
1560  
1561 B<Parameters:>
1562  
1563 =over 4
1564  
1565 =item C<resource> (string, B<required>) — Resource type (e.g. C<Deployment>, C<ConfigMap>)
1566  
1567 =item C<manifest> (object, B<required>) — Resource manifest. Must include C<metadata.name>.
1568  
1569 =item C<namespace> (string) — Target namespace
1570  
1571 =back
1572  
1573 Returns JSON confirmation with the action taken (C<created> or C<updated>).
1574  
1575 =head2 run_stdio
1576  
1577 # As class method:
1578 MCP::K8s->run_stdio;
1579  
1580 # As instance method:
1581 my $k8s = MCP::K8s->new(%opts);
1582 $k8s->run_stdio;
1583  
1584 Start the MCP server on stdio. If called as a class method, creates a
1585 new instance first. This is the main entry point used by the C<mcp-k8s>
1586 script.
1587  
1588 Discovery is run here, before the transport starts. L</_tools> would do it
1589 on the first C<tools/list> anyway, so this is not what makes the
1590 descriptions correct — it is what makes an unreachable cluster fail at
1591 process start, on stderr, instead of turning into a JSON-RPC internal error
1592 once a client is already attached.
1593  
1594 =head1 ENVIRONMENT
1595  
1596 =over 4
1597  
1598 =item C<KUBECONFIG>
1599  
1600 Path to kubeconfig file. Default: C<~/.kube/config>.
1601 Standard Kubernetes environment variable, also used by C<kubectl>.
1602  
1603 =item C<MCP_K8S_CONTEXT>
1604  
1605 Kubeconfig context to use. Default: the kubeconfig's C<current-context>.
1606  
1607 =item C<MCP_K8S_TOKEN>
1608  
1609 Bearer token for direct authentication. Bypasses kubeconfig entirely.
1610 Useful for CI/CD pipelines or when you have a service account token.
1611  
1612 =item C<MCP_K8S_SERVER>
1613  
1614 Kubernetes API server URL. Used with C<MCP_K8S_TOKEN> or in-cluster auth.
1615 Default when in-cluster: C<https://kubernetes.default.svc.cluster.local>.
1616  
1617 =item C<MCP_K8S_NAMESPACES>
1618  
1619 Comma-separated list of namespaces to operate on.
1620 Default: auto-discovered from the cluster (lists all namespaces the
1621 service account can see). Falls back to C<default> if discovery fails.
1622  
1623 =back
1624  
1625 =head1 AUTHENTICATION
1626  
1627 MCP::K8s supports three authentication methods, tried in order:
1628  
1629 =over 4
1630  
1631 =item 1. B<Direct token> — Set C<MCP_K8S_TOKEN> (and optionally C<MCP_K8S_SERVER>)
1632  
1633 =item 2. B<In-cluster> — Auto-detected when running as a Kubernetes pod (reads mounted service account token from C</var/run/secrets/kubernetes.io/serviceaccount/token>)
1634  
1635 =item 3. B<Kubeconfig> — Reads C<~/.kube/config> (or C<$KUBECONFIG>), optionally filtered by C<MCP_K8S_CONTEXT>. An embedder names a specific file with the L</kubeconfig_path> constructor argument.
1636  
1637 =back
1638  
1639 For in-cluster and direct token auth, the CA certificate at
1640 C</var/run/secrets/kubernetes.io/serviceaccount/ca.crt> is automatically
1641 used if present.
1642  
1643 =head1 RBAC SETUP
1644  
1645 Use a dedicated ServiceAccount with minimal permissions for AI access.
1646 Example RBAC manifests are included in the C<examples/> directory:
1647  
1648 =over 4
1649  
1650 =item C<examples/readonly-serviceaccount.yaml> — Read-only access (recommended starting point)
1651  
1652 =item C<examples/deployer-serviceaccount.yaml> — Read + deploy/restart capabilities
1653  
1654 =item C<examples/full-ops-serviceaccount.yaml> — Full access except secrets
1655  
1656 =back
1657  
1658 RBAC is the single source of truth — if the service account shouldn't have
1659 access, don't grant it via RBAC. MCP::K8s does B<not> implement
1660 application-layer permission filtering.
1661  
1662 =head1 CLAUDE DESKTOP INTEGRATION
1663  
1664 Add this to your Claude Desktop MCP configuration
1665 (C<~/.config/claude/claude_desktop_config.json>):
1666  
1667 {
1668 "mcpServers": {
1669 "kubernetes": {
1670 "command": "mcp-k8s",
1671 "env": {
1672 "MCP_K8S_CONTEXT": "my-cluster",
1673 "MCP_K8S_NAMESPACES": "default,production"
1674 }
1675 }
1676 }
1677 }
1678  
1679 =head1 CLAUDE CODE INTEGRATION
1680  
1681 Add to your project's C<.mcp.json> or global MCP settings:
1682  
1683 {
1684 "mcpServers": {
1685 "kubernetes": {
1686 "command": "mcp-k8s",
1687 "env": {
1688 "MCP_K8S_CONTEXT": "dev-cluster"
1689 }
1690 }
1691 }
1692 }
1693  
1694 =head1 LANGERTHA RAIDER INTEGRATION
1695  
1696 Use L<Langertha::Raider> to build an autonomous AI agent that can
1697 interact with your Kubernetes cluster using MCP::K8s as its tool source:
1698  
1699 use IO::Async::Loop;
1700 use Future::AsyncAwait;
1701 use Net::Async::MCP;
1702 use Langertha::Engine::Anthropic;
1703 use Langertha::Raider;
1704 use MCP::K8s;
1705  
1706 my $k8s = MCP::K8s->new(
1707 namespaces => ['default', 'production'],
1708 );
1709  
1710 my $loop = IO::Async::Loop->new;
1711 my $mcp = Net::Async::MCP->new(server => $k8s->server);
1712 $loop->add($mcp);
1713  
1714 async sub main {
1715 await $mcp->initialize;
1716  
1717 my $engine = Langertha::Engine::Anthropic->new(
1718 api_key => $ENV{ANTHROPIC_API_KEY},
1719 model => 'claude-sonnet-4-6',
1720 mcp_servers => [$mcp],
1721 );
1722  
1723 my $raider = Langertha::Raider->new(
1724 engine => $engine,
1725 mission => 'You are a Kubernetes operations assistant. '
1726 . 'Always check permissions first, then help the user '
1727 . 'investigate and manage their cluster.',
1728 );
1729  
1730 # First raid: discover capabilities
1731 my $r1 = await $raider->raid_f('What can I do on this cluster?');
1732 say $r1;
1733  
1734 # Second raid: uses history from the first
1735 my $r2 = await $raider->raid_f('List all pods and check for any issues.');
1736 say $r2;
1737 }
1738  
1739 main()->get;
1740  
1741 The Raider maintains conversation history across raids, so the LLM
1742 can reference earlier context (e.g. the RBAC permissions it discovered)
1743 in follow-up interactions.
1744  
1745 A ready-to-run demo is included in C<examples/raider-configmap-demo.pl> — an AI
1746 creates, reads, updates, and deletes a ConfigMap. See the script's POD
1747 for requirements.
1748  
1749 =head1 SECURITY CONSIDERATIONS
1750  
1751 =over 4
1752  
1753 =item * The server inherits the permissions of whatever kubeconfig context
1754 it connects with. Use a dedicated service account with minimal RBAC
1755 permissions for AI assistant access.
1756  
1757 =item * All tool calls check RBAC permissions B<before> executing. Even if
1758 the service account has broad permissions, the permission check provides
1759 a clear audit trail.
1760  
1761 =item * Secrets are supported as a resource type. If your service account
1762 can read secrets, the LLM will be able to read them too. Consider excluding
1763 C<secrets> from RBAC roles used for AI access.
1764  
1765 =back
1766  
1767 =head1 SEE ALSO
1768  
1769 L<MCP::K8s::Permissions> — RBAC discovery engine
1770  
1771 L<MCP::Kubernetes> — Alias for this module
1772  
1773 L<Langertha::Raider> — Autonomous agent with conversation history and MCP tools
1774  
1775 L<Kubernetes::REST> — The underlying Kubernetes API client
1776  
1777 L<IO::K8s> — Typed Kubernetes resource objects
1778  
1779 L<MCP::Server> — MCP protocol implementation
1780  
1781 L<Kubernetes::REST::Kubeconfig> — Kubeconfig parsing
1782  
1783 L<https://modelcontextprotocol.io/> — Model Context Protocol specification
1784  
1785 L<https://kubernetes.io/docs/reference/access-authn-authz/rbac/> — Kubernetes RBAC
1786  
1787 =head1 SUPPORT
1788  
1789 =head2 Issues
1790  
1791 Please report bugs and feature requests on GitHub at
1792 L<https://github.com/Getty/p5-mcp-k8s/issues>.
1793  
1794 =head1 CONTRIBUTING
1795  
1796 Contributions are welcome! Please fork the repository and submit a pull request.
1797  
1798 =head1 AUTHOR
1799  
1800 Torsten Raudssus <torsten@raudssus.de>
1801  
1802 =head1 COPYRIGHT AND LICENSE
1803  
1804 This software is copyright (c) 2026 by Torsten Raudssus.
1805  
1806 This is free software; you can redistribute it and/or modify it under
1807 the same terms as the Perl 5 programming language system itself.
1808  
1809 =cut
↑ Summary K8s/Permissions.pm »