blib/lib/Net/Async/MCP/Transport/Stdio.pm

filter: Statementstmt 97.8% 226 / 231 Branchbran 76.3% 87 / 114 Conditioncond 51.0% 25 / 49 MC/DCmcdc 26.6% 8 / 30 Subroutinesub 100% 39 / 39 Podpod 100% 7 / 7 totaltotal 83.4% 392 / 470 CC 81 SCAR 16.3
CC
81
Cov
86%
_on_stdout_read
11.2
_on_stderr_read
8.2
_on_server_request
7.6
CRAP 5.1
« blib/lib/Net/Async/MCP/Transport/HTTP.pm ↑ Summary blib/lib/Net/Async/MCP/Transport/InProcess.pm »
1 package Net::Async::MCP::Transport::Stdio;
2 # ABSTRACT: Stdio MCP transport via subprocess JSON-RPC
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Encode qw( decode );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use Scalar::Util qw( weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 5 ▶use Net::Async::MCP::JSONRPC;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15  
16 33 ▶sub _init {
Subroutine _init: called CC=2 SCAR=6.9
17 33 my ( $self, $params ) = @_;
18 $self->{command} = delete $params->{command}
19 33 ▶ or croak "command is required";
Branch: 1 branch
BranchTrueFalseTotal
$self->{"command"} = delete $params->{"command"} or croak("command is required") 33 0 33
20 33 $self->{pending} = {};
21 33 $self->{next_id} = 0;
22 33 $self->{buffer} = '';
23 33 $self->{closed} = 0;
24 33 $self->{json} = JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
25  
26 33 $self->{stderr_buffer} = '';
27 33 $self->{stderr_tail} = [];
28 33 $self->SUPER::_init($params);
29 }
30  
31 # Private: how many lines of the server's stderr are kept for stderr_tail and
32 # the failure of the requests it leaves unanswered.
33 5 my $STDERR_TAIL_LINES = 20;
34  
35 37 ▶sub configure {
Subroutine configure: called CC=4 SCAR=14.2
Pod documented
36 37 my ( $self, %params ) = @_;
37 37 ▶ if (exists $params{command}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"command"}) 0 37 37
38 0 $self->{command} = delete $params{command};
39 }
40 37 for my $key (qw( env cwd timeout on_notification on_stderr on_request )) {
41 222 ▶ $self->{$key} = delete $params{$key} if exists $params{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$key} 53 169 222
42 }
43 37 $self->SUPER::configure(%params);
44 }
45  
46  
47 33 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=5 SCAR=16.4
48 33 my ( $self, $loop ) = @_;
49 33 $self->SUPER::_add_to_loop($loop);
50  
51 33 require IO::Async::Process;
52  
53 # A working directory that does not exist is checked here rather than left to
54 # IO::Async, which croaks about it from inside loop->add - halfway through
55 # adding this transport, and before anyone holds a request that could carry
56 # the reason. Failing the start instead makes it the answer to the first
57 # request, the same as a command that cannot be executed.
58 33 my $cwd = $self->{cwd};
59 33 ▶ if (defined $cwd && !-d $cwd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cwd and not -d $cwd) 1 32 33
Condition100%3/3
defined $cwd and not -d $cwd
!ll&&!rl&&r
3111
MC/DC100%2/2
defined $cwd and not -d $cwd
defined $cwd not -d $cwd
Truth table100%3/3
A and not(B)
A= defined $cwdB= not -d $cwd
ABresult
0X0
100
111
60 1 $self->{closed} = 1;
61 1 $self->{exit_message} = $self->_cannot_run("no such working directory '$cwd'");
62 1 return;
63 }
64  
65 32 my @setup;
66 32 ▶ push @setup, env => $self->_child_env if $self->{env};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"env"} 13 19 32
67 32 ▶ push @setup, chdir => $cwd if defined $cwd;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cwd 1 31 32
68  
69 # These callbacks end up on the process, and on the child streams the process
70 # owns, while the transport owns the process - so capturing the transport
71 # strongly here would close a cycle no refcount ever breaks, and the transport
72 # would outlive its own client. Weakening them costs nothing: as long as
73 # either callback can still fire, the loop holds the transport for us. The
74 # loop keeps its notifiers alive strongly, and taking the transport out of the
75 # loop takes the process out with it, which unwatches the child and silences
76 # both callbacks. So the weak reference is never undef where it matters; the
77 # guards below are for the DESTROY-ordering case only.
78 32 weaken( my $weak_self = $self );
79  
80 my $process = IO::Async::Process->new(
81 command => $self->{command},
82 setup => \@setup,
83 stdin => { via => 'pipe_write' },
84 stdout => {
85 103 ▶ on_read => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
86 103 my ( $stream, $buffref, $eof ) = @_;
87 103 ▶ my $self = $weak_self or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 0 103 0 103
88 103 $self->_on_stdout_read($buffref, $eof);
89 103 return 0;
90 },
91 },
92 stderr => {
93 45 ▶ on_read => sub {
Subroutine __ANON__: called CC=2 SCAR=7.9
94 45 my ( $stream, $buffref, $eof ) = @_;
95 0 ▶ my $self = $weak_self or do { $$buffref = ''; return 0 };
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or do { $$buffref = ""; return 0 } 45 0 45
96 45 $self->_on_stderr_read($buffref, $eof);
97 45 return 0;
98 },
99 },
100 30 ▶ on_finish => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
101 30 my ( $proc, $exitcode ) = @_;
102 30 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 30 0 30
103 30 $self->_on_finish($exitcode);
104 },
105 # A command that could not be executed at all. Without this handler
106 # IO::Async reports it through on_finish as an ordinary exit, and the
107 # reason - the errno of the failed exec - would be lost.
108 1 ▶ on_exception => sub {
Subroutine __ANON__: called CC=4 SCAR=16.9
109 1 my ( $proc, $exception, $errno, $exitcode ) = @_;
110 1 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 1 0 1
111 1 ▶ $self->_on_finish($exitcode,
Branch: 1 branch
BranchTrueFalseTotal
length "$errno" ? : 1 0 1
Condition0%0/2
$exception // "unknown error"
l!l
00
MC/DC0%0/1
$exception // "unknown error"
$exception
Truth table0%0/2
A
A= $exception
Aresult
11
00
112 $self->_cannot_run(length "$errno" ? "$errno" : $exception // 'unknown error'));
113 },
114 32 );
115  
116 32 $self->{process} = $process;
117 32 $self->add_child($process);
118 }
119  
120 # Private: the environment of the subprocess - this process's own, with env
121 # laid over it, a key whose value is undef removing that variable.
122 13 ▶sub _child_env {
Subroutine _child_env: called CC=3 SCAR=11.0
123 13 my ( $self ) = @_;
124 13 my %env = %ENV;
125 13 my $overlay = $self->{env};
126 13 for my $key (keys %$overlay) {
127 11 ▶ if (defined $overlay->{$key}) { $env{$key} = $overlay->{$key} }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $overlay->{$key}) { } 10 1 11
128 1 else { delete $env{$key} }
129 }
130 13 return \%env;
131 }
132  
133 # Private: the one-line reason a subprocess never got to run.
134 2 ▶sub _cannot_run {
Subroutine _cannot_run: called CC=2 SCAR=7.0
135 2 my ( $self, $reason ) = @_;
136 2 my $command = $self->{command};
137 2 ▶ my $program = ref $command eq 'ARRAY' ? $command->[0] : $command;
Branch: 1 branch
BranchTrueFalseTotal
ref $command eq 'ARRAY' ? : 2 0 2
138 2 $reason =~ s/\s+\z//;
139 2 return 'MCP server failed to start: cannot run '.$program.': '.$reason;
140 }
141  
142 31 ▶sub _remove_from_loop {
Subroutine _remove_from_loop: called CC=7 SCAR=19.6
143 31 my ( $self, $loop ) = @_;
144  
145 # Leaving the loop takes the process along, it being a child of this
146 # transport, and with it the watches on the child's streams that _on_finish
147 # waits for. So _on_finish will not run again, and everything it would have
148 # settled has to be settled here instead, or it stays pending for the rest
149 # of the program: the requests still waiting for an answer, and a close
150 # still waiting for the exit.
151 #
152 # Both are failed rather than completed, because completing either would be
153 # a claim this transport cannot make. Nothing here saw a response go missing
154 # or a process die; what it knows is that neither can reach it any more. The
155 # two messages differ in what was lost so a caller holding both can tell
156 # them apart.
157 #
158 # Same shape as _on_finish, and for the same reasons: the keys are taken
159 # before the loop, so a handler that touches the pending table as its future
160 # fails cannot disturb the iteration, and every future is deleted as it is
161 # settled, so neither path can reach one the other already answered.
162 31 for my $id (keys %{$self->{pending}}) {
163 1 my $future = delete $self->{pending}{$id};
164 1 ▶ $future->fail("MCP server process left the loop before the request was answered")
Branch: 1 branch
BranchTrueFalseTotal
if $future and not $future->is_ready 1 0 1
Condition33%1/3
$future and not $future->is_ready
!ll&&!rl&&r
001
MC/DC0%0/2
$future and not $future->is_ready
$future not $future->is_ready
Truth table33%1/3
A and not(B)
A= $futureB= not $future->is_ready
ABresult
0X0
100
111
165 if $future && !$future->is_ready;
166 }
167  
168 31 ▶ if ($self->{close_future} && !$self->{close_future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"close_future"} and not $self->{"close_future"}->is_ready) 1 30 31
Condition100%3/3
$self->{"close_future"} and not $self->{"close_future"}->is_ready
!ll&&!rl&&r
3271
MC/DC100%2/2
$self->{"close_future"} and not $self->{"close_future"}->is_ready
$self->{"close_future"} not $self->{"close_future"}->is_ready
Truth table100%3/3
A and not(B)
A= $self->{"close_future"}B= not $self->{"close_future"}->is_ready
ABresult
0X0
100
111
169 ( delete $self->{close_future} )
170 1 ->fail("MCP server process left the loop before it exited");
171 }
172  
173 31 ▶ if (my $escalation = delete $self->{close_escalation}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $escalation = delete $self->{"close_escalation"}) 1 30 31
174 1 $escalation->cancel;
175 }
176  
177 31 $self->SUPER::_remove_from_loop($loop);
178 }
179  
180 91 ▶sub send_request {
Subroutine send_request: called CC=6 SCAR=17.9
Pod documented
181 91 my ( $self, $method, $params, %options ) = @_;
182  
183 91 ▶ if ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"closed"}) 5 86 91
184 5 ▶ return Future->fail($self->{exit_message} // "MCP server process has exited");
Condition50%1/2
$self->{"exit_message"} // "MCP server process has exited"
l!l
50
MC/DC0%0/1
$self->{"exit_message"} // "MCP server process has exited"
$self->{"exit_message"}
Truth table50%1/2
A
A= $self->{"exit_message"}
Aresult
11
00
185 }
186  
187 # resolve_on_notification names the notification a server answers a request
188 # with in place of a response - how subscriptions/listen is answered. This
189 # transport cannot settle a request from a notification: the answer would
190 # arrive at on_notification like any other, leaving the request waiting for
191 # a response the server is not going to send. Refused on the spot rather
192 # than left to hang, and nothing is written: a request that went out anyway
193 # would open a subscription on the server that nothing here could stop.
194 86 ▶ if (defined $options{resolve_on_notification}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options{"resolve_on_notification"}) 1 85 86
195 1 return Future->fail("MCP subscriptions/listen is not usable over the stdio "
196 . "transport: the transport cannot settle a request from a notification "
197 . "(resolve_on_notification)");
198 }
199  
200 85 my $id = ++$self->{next_id};
201 85 ▶ my $request = {
Branch: 1 branch
BranchTrueFalseTotal
defined $params ? : 57 28 85
202 jsonrpc => '2.0',
203 id => $id,
204 method => $method,
205 defined $params ? ( params => $params ) : (),
206 };
207  
208 85 my $json_line = $self->{json}->encode($request) . "\n";
209 85 $self->{process}->stdin->write($json_line);
210  
211 85 my $future = $self->loop->new_future;
212 85 $self->{pending}{$id} = $future;
213  
214 # The pending table holds the future and the future holds this callback, so
215 # the callback must not hold the transport: that closes a reference cycle no
216 # refcount ever breaks. Future drops its on_cancel list as soon as a future
217 # is marked ready, so a request answered by the server, or failed by
218 # _on_finish, never reaches this code.
219 85 weaken( my $weak_self = $self );
220 4 ▶ $future->on_cancel(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
221 4 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 4 0 4
222 4 delete $self->{pending}{$id};
223 4 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 1 3 4
224 3 $self->send_notification('notifications/cancelled', { requestId => $id });
225 3 return;
226 85 });
227  
228 # The loop holds the timer until it fires, and the request holds it to stop
229 # it the moment the request is settled any other way - answered, failed by
230 # the exit, cancelled - so a finished request leaves no timer behind. The
231 # timer holds the transport weakly, for the same reason as on_cancel above.
232 85 my $timeout = $self->{timeout};
233 85 ▶ if (defined $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timeout) 11 74 85
234 5 ▶ my $timer = $self->loop->delay_future(after => $timeout)->on_done(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
235 5 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 5 0 5
236 5 $self->_time_out($id, $method, $timeout);
237 11 });
238 11 ▶ $future->on_ready(sub { $timer->cancel unless $timer->is_ready });
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless $timer->is_ready 6 5 11
239 }
240  
241 85 return $future;
242 }
243  
244 # Private: a request whose timeout ran out before its answer arrived. Cancelled
245 # the way a caller's ->cancel cancels it - the entry dropped, so a late answer
246 # lands on nothing, and the server told unless it is already going - but
247 # failed rather than cancelled, so the caller learns why.
248 5 ▶sub _time_out {
Subroutine _time_out: called CC=3 SCAR=11.3
249 5 my ( $self, $id, $method, $timeout ) = @_;
250 5 ▶ my $future = delete $self->{pending}{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $future = delete $self->{"pending"}{$id} or return 5 0 5
251 $self->send_notification('notifications/cancelled', {
252 requestId => $id,
253 reason => 'timed out after '.$timeout.'s',
254 5 ▶ }) unless $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"closed"} 5 0 5
255 5 $future->fail('MCP stdio request '.$method.' timed out after '.$timeout.'s', 'timeout');
256 5 return;
257 }
258  
259  
260 19 ▶sub send_notification {
Subroutine send_notification: called CC=4 SCAR=15.0
Pod documented
261 19 my ( $self, $method, $params ) = @_;
262  
263 19 ▶ if ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"closed"}) 0 19 19
264 0 ▶ return Future->fail($self->{exit_message} // "MCP server process has exited");
Condition0%0/2
$self->{"exit_message"} // "MCP server process has exited"
l!l
00
MC/DC0%0/1
$self->{"exit_message"} // "MCP server process has exited"
$self->{"exit_message"}
Truth table0%0/2
A
A= $self->{"exit_message"}
Aresult
11
00
265 }
266  
267 19 ▶ my $request = {
Branch: 1 branch
BranchTrueFalseTotal
defined $params ? : 8 11 19
268 jsonrpc => '2.0',
269 method => $method,
270 defined $params ? ( params => $params ) : (),
271 };
272  
273 19 my $json_line = $self->{json}->encode($request) . "\n";
274 19 $self->{process}->stdin->write($json_line);
275  
276 19 return Future->done;
277 }
278  
279  
280 # Private: how long close waits for the subprocess after closing its stdin
281 # before sending SIGTERM, and again after that before SIGKILL.
282 5 my $CLOSE_GRACE = 2;
283  
284 30 ▶sub close {
Subroutine close: called CC=5 SCAR=17.6
Pod documented
285 30 my ( $self ) = @_;
286 30 ▶ return $self->{close_future} // Future->done if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 30 30
Condition0%0/3
$self->{"close_future"} // "Future"->done
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"close_future"} // "Future"->done
$self->{"close_future"} "Future"->done
Truth table0%0/3
A // B
A= $self->{"close_future"}B= "Future"->done
ABresult
1X1
011
000
287  
288 30 $self->{closed} = 1;
289  
290 30 ▶ if ($self->{process} && $self->{process}->is_running) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"process"} and $self->{"process"}->is_running) 30 0 30
Condition33%1/3
$self->{"process"} and $self->{"process"}->is_running
!ll&&!rl&&r
0030
MC/DC0%0/2
$self->{"process"} and $self->{"process"}->is_running
$self->{"process"} $self->{"process"}->is_running
Truth table33%1/3
A and B
A= $self->{"process"}B= $self->{"process"}->is_running
ABresult
0X0
100
111
291 30 my $future = $self->loop->new_future;
292 30 $self->{close_future} = $future;
293  
294 # The order the MCP stdio binding gives: close the server's stdin, which
295 # is how a server learns that its client is done, and only signal one that
296 # is still there after a grace period - first SIGTERM, then SIGKILL.
297 # Held on the transport, and cancelled by _on_finish, so the signals are
298 # never sent to a process that already exited on its own.
299 30 weaken( my $weak_self = $self );
300 30 $self->{process}->stdin->close_when_empty;
301 $self->{close_escalation} = $self->loop->delay_future(after => $CLOSE_GRACE)
302 1 ▶ ->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
303 1 ▶ my $self = $weak_self or return Future->done;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return "Future"->done 1 0 1
304 1 $self->_signal('TERM');
305 1 return $self->loop->delay_future(after => $CLOSE_GRACE);
306 })
307 1 ▶ ->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
308 1 ▶ my $self = $weak_self or return Future->done;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return "Future"->done 1 0 1
309 1 $self->_signal('KILL');
310 1 return Future->done;
311 30 });
312  
313 30 return $future;
314 }
315  
316 0 return Future->done;
317 }
318  
319 # Private: a signal to the subprocess, if it is still there to receive one.
320 2 ▶sub _signal {
Subroutine _signal: called CC=3 SCAR=12.5
321 2 my ( $self, $signal ) = @_;
322 2 my $process = $self->{process};
323 2 ▶ $process->kill($signal) if $process && $process->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $process and $process->is_running 2 0 2
Condition33%1/3
$process and $process->is_running
!ll&&!rl&&r
002
MC/DC0%0/2
$process and $process->is_running
$process $process->is_running
Truth table33%1/3
A and B
A= $processB= $process->is_running
ABresult
0X0
100
111
324 }
325  
326  
327 4 ▶sub is_alive { !$_[0]->{closed} }
Subroutine is_alive: called CC=1 SCAR=0.0
Pod documented
328  
329  
330 16 ▶sub mirrors_header_params { 0 }
Subroutine mirrors_header_params: called CC=1 SCAR=0.0
Pod documented
331  
332  
333  
334 103 ▶sub _on_stdout_read {
Subroutine _on_stdout_read: called CC=11 SCAR=24.2
335 103 my ( $self, $buffref, $eof ) = @_;
336 103 $self->{buffer} .= $$buffref;
337 103 $$buffref = '';
338  
339 103 ▶ while ($self->{buffer} =~ s/^(.*?)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"buffer"} =~ s/^(.*?)\n//) 86 103 189
340 86 my $line = $1;
341 86 $line =~ s/\r$//;
342 86 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 86 86
343  
344 86 my $response = eval { $self->{json}->decode($line) };
345 86 ▶ next unless $response && ref $response eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $response and ref $response eq "HASH" 0 86 86
Condition33%1/3
$response and ref $response eq "HASH"
!ll&&!rl&&r
0086
MC/DC0%0/2
$response and ref $response eq "HASH"
$response ref $response eq "HASH"
Truth table33%1/3
A and B
A= $responseB= ref $response eq "HASH"
ABresult
0X0
100
111
346  
347 # A line that answers no request is a notification the server sent of its
348 # own accord, and goes to the event rather than the pending table: the
349 # notifications/progress of a running tools/call is only worth anything
350 # while the call is still running. A line with neither an id nor a method
351 # is no JSON-RPC message this client can place at all, and is dropped.
352 86 my $id = $response->{id};
353 86 ▶ if (!defined $id) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 8 78 86
354 8 ▶ next unless defined $response->{method};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $response->{"method"} 2 6 8
355 6 $self->maybe_invoke_event(on_notification => $response);
356 6 next;
357 }
358  
359 # An id with neither a result nor an error is a server-initiated request,
360 # which on_request may answer. It has to be recognised before the lookup
361 # below rather than after it: the server numbers its own requests, nothing
362 # keeps those numbers apart from ours, and a collision would otherwise
363 # answer a live request of ours with nothing.
364 78 ▶ unless (exists $response->{result} || exists $response->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $response->{"result"} or exists $response->{"error"}) 4 74 78
Condition100%3/3
exists $response->{"result"} or exists $response->{"error"}
l!l&&r!l&&!r
58164
MC/DC100%2/2
exists $response->{"result"} or exists $response->{"error"}
exists $response->{"result"} exists $response->{"error"}
Truth table100%3/3
A or B
A= exists $response->{"result"}B= exists $response->{"error"}
ABresult
1X1
011
000
365 4 ▶ $self->_on_server_request($response) if defined $response->{method};
Branch: 1 branch
BranchTrueFalseTotal
if defined $response->{"method"} 4 0 4
366 4 next;
367 }
368  
369 74 my $future = delete $self->{pending}{$id};
370 74 ▶ next unless $future;
Branch: 1 branch
BranchTrueFalseTotal
unless $future 3 71 74
371  
372 71 $self->_settle_response($future, $response);
373 }
374 }
375  
376 # Private: the class that reads the error of a response, named once.
377 20 ▶sub _jsonrpc_class { 'Net::Async::MCP::JSONRPC' }
Subroutine _jsonrpc_class: called CC=1 SCAR=0.0
378  
379 # Private: the answer to a request of ours, read without trusting its shape -
380 # the subprocess is whatever the host was told to run. Every branch settles
381 # the future, which has already left the pending table: one that died here
382 # would take the loop down and leave the request waiting forever.
383 71 ▶sub _settle_response {
Subroutine _settle_response: called CC=4 SCAR=13.9
384 71 my ( $self, $future, $response ) = @_;
385  
386 # The raw JSON-RPC error object travels with the message as the details of
387 # a failure in category "mcp", so a caller can read the code and any
388 # error->{data} the server sent instead of parsing the message for them. An
389 # error in any other shape - a string, a number, false - still says the
390 # request failed, with the text it carries and no category.
391 71 ▶ if (defined(my $err = $response->{error})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $err = $response->{"error"})) 15 56 71
392 15 my @failure = $self->_jsonrpc_class->error_failure($response);
393 15 ▶ return $future->fail(@failure) if @failure;
Branch: 1 branch
BranchTrueFalseTotal
if @failure 10 5 15
394 5 return $future->fail('MCP stdio error response: '.$self->_jsonrpc_class->error_text($err));
395 }
396  
397 # "error": null sits next to every result in JSON-RPC 1.0 and says nothing
398 # there. Without a result it answers nothing, and an undef handed out as the
399 # result would be a success the server never reported.
400 56 ▶ return $future->done($response->{result}) if exists $response->{result};
Branch: 1 branch
BranchTrueFalseTotal
if exists $response->{"result"} 55 1 56
401 1 return $future->fail('MCP stdio invalid response: a null error and no result');
402 }
403  
404 # Private: a request the server sent, answered with whatever on_request
405 # returns, if anything.
406 4 ▶sub _on_server_request {
Subroutine _on_server_request: called CC=7 SCAR=20.2
407 4 my ( $self, $request ) = @_;
408 4 ▶ return unless $self->can_event('on_request');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can_event("on_request") 2 2 4
409  
410 2 my $answer = $self->invoke_event(on_request => $request);
411 return unless ref $answer eq 'HASH'
412 2 ▶ && ( exists $answer->{result} || exists $answer->{error} );
Branch: 1 branch
BranchTrueFalseTotal
unless ref $answer eq "HASH" and exists $answer->{"result"} || exists $answer->{"error"} 0 2 2
Condition50%3/6
ref $answer eq "HASH" and exists $answer->{"result"} || exists $answer->{"error"}
!ll&&!rl&&r
002
exists $answer->{"result"} or exists $answer->{"error"}
l!l&&r!l&&!r
110
MC/DC0%0/3
ref $answer eq "HASH" and exists $answer->{"result"} || exists $answer->{"error"}
ref $answer eq "HASH" exists $answer->{"result"} exists $answer->{"error"}
Truth table50%2/4
A and B or C
A= ref $answer eq "HASH"B= exists $answer->{"result"}C= exists $answer->{"error"}
ABCresult
0XX0
1000
11X1
1011
413 2 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 2 2
414  
415 my $response = {
416 jsonrpc => '2.0',
417 id => $request->{id},
418 exists $answer->{error}
419 ? ( error => $answer->{error} )
420 2 ▶ : ( result => $answer->{result} ),
Branch: 1 branch
BranchTrueFalseTotal
exists $answer->{'error'} ? : 1 1 2
421 };
422 2 $self->{process}->stdin->write($self->{json}->encode($response) . "\n");
423 2 return;
424 }
425  
426 # Private: the server's stderr, split into lines for on_stderr and the tail.
427 45 ▶sub _on_stderr_read {
Subroutine _on_stderr_read: called CC=8 SCAR=21.0
428 45 my ( $self, $buffref, $eof ) = @_;
429 45 $self->{stderr_buffer} .= $$buffref;
430 45 $$buffref = '';
431  
432 45 my @lines;
433 45 ▶ while ($self->{stderr_buffer} =~ s/^(.*?)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stderr_buffer"} =~ s/^(.*?)\n//) 38 45 83
434 38 push @lines, $1;
435 }
436 # The last line of a server that exits without a final newline is a line
437 # all the same, and often the one that says why it exited.
438 push @lines, delete $self->{stderr_buffer}
439 45 ▶ if $eof && length $self->{stderr_buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $eof and length $self->{"stderr_buffer"} 0 45 45
Condition66%2/3
$eof and length $self->{"stderr_buffer"}
!ll&&!rl&&r
14310
MC/DC0%0/2
$eof and length $self->{"stderr_buffer"}
$eof length $self->{"stderr_buffer"}
Truth table66%2/3
A and B
A= $eofB= length $self->{"stderr_buffer"}
ABresult
0X0
100
111
440 45 ▶ $self->{stderr_buffer} //= '';
Condition50%1/2
$self->{"stderr_buffer"} //= ""
l!l
450
MC/DC0%0/1
$self->{"stderr_buffer"} //= ""
$self->{"stderr_buffer"}
Truth table50%1/2
A
A= $self->{"stderr_buffer"}
Aresult
11
00
441  
442 45 for my $line (@lines) {
443 38 $line =~ s/\r\z//;
444 38 $line = decode('UTF-8', $line);
445  
446 38 ▶ if ($line =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\S/) 38 0 38
447 38 my $tail = $self->{stderr_tail};
448 38 push @$tail, $line;
449 38 ▶ shift @$tail while @$tail > $STDERR_TAIL_LINES;
Branch: 1 branch
BranchTrueFalseTotal
@$tail > $STDERR_TAIL_LINES and do { shift @$tail } 6 38 44
450 }
451  
452 38 $self->maybe_invoke_event(on_stderr => $line);
453 }
454 }
455  
456 32 ▶sub stderr_tail { @{ $_[0]->{stderr_tail} } }
Subroutine stderr_tail: called CC=1 SCAR=0.0
Pod documented
457  
458  
459 31 ▶sub _on_finish {
Subroutine _on_finish: called CC=7 SCAR=19.8
460 31 my ( $self, $exitcode, $reason ) = @_;
461 31 $self->{closed} = 1;
462  
463 31 ▶ if (my $escalation = delete $self->{close_escalation}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $escalation = delete $self->{"close_escalation"}) 29 2 31
464 29 $escalation->cancel;
465 }
466  
467 31 my $message = $self->{exit_message} = $self->_exit_message($exitcode, $reason);
468 31 for my $id (keys %{$self->{pending}}) {
469 4 my $future = delete $self->{pending}{$id};
470 4 ▶ $future->fail($message)
Branch: 1 branch
BranchTrueFalseTotal
if $future and not $future->is_ready 4 0 4
Condition33%1/3
$future and not $future->is_ready
!ll&&!rl&&r
004
MC/DC0%0/2
$future and not $future->is_ready
$future not $future->is_ready
Truth table33%1/3
A and not(B)
A= $futureB= not $future->is_ready
ABresult
0X0
100
111
471 if $future && !$future->is_ready;
472 }
473  
474 31 ▶ if ($self->{close_future} && !$self->{close_future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"close_future"} and not $self->{"close_future"}->is_ready) 29 2 31
Condition66%2/3
$self->{"close_future"} and not $self->{"close_future"}->is_ready
!ll&&!rl&&r
2029
MC/DC50%1/2
$self->{"close_future"} and not $self->{"close_future"}->is_ready
$self->{"close_future"} not $self->{"close_future"}->is_ready
Truth table66%2/3
A and not(B)
A= $self->{"close_future"}B= not $self->{"close_future"}->is_ready
ABresult
0X0
100
111
475 29 $self->{close_future}->done;
476 }
477 }
478  
479 # Private: why the subprocess can no longer answer, on one line: the reason it
480 # never ran, or its exit status, followed by what it last wrote to stderr.
481 31 ▶sub _exit_message {
Subroutine _exit_message: called CC=4 SCAR=13.9
482 31 my ( $self, $exitcode, $reason ) = @_;
483  
484 31 ▶ my $message = $reason // 'MCP server process exited ('
Branch: 1 branch
BranchTrueFalseTotal
$exitcode & 127 ? : 1 29 30
Condition100%2/2
$reason // 'MCP server process exited (' . ($exitcode & 127 ? 'signal ' . ($exitcode & 127) : 'code ' . ($exitcode >> 8)) . ')'
l!l
130
MC/DC100%1/1
$reason // 'MCP server process exited (' . ($exitcode & 127 ? 'signal ' . ($exitcode & 127) : 'code ' . ($exitcode >> 8)) . ')'
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
485 . ( $exitcode & 127 ? 'signal ' . ( $exitcode & 127 ) : 'code ' . ( $exitcode >> 8 ) )
486 . ')';
487  
488 31 my @tail = $self->stderr_tail;
489 31 ▶ $message .= '; stderr: ' . join(' | ', @tail) if @tail;
Branch: 1 branch
BranchTrueFalseTotal
if @tail 13 18 31
490 31 return $message;
491 }
492  
493  
494 5 1;
495  
496 __END__
« blib/lib/Net/Async/MCP/Transport/HTTP.pm ↑ Summary blib/lib/Net/Async/MCP/Transport/InProcess.pm »