K8s.pm

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