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

filter: Statementstmt 95.1% 78 / 82 Branchbran 56.8% 25 / 44 Conditioncond 56.5% 13 / 23 MC/DCmcdc 28.5% 4 / 14 Subroutinesub 82.3% 14 / 17 Podpod 100% 1 / 1 totaltotal 74.5% 135 / 181 CC 32 SCAR 18.5
CC
32
Cov
78%
attach
14.3
_open
8.1
_shutdown
6.1
CRAP 6.4
« blib/lib/AnyEvent/MCP/Config.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 57 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
109 57 ▶use parent "AnyEvent::MCP::Client";
Subroutine BEGIN: called CC=1 SCAR=0.0
110 57 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
111 57 ▶use AnyEvent::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
112 57 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
113 57 ▶use Scalar::Util qw(weaken blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
114  
115 118 ▶sub attach {
Subroutine attach: called CC=8 SCAR=26.6
Pod documented
116 118 my ($self, $fh_in, $fh_out) = @_;
117  
118 118 ▶ $self->close if $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} 0 118 118
119 118 weaken $self;
120 $self->{read_handle} = blessed $fh_in && $fh_in->isa ("AnyEvent::Handle")
121 118 ▶ ? $fh_in : AnyEvent::Handle->new (%{$self->{handle} || {}}, fh => $fh_in);
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($fh_in) && $fh_in->isa('AnyEvent::Handle') ? : 5 113 118
Condition60%3/5
builtin::blessed($fh_in) and $fh_in->isa("AnyEvent::Handle")
!ll&&!rl&&r
11305
$self->{'handle'} || {}
l!l
0113
MC/DC50%1/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 table66%2/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 118 ▶ $self->{read_handle}{rbuf_max} = $self->{max_size} || 8 * 1024 * 1024;
Condition50%1/2
$self->{'max_size'} || 8388608
l!l
0118
MC/DC0%0/1
$self->{'max_size'} || 8388608
$self->{'max_size'}
Truth table50%1/2
A
A= $self->{'max_size'}
Aresult
11
00
123 118 $self->{read_handle}->on_read (undef);
124 118 ▶ $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 9 0 9
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 118 ▶ ) : $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
$fh_out ? : 0 118 118
133 118 $self->_read;
134 }
135  
136 117 ▶sub _open {
Subroutine _open: called CC=8 SCAR=20.9
137 117 my ($self, $done) = @_;
138  
139 117 ▶ return $done->(1, undef) if $self->{read_handle};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} 8 109 117
140 return $done->(0, { transport => 1, message => "No command or attached stream" })
141 109 ▶ unless $self->{command};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"command"} 0 109 109
142  
143 109 my $ok = eval {
144 109 ▶ local %ENV = (%ENV, %{$self->{env} || {}});
Condition100%2/2
$self->{'env'} || {}
l!l
1054
MC/DC100%1/1
$self->{'env'} || {}
$self->{'env'}
Truth table100%2/2
A
A= $self->{'env'}
Aresult
11
00
145 109 my ($parent, $child) = AnyEvent::Util::portable_socketpair;
146 109 ▶ die "Cannot create MCP socketpair: $!\n" unless defined $parent && defined $child;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $parent and defined $child 0 109 109
Condition33%1/3
defined $parent and defined $child
!ll&&!rl&&r
00109
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 109 my $pid;
149 my $cv = AnyEvent::Util::run_cmd (
150 109 ▶ ref $self->{command} eq "ARRAY" ? $self->{command} : ["/bin/sh", "-c", $self->{command}],
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'command'} eq 'ARRAY' ? : 84 25 109
151 "<" => $child, ">" => $child, '$$' => \$pid, close_all => 1,
152 );
153 109 close $child;
154 109 $self->{pid} = $pid;
155 109 $self->attach ($parent);
156  
157 109 weaken $self;
158 69 ▶ $cv->cb (sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
159 69 my $status = $_[0]->recv;
160 69 ▶ if ($self && $self->{pid} == $pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self and $self->{"pid"} == $pid) 1 68 69
Condition100%3/3
$self and $self->{"pid"} == $pid
!ll&&!rl&&r
43251
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 109 });
166 109 $self->{child} = $cv;
167 109 1
168 };
169 109 ▶ $done->($ok ? (1, undef) : (0, { transport => 1, message => "$@" }));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 109 0 109
170 }
171  
172 851 ▶sub _read {
Subroutine _read: called CC=1 SCAR=0.2
173 851 my ($self) = @_;
174  
175 851 weaken $self;
176  
177 733 ▶ $self->{read_handle}->push_read (line => sub {
Subroutine __ANON__: called CC=5 SCAR=17.5
178 733 my ($handle, $line) = @_;
179  
180 733 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 733 733
181 733 my $ok = eval {
182 733 $self->_receive (JSON::XS::decode_json $line);
183 733 1
184 };
185 733 ▶ return $self->close ("$@") unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 733 733
186 733 ▶ $self->_read if $self->{read_handle} && !$handle->destroyed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"read_handle"} and not $handle->destroyed 733 0 733
Condition33%1/3
$self->{"read_handle"} and not $handle->destroyed
!ll&&!rl&&r
00733
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 851 });
188 }
189  
190 760 ▶sub _send {
Subroutine _send: called CC=3 SCAR=11.2
191 760 my ($self, $message, $done) = @_;
192  
193 760 my $ok = eval {
194 760 ▶ 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" 760 0 760
195 760 $handle->push_write (JSON::XS::encode_json ($message) . "\n");
196 760 1
197 };
198 760 ▶ $done->($ok ? (1, undef) : (0, { transport => 1, message => "$@" }));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 760 0 760
199 }
200  
201 205 ▶sub _shutdown {
Subroutine _shutdown: called CC=6 SCAR=18.2
202 205 my ($self) = @_;
203  
204 205 my $read = delete $self->{read_handle};
205 205 my $write = delete $self->{write_handle};
206 205 ▶ $read->destroy if $read;
Branch: 1 branch
BranchTrueFalseTotal
if $read 118 87 205
207 205 ▶ $write->destroy if $write && $write != $read;
Branch: 1 branch
BranchTrueFalseTotal
if $write and $write != $read 0 205 205
Condition66%2/3
$write and $write != $read
!ll&&!rl&&r
871180
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 205 ▶ if (my $pid = delete $self->{pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pid = delete $self->{"pid"}) 108 97 205
209 108 ▶ kill TERM => $pid unless $self->{idle_shutdown_expected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_shutdown_expected"} 108 0 108
210 }
211 205 delete $self->{child};
212 }
213  
214 57 1
« blib/lib/AnyEvent/MCP/Config.pm ↑ Summary blib/lib/AnyEvent/MCP/Helper.pm »