MCP/Transport/Stdio.pm

filter: Statementstmt 97.6% 123 / 126 Branchbran 73.0% 38 / 52 Conditioncond 47.6% 10 / 21 MC/DCmcdc 21.4% 3 / 14 Subroutinesub 100% 22 / 22 Podpod 100% 6 / 6 totaltotal 83.8% 202 / 241 CC 36 SCAR 16.2
CC
36
Cov
86%
_on_stdout_read
11.1
_on_finish
7.3
_remove_from_loop
6.4
CRAP 5.1
« MCP.pm ↑ Summary MCP/Transport/InProcess.pm »
1 package Net::Async::MCP::Transport::Stdio;
2 # ABSTRACT: Stdio MCP transport via subprocess JSON-RPC
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 3 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use Scalar::Util qw( weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 9 ▶sub _init {
Subroutine _init: called CC=2 SCAR=7.0
14 9 my ( $self, $params ) = @_;
15 $self->{command} = delete $params->{command}
16 9 ▶ or croak "command is required";
Branch: 1 branch
BranchTrueFalseTotal
$self->{"command"} = delete $params->{"command"} or croak("command is required") 9 0 9
17 9 $self->{pending} = {};
18 9 $self->{next_id} = 0;
19 9 $self->{buffer} = '';
20 9 $self->{closed} = 0;
21 9 $self->{json} = JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
22 9 $self->SUPER::_init($params);
23 }
24  
25 11 ▶sub configure {
Subroutine configure: called CC=3 SCAR=11.3
Pod documented
26 11 my ( $self, %params ) = @_;
27 11 ▶ if (exists $params{command}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"command"}) 0 11 11
28 0 $self->{command} = delete $params{command};
29 }
30 $self->{on_notification} = delete $params{on_notification}
31 11 ▶ if exists $params{on_notification};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{"on_notification"} 6 5 11
32 11 $self->SUPER::configure(%params);
33 }
34  
35 9 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=1 SCAR=0.0
36 9 my ( $self, $loop ) = @_;
37 9 $self->SUPER::_add_to_loop($loop);
38  
39 9 require IO::Async::Process;
40  
41 # These callbacks end up on the process, and on the child streams the process
42 # owns, while the transport owns the process - so capturing the transport
43 # strongly here would close a cycle no refcount ever breaks, and the transport
44 # would outlive its own client. Weakening them costs nothing: as long as
45 # either callback can still fire, the loop holds the transport for us. The
46 # loop keeps its notifiers alive strongly, and taking the transport out of the
47 # loop takes the process out with it, which unwatches the child and silences
48 # both callbacks. So the weak reference is never undef where it matters; the
49 # guards below are for the DESTROY-ordering case only.
50 9 weaken( my $weak_self = $self );
51  
52 my $process = IO::Async::Process->new(
53 command => $self->{command},
54 stdin => { via => 'pipe_write' },
55 stdout => {
56 28 ▶ on_read => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
57 28 my ( $stream, $buffref, $eof ) = @_;
58 28 ▶ my $self = $weak_self or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 0 28 0 28
59 28 $self->_on_stdout_read($buffref, $eof);
60 28 return 0;
61 },
62 },
63 stderr => {
64 8 ▶ on_read => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
65 8 my ( $stream, $buffref, $eof ) = @_;
66 8 $$buffref = '';
67 8 return 0;
68 },
69 },
70 8 ▶ on_finish => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
71 8 my ( $proc, $exitcode ) = @_;
72 8 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 8 0 8
73 8 $self->_on_finish($exitcode);
74 },
75 9 );
76  
77 9 $self->{process} = $process;
78 9 $self->add_child($process);
79 }
80  
81 7 ▶sub _remove_from_loop {
Subroutine _remove_from_loop: called CC=6 SCAR=18.6
82 7 my ( $self, $loop ) = @_;
83  
84 # Leaving the loop takes the process along, it being a child of this
85 # transport, and with it the watches on the child's streams that _on_finish
86 # waits for. So _on_finish will not run again, and everything it would have
87 # settled has to be settled here instead, or it stays pending for the rest
88 # of the program: the requests still waiting for an answer, and a close
89 # still waiting for the exit.
90 #
91 # Both are failed rather than completed, because completing either would be
92 # a claim this transport cannot make. Nothing here saw a response go missing
93 # or a process die; what it knows is that neither can reach it any more. The
94 # two messages differ in what was lost so a caller holding both can tell
95 # them apart.
96 #
97 # Same shape as _on_finish, and for the same reasons: the keys are taken
98 # before the loop, so a handler that touches the pending table as its future
99 # fails cannot disturb the iteration, and every future is deleted as it is
100 # settled, so neither path can reach one the other already answered.
101 7 for my $id (keys %{$self->{pending}}) {
102 1 my $future = delete $self->{pending}{$id};
103 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
104 if $future && !$future->is_ready;
105 }
106  
107 7 ▶ 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 6 7
Condition66%2/3
$self->{"close_future"} and not $self->{"close_future"}->is_ready
!ll&&!rl&&r
061
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
108 ( delete $self->{close_future} )
109 1 ->fail("MCP server process left the loop before it exited");
110 }
111  
112 7 $self->SUPER::_remove_from_loop($loop);
113 }
114  
115 26 ▶sub send_request {
Subroutine send_request: called CC=4 SCAR=13.9
Pod documented
116 26 my ( $self, $method, $params, %options ) = @_;
117  
118 26 ▶ if ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"closed"}) 1 25 26
119 1 return Future->fail("MCP server process has exited");
120 }
121  
122 # resolve_on_notification names the notification a server answers a request
123 # with in place of a response - how subscriptions/listen is answered. This
124 # transport cannot settle a request from a notification: the answer would
125 # arrive at on_notification like any other, leaving the request waiting for
126 # a response the server is not going to send. Refused on the spot rather
127 # than left to hang, and nothing is written: a request that went out anyway
128 # would open a subscription on the server that nothing here could stop.
129 25 ▶ if (defined $options{resolve_on_notification}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options{"resolve_on_notification"}) 1 24 25
130 1 return Future->fail("MCP subscriptions/listen is not usable over the stdio "
131 . "transport: the transport cannot settle a request from a notification "
132 . "(resolve_on_notification)");
133 }
134  
135 24 my $id = ++$self->{next_id};
136 24 ▶ my $request = {
Branch: 1 branch
BranchTrueFalseTotal
defined $params ? : 16 8 24
137 jsonrpc => '2.0',
138 id => $id,
139 method => $method,
140 defined $params ? ( params => $params ) : (),
141 };
142  
143 24 my $json_line = $self->{json}->encode($request) . "\n";
144 24 $self->{process}->stdin->write($json_line);
145  
146 24 my $future = $self->loop->new_future;
147 24 $self->{pending}{$id} = $future;
148  
149 # The pending table holds the future and the future holds this callback, so
150 # the callback must not hold the transport: that closes a reference cycle no
151 # refcount ever breaks. Future drops its on_cancel list as soon as a future
152 # is marked ready, so a request answered by the server, or failed by
153 # _on_finish, never reaches this code.
154 24 weaken( my $weak_self = $self );
155 2 ▶ $future->on_cancel(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
156 2 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 2 0 2
157 2 delete $self->{pending}{$id};
158 2 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 1 1 2
159 1 $self->send_notification('notifications/cancelled', { requestId => $id });
160 1 return;
161 24 });
162  
163 24 return $future;
164 }
165  
166  
167 1 ▶sub send_notification {
Subroutine send_notification: called CC=3 SCAR=11.6
Pod documented
168 1 my ( $self, $method, $params ) = @_;
169  
170 1 ▶ if ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"closed"}) 0 1 1
171 0 return Future->fail("MCP server process has exited");
172 }
173  
174 1 ▶ my $request = {
Branch: 1 branch
BranchTrueFalseTotal
defined $params ? : 1 0 1
175 jsonrpc => '2.0',
176 method => $method,
177 defined $params ? ( params => $params ) : (),
178 };
179  
180 1 my $json_line = $self->{json}->encode($request) . "\n";
181 1 $self->{process}->stdin->write($json_line);
182  
183 1 return Future->done;
184 }
185  
186  
187 9 ▶sub close {
Subroutine close: called CC=4 SCAR=15.0
Pod documented
188 9 my ( $self ) = @_;
189 9 ▶ return Future->done if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 9 9
190  
191 9 $self->{closed} = 1;
192  
193 9 ▶ if ($self->{process} && $self->{process}->is_running) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"process"} and $self->{"process"}->is_running) 9 0 9
Condition33%1/3
$self->{"process"} and $self->{"process"}->is_running
!ll&&!rl&&r
009
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
194 9 my $future = $self->loop->new_future;
195 9 $self->{close_future} = $future;
196 9 $self->{process}->kill('TERM');
197 9 return $future;
198 }
199  
200 0 return Future->done;
201 }
202  
203  
204 2 ▶sub is_alive { !$_[0]->{closed} }
Subroutine is_alive: called CC=1 SCAR=0.0
Pod documented
205  
206  
207 9 ▶sub mirrors_header_params { 0 }
Subroutine mirrors_header_params: called CC=1 SCAR=0.0
Pod documented
208  
209  
210  
211 28 ▶sub _on_stdout_read {
Subroutine _on_stdout_read: called CC=11 SCAR=24.1
212 28 my ( $self, $buffref, $eof ) = @_;
213 28 $self->{buffer} .= $$buffref;
214 28 $$buffref = '';
215  
216 28 ▶ while ($self->{buffer} =~ s/^(.*?)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"buffer"} =~ s/^(.*?)\n//) 30 28 58
217 30 my $line = $1;
218 30 $line =~ s/\r$//;
219 30 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 30 30
220  
221 30 my $response = eval { $self->{json}->decode($line) };
222 30 ▶ next unless $response && ref $response eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $response and ref $response eq "HASH" 0 30 30
Condition33%1/3
$response and ref $response eq "HASH"
!ll&&!rl&&r
0030
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
223  
224 # A line that answers no request is a notification the server sent of its
225 # own accord, and goes to the event rather than the pending table: the
226 # notifications/progress of a running tools/call is only worth anything
227 # while the call is still running. A line with neither an id nor a method
228 # is no JSON-RPC message this client can place at all, and is dropped.
229 30 my $id = $response->{id};
230 30 ▶ if (!defined $id) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 7 23 30
231 7 ▶ next unless defined $response->{method};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $response->{"method"} 2 5 7
232 5 $self->maybe_invoke_event(on_notification => $response);
233 5 next;
234 }
235  
236 # An id with neither a result nor an error is a server-initiated request,
237 # which this client does not answer. It has to be recognised before the
238 # lookup below rather than after it: the server numbers its own requests,
239 # nothing keeps those numbers apart from ours, and a collision would
240 # otherwise answer a live request of ours with nothing.
241 23 ▶ next unless exists $response->{result} || exists $response->{error};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $response->{"result"} or exists $response->{"error"} 2 21 23
Condition100%3/3
exists $response->{"result"} or exists $response->{"error"}
l!l&&r!l&&!r
2012
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
242  
243 21 my $future = delete $self->{pending}{$id};
244 21 ▶ next unless $future;
Branch: 1 branch
BranchTrueFalseTotal
unless $future 1 20 21
245  
246 # The raw JSON-RPC error object travels with the message as the details of
247 # a failure in category "mcp", so a caller can read the code and any
248 # error->{data} the server sent instead of parsing the message for them.
249 20 ▶ if (my $err = $response->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $response->{'error'}) { } 1 19 20
250 1 $future->fail("MCP error $err->{code}: $err->{message}", mcp => $err);
251 }
252 else {
253 19 $future->done($response->{result});
254 }
255 }
256 }
257  
258 8 ▶sub _on_finish {
Subroutine _on_finish: called CC=6 SCAR=19.9
259 8 my ( $self, $exitcode ) = @_;
260 8 $self->{closed} = 1;
261  
262 8 for my $id (keys %{$self->{pending}}) {
263 1 my $future = delete $self->{pending}{$id};
264 1 ▶ $future->fail("MCP server process exited (code $exitcode)")
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
265 if $future && !$future->is_ready;
266 }
267  
268 8 ▶ if ($self->{close_future} && !$self->{close_future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"close_future"} and not $self->{"close_future"}->is_ready) 8 0 8
Condition33%1/3
$self->{"close_future"} and not $self->{"close_future"}->is_ready
!ll&&!rl&&r
008
MC/DC0%0/2
$self->{"close_future"} and not $self->{"close_future"}->is_ready
$self->{"close_future"} not $self->{"close_future"}->is_ready
Truth table33%1/3
A and not(B)
A= $self->{"close_future"}B= not $self->{"close_future"}->is_ready
ABresult
0X0
100
111
269 8 $self->{close_future}->done;
270 }
271 }
272  
273  
274 3 1;
275  
276 __END__
« MCP.pm ↑ Summary MCP/Transport/InProcess.pm »