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 34 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
109 34 ▶use parent "AnyEvent::MCP::Client";
Subroutine BEGIN: called CC=1 SCAR=0.0
110 34 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
111 34 ▶use AnyEvent::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
112 34 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
113 34 ▶use Scalar::Util qw(weaken blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
114  
115 50 ▶sub attach {
Subroutine attach: called CC=8 SCAR=28.1
Pod documented
116 50 my ($self, $fh_in, $fh_out) = @_;
117  
118 50 ▶ $self->close if $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} 0 50 50
119 50 weaken $self;
120 $self->{read_handle} = blessed $fh_in && $fh_in->isa ("AnyEvent::Handle")
121 50 ▶ ? $fh_in : AnyEvent::Handle->new (%{$self->{handle} || {}}, fh => $fh_in);
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($fh_in) && $fh_in->isa('AnyEvent::Handle') ? : 0 50 50
Condition40%2/5
builtin::blessed($fh_in) and $fh_in->isa("AnyEvent::Handle")
!ll&&!rl&&r
5000
$self->{'handle'} || {}
l!l
050
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 50 ▶ $self->{read_handle}{rbuf_max} = $self->{max_size} || 8 * 1024 * 1024;
Condition50%1/2
$self->{'max_size'} || 8388608
l!l
050
MC/DC0%0/1
$self->{'max_size'} || 8388608
$self->{'max_size'}
Truth table50%1/2
A
A= $self->{'max_size'}
Aresult
11
00
123 50 $self->{read_handle}->on_read (undef);
124 50 ▶ $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 50 ▶ ) : $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
$fh_out ? : 0 50 50
133 50 $self->_read;
134 }
135  
136 50 ▶sub _open {
Subroutine _open: called CC=8 SCAR=20.9
137 50 my ($self, $done) = @_;
138  
139 50 ▶ return $done->(1, undef) if $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} 4 46 50
140 return $done->(0, { transport => 1, message => "No command or attached stream" })
141 46 ▶ unless $self->{command};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"command"} 0 46 46
142  
143 46 my $ok = eval {
144 46 ▶ local %ENV = (%ENV, %{$self->{env} || {}});
Condition100%2/2
$self->{'env'} || {}
l!l
424
MC/DC100%1/1
$self->{'env'} || {}
$self->{'env'}
Truth table100%2/2
A
A= $self->{'env'}
Aresult
11
00
145 46 my ($parent, $child) = AnyEvent::Util::portable_socketpair;
146 46 ▶ die "Cannot create MCP socketpair: $!\n" unless defined $parent && defined $child;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $parent and defined $child 0 46 46
Condition33%1/3
defined $parent and defined $child
!ll&&!rl&&r
0046
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 46 my $pid;
149 my $cv = AnyEvent::Util::run_cmd (
150 46 ▶ ref $self->{command} eq "ARRAY" ? $self->{command} : ["/bin/sh", "-c", $self->{command}],
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'command'} eq 'ARRAY' ? : 28 18 46
151 "<" => $child, ">" => $child, '$$' => \$pid, close_all => 1,
152 );
153 46 close $child;
154 46 $self->{pid} = $pid;
155 46 $self->attach ($parent);
156  
157 46 weaken $self;
158 21 ▶ $cv->cb (sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
159 21 my $status = $_[0]->recv;
160 21 ▶ if ($self && $self->{pid} == $pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self and $self->{"pid"} == $pid) 1 20 21
Condition100%3/3
$self and $self->{"pid"} == $pid
!ll&&!rl&&r
8121
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 46 });
166 46 $self->{child} = $cv;
167 46 1
168 };
169 46 ▶ $done->($ok ? (1, undef) : (0, { transport => 1, message => "$@" }));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 46 0 46
170 }
171  
172 341 ▶sub _read {
Subroutine _read: called CC=1 SCAR=0.2
173 341 my ($self) = @_;
174  
175 341 weaken $self;
176  
177 291 ▶ $self->{read_handle}->push_read (line => sub {
Subroutine __ANON__: called CC=5 SCAR=17.5
178 291 my ($handle, $line) = @_;
179  
180 291 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 291 291
181 291 my $ok = eval {
182 291 $self->_receive (JSON::XS::decode_json $line);
183 291 1
184 };
185 291 ▶ return $self->close ("$@") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 291 291
186 291 ▶ $self->_read if $self->{read_handle} && !$handle->destroyed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} and not $handle->destroyed 291 0 291
Condition33%1/3
$self->{"read_handle"} and not $handle->destroyed
!ll&&!rl&&r
00291
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 341 });
188 }
189  
190 303 ▶sub _send {
Subroutine _send: called CC=3 SCAR=11.2
191 303 my ($self, $message, $done) = @_;
192  
193 303 my $ok = eval {
194 303 ▶ 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" 303 0 303
195 303 $handle->push_write (JSON::XS::encode_json ($message) . "\n");
196 303 1
197 };
198 303 ▶ $done->($ok ? (1, undef) : (0, { transport => 1, message => "$@" }));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 303 0 303
199 }
200  
201 79 ▶sub _shutdown {
Subroutine _shutdown: called CC=6 SCAR=18.2
202 79 my ($self) = @_;
203  
204 79 my $read = delete $self->{read_handle};
205 79 my $write = delete $self->{write_handle};
206 79 ▶ $read->destroy if $read;
Branch: 1 branch
BranchTrueFalseTotal
if $read 50 29 79
207 79 ▶ $write->destroy if $write && $write != $read;
Branch: 1 branch
BranchTrueFalseTotal
if $write and $write != $read 0 79 79
Condition66%2/3
$write and $write != $read
!ll&&!rl&&r
29500
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 79 ▶ if (my $pid = delete $self->{pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = delete $self->{"pid"}) 45 34 79
209 45 ▶ kill TERM => $pid unless $self->{idle_shutdown_expected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_shutdown_expected"} 45 0 45
210 }
211 79 delete $self->{child};
212 }
213  
214 34 1
« blib/lib/AnyEvent/MCP/Workdirs.pm ↑ Summary blib/lib/AnyEvent/MCP/Helper.pm »