blib/lib/App/MCP/CLI/Client.pm

filter: Statementstmt 89.8% 309 / 344 Branchbran 62.6% 134 / 214 Conditioncond 49.0% 49 / 100 MC/DCmcdc 18.1% 10 / 55 Subroutinesub 100% 40 / 40 Podpod 100% 10 / 10 totaltotal 72.3% 552 / 763 CC 151 SCAR 30.0
CC
151
Cov
75%
content_text
99.0
_read_some
23.3
_connect_sse
16.1
CRAP 20.0
« blib/lib/App/MCP/CLI/Config.pm ↑ Summary blib/lib/App/MCP/CLI/Command/servers.pm »
1 package App::MCP::CLI::Client;
2  
3 31 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 31 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 31 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 31 our $VERSION = qv('v0.0.1');
8 31 our $AUTHORITY = 'cpan:MANWAR';
9  
10 31 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 31 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 31 ▶use IPC::Open2;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 31 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 31 ▶use POSIX qw(WNOHANG);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 31 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 31 ▶use Time::HiRes qw(time sleep);
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 31 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
19 31 our @EXPORT_OK = qw(content_text);
20  
21 31 ▶use constant PROTOCOL_VERSION => '2024-11-05';
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 =encoding utf8
24  
25 =head1 NAME
26  
27 App::MCP::CLI::Client - Transport-neutral MCP client used by all mcpcli sub-commands
28  
29 =head1 VERSION
30  
31 This module is distributed as part of L<App::MCP::CLI> v0.0.1.
32  
33 =head1 SYNOPSIS
34  
35 use App::MCP::CLI::Client;
36 use App::MCP::CLI::Config qw(load_config resolve_server_cmd);
37  
38 my ($cmd, $url, $env) = resolve_server_cmd(load_config(), 'my-server');
39  
40 my $client = App::MCP::CLI::Client->new(
41 cmd => $cmd, # stdio transport, or
42 url => $url, # HTTP/SSE transport
43 env => $env,
44 timeout => 30,
45 );
46  
47 $client->connect; # initialize + notifications/initialized
48 my $tools = $client->list_tools; # arrayref of tool descriptors
49 my $res = $client->call_tool('add_numbers', { a => 1, b => 2 });
50 print content_text($res->{result}) if $res->{result};
51 $client->close;
52  
53 =head1 DESCRIPTION
54  
55 C<App::MCP::CLI::Client> hides the differences between the two transports
56 supported by C<mcpcli> behind one small API, so every sub-command gets the
57 same behaviour:
58  
59 =over 4
60  
61 =item * Every wait for the server is bounded by a timeout (default 30 seconds).
62  
63 =item * If a stdio server exits unexpectedly, or an SSE stream is closed, a
64 clear error is raised instead of a JSON parse failure.
65  
66 =item * Responses are matched to requests by C<id>. Notifications and log
67 lines sent by the server in between are skipped, and server-initiated
68 C<ping> requests are answered.
69  
70 =item * The C<initialize> request is followed by the
71 C<notifications/initialized> notification, as required by the
72 C<2024-11-05> lifecycle.
73  
74 =back
75  
76 B<stdio>: the server is started with L<IPC::Open2>; messages are
77 newline-delimited JSON.
78  
79 B<HTTP/SSE> (protocol revision C<2024-11-05>): a long-lived C<GET> opens the
80 event stream, the C<endpoint> event announces where to C<POST>, and each
81 response is accepted either in the C<POST> reply body or as a C<message>
82 event on the stream. C<https://> URLs need L<IO::Socket::SSL>.
83  
84 All errors are raised with C<die> and a message ending in a newline.
85  
86 =head1 METHODS
87  
88 =head2 new( %args )
89  
90 Arguments: C<cmd> (arrayref) or C<url> (string); optional C<env> (hashref
91 applied only to the spawned process), C<timeout> (seconds, C<0> disables),
92 C<headers> (hashref, SSE only) and C<client_name>.
93  
94 Set the environment variable C<MCPCLI_DEBUG> to see every JSON-RPC message on
95 STDERR.
96  
97 =cut
98  
99 30 ▶sub new {
Subroutine new: called CC=7 SCAR=19.9
Pod documented
100 30 my ($class, %a) = @_;
101  
102 die "Client needs either a command or a URL.\n"
103 30 ▶ unless $a{cmd} || defined $a{url};
Branch: 1 branch
BranchTrueFalseTotal
unless $a{"cmd"} or defined $a{"url"} 0 30 30
Condition66%2/3
$a{"cmd"} or defined $a{"url"}
l!l&&r!l&&!r
2550
MC/DC0%0/2
$a{"cmd"} or defined $a{"url"}
$a{"cmd"} defined $a{"url"}
Truth table66%2/3
A or B
A= $a{"cmd"}B= defined $a{"url"}
ABresult
1X1
011
000
104  
105 return bless {
106 cmd => $a{cmd},
107 url => $a{url},
108 env => $a{env} || {},
109 headers => $a{headers} || {},
110 timeout => defined $a{timeout} ? $a{timeout} : 30,
111 30 ▶ name => $a{client_name} // 'mcpcli',
Branch: 1 branch
BranchTrueFalseTotal
defined $a{'timeout'} ? : 29 1 30
Condition83%5/6
$a{'env'} || {}
l!l
237
$a{'headers'} || {}
l!l
030
$a{"client_name"} // "mcpcli"
l!l
822
MC/DC100%1/1
$a{'env'} || {}
$a{'env'}
MC/DC0%0/1
$a{'headers'} || {}
$a{'headers'}
MC/DC100%1/1
$a{"client_name"} // "mcpcli"
$a{"client_name"}
Truth table100%2/2
A
A= $a{'env'}
Aresult
11
00
Truth table50%1/2
A
A= $a{'headers'}
Aresult
11
00
Truth table100%2/2
A
A= $a{"client_name"}
Aresult
11
00
112 next_id => 1,
113 buf => '',
114 json => JSON::MaybeXS->new(utf8 => 1, allow_nonref => 1),
115 }, $class;
116 }
117  
118 =head2 is_sse
119  
120 True when the client talks HTTP/SSE.
121  
122 =cut
123  
124 327 ▶sub is_sse { defined $_[0]{url} }
Subroutine is_sse: called CC=1 SCAR=0.0
Pod documented
125  
126 =head2 server_info
127  
128 The C<serverInfo> hashref reported by the server (after L</connect>).
129  
130 =cut
131  
132 2 ▶sub server_info { $_[0]{server_info} || {} }
Subroutine server_info: called CC=2 SCAR=7.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{"server_info"} or {} 2 0 2
133  
134 98 ▶sub _deadline {
Subroutine _deadline: called CC=2 SCAR=7.2
135 98 my ($self) = @_;
136 98 ▶ return time + ($self->{timeout} > 0 ? $self->{timeout} : 1e9);
Branch: 1 branch
BranchTrueFalseTotal
$self->{'timeout'} > 0 ? : 98 0 98
137 }
138  
139 364 ▶sub _debug {
Subroutine _debug: called CC=2 SCAR=8.1
140 364 my ($self, $dir, $data) = @_;
141 364 ▶ return unless $ENV{MCPCLI_DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
unless $ENV{"MCPCLI_DEBUG"} 364 0 364
142 0 print STDERR "[mcpcli $dir] $data\n";
143 }
144  
145 =head2 connect
146  
147 Starts the transport and performs the MCP handshake. Returns the client.
148  
149 =cut
150  
151 30 ▶sub connect {
Subroutine connect: called CC=5 SCAR=16.4
Pod documented
152 30 my ($self) = @_;
153  
154 30 ▶ $self->is_sse ? $self->_connect_sse : $self->_connect_stdio;
Branch: 1 branch
BranchTrueFalseTotal
$self->is_sse ? : 5 25 30
155  
156 28 my $res = eval { $self->request('initialize', {
157 protocolVersion => PROTOCOL_VERSION,
158 capabilities => {},
159 28 clientInfo => { name => $self->{name}, version => "$VERSION" },
160 }) };
161 28 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 2 26 28
162 2 $self->close;
163 2 die $err;
164 }
165 26 ▶ if ($res->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error"}) 0 26 26
166 0 $self->close;
167 0 die "Server rejected initialize: $res->{error}{message}\n";
168 }
169  
170 26 ▶ $self->{server_info} = $res->{result}{serverInfo} || {};
Condition50%1/2
$res->{'result'}{'serverInfo'} || {}
l!l
260
MC/DC0%0/1
$res->{'result'}{'serverInfo'} || {}
$res->{'result'}{'serverInfo'}
Truth table50%1/2
A
A= $res->{'result'}{'serverInfo'}
Aresult
11
00
171 26 $self->notify('notifications/initialized');
172  
173 26 return $self;
174 }
175  
176 =head2 request( $method [, $params] )
177  
178 Sends a JSON-RPC request and returns the full response hashref (which has
179 either a C<result> or an C<error> key). Dies on timeout or transport failure.
180  
181 =cut
182  
183 93 ▶sub request {
Subroutine request: called CC=10 SCAR=23.7
Pod documented
184 93 my ($self, $method, $params) = @_;
185  
186 93 my $id = $self->{next_id}++;
187 93 my $msg = { jsonrpc => '2.0', id => $id, method => $method };
188 93 ▶ $msg->{params} = $params if defined $params;
Branch: 1 branch
BranchTrueFalseTotal
if defined $params 70 23 93
189  
190 93 my $deadline = $self->_deadline;
191 93 my $inline = $self->_send($msg);
192  
193 return $inline
194 if ref $inline eq 'HASH' && defined $inline->{id} && "$inline->{id}" eq "$id"
195 93 ▶ && !exists $inline->{method};
Branch: 1 branch
BranchTrueFalseTotal
if ref $inline eq "HASH" and defined $inline->{"id"} and qq[$inline->{"id"}] eq "$id" and not exists $inline->{"method"} 3 90 93
Condition66%6/9
ref $inline eq "HASH" and defined $inline->{"id"} and qq[$inline->{"id"}] eq "$id" and not exists $inline->{"method"}
!ll&&!rl&&r
9003
ref $inline eq "HASH" and defined $inline->{"id"} and qq[$inline->{"id"}] eq "$id"
!ll&&!rl&&r
9003
ref $inline eq "HASH" and defined $inline->{"id"}
!ll&&!rl&&r
9003
MC/DC25%1/4
ref $inline eq "HASH" and defined $inline->{"id"} and qq[$inline->{"id"}] eq "$id" and not exists $inline->{"method"}
ref $inline eq "HASH" defined $inline->{"id"} qq[$inline->{"id"}] eq "$id" not exists $inline->{"method"}
Truth table40%2/5
A and B and C and not(D)
A= ref $inline eq "HASH"B= defined $inline->{"id"}C= qq[$inline->{"id"}] eq "$id"D= not exists $inline->{"method"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
196  
197 90 while (1) {
198 170 my $m = $self->_next_message($deadline, $method);
199 165 ▶ next unless ref $m eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $m eq "HASH" 0 165 165
200  
201 165 ▶ if (exists $m->{method}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $m->{"method"}) 80 85 165
202 80 $self->_answer_server_message($m);
203 80 next;
204 }
205  
206 85 ▶ next unless defined $m->{id} && "$m->{id}" eq "$id";
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m->{"id"} and qq[$m->{"id"}] eq "$id" 0 85 85
Condition33%1/3
defined $m->{"id"} and qq[$m->{"id"}] eq "$id"
!ll&&!rl&&r
0085
MC/DC0%0/2
defined $m->{"id"} and qq[$m->{"id"}] eq "$id"
defined $m->{"id"} qq[$m->{"id"}] eq "$id"
Truth table33%1/3
A and B
A= defined $m->{"id"}B= qq[$m->{"id"}] eq "$id"
ABresult
0X0
100
111
207 85 return $m;
208 }
209 }
210  
211 =head2 notify( $method [, $params] )
212  
213 Sends a JSON-RPC notification (no response is expected).
214  
215 =cut
216  
217 26 ▶sub notify {
Subroutine notify: called CC=2 SCAR=7.0
Pod documented
218 26 my ($self, $method, $params) = @_;
219 26 my $msg = { jsonrpc => '2.0', method => $method };
220 26 ▶ $msg->{params} = $params if defined $params;
Branch: 1 branch
BranchTrueFalseTotal
if defined $params 0 26 26
221 26 $self->_send($msg);
222 26 return;
223 }
224  
225 =head2 list_tools
226  
227 Returns an arrayref of every tool the server advertises, following
228 C<nextCursor> pagination. Dies if the server answers with an error.
229  
230 =cut
231  
232 23 ▶sub list_tools {
Subroutine list_tools: called CC=7 SCAR=19.8
Pod documented
233 23 my ($self) = @_;
234  
235 23 my (@tools, $cursor);
236 23 my $pages = 0;
237 23 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
defined $cursor and length $cursor and ++$pages < 100 and do { do { my $res = $self->request("tools/list", defined $cursor ? {"cursor", $cursor} : undef); die qq[tools/list failed: $res->{"error"}{"message"}\n] if $res->{"error"}; push @tools, @{$res->{"result"}{"tools"} // [];}; $cursor = $res->{"result"}{"nextCursor"} } } 19 23 42
Condition66%4/6
defined $cursor and length $cursor and ++$pages < 100
!ll&&!rl&&r
23019
defined $cursor and length $cursor
!ll&&!rl&&r
23019
MC/DC33%1/3
defined $cursor and length $cursor and ++$pages < 100
defined $cursor length $cursor ++$pages < 100
Truth table50%2/4
A and B and C
A= defined $cursorB= length $cursorC= ++$pages < 100
ABCresult
0XX0
10X0
1100
1111
238 42 ▶ my $res = $self->request('tools/list',
Branch: 1 branch
BranchTrueFalseTotal
defined $cursor ? : 19 23 42
239 defined $cursor ? { cursor => $cursor } : undef);
240 42 ▶ die "tools/list failed: $res->{error}{message}\n" if $res->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"error"} 0 42 42
241  
242 42 ▶ push @tools, @{ $res->{result}{tools} // [] };
Condition50%1/2
$res->{"result"}{"tools"} // []
l!l
420
MC/DC0%0/1
$res->{"result"}{"tools"} // []
$res->{"result"}{"tools"}
Truth table50%1/2
A
A= $res->{"result"}{"tools"}
Aresult
11
00
243 42 $cursor = $res->{result}{nextCursor};
244 } while (defined $cursor && length $cursor && ++$pages < 100);
245  
246 23 return \@tools;
247 }
248  
249 =head2 call_tool( $name, \%arguments )
250  
251 Sends C<tools/call> and returns the full response hashref.
252  
253 =cut
254  
255 23 ▶sub call_tool {
Subroutine call_tool: called CC=2 SCAR=6.9
Pod documented
256 23 my ($self, $name, $args) = @_;
257 23 ▶ return $self->request('tools/call', {
Condition100%2/2
$args || {}
l!l
167
MC/DC100%1/1
$args || {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
258 name => $name,
259 arguments => $args || {},
260 });
261 }
262  
263 =head2 content_text( $result )
264  
265 Exported on request. Renders the C<content> blocks of a C<tools/call> result
266 as text: text blocks are returned verbatim, other block types (image, audio,
267 resources) become a short placeholder so that nothing is silently dropped.
268 Falls back to pretty-printed C<structuredContent> when there is no content.
269  
270 =cut
271  
272 19 ▶sub content_text {
Subroutine content_text: called CC=21 SCAR=46.0
Pod documented
273 19 my ($result) = @_;
274 19 ▶ return '' unless ref $result eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $result eq "HASH" 0 19 19
275  
276 19 my @out;
277 19 ▶ for my $b (@{ $result->{content} // [] }) {
Condition50%1/2
$result->{"content"} // []
l!l
190
MC/DC0%0/1
$result->{"content"} // []
$result->{"content"}
Truth table50%1/2
A
A= $result->{"content"}
Aresult
11
00
278 19 ▶ next unless ref $b eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $b eq "HASH" 0 19 19
279 19 ▶ my $type = $b->{type} // '';
Condition50%1/2
$b->{"type"} // ""
l!l
190
MC/DC0%0/1
$b->{"type"} // ""
$b->{"type"}
Truth table50%1/2
A
A= $b->{"type"}
Aresult
11
00
280  
281 19 ▶ if ($type eq 'text') {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'text') { } 17 2 19
elsif ($type eq 'image' or $type eq 'audio') { } 2 0 2
elsif ($type eq 'resource') { } 0 0 0
elsif ($type eq 'resource_link') { } 0 0 0
282 17 ▶ push @out, $b->{text} // '';
Condition50%1/2
$b->{"text"} // ""
l!l
170
MC/DC0%0/1
$b->{"text"} // ""
$b->{"text"}
Truth table50%1/2
A
A= $b->{"text"}
Aresult
11
00
283 }
284 ▶ elsif ($type eq 'image' || $type eq 'audio') {
Condition33%1/3
$type eq "image" or $type eq "audio"
l!l&&r!l&&!r
200
MC/DC0%0/2
$type eq "image" or $type eq "audio"
$type eq "image" $type eq "audio"
Truth table33%1/3
A or B
A= $type eq "image"B= $type eq "audio"
ABresult
1X1
011
000
285 push @out, sprintf('[%s: %s, %d bytes base64, not displayed]',
286 2 ▶ $type, $b->{mimeType} // 'unknown type', length($b->{data} // ''));
Condition50%2/4
$b->{"mimeType"} // "unknown type"
l!l
20
$b->{"data"} // ""
l!l
20
MC/DC0%0/1
$b->{"mimeType"} // "unknown type"
$b->{"mimeType"}
MC/DC0%0/1
$b->{"data"} // ""
$b->{"data"}
Truth table50%1/2
A
A= $b->{"mimeType"}
Aresult
11
00
Truth table50%1/2
A
A= $b->{"data"}
Aresult
11
00
287 }
288 elsif ($type eq 'resource') {
289 0 ▶ my $r = $b->{resource} || {};
Condition0%0/2
$b->{'resource'} || {}
l!l
00
MC/DC0%0/1
$b->{'resource'} || {}
$b->{'resource'}
Truth table0%0/2
A
A= $b->{'resource'}
Aresult
11
00
290 push @out, defined $r->{text}
291 ? $r->{text}
292 0 ▶ : sprintf('[resource: %s (%s)]', $r->{uri} // '?', $r->{mimeType} // 'unknown type');
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{'text'} ? : 0 0 0
Condition0%0/4
$r->{"uri"} // "?"
l!l
00
$r->{"mimeType"} // "unknown type"
l!l
00
MC/DC0%0/1
$r->{"uri"} // "?"
$r->{"uri"}
MC/DC0%0/1
$r->{"mimeType"} // "unknown type"
$r->{"mimeType"}
Truth table0%0/2
A
A= $r->{"uri"}
Aresult
11
00
Truth table0%0/2
A
A= $r->{"mimeType"}
Aresult
11
00
293 }
294 elsif ($type eq 'resource_link') {
295 0 ▶ push @out, sprintf('[resource link: %s]', $b->{uri} // '?');
Condition0%0/2
$b->{"uri"} // "?"
l!l
00
MC/DC0%0/1
$b->{"uri"} // "?"
$b->{"uri"}
Truth table0%0/2
A
A= $b->{"uri"}
Aresult
11
00
296 }
297 else {
298 0 push @out, JSON::MaybeXS->new(canonical => 1)->encode($b);
299 }
300 }
301  
302 19 ▶ if (!@out && defined $result->{structuredContent}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @out and defined $result->{"structuredContent"}) 0 19 19
Condition33%1/3
not @out and defined $result->{"structuredContent"}
!ll&&!rl&&r
1900
MC/DC0%0/2
not @out and defined $result->{"structuredContent"}
not @out defined $result->{"structuredContent"}
Truth table33%1/3
not(A) and B
A= not @outB= defined $result->{"structuredContent"}
ABresult
0X0
100
111
303 push @out, JSON::MaybeXS->new(canonical => 1, pretty => 1)
304 0 ->encode($result->{structuredContent});
305 }
306  
307 19 return join("\n", @out);
308 }
309  
310 =head2 close
311  
312 Shuts the connection down. For stdio servers, stdin is closed first; a server
313 that has not exited after two seconds is sent C<SIGTERM>, then C<SIGKILL>.
314 Safe to call more than once.
315  
316 =cut
317  
318 57 ▶sub close {
Subroutine close: called CC=11 SCAR=24.1
Pod documented
319 57 my ($self) = @_;
320 57 ▶ return if $self->{closed}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"}++ 29 28 57
321  
322 28 ▶ if ($self->{sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"sse"}) 4 24 28
323 4 ▶ eval { $self->{sse}{sock}->close } if $self->{sse}{sock};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse"}{"sock"} 4 0 4
324 4 return;
325 }
326  
327 24 ▶ return unless $self->{pid};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"pid"} 0 24 24
328  
329 24 eval { CORE::close($self->{in}) };
330 24 my $pid = $self->{pid};
331 24 my $done = 0;
332  
333 24 for my $grace ([2, 'TERM'], [1, 'KILL']) {
334 26 my $until = time + $grace->[0];
335 26 ▶ while (time < $until) {
Branch: 1 branch
BranchTrueFalseTotal
if (&App::MCP::CLI::Client::time() < $until) 180 2 182
336 180 my $k = waitpid($pid, WNOHANG);
337 180 ▶ if ($k == $pid || $k == -1) { $done = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($k == $pid or $k == -1) 24 156 180
Condition66%2/3
$k == $pid or $k == -1
l!l&&r!l&&!r
240156
MC/DC50%1/2
$k == $pid or $k == -1
$k == $pid $k == -1
Truth table66%2/3
A or B
A= $k == $pidB= $k == -1
ABresult
1X1
011
000
338 156 sleep 0.05;
339 }
340 26 ▶ last if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 24 2 26
341 2 kill $grace->[1], $pid;
342 }
343 24 ▶ waitpid($pid, 0) unless $done;
Branch: 1 branch
BranchTrueFalseTotal
unless $done 0 24 24
344  
345 24 eval { CORE::close($self->{out}) };
346 24 return;
347 }
348  
349 30 ▶sub DESTROY { local ($@, $!, $?); $_[0]->close if $_[0]{pid} || $_[0]{sse} }
Subroutine DESTROY: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]{"pid"} or $_[0]{"sse"} 28 2 30
Condition100%3/3
$_[0]{"pid"} or $_[0]{"sse"}
l!l&&r!l&&!r
2442
MC/DC100%2/2
$_[0]{"pid"} or $_[0]{"sse"}
$_[0]{"pid"} $_[0]{"sse"}
Truth table100%3/3
A or B
A= $_[0]{"pid"}B= $_[0]{"sse"}
ABresult
1X1
011
000
350  
351 # stdio
352  
353 1 ▶sub _clean_err {
Subroutine _clean_err: called CC=1 SCAR=0.0
354 1 my ($e) = @_;
355 1 $e =~ s/ at \S+ line \d+\.?\s*\z//;
356 1 $e =~ s/\s+\z//;
357 1 return "$e\n";
358 }
359  
360 25 ▶sub _connect_stdio {
Subroutine _connect_stdio: called CC=6 SCAR=18.9
361 25 my ($self) = @_;
362  
363 25 my ($out, $in);
364 25 my $cmd = $self->{cmd};
365 25 ▶ die "No command to start the MCP server.\n" unless $cmd && defined $cmd->[0] && length $cmd->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $cmd and defined $cmd->[0] and length $cmd->[0] 0 25 25
Condition33%2/6
$cmd and defined $cmd->[0] and length $cmd->[0]
!ll&&!rl&&r
0025
$cmd and defined $cmd->[0]
!ll&&!rl&&r
0025
MC/DC0%0/3
$cmd and defined $cmd->[0] and length $cmd->[0]
$cmd defined $cmd->[0] length $cmd->[0]
Truth table25%1/4
A and B and C
A= $cmdB= defined $cmd->[0]C= length $cmd->[0]
ABCresult
0XX0
10X0
1100
1111
366  
367 # The environment applies to this child only, never to our own process.
368 25 my @keys = keys %{ $self->{env} };
369 25 local @ENV{@keys} = @{ $self->{env} }{@keys};
370  
371 25 my $pid = eval { open2($out, $in, @$cmd) };
372 25 ▶ die "Failed to start MCP server '@$cmd': " . _clean_err($@ || $!)
Branch: 1 branch
BranchTrueFalseTotal
unless $pid 1 24 25
Condition33%1/3
$@ || $!
l!l&&r!l&&!r
100
MC/DC0%0/2
$@ || $!
$@ $!
Truth table33%1/3
A || B
A= $@B= $!
ABresult
1X1
011
000
373 unless $pid;
374  
375 24 $in->autoflush(1);
376 24 @$self{qw(pid in out)} = ($pid, $in, $out);
377 24 return;
378 }
379  
380 146 ▶sub _read_some {
Subroutine _read_some: called CC=12 SCAR=31.5
381 146 my ($fh, $deadline, $what) = @_;
382  
383 146 while (1) {
384 146 ▶ unless (blessed($fh) && $fh->can('pending') && $fh->pending) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($fh) and $fh->can("pending") and $fh->pending) 146 0 146
Condition50%3/6
builtin::blessed($fh) and $fh->can("pending") and $fh->pending
!ll&&!rl&&r
14600
builtin::blessed($fh) and $fh->can("pending")
!ll&&!rl&&r
117290
MC/DC0%0/3
builtin::blessed($fh) and $fh->can("pending") and $fh->pending
builtin::blessed($fh) $fh->can("pending") $fh->pending
Truth table50%2/4
A and B and C
A= builtin::blessed($fh)B= $fh->can("pending")C= $fh->pending
ABCresult
0XX0
10X0
1100
1111
385 146 my $left = $deadline - time;
386 146 ▶ die "Timed out waiting for $what.\n" if $left <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $left <= 0 0 146 146
387  
388 146 my $rin = '';
389 146 vec($rin, fileno($fh), 1) = 1;
390 146 my $n = select(my $rout = $rin, undef, undef, $left);
391 146 ▶ if ($n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n < 0) 0 146 146
392 0 ▶ next if $!{EINTR};
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EINTR"} 0 0 0
393 0 die "select failed: $!\n";
394 }
395 146 ▶ die "Timed out waiting for $what.\n" if $n == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 2 144 146
396 }
397  
398 144 my $r = sysread($fh, my $chunk, 65536);
399 144 ▶ if (!defined $r) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $r) 0 144 144
400 0 ▶ next if $!{EINTR} || $!{EAGAIN};
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EINTR"} or $!{"EAGAIN"} 0 0 0
Condition0%0/3
$!{"EINTR"} or $!{"EAGAIN"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$!{"EINTR"} or $!{"EAGAIN"}
$!{"EINTR"} $!{"EAGAIN"}
Truth table0%0/3
A or B
A= $!{"EINTR"}B= $!{"EAGAIN"}
ABresult
1X1
011
000
401 0 die "Read error while waiting for $what: $!\n";
402 }
403 144 ▶ return $r ? $chunk : undef;
Branch: 1 branch
BranchTrueFalseTotal
$r ? : 141 3 144
404 }
405 }
406  
407 162 ▶sub _stdio_message {
Subroutine _stdio_message: called CC=5 SCAR=16.1
408 162 my ($self, $deadline, $what) = @_;
409  
410 162 while (1) {
411 354 ▶ if ($self->{buf} =~ s/\A([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"buf"} =~ s/\A([^\n]*)\n//) 237 117 354
412 237 my $line = $1;
413 237 $line =~ s/\r\z//;
414 237 ▶ next unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 237 237
415  
416 237 $self->_debug('<-', $line);
417 237 my $m = eval { $self->{json}->decode($line) };
418 237 ▶ next unless ref $m; # tolerate stray non-JSON output on stdout
Branch: 1 branch
BranchTrueFalseTotal
unless ref $m 80 157 237
419 157 return $m;
420 }
421  
422 117 my $chunk = _read_some($self->{out}, $deadline, "the MCP server's reply to '$what'");
423 115 ▶ die "The MCP server closed the connection (did the process exit?).\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk 3 112 115
424 unless defined $chunk;
425 112 $self->{buf} .= $chunk;
426 }
427 }
428  
429 # SSE
430  
431 8 ▶sub _parse_url {
Subroutine _parse_url: called CC=6 SCAR=19.9
432 8 my ($url) = @_;
433  
434 8 ▶ $url =~ m{^(https?)://(\[[^\]]+\]|[^/:?#]+)(?::(\d+))?([^#]*)}i
Branch: 1 branch
BranchTrueFalseTotal
$url =~ m(^(https?)://(\[[^\]]+\]|[^/:?#]+)(?::(\d+))?([^#]*))i or die "Invalid URL: $url\n" 8 0 8
435 or die "Invalid URL: $url\n";
436  
437 8 my ($scheme, $host, $port, $path) = (lc $1, $2, $3, $4);
438 8 ▶ $path = "/$path" unless $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
unless $path =~ m[^/] 0 8 8
439  
440 8 my $hostport = $host;
441 8 ▶ $hostport .= ":$port" if defined $port;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 8 0 8
442 8 (my $bare = $host) =~ s/^\[|\]$//g;
443  
444 return {
445 8 ▶ scheme => $scheme,
Branch: 1 branch
BranchTrueFalseTotal
$scheme eq 'https' ? : 0 0 0
Condition50%1/2
$port // ($scheme eq "https" ? 443 : 80)
l!l
80
MC/DC0%0/1
$port // ($scheme eq "https" ? 443 : 80)
$port
Truth table50%1/2
A
A= $port
Aresult
11
00
446 host => $bare,
447 port => $port // ($scheme eq 'https' ? 443 : 80),
448 path => $path,
449 origin => "$scheme://$hostport",
450 };
451 }
452  
453 5 ▶sub _open_socket {
Subroutine _open_socket: called CC=8 SCAR=26.4
454 5 my ($self, $u) = @_;
455  
456 my %opt = (PeerHost => $u->{host}, PeerPort => $u->{port},
457 5 ▶ Timeout => $self->{timeout} > 0 ? $self->{timeout} : 60);
Branch: 1 branch
BranchTrueFalseTotal
$self->{'timeout'} > 0 ? : 5 0 5
458 5 my $sock;
459  
460 5 ▶ if ($u->{scheme} eq 'https') {
Branch: 1 branch
BranchTrueFalseTotal
if ($u->{'scheme'} eq 'https') { } 0 5 5
461 0 ▶ eval { require IO::Socket::SSL; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require IO::Socket::SSL; 1 } } or die "https:// MCP servers need IO::Socket::SSL, which is not installed.\n" 0 0 0
462 or die "https:// MCP servers need IO::Socket::SSL, which is not installed.\n";
463 31 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
464 0 ▶ $sock = IO::Socket::SSL->new(%opt)
Branch: 1 branch
BranchTrueFalseTotal
$sock = "IO::Socket::SSL"->new(%opt) or die qq[Cannot connect to $u->{"origin"}: $IO::Socket::SSL::SSL_ERROR\n] 0 0 0
465 or die "Cannot connect to $u->{origin}: $IO::Socket::SSL::SSL_ERROR\n";
466 }
467 else {
468 5 my $class = eval { require IO::Socket::IP; 1 } ? 'IO::Socket::IP'
469 0 ▶ : do { require IO::Socket::INET; 'IO::Socket::INET' };
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require IO::Socket::IP; 1 } } ? : 5 0 5
470 5 ▶ $sock = $class->new(%opt)
Branch: 1 branch
BranchTrueFalseTotal
$sock = $class->new(%opt) or die qq[Cannot connect to $u->{"origin"}: ] . ($@ || $!) . "\n" 4 1 5
Condition33%1/3
$@ || $!
l!l&&r!l&&!r
100
MC/DC0%0/2
$@ || $!
$@ $!
Truth table33%1/3
A || B
A= $@B= $!
ABresult
1X1
011
000
471 or die "Cannot connect to $u->{origin}: " . ($@ || $!) . "\n";
472 }
473  
474 4 return $sock;
475 }
476  
477 4 ▶sub _resolve_endpoint {
Subroutine _resolve_endpoint: called CC=3 SCAR=11.6
478 4 my ($base, $ep) = @_;
479  
480 4 $ep =~ s/^\s+|\s+$//g;
481 4 ▶ return $ep if $ep =~ m{^https?://}i;
Branch: 1 branch
BranchTrueFalseTotal
if $ep =~ m[^https?://]i 1 3 4
482  
483 3 my $u = _parse_url($base);
484 3 ▶ return $u->{origin} . $ep if $ep =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $ep =~ m[^/] 3 0 3
485  
486 0 (my $dir = $u->{path}) =~ s{[^/]*\z}{};
487 0 return $u->{origin} . $dir . $ep;
488 }
489  
490 5 ▶sub _connect_sse {
Subroutine _connect_sse: called CC=15 SCAR=27.8
491 5 my ($self) = @_;
492  
493 5 my $u = _parse_url($self->{url});
494 5 my $deadline = $self->_deadline;
495 5 my $sock = $self->_open_socket($u);
496  
497 0 my $extra = join '', map { "$_: $self->{headers}{$_}\r\n" } sort keys %{ $self->{headers} };
498 4 my $host = $u->{origin};
499 4 $host =~ s{^https?://}{};
500  
501 4 ▶ print {$sock} "GET $u->{path} HTTP/1.1\r\nHost: $host\r\n"
Branch: 1 branch
BranchTrueFalseTotal
print {$sock;} qq[GET $u->{"path"} HTTP/1.1\r\nHost: $host\r\n] . "Accept: text/event-stream\r\nCache-Control: no-cache\r\n" . "Connection: keep-alive\r\n$extra\r\n" or die qq[Cannot send request to $u->{"origin"}: $!\n] 4 0 4
502 . "Accept: text/event-stream\r\nCache-Control: no-cache\r\n"
503 . "Connection: keep-alive\r\n$extra\r\n"
504 or die "Cannot send request to $u->{origin}: $!\n";
505  
506 4 my $raw = '';
507 4 ▶ until ($raw =~ /\r?\n\r?\n/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($raw =~ /\r?\n\r?\n/) 6 4 10
508 6 my $chunk = _read_some($sock, $deadline, 'the SSE response headers');
509 6 ▶ die "SSE endpoint closed the connection before sending headers.\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk 0 6 6
510 unless defined $chunk;
511 6 $raw .= $chunk;
512 }
513 4 $raw =~ s/\A(.*?)\r?\n\r?\n//s;
514 4 my @head = split /\r?\n/, $1;
515 4 ▶ my ($code, $reason) = (shift(@head) // '') =~ m{^HTTP/\S+\s+(\d+)\s*(.*)}
Branch: 1 branch
BranchTrueFalseTotal
() = (shift @head // "") =~ m[^HTTP/\S+\s+(\d+)\s*(.*)] or die "SSE endpoint sent an invalid HTTP response.\n" 4 0 4
Condition50%1/2
shift @head // ""
l!l
40
MC/DC0%0/1
shift @head // ""
shift @head
Truth table50%1/2
A
A= shift @head
Aresult
11
00
516 or die "SSE endpoint sent an invalid HTTP response.\n";
517 4 ▶ die "Failed to connect to SSE endpoint ($code): $reason\n" unless $code == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $code == 200 0 4 4
518  
519 4 ▶ my %h = map { /^([^:]+):\s*(.*)$/ ? (lc $1, $2) : () } @head;
Branch: 1 branch
BranchTrueFalseTotal
/^([^:]+):\s*(.*)$/ ? : 15 0 15
520  
521 $self->{sse} = {
522 sock => $sock,
523 raw => $raw,
524 text => '',
525 chunked => (($h{'transfer-encoding'} // '') =~ /chunked/i ? 1 : 0),
526 4 ▶ remaining => (exists $h{'content-length'} ? $h{'content-length'} : undef),
Branch: 2 branches
BranchTrueFalseTotal
($h{'transfer-encoding'} // '') =~ /chunked/i ? : 3 1 4
exists $h{'content-length'} ? : 1 3 4
Condition100%2/2
$h{"transfer-encoding"} // ""
l!l
31
MC/DC100%1/1
$h{"transfer-encoding"} // ""
$h{"transfer-encoding"}
Truth table100%2/2
A
A= $h{"transfer-encoding"}
Aresult
11
00
527 eof => 0,
528 };
529  
530 4 my $ep;
531 4 ▶ while (!defined $ep) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ep) 4 4 8
532 4 my $ev = $self->_sse_event($deadline, 'the SSE endpoint event');
533 4 ▶ die "SSE stream ended before announcing a POST endpoint.\n" unless $ev;
Branch: 1 branch
BranchTrueFalseTotal
unless $ev 0 4 4
534 4 ▶ $ep = $ev->{data} if $ev->{event} eq 'endpoint';
Branch: 1 branch
BranchTrueFalseTotal
if $ev->{"event"} eq "endpoint" 4 0 4
535 }
536  
537 4 $self->{post_url} = _resolve_endpoint($self->{url}, $ep);
538 $self->{ua} = HTTP::Tiny->new(
539 4 ▶ timeout => ($self->{timeout} > 0 ? $self->{timeout} : 3600),
Branch: 1 branch
BranchTrueFalseTotal
$self->{'timeout'} > 0 ? : 4 0 4
540 );
541 4 return;
542 }
543  
544 23 ▶sub _sse_decode {
Subroutine _sse_decode: called CC=12 SCAR=25.8
545 23 my ($st) = @_;
546  
547 23 ▶ if ($st->{chunked}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($st->{"chunked"}) 22 1 23
548 22 while (1) {
549 44 ▶ if ($st->{need_crlf}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($st->{"need_crlf"}) 22 22 44
550 22 ▶ return if length($st->{raw}) < 2;
Branch: 1 branch
BranchTrueFalseTotal
if length $st->{"raw"} < 2 0 22 22
551 22 substr($st->{raw}, 0, 2, '');
552 22 $st->{need_crlf} = 0;
553 }
554 44 ▶ if (!defined $st->{chunk_left}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $st->{"chunk_left"}) 44 0 44
555 44 ▶ return unless $st->{raw} =~ s/\A([0-9a-fA-F]+)[^\r\n]*\r\n//;
Branch: 1 branch
BranchTrueFalseTotal
unless $st->{"raw"} =~ s/\A([0-9a-fA-F]+)[^\r\n]*\r\n// 22 22 44
556 22 $st->{chunk_left} = hex $1;
557 0 ▶ if (!$st->{chunk_left}) { $st->{eof} = 1; return }
Branch: 1 branch
BranchTrueFalseTotal
unless ($st->{"chunk_left"}) 0 22 22
558 }
559 22 ▶ return unless length $st->{raw};
Branch: 1 branch
BranchTrueFalseTotal
unless length $st->{"raw"} 0 22 22
560  
561 my $take = length($st->{raw}) < $st->{chunk_left}
562 22 ▶ ? length($st->{raw}) : $st->{chunk_left};
Branch: 1 branch
BranchTrueFalseTotal
length $st->{'raw'} < $st->{'chunk_left'} ? : 0 22 22
563 22 $st->{text} .= substr($st->{raw}, 0, $take, '');
564 22 $st->{chunk_left} -= $take;
565 22 ▶ if (!$st->{chunk_left}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($st->{"chunk_left"}) 22 0 22
566 22 $st->{chunk_left} = undef;
567 22 $st->{need_crlf} = 1;
568 }
569 }
570 }
571  
572 1 my $n = length $st->{raw};
573 1 $st->{text} .= $st->{raw};
574 1 $st->{raw} = '';
575 1 ▶ if (defined $st->{remaining}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $st->{"remaining"}) 1 0 1
576 1 $st->{remaining} -= $n;
577 1 ▶ $st->{eof} = 1 if $st->{remaining} <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $st->{"remaining"} <= 0 1 0 1
578 }
579 1 return;
580 }
581  
582 12 ▶sub _sse_event {
Subroutine _sse_event: called CC=14 SCAR=27.7
583 12 my ($self, $deadline, $what) = @_;
584 12 my $st = $self->{sse};
585  
586 12 while (1) {
587 35 ▶ _sse_decode($st) if length $st->{raw};
Branch: 1 branch
BranchTrueFalseTotal
if length $st->{"raw"} 23 12 35
588  
589 # A response with a fixed length (or a terminated chunked body) is a
590 # finished stream: release the connection at once so that
591 # single-threaded servers can accept our POSTs.
592 35 ▶ if ($st->{eof} && !$st->{released}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($st->{"eof"} and not $st->{"released"}++) 1 34 35
Condition66%2/3
$st->{"eof"} and not $st->{"released"}++
!ll&&!rl&&r
3401
MC/DC50%1/2
$st->{"eof"} and not $st->{"released"}++
$st->{"eof"} not $st->{"released"}++
Truth table66%2/3
A and not(B)
A= $st->{"eof"}B= not $st->{"released"}++
ABresult
0X0
100
111
593 1 eval { $st->{sock}->close };
594 }
595  
596 35 ▶ if ($st->{text} =~ s/\A(.*?)\r?\n\r?\n//s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($st->{"text"} =~ s/\A(.*?)\r?\n\r?\n//s) 12 23 35
597 12 my ($event, @data) = ('message');
598 12 for my $line (split /\r?\n/, $1) {
599 24 ▶ next if $line =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^:/ 0 24 24
600 24 my ($f, $v) = split /:/, $line, 2;
601 24 ▶ $v = '' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 24 24
602 24 $v =~ s/^ //;
603 24 ▶ if ($f eq 'event') { $event = $v }
Branch: 2 branches
BranchTrueFalseTotal
if ($f eq 'event') { } 12 12 24
elsif ($f eq 'data') { } 12 0 12
604 12 elsif ($f eq 'data') { push @data, $v }
605 }
606 12 ▶ next unless @data || $event ne 'message';
Branch: 1 branch
BranchTrueFalseTotal
unless @data or $event ne "message" 0 12 12
Condition33%1/3
@data or $event ne "message"
l!l&&r!l&&!r
1200
MC/DC0%0/2
@data or $event ne "message"
@data $event ne "message"
Truth table33%1/3
A or B
A= @dataB= $event ne "message"
ABresult
1X1
011
000
607 12 return { event => $event, data => join("\n", @data) };
608 }
609  
610 23 ▶ return if $st->{eof};
Branch: 1 branch
BranchTrueFalseTotal
if $st->{"eof"} 0 23 23
611  
612 23 my $chunk = _read_some($st->{sock}, $deadline, $what);
613 0 ▶ if (!defined $chunk) { $st->{eof} = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $chunk) 0 23 23
614 23 $st->{raw} .= $chunk;
615 }
616 }
617  
618 8 ▶sub _sse_message {
Subroutine _sse_message: called CC=4 SCAR=14.2
619 8 my ($self, $deadline, $what) = @_;
620  
621 8 while (1) {
622 8 ▶ my $ev = $self->_sse_event($deadline, "the MCP server's reply to '$what'")
Branch: 1 branch
BranchTrueFalseTotal
my $ev = $self->_sse_event($deadline, "the MCP server's reply to '${what}'") or die "The SSE stream was closed before the server replied to '${what}'.\n" 8 0 8
623 or die "The SSE stream was closed before the server replied to '$what'.\n";
624 8 ▶ next unless $ev->{event} eq 'message';
Branch: 1 branch
BranchTrueFalseTotal
unless $ev->{"event"} eq "message" 0 8 8
625  
626 8 $self->_debug('<-', $ev->{data});
627 8 my $m = eval { $self->{json}->decode($ev->{data}) };
628 8 ▶ return $m if ref $m;
Branch: 1 branch
BranchTrueFalseTotal
if ref $m 8 0 8
629 }
630 }
631  
632 # shared
633  
634 170 ▶sub _next_message {
Subroutine _next_message: called CC=2 SCAR=6.9
635 170 my ($self, $deadline, $what) = @_;
636 170 ▶ return $self->is_sse
Branch: 1 branch
BranchTrueFalseTotal
$self->is_sse ? : 8 162 170
637 ? $self->_sse_message($deadline, $what)
638 : $self->_stdio_message($deadline, $what);
639 }
640  
641 # Sends a message. For SSE, returns the JSON-RPC message found in the POST
642 # reply body, if any (some servers answer inline instead of on the stream).
643 119 ▶sub _send {
Subroutine _send: called CC=10 SCAR=25.1
644 119 my ($self, $msg) = @_;
645  
646 119 my $raw = $self->{json}->encode($msg);
647 119 $self->_debug('->', $raw);
648  
649 119 ▶ if ($self->is_sse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_sse) 15 104 119
650 15 ▶ die "The SSE connection is closed.\n" if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 15 15
651 my $res = $self->{ua}->post($self->{post_url}, {
652 15 headers => { 'content-type' => 'application/json', %{ $self->{headers} } },
653 content => $raw,
654 });
655 15 ▶ unless ($res->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->{"success"}) 0 15 15
656 0 ▶ my $detail = $res->{status} == 599 ? " - $res->{content}" : '';
Branch: 1 branch
BranchTrueFalseTotal
$res->{'status'} == 599 ? : 0 0 0
657 0 $detail =~ s/\s+\z//;
658 0 die "MCP HTTP request failed ($res->{status} $res->{reason})$detail\n";
659 }
660  
661 15 ▶ return unless length($res->{content} // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($res->{"content"} // "") 0 15 15
Condition50%1/2
$res->{"content"} // ""
l!l
150
MC/DC0%0/1
$res->{"content"} // ""
$res->{"content"}
Truth table50%1/2
A
A= $res->{"content"}
Aresult
11
00
662 15 my $m = eval { $self->{json}->decode($res->{content}) };
663 15 ▶ return ref $m eq 'HASH' ? $m : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $m eq 'HASH' ? : 4 11 15
664 }
665  
666 104 ▶ die "The MCP server connection is closed.\n" if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 104 104
667 104 local $SIG{PIPE} = 'IGNORE';
668 104 my $in = $self->{in};
669 104 ▶ print {$in} "$raw\n"
Branch: 1 branch
BranchTrueFalseTotal
print {$in;} "$raw\n" or die "Failed to write to the MCP server (has it exited?): $!\n" 104 0 104
670 or die "Failed to write to the MCP server (has it exited?): $!\n";
671 104 return;
672 }
673  
674 80 ▶sub _answer_server_message {
Subroutine _answer_server_message: called CC=4 SCAR=25.0
675 80 my ($self, $m) = @_;
676 80 ▶ return unless defined $m->{id}; # a notification: nothing to answer
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m->{"id"} 80 0 80
677  
678 0 my $reply = { jsonrpc => '2.0', id => $m->{id} };
679 0 ▶ if (($m->{method} // '') eq 'ping') {
Branch: 1 branch
BranchTrueFalseTotal
if (($m->{'method'} // '') eq 'ping') { } 0 0 0
Condition0%0/2
$m->{"method"} // ""
l!l
00
MC/DC0%0/1
$m->{"method"} // ""
$m->{"method"}
Truth table0%0/2
A
A= $m->{"method"}
Aresult
11
00
680 0 $reply->{result} = {};
681 }
682 else {
683 0 $reply->{error} = { code => -32601, message => "Method not supported by mcpcli: $m->{method}" };
684 }
685 0 eval { $self->_send($reply) };
686 0 return;
687 }
688  
689 =head1 SEE ALSO
690  
691 =over 4
692  
693 =item * L<App::MCP::CLI::Config>
694  
695 =item * L<App::MCP::CLI::Command::call>
696  
697 =item * L<App::MCP::CLI::Command::list>
698  
699 =item * L<App::MCP::CLI::Command::interactive>
700  
701 =item * MCP transports: L<https://modelcontextprotocol.io/specification/2024-11-05/basic/transports>
702  
703 =back
704  
705 =head1 AUTHOR
706  
707 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
708  
709 =head1 REPOSITORY
710  
711 L<https://github.com/manwar/App-MCP-CLI>
712  
713 =head1 BUGS
714  
715 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/App-MCP-CLI/issues>.
716  
717 =head1 LICENSE AND COPYRIGHT
718  
719 Copyright (C) 2026 Mohammad Sajid Anwar.
720  
721 This program is free software; you can redistribute it and / or modify it under
722 the terms of the the Artistic License (2.0). You may obtain a copy of the full
723 license at:
724  
725 L<http://www.perlfoundation.org/artistic_license_2_0>
726  
727 =cut
728  
729 31 1; # End of App::MCP::CLI::Client
« blib/lib/App/MCP/CLI/Config.pm ↑ Summary blib/lib/App/MCP/CLI/Command/servers.pm »