blib/lib/AnyEvent/MCP/Client/JSONL.pm

filter: Statementstmt 95.1% 78 / 82 Branchbran 54.5% 24 / 44 Conditioncond 52.1% 12 / 23 MC/DCmcdc 21.4% 3 / 14 Subroutinesub 82.3% 14 / 17 Podpod 100% 1 / 1 totaltotal 72.9% 132 / 181 CC 32 SCAR 19.1
CC
32
Cov
77%
attach
16.6
_open
8.1
_shutdown
6.1
CRAP 6.8
« blib/lib/AnyEvent/MCP/Workdirs.pm ↑ Summary blib/lib/AnyEvent/MCP/Helper.pm »
1 =head1 NAME
2  
3 AnyEvent::MCP::Client::JSONL - MCP byte streams and stdio subprocesses
4  
5 =head1 SYNOPSIS
6  
7 use AnyEvent::MCP::Client::JSONL;
8  
9 my $client = AnyEvent::MCP::Client::JSONL->new (
10 command => [$program, @args],
11 env => { PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "stdio" },
12 );
13  
14 =head1 DESCRIPTION
15  
16 Use this transport when the MCP server is a subprocess or an already
17 connected byte stream. It reads one JSON-RPC message per line, so stdout
18 on a conventional stdio transport must contain protocol messages only.
19 The C<command> mode here connects the child's stdin and stdout to a
20 socketpair; diagnostic output belongs on stderr. A stray banner or log
21 message on the protocol stream can break the connection.
22  
23 An argument array executes the program directly; a command string runs
24 through a shell. Prefer the array form when no shell syntax is needed.
25 The process starts on the first connection, not when the client object
26 is constructed.
27  
28 =head1 FIRST CALL
29  
30 To invoke a bundled server as a subprocess:
31  
32 use AnyEvent;
33 use AnyEvent::MCP::Client::JSONL;
34  
35 my $client = AnyEvent::MCP::Client::JSONL->new (
36 command => ["mcp-fs", "--stdio", "/home/alice/src/project"],
37 );
38 my $cv = AE::cv;
39 $client->call (workdirs => {}, sub { $cv->send (@_) });
40 my ($success, $result) = $cv->recv;
41 $success or die "$result->{message}\n";
42 !$result->{isError} or die "$result->{content}[0]{text}\n";
43  
44 This assumes the project exists and C<mcp-fs> is installed on C<PATH>.
45 The subprocess is created on first use and reaped when it exits.
46 The caller owns the client and its event loop; callbacks also distinguish
47 protocol success from tool errors. See
48 L<AnyEvent::MCP::Server::Simple/TUTORIAL> for a complete echo server
49 and a matching client example.
50  
51 =head1 METHODS
52  
53 =over
54  
55 =item $client = AnyEvent::MCP::Client::JSONL->new (%config)
56  
57 Accepts the common L<AnyEvent::MCP::Client> options and these transport
58 options:
59  
60 =over
61  
62 =item command => [$program, $arg...]
63  
64 =item command => $shell_command
65  
66 Argument array for direct execution, or a string run through C</bin/sh -c>.
67 The child inherits stderr. No command runs until connecting.
68 Omit this option when using C<attach> instead.
69  
70 =item env => { %environment }
71  
72 Child environment overrides. Unspecified variables are inherited from
73 the parent; the parent environment is unchanged.
74  
75 =item handle => { %handle }
76  
77 L<AnyEvent::Handle> options. The filehandle and read/error/EOF callbacks
78 are managed by this transport.
79  
80 =item max_size => $bytes
81  
82 Bounds a buffered incoming JSON line, defaulting to 8 MiB.
83  
84 =back
85  
86 C<name> does not load transport defaults. The library does not infer a
87 subprocess command or environment.
88  
89 =item $client->attach ($fh_in, $fh_out)
90  
91 Uses existing handles instead of a command. C<$fh_in> may also be an
92 L<AnyEvent::Handle>, whose buffered input is preserved. C<$fh_out> defaults to C<$fh_in>
93 for a bidirectional socket. The client takes ownership. Attach before sending
94 requests. Closing an attached connection requires attaching new handles before
95 reconnecting.
96  
97 Closing a subprocess connection sends SIGTERM and keeps its child watcher
98 alive until the child has been reaped. It does not restart an outstanding call.
99 An accepted multibroker idle shutdown is the exception: its child can exit
100 and perform cleanup without receiving SIGTERM.
101  
102 =back
103  
104 =cut
105  
106 package AnyEvent::MCP::Client::JSONL;
107  
108 33 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
109 33 ▶use parent "AnyEvent::MCP::Client";
Subroutine BEGIN: called CC=1 SCAR=0.0
110 33 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
111 33 ▶use AnyEvent::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
112 33 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
113 33 ▶use Scalar::Util qw(weaken blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
114  
115 49 ▶sub attach {
Subroutine attach: called CC=8 SCAR=28.1
Pod documented
116 49 my ($self, $fh_in, $fh_out) = @_;
117  
118 49 ▶ $self->close if $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} 0 49 49
119 49 weaken $self;
120 $self->{read_handle} = blessed $fh_in && $fh_in->isa ("AnyEvent::Handle")
121 49 ▶ ? $fh_in : AnyEvent::Handle->new (%{$self->{handle} || {}}, fh => $fh_in);
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($fh_in) && $fh_in->isa('AnyEvent::Handle') ? : 0 49 49
Condition40%2/5
builtin::blessed($fh_in) and $fh_in->isa("AnyEvent::Handle")
!ll&&!rl&&r
4900
$self->{'handle'} || {}
l!l
049
MC/DC0%0/2
builtin::blessed($fh_in) and $fh_in->isa("AnyEvent::Handle")
builtin::blessed($fh_in) $fh_in->isa("AnyEvent::Handle")
MC/DC0%0/1
$self->{'handle'} || {}
$self->{'handle'}
Truth table33%1/3
A and B
A= builtin::blessed($fh_in)B= $fh_in->isa("AnyEvent::Handle")
ABresult
0X0
100
111
Truth table50%1/2
A
A= $self->{'handle'}
Aresult
11
00
122 49 ▶ $self->{read_handle}{rbuf_max} = $self->{max_size} || 8 * 1024 * 1024;
Condition50%1/2
$self->{'max_size'} || 8388608
l!l
049
MC/DC0%0/1
$self->{'max_size'} || 8388608
$self->{'max_size'}
Truth table50%1/2
A
A= $self->{'max_size'}
Aresult
11
00
123 49 $self->{read_handle}->on_read (undef);
124 49 ▶ $self->{read_handle}->on_error (sub { $self->close ($_[2]) if $self });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $self 1 0 1
125 0 ▶ $self->{read_handle}->on_eof (sub { $self->close ("MCP stream closed") if $self });
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
if $self 0 0 0
126 $self->{write_handle} = $fh_out ? AnyEvent::Handle->new (
127 0 ▶ %{$self->{handle} || {}},
Condition0%0/2
$self->{'handle'} || {}
l!l
00
MC/DC0%0/1
$self->{'handle'} || {}
$self->{'handle'}
Truth table0%0/2
A
A= $self->{'handle'}
Aresult
11
00
128 fh => $fh_out,
129 on_read => undef,
130 0 ▶ on_error => sub { $self->close ($_[2]) if $self },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $self 0 0 0
131 0 ▶ on_eof => sub { $self->close ("MCP output closed") if $self },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $self 0 0 0
132 49 ▶ ) : $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
$fh_out ? : 0 49 49
133 49 $self->_read;
134 }
135  
136 49 ▶sub _open {
Subroutine _open: called CC=8 SCAR=20.9
137 49 my ($self, $done) = @_;
138  
139 49 ▶ return $done->(1, undef) if $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} 4 45 49
140 return $done->(0, { transport => 1, message => "No command or attached stream" })
141 45 ▶ unless $self->{command};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"command"} 0 45 45
142  
143 45 my $ok = eval {
144 45 ▶ local %ENV = (%ENV, %{$self->{env} || {}});
Condition100%2/2
$self->{'env'} || {}
l!l
414
MC/DC100%1/1
$self->{'env'} || {}
$self->{'env'}
Truth table100%2/2
A
A= $self->{'env'}
Aresult
11
00
145 45 my ($parent, $child) = AnyEvent::Util::portable_socketpair;
146 45 ▶ die "Cannot create MCP socketpair: $!\n" unless defined $parent && defined $child;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $parent and defined $child 0 45 45
Condition33%1/3
defined $parent and defined $child
!ll&&!rl&&r
0045
MC/DC0%0/2
defined $parent and defined $child
defined $parent defined $child
Truth table33%1/3
A and B
A= defined $parentB= defined $child
ABresult
0X0
100
111
147  
148 45 my $pid;
149 my $cv = AnyEvent::Util::run_cmd (
150 45 ▶ ref $self->{command} eq "ARRAY" ? $self->{command} : ["/bin/sh", "-c", $self->{command}],
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'command'} eq 'ARRAY' ? : 27 18 45
151 "<" => $child, ">" => $child, '$$' => \$pid, close_all => 1,
152 );
153 45 close $child;
154 45 $self->{pid} = $pid;
155 45 $self->attach ($parent);
156  
157 45 weaken $self;
158 20 ▶ $cv->cb (sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
159 20 my $status = $_[0]->recv;
160 20 ▶ if ($self && $self->{pid} == $pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self and $self->{"pid"} == $pid) 1 19 20
Condition100%3/3
$self and $self->{"pid"} == $pid
!ll&&!rl&&r
8111
MC/DC100%2/2
$self and $self->{"pid"} == $pid
$self $self->{"pid"} == $pid
Truth table100%3/3
A and B
A= $selfB= $self->{"pid"} == $pid
ABresult
0X0
100
111
161 1 delete $self->{pid};
162 1 delete $self->{child};
163 1 $self->close ("MCP child exited (status $status)");
164 }
165 45 });
166 45 $self->{child} = $cv;
167 45 1
168 };
169 45 ▶ $done->($ok ? (1, undef) : (0, { transport => 1, message => "$@" }));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 45 0 45
170 }
171  
172 319 ▶sub _read {
Subroutine _read: called CC=1 SCAR=0.2
173 319 my ($self) = @_;
174  
175 319 weaken $self;
176  
177 270 ▶ $self->{read_handle}->push_read (line => sub {
Subroutine __ANON__: called CC=5 SCAR=17.5
178 270 my ($handle, $line) = @_;
179  
180 270 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 270 270
181 270 my $ok = eval {
182 270 $self->_receive (JSON::XS::decode_json $line);
183 270 1
184 };
185 270 ▶ return $self->close ("$@") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 270 270
186 270 ▶ $self->_read if $self->{read_handle} && !$handle->destroyed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} and not $handle->destroyed 270 0 270
Condition33%1/3
$self->{"read_handle"} and not $handle->destroyed
!ll&&!rl&&r
00270
MC/DC0%0/2
$self->{"read_handle"} and not $handle->destroyed
$self->{"read_handle"} not $handle->destroyed
Truth table33%1/3
A and not(B)
A= $self->{"read_handle"}B= not $handle->destroyed
ABresult
0X0
100
111
187 319 });
188 }
189  
190 282 ▶sub _send {
Subroutine _send: called CC=3 SCAR=11.2
191 282 my ($self, $message, $done) = @_;
192  
193 282 my $ok = eval {
194 282 ▶ my $handle = $self->{write_handle} or die "MCP stream is not connected\n";
Branch: 1 branch
BranchTrueFalseTotal
my $handle = $self->{"write_handle"} or die "MCP stream is not connected\n" 282 0 282
195 282 $handle->push_write (JSON::XS::encode_json ($message) . "\n");
196 282 1
197 };
198 282 ▶ $done->($ok ? (1, undef) : (0, { transport => 1, message => "$@" }));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 282 0 282
199 }
200  
201 77 ▶sub _shutdown {
Subroutine _shutdown: called CC=6 SCAR=18.2
202 77 my ($self) = @_;
203  
204 77 my $read = delete $self->{read_handle};
205 77 my $write = delete $self->{write_handle};
206 77 ▶ $read->destroy if $read;
Branch: 1 branch
BranchTrueFalseTotal
if $read 49 28 77
207 77 ▶ $write->destroy if $write && $write != $read;
Branch: 1 branch
BranchTrueFalseTotal
if $write and $write != $read 0 77 77
Condition66%2/3
$write and $write != $read
!ll&&!rl&&r
28490
MC/DC0%0/2
$write and $write != $read
$write $write != $read
Truth table66%2/3
A and B
A= $writeB= $write != $read
ABresult
0X0
100
111
208 77 ▶ if (my $pid = delete $self->{pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = delete $self->{"pid"}) 44 33 77
209 44 ▶ kill TERM => $pid unless $self->{idle_shutdown_expected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_shutdown_expected"} 44 0 44
210 }
211 77 delete $self->{child};
212 }
213  
214 33 1
« blib/lib/AnyEvent/MCP/Workdirs.pm ↑ Summary blib/lib/AnyEvent/MCP/Helper.pm »