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

filter: Statementstmt 96.8% 334 / 345 Branchbran 80.2% 154 / 192 Conditioncond 73.7% 76 / 103 MC/DCmcdc 52.5% 31 / 59 Subroutinesub 96.6% 58 / 60 Podpod 100% 11 / 11 totaltotal 86.2% 664 / 770 CC 142 SCAR 19.1
CC
142
Cov
88%
__ANON__
17.5
_remove_from_loop
11.9
_standard_headers
11.0
CRAP 6.7
« blib/lib/Net/Async/MCP.pm ↑ Summary blib/lib/Net/Async/MCP/Transport/Stdio.pm »
1 package Net::Async::MCP::Transport::HTTP;
2 # ABSTRACT: Streamable HTTP MCP transport via Net::Async::HTTP
3 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Encode qw( encode is_utf8 );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use Scalar::Util qw( blessed weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 6 ▶use Net::Async::MCP::JSONRPC;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16  
17 # The methods whose name-ish parameter is mirrored into Mcp-Name, and the
18 # parameter it is taken from. Same table as MCP::Client and MCP::Server's HTTP
19 # transport, which compares the header against exactly this field of the body.
20 6 my %NAME_PARAM = (
21 'prompts/get' => 'name',
22 'resources/read' => 'uri',
23 'tools/call' => 'name',
24 );
25  
26 6 my $DEFAULT_STALL_TIMEOUT = 60;
27  
28 # Where a subscription's acknowledgement carries the id every later message on
29 # that stream is tagged with, and the only handle there is on a running
30 # subscription. Written out for the same reason the protocol version key above
31 # is: it is a name on the wire, not something a locally installed L<MCP> has
32 # any say in.
33 6 my $SUBSCRIPTION_ID_META = 'io.modelcontextprotocol/subscriptionId';
34  
35 48 ▶sub _init {
Subroutine _init: called CC=5 SCAR=16.1
36 48 my ( $self, $params ) = @_;
37 $self->{url} = delete $params->{url}
38 48 ▶ or croak "url is required";
Branch: 1 branch
BranchTrueFalseTotal
$self->{"url"} = delete $params->{"url"} or croak("url is required") 48 0 48
39 # exists, not defined: an explicit undef is a caller switching a timeout off,
40 # and has to survive the default applied below.
41 48 for my $key (qw( headers timeout stall_timeout )) {
42 144 ▶ $self->{$key} = delete $params->{$key} if exists $params->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{$key} 9 135 144
43 }
44 $self->{stall_timeout} = $DEFAULT_STALL_TIMEOUT
45 48 ▶ unless exists $self->{stall_timeout};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"stall_timeout"} 46 2 48
46 48 $self->{next_id} = 0;
47 48 $self->{json} = JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
48  
49 # Every request that has not finished, by JSON-RPC id: the Future the caller
50 # holds, the exchange it is being answered over, and the subscription it
51 # opened where it opened one. Both halves are needed here rather than only
52 # the one the caller sees, because leaving the loop has to settle the Future
53 # and close the stream, and neither can be reached from the other.
54 48 $self->{pending} = {};
55  
56 # Subscription id to the request id of the exchange carrying it, which is
57 # what turns the one handle a caller has on a running subscription into the
58 # stream to close.
59 48 $self->{subscriptions} = {};
60  
61 # Exchanges this transport starts on its own and nobody waits for - the
62 # answer to a request the server sent, the notifications/cancelled of a
63 # cancelled legacy request - held until they finish, since a Future nothing
64 # refers to is collected mid-flight.
65 48 $self->{background} = {};
66  
67 48 $self->SUPER::_init($params);
68 }
69  
70 53 ▶sub configure {
Subroutine configure: called CC=8 SCAR=21.0
Pod documented
71 53 my ( $self, %params ) = @_;
72 53 ▶ if (exists $params{url}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"url"}) 0 53 53
73 0 $self->{url} = delete $params{url};
74 }
75 53 ▶ $self->{headers} = delete $params{headers} if exists $params{headers};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{"headers"} 1 52 53
76 53 for my $event (qw( on_notification on_subscription_end on_request )) {
77 159 ▶ $self->{$event} = delete $params{$event} if exists $params{$event};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$event} 50 109 159
78 }
79 53 for my $key (qw( timeout stall_timeout )) {
80 106 ▶ next unless exists $params{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $params{$key} 105 1 106
81 1 $self->{$key} = delete $params{$key};
82 # Only once this transport has joined a loop is there an HTTP client to
83 # reconfigure; before that _add_to_loop picks the values up itself.
84 1 ▶ $self->{http}->configure($key => $self->{$key}) if $self->{http};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"http"} 1 0 1
85 }
86 53 $self->SUPER::configure(%params);
87 }
88  
89 17 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=1 SCAR=0.0
90 17 my ( $self, $loop ) = @_;
91 17 $self->SUPER::_add_to_loop($loop);
92  
93 17 require Net::Async::HTTP;
94  
95 my $http = Net::Async::HTTP->new(
96 max_connections_per_host => 0,
97 timeout => $self->{timeout},
98 stall_timeout => $self->{stall_timeout},
99 17 );
100 17 $self->{http} = $http;
101 17 $self->add_child($http);
102 }
103  
104 16 ▶sub _remove_from_loop {
Subroutine _remove_from_loop: called CC=10 SCAR=24.8
105 16 my ( $self, $loop ) = @_;
106  
107 # Leaving the loop takes the HTTP client along, it being a child of this
108 # transport, and with it every connection an answer could still arrive over.
109 # So nothing still open can ever be settled from outside again, and it has to
110 # be settled here or it stays pending for the rest of the program - the same
111 # lesson as L<Net::Async::MCP::Transport::Stdio>'s own _remove_from_loop.
112 #
113 # The caller's Future is failed rather than completed: nothing here saw a
114 # response go missing, what it knows is that none can reach it any more. Its
115 # exchange is cancelled afterwards, which closes the stream; doing it the
116 # other way round would settle the Future as cancelled and lose the reason
117 # with it.
118 16 for my $id (keys %{ $self->{pending} }) {
119 2 ▶ my $pending = delete $self->{pending}{$id} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $pending = delete $self->{"pending"}{$id} or next 2 0 2
120  
121 delete $self->{subscriptions}{ $pending->{subscription} }
122 2 ▶ if defined $pending->{subscription};
Branch: 1 branch
BranchTrueFalseTotal
if defined $pending->{"subscription"} 1 1 2
123  
124 2 my $outcome = $pending->{outcome};
125 2 ▶ $outcome->fail("MCP HTTP transport left the loop before the request was answered")
Branch: 1 branch
BranchTrueFalseTotal
if $outcome and not $outcome->is_ready 1 1 2
Condition66%2/3
$outcome and not $outcome->is_ready
!ll&&!rl&&r
011
MC/DC50%1/2
$outcome and not $outcome->is_ready
$outcome not $outcome->is_ready
Truth table66%2/3
A and not(B)
A= $outcomeB= not $outcome->is_ready
ABresult
0X0
100
111
126 if $outcome && !$outcome->is_ready;
127  
128 2 my $exchange = $pending->{exchange};
129 2 ▶ $exchange->cancel if $exchange && !$exchange->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $exchange and not $exchange->is_ready 2 0 2
Condition33%1/3
$exchange and not $exchange->is_ready
!ll&&!rl&&r
002
MC/DC0%0/2
$exchange and not $exchange->is_ready
$exchange not $exchange->is_ready
Truth table33%1/3
A and not(B)
A= $exchangeB= not $exchange->is_ready
ABresult
0X0
100
111
130 }
131  
132 16 for my $future (values %{ $self->{background} }) {
133 0 ▶ $future->cancel unless $future->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $future->is_ready 0 0 0
134 }
135 16 $self->{background} = {};
136  
137 16 $self->SUPER::_remove_from_loop($loop);
138 }
139  
140 # The Future a caller is handed. An IO::Async::Future wherever there is a loop
141 # to take one from, which is every transport that has an HTTP client to send
142 # with: only the plain Future knows no ->await, and a caller's ->get on one
143 # that is not ready yet dies instead of running the loop until it is.
144 78 ▶sub _new_future {
Subroutine _new_future: called CC=2 SCAR=6.9
145 78 my ( $self ) = @_;
146 78 ▶ my $loop = $self->loop or return Future->new;
Branch: 1 branch
BranchTrueFalseTotal
my $loop = $self->loop or return "Future"->new 38 40 78
147 38 return $loop->new_future;
148 }
149  
150  
151 65 ▶sub send_request {
Subroutine send_request: called CC=2 SCAR=7.0
Pod documented
152 65 my ( $self, $method, $params, %options ) = @_;
153  
154 65 my $id = ++$self->{next_id};
155 65 ▶ my $request = {
Branch: 1 branch
BranchTrueFalseTotal
defined $params ? : 65 0 65
156 jsonrpc => '2.0',
157 id => $id,
158 method => $method,
159 defined $params ? ( params => $params ) : (),
160 };
161  
162 65 my $body = $self->{json}->encode($request);
163  
164 65 require HTTP::Request;
165 my $http_req = HTTP::Request->new(
166 POST => $self->{url},
167 65 [ $self->_standard_headers($method, $params, %options) ],
168 $body,
169 );
170  
171 # The session this request is made in, if any: a 404 to it means the server
172 # ended that session, and only that session - see _handle_response.
173 65 $options{sent_session} = $http_req->header('Mcp-Session-Id');
174  
175 # The Future the caller holds, and deliberately not the one the exchange
176 # below ends in. What answers a request is its message, and the end of the
177 # body that message arrived in is a different moment: a server is free to
178 # hold an event stream open after its response, and for a subscription it
179 # always does - that request is answered by a notification and the stream
180 # then runs for as long as the subscription does. Waiting for the body to
181 # end would mean waiting for the stall timeout in the first case and forever
182 # in the second.
183 65 my $outcome = $self->_new_future;
184 65 my $pending = $self->{pending}{$id} = { outcome => $outcome };
185  
186 my $exchange = $self->{http}->do_request(
187 request => $http_req,
188 63 ▶ on_header => sub { $self->_response_reader($outcome, $id, \%options, @_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
189 )->then(
190 53 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
191 53 my ( $result ) = @_;
192  
193 # Both body readers end in the Future for the JSON-RPC outcome, and
194 # Net::Async::HTTP passes whatever they return through as the result of
195 # its own. A response object instead means the body never reached them:
196 # a redirect, which it consumes itself rather than handing over - it does
197 # not follow one for a POST, so this is where a redirected endpoint ends
198 # up, and the status line is all there is to report.
199 53 ▶ return $result if blessed($result) && $result->isa('Future');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($result) and $result->isa("Future") 52 1 53
Condition66%2/3
builtin::blessed($result) and $result->isa("Future")
!ll&&!rl&&r
0152
MC/DC50%1/2
builtin::blessed($result) and $result->isa("Future")
builtin::blessed($result) $result->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($result)B= $result->isa("Future")
ABresult
0X0
100
111
200 1 return $self->_handle_response($result, $options{sent_session});
201 },
202 2 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
203 2 my ( $message, $category, @details ) = @_;
204  
205 # Net::Async::HTTP failing on its own means no answer came: the
206 # connection could not be made, broke off or timed out. It reports a
207 # refused connection or an unknown host with no category at all, which
208 # would make it look like a status line - a server's answer - so it is
209 # given one here.
210 2 ▶ return Future->fail($message, $category // 'connect', @details);
Condition50%1/2
$category // "connect"
l!l
02
MC/DC0%0/1
$category // "connect"
$category
Truth table50%1/2
A
A= $category
Aresult
11
00
211 },
212 65 );
213  
214 # Held on the transport because the caller no longer holds it: a Future
215 # nothing refers to is collected mid-flight, and this one is the request.
216 65 $pending->{exchange} = $exchange;
217  
218 # These callbacks live on the two Futures the pending entry holds, so
219 # capturing the transport strongly would close a cycle no refcount breaks.
220 # It is never undef where it matters: a transport with a request in flight is
221 # in a loop, and the loop holds it.
222 65 weaken( my $weak_self = $self );
223  
224 # Cancelling the answer cancels the request, which over Streamable HTTP
225 # means closing the stream it would have been answered on - there is no
226 # notifications/cancelled in this binding. Reached through the pending table
227 # rather than by capturing the exchange, which would be the other half of
228 # the same cycle.
229 #
230 # The legacy revisions say otherwise: a closed stream is not a cancellation
231 # there, and the server is told with notifications/cancelled instead. The
232 # stream is closed all the same, there being nobody left to read it.
233 1 ▶ $outcome->on_cancel(sub {
Subroutine __ANON__: called CC=7 SCAR=23.4
234 1 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 1 0 1
235 $self->_in_background($self->send_notification('notifications/cancelled',
236 { requestId => $id, reason => 'cancelled by the client' }))
237 1 ▶ if $self->{legacy} && $self->{http};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"legacy"} and $self->{"http"} 1 0 1
Condition33%1/3
$self->{"legacy"} and $self->{"http"}
!ll&&!rl&&r
001
MC/DC0%0/2
$self->{"legacy"} and $self->{"http"}
$self->{"legacy"} $self->{"http"}
Truth table33%1/3
A and B
A= $self->{"legacy"}B= $self->{"http"}
ABresult
0X0
100
111
238 1 ▶ my $exchange = ( $self->{pending}{$id} // {} )->{exchange} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $exchange = +($self->{"pending"}{$id} // {})->{"exchange"} or return 1 0 1
Condition50%1/2
$self->{"pending"}{$id} // {}
l!l
10
MC/DC0%0/1
$self->{"pending"}{$id} // {}
$self->{"pending"}{$id}
Truth table50%1/2
A
A= $self->{"pending"}{$id}
Aresult
11
00
239 1 ▶ $exchange->cancel unless $exchange->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $exchange->is_ready 1 0 1
240 65 });
241  
242 64 ▶ $exchange->on_ready(sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
243 64 my ( $finished ) = @_;
244  
245 64 ▶ if ( my $self = $weak_self ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $self = $weak_self) 64 0 64
246 64 my $ended = delete $self->{pending}{$id};
247  
248 # Whether the subscription is still registered tells who ended it:
249 # stop_subscription and close take the entry out before they close the
250 # stream, so an end that came from the server's side - a stream the
251 # server closed, a connection that failed - reaches here with the entry
252 # standing, and that is the end on_subscription_end reports. An end this
253 # client caused itself has nobody waiting to be told.
254 64 ▶ if ($ended && defined $ended->{subscription}
Branch: 1 branch
BranchTrueFalseTotal
if ($ended and defined $ended->{"subscription"} and delete $self->{"subscriptions"}{$ended->{"subscription"}}) 3 61 64
Condition100%6/6
$ended and defined $ended->{"subscription"} and delete $self->{"subscriptions"}{$ended->{"subscription"}}
!ll&&!rl&&r
5653
$ended and defined $ended->{"subscription"}
!ll&&!rl&&r
2548
MC/DC100%3/3
$ended and defined $ended->{"subscription"} and delete $self->{"subscriptions"}{$ended->{"subscription"}}
$ended defined $ended->{"subscription"} delete $self->{"subscriptions"}{$ended->{"subscription"}}
Truth table100%4/4
A and B and C
A= $endedB= defined $ended->{"subscription"}C= delete $self->{"subscriptions"}{$ended->{"subscription"}}
ABCresult
0XX0
10X0
1100
1111
255 && delete $self->{subscriptions}{ $ended->{subscription} }) {
256 3 $self->maybe_invoke_event(on_subscription_end => $ended->{subscription});
257 }
258 }
259  
260 # An exchange that ends after the caller was answered has nothing left to
261 # tell it. This is every subscription: it was settled by its
262 # acknowledgement, and the stream ending afterwards - closed by
263 # L</stop_subscription>, by the server, or by the connection failing - is
264 # reported through L</on_subscription_end> above rather than through this
265 # Future, which was settled long before.
266 64 ▶ return if $outcome->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $outcome->is_ready 15 49 64
267  
268 # Otherwise the exchange is where the answer comes from: an HTTP error, a
269 # body that could not be read, a stream that ended without saying
270 # anything, or a plain JSON response that was only complete at the end.
271 49 ▶ return $outcome->cancel if $finished->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $finished->is_cancelled 1 48 49
272 48 ▶ return $outcome->fail($finished->failure) if $finished->is_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $finished->is_failed 19 29 48
273 29 return $outcome->done($finished->get);
274 65 });
275  
276 65 return $outcome;
277 }
278  
279  
280  
281 12 ▶sub send_notification {
Subroutine send_notification: called CC=2 SCAR=6.9
Pod documented
282 12 my ( $self, $method, $params ) = @_;
283  
284 12 ▶ my $request = {
Branch: 1 branch
BranchTrueFalseTotal
defined $params ? : 1 11 12
285 jsonrpc => '2.0',
286 method => $method,
287 defined $params ? ( params => $params ) : (),
288 };
289  
290 12 my $body = $self->{json}->encode($request);
291  
292 12 require HTTP::Request;
293 my $http_req = HTTP::Request->new(
294 POST => $self->{url},
295 12 [ $self->_standard_headers($method, $params) ],
296 $body,
297 );
298  
299 12 my $sent_session = $http_req->header('Mcp-Session-Id');
300 12 ▶ return $self->{http}->do_request(request => $http_req)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
301 12 my ( $response ) = @_;
302 12 return $self->_handle_notification_response($response, $sent_session);
303 12 });
304 }
305  
306  
307 8 ▶sub close {
Subroutine close: called CC=5 SCAR=16.3
Pod documented
308 8 my ( $self ) = @_;
309 8 $self->stop_subscription($_) for keys %{ $self->{subscriptions} };
310  
311 8 my $session = delete $self->{session_id};
312 8 ▶ return Future->done unless defined $session && $self->{http};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $session and $self->{"http"} 2 6 8
Condition66%2/3
defined $session and $self->{"http"}
!ll&&!rl&&r
206
MC/DC50%1/2
defined $session and $self->{"http"}
defined $session $self->{"http"}
Truth table66%2/3
A and B
A= defined $sessionB= $self->{"http"}
ABresult
0X0
100
111
313  
314 6 require HTTP::Request;
315 my @headers = (
316 'Mcp-Session-Id' => $session,
317 defined $self->{legacy_protocol_version}
318 6 ▶ ? ( 'MCP-Protocol-Version' => $self->{legacy_protocol_version} ) : (),
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'legacy_protocol_version'} ? : 6 0 6
319 );
320 my $http_req = HTTP::Request->new(DELETE => $self->{url},
321 6 [ $self->_caller_headers(@headers), @headers ]);
322  
323 # 405 is the answer the specification gives a server that lets no client end
324 # its session, and 404 one whose session is already gone: either way there is
325 # no session left on this side, which is all a close is after.
326 return $self->{http}->do_request(request => $http_req)->then(
327 6 ▶ sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
328 6 my ( $response ) = @_;
329 6 my $code = $response->code;
330 6 ▶ return Future->done
Branch: 1 branch
BranchTrueFalseTotal
if $response->is_success or $code == 404 or $code == 405 5 1 6
Condition83%5/6
$response->is_success or $code == 404 or $code == 405
l!l&&r!l&&!r
411
$response->is_success or $code == 404
l!l&&r!l&&!r
402
MC/DC66%2/3
$response->is_success or $code == 404 or $code == 405
$response->is_success $code == 404 $code == 405
Truth table75%3/4
A or B or C
A= $response->is_successB= $code == 404C= $code == 405
ABCresult
1XX1
01X1
0011
0000
331 if $response->is_success || $code == 404 || $code == 405;
332 1 return Future->fail("MCP HTTP session $session could not be ended: "
333 . $response->status_line);
334 },
335 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
336 0 my ( $message ) = @_;
337 0 return Future->fail("MCP HTTP session $session could not be ended: $message");
338 },
339 6 );
340 }
341  
342  
343 12 ▶sub stop_subscription {
Subroutine stop_subscription: called CC=3 SCAR=11.0
Pod documented
344 12 my ( $self, $subscription_id ) = @_;
345  
346 12 ▶ return 0 unless defined $subscription_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $subscription_id 0 12 12
347 12 my $id = delete $self->{subscriptions}{$subscription_id};
348 12 ▶ return 0 unless defined $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 7 5 12
349  
350 5 $self->_close_stream($id);
351 5 return 1;
352 }
353  
354  
355 2 ▶sub is_alive { 1 }
Subroutine is_alive: called CC=1 SCAR=0.0
Pod documented
356  
357  
358 12 ▶sub mirrors_header_params { $_[0]->{legacy} ? 0 : 1 }
Subroutine mirrors_header_params: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'legacy'} ? : 4 8 12
359  
360  
361 12 ▶sub start_legacy_session {
Subroutine start_legacy_session: called CC=1 SCAR=0.0
Pod documented
362 12 my ( $self ) = @_;
363 12 $self->{legacy} = 1;
364 12 delete $self->{legacy_protocol_version};
365 12 delete $self->{session_id};
366 12 return;
367 }
368  
369  
370 12 ▶sub set_legacy_protocol_version {
Subroutine set_legacy_protocol_version: called CC=1 SCAR=0.0
Pod documented
371 12 my ( $self, $version ) = @_;
372 12 $self->{legacy_protocol_version} = $version;
373 12 return;
374 }
375  
376  
377 1 ▶sub end_legacy_session {
Subroutine end_legacy_session: called CC=1 SCAR=0.0
Pod documented
378 1 my ( $self ) = @_;
379 1 delete @{$self}{qw( legacy legacy_protocol_version session_id )};
380 1 return;
381 }
382  
383  
384 9 ▶sub session_id { $_[0]->{session_id} }
Subroutine session_id: called CC=1 SCAR=0.0
Pod documented
385  
386  
387  
388 # Net::Async::HTTP hands the response header over as soon as it has it and
389 # takes the callback for the body in return, so this is where the content type
390 # decides how the body is read: an event stream carries notifications the
391 # server sends before its response and has to be read as it arrives, while
392 # every other body says nothing until it is complete and is judged whole.
393 63 ▶sub _response_reader {
Subroutine _response_reader: called CC=8 SCAR=21.7
394 63 my ( $self, $outcome, $id, $options, $header ) = @_;
395  
396 # The answer to the initialize that opens a legacy session is where the
397 # session id is handed out, in a header of the response rather than in the
398 # message, so it is taken here before the body is read at all.
399 63 ▶ if ($options->{start_session} && $header->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"start_session"} and $header->is_success) 11 52 63
Condition66%2/3
$options->{"start_session"} and $header->is_success
!ll&&!rl&&r
52011
MC/DC50%1/2
$options->{"start_session"} and $header->is_success
$options->{"start_session"} $header->is_success
Truth table66%2/3
A and B
A= $options->{"start_session"}B= $header->is_success
ABresult
0X0
100
111
400 11 my $session = $header->header('Mcp-Session-Id');
401 11 ▶ if (defined $session && $session !~ /\A[\x21-\x7e]+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $session and not $session =~ /\A[\x21-\x7e]+\z/) 0 11 11
Condition66%2/3
defined $session and not $session =~ /\A[\x21-\x7e]+\z/
!ll&&!rl&&r
1100
MC/DC0%0/2
defined $session and not $session =~ /\A[\x21-\x7e]+\z/
defined $session not $session =~ /\A[\x21-\x7e]+\z/
Truth table66%2/3
A and not(B)
A= defined $sessionB= not $session =~ /\A[\x21-\x7e]+\z/
ABresult
0X0
100
111
402 0 $outcome->fail("MCP HTTP server sent an Mcp-Session-Id that is not visible "
403 . "ASCII, which the specification requires");
404 0 ▶ return sub { return $outcome };
Subroutine __ANON__: not called CC=1 SCAR=6.9
405 }
406 11 $self->{session_id} = $session;
407 }
408  
409 63 ▶ return $self->_sse_reader($outcome, $id, $options)
Branch: 1 branch
BranchTrueFalseTotal
if $header->is_success and ($header->content_type // "") =~ m[^text/event-stream]i 18 45 63
Condition80%4/5
$header->is_success and ($header->content_type // "") =~ m[^text/event-stream]i
!ll&&!rl&&r
162918
$header->content_type // ""
l!l
470
MC/DC50%1/2
$header->is_success and ($header->content_type // "") =~ m[^text/event-stream]i
$header->is_success $header->content_type
Truth table66%2/3
A and B
A= $header->is_successB= $header->content_type
ABresult
0X0
100
111
410 if $header->is_success
411 && ($header->content_type // '') =~ m{^text/event-stream}i;
412  
413 90 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
414 90 ▶ return $header->add_content(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 45 45 90
415 45 return $self->_handle_response($header, $options->{sent_session});
416 45 };
417 }
418  
419 # Reads an SSE body as it arrives. Returns the callback Net::Async::HTTP feeds
420 # the body to: once per chunk of bytes as it lands, and once with no arguments
421 # at the end of the stream, where whatever it returns becomes the result of the
422 # request's Future - here the Future the JSON-RPC outcome is reported through.
423 #
424 # A chunk ends wherever the network put it, mid-line and mid-character
425 # included, so nothing leaves the buffer before its newline has arrived and
426 # nothing is decoded before its event is complete.
427 31 ▶sub _sse_reader {
Subroutine _sse_reader: called CC=3 SCAR=11.0
428 31 my ( $self, $outcome, $id, $options ) = @_;
429  
430 # A reader driven directly rather than from send_request answers nobody, but
431 # still has to have something to settle: _handle_sse_response reads a whole
432 # body through here and hands back what this ends up with.
433 31 ▶ $outcome //= $self->_new_future;
Condition66%2/3
$outcome //= $self->_new_future
l!l&&r!l&&!r
18130
MC/DC0%0/2
$outcome //= $self->_new_future
$outcome $self->_new_future
Truth table66%2/3
A //= B
A= $outcomeB= $self->_new_future
ABresult
1X1
011
000
434  
435 # What the client said settles this request in place of a response. Named by
436 # the client and not worked out here: which method that is is MCP semantics,
437 # and a transport reading the request's own method and deciding for itself
438 # would be guessing where it was told.
439 31 ▶ my $resolve_on = ( $options // {} )->{resolve_on_notification};
Condition100%2/2
$options // {}
l!l
1813
MC/DC100%1/1
$options // {}
$options
Truth table100%2/2
A
A= $options
Aresult
11
00
440  
441 31 my $buffer = '';
442 31 my @data;
443  
444 # One line of the stream, its newline already taken off. A blank line ends
445 # an event, a line opening with a colon is a comment - the shape of the
446 # keep-alives a server sends to hold an idle stream open - and every other
447 # line is a field, of which this client reads only "data".
448 113 ▶ my $line = sub {
Subroutine __ANON__: called CC=17 SCAR=28.6
449 113 my ( $text ) = @_;
450  
451 113 $text =~ s/\r\z//;
452  
453 113 ▶ if (length $text) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $text) 51 62 113
454 51 ▶ return if $text =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /^:/ 3 48 51
455 48 my ( $field, $value ) = split /:/, $text, 2;
456 48 ▶ return unless defined $field && $field eq 'data';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $field and $field eq "data" 5 43 48
Condition66%2/3
defined $field and $field eq "data"
!ll&&!rl&&r
0543
MC/DC50%1/2
defined $field and $field eq "data"
defined $field $field eq "data"
Truth table66%2/3
A and B
A= defined $fieldB= $field eq "data"
ABresult
0X0
100
111
457 43 ▶ $value = '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 43 43
458 43 $value =~ s/^ //;
459 43 push @data, $value;
460 43 return;
461 }
462  
463 62 my $event = join "\n", @data;
464 62 @data = ();
465 62 ▶ return unless length $event;
Branch: 1 branch
BranchTrueFalseTotal
unless length $event 20 42 62
466  
467 # Not every event is JSON-RPC this client can use, and one that is not is
468 # no reason to abandon a stream that still owes it a response.
469 42 my $decoded = eval { $self->{json}->decode($event) };
470 42 ▶ return unless ref $decoded eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $decoded eq "HASH" 0 42 42
471  
472 # An event that answers no request is a notification - unless it is the
473 # one the client named as this request's answer, which is how a
474 # subscription is acknowledged: it settles the request rather than being
475 # delivered as an event of its own, since it is what the caller asked for
476 # and not something that happened while it waited.
477 42 ▶ unless (exists $decoded->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $decoded->{"id"}) 26 16 42
478 return $self->_open_subscription($outcome, $id, $decoded)
479 if defined $resolve_on
480 && !$outcome->is_ready
481 26 ▶ && ( $decoded->{method} // '' ) eq $resolve_on;
Branch: 1 branch
BranchTrueFalseTotal
if defined $resolve_on and not $outcome->is_ready and ($decoded->{"method"} // "") eq $resolve_on 10 16 26
Condition75%6/8
defined $resolve_on and not $outcome->is_ready and ($decoded->{"method"} // "") eq $resolve_on
!ll&&!rl&&r
16010
defined $resolve_on and not $outcome->is_ready
!ll&&!rl&&r
13310
$decoded->{"method"} // ""
l!l
100
MC/DC66%2/3
defined $resolve_on and not $outcome->is_ready and ($decoded->{"method"} // "") eq $resolve_on
defined $resolve_on not $outcome->is_ready $decoded->{"method"}
Truth table75%3/4
A and not(B) and C
A= defined $resolve_onB= not $outcome->is_readyC= $decoded->{"method"}
ABCresult
0XX0
10X0
1100
1111
482  
483 16 return $self->maybe_invoke_event(on_notification => $decoded);
484 }
485  
486 # An event that does answer settles the request the moment it lands rather
487 # than at the end of the body: a stream holds the answer to exactly one
488 # request, so the first one is kept and what comes after cannot make an
489 # earlier answer untrue. An id without a result or an error is a
490 # server-initiated request, which goes to on_request.
491 16 ▶ unless (exists $decoded->{result} || exists $decoded->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $decoded->{"result"} or exists $decoded->{"error"}) 2 14 16
Condition100%3/3
exists $decoded->{"result"} or exists $decoded->{"error"}
l!l&&r!l&&!r
1042
MC/DC100%2/2
exists $decoded->{"result"} or exists $decoded->{"error"}
exists $decoded->{"result"} exists $decoded->{"error"}
Truth table100%3/3
A or B
A= exists $decoded->{"result"}B= exists $decoded->{"error"}
ABresult
1X1
011
000
492 2 ▶ $self->_on_server_request($decoded) if defined $decoded->{method};
Branch: 1 branch
BranchTrueFalseTotal
if defined $decoded->{"method"} 2 0 2
493 2 return;
494 }
495  
496 14 ▶ $self->_settle_response($outcome, $decoded) unless $outcome->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $outcome->is_ready 14 0 14
497  
498 14 return;
499 31 };
500  
501 261 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
502 261 ▶ unless (@_) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_) 18 243 261
503 # The end of the stream terminates whatever it interrupted: a server
504 # that closed right behind its last data line still said it.
505 18 ▶ $line->($buffer) if length $buffer;
Branch: 1 branch
BranchTrueFalseTotal
if length $buffer 0 18 18
506 18 $buffer = '';
507 18 $line->('');
508 18 return $self->_sse_result($outcome, $resolve_on);
509 }
510  
511 243 my ( $chunk ) = @_;
512 243 ▶ return unless defined $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk 0 243 243
513  
514 # The JSON decoder has utf8 => 1 and wants bytes, which is what
515 # Net::Async::HTTP hands over. Characters would be decoded a second time
516 # and every non-ASCII event lost to the failed decode above.
517 243 ▶ $chunk = encode('UTF-8', $chunk) if is_utf8($chunk);
Branch: 1 branch
BranchTrueFalseTotal
if &is_utf8($chunk) 1 242 243
518  
519 243 $buffer .= $chunk;
520 243 ▶ $line->($1) while $buffer =~ s/^([^\n]*)\n//;
Branch: 1 branch
BranchTrueFalseTotal
$buffer =~ s/^([^\n]*)\n// and do { &$line($1) } 95 243 338
521  
522 243 return;
523 31 };
524 }
525  
526 # A request the server sent on a response stream, answered with whatever
527 # on_request returns, if anything. The answer is a POST of its own - there is
528 # no other way back to the server - carrying the session like every POST.
529 2 ▶sub _on_server_request {
Subroutine _on_server_request: called CC=7 SCAR=20.3
530 2 my ( $self, $request ) = @_;
531 2 ▶ return unless $self->can_event('on_request');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can_event("on_request") 0 2 2
532  
533 2 my $answer = $self->invoke_event(on_request => $request);
534 return unless ref $answer eq 'HASH'
535 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
536 2 ▶ return unless $self->{http};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"http"} 0 2 2
537  
538 my $response = {
539 jsonrpc => '2.0',
540 id => $request->{id},
541 exists $answer->{error}
542 ? ( error => $answer->{error} )
543 2 ▶ : ( result => $answer->{result} ),
Branch: 1 branch
BranchTrueFalseTotal
exists $answer->{'error'} ? : 1 1 2
544 };
545  
546 # A response has no method of its own to name in Mcp-Method, which only a
547 # modern server would read and no modern server sends requests to answer.
548 2 my @headers = $self->_session_headers;
549 2 my @standard = (
550 'Content-Type' => 'application/json',
551 'Accept' => 'application/json, text/event-stream',
552 @headers,
553 );
554  
555 2 require HTTP::Request;
556 my $http_req = HTTP::Request->new(POST => $self->{url},
557 [ $self->_caller_headers(@standard), @standard ],
558 2 $self->{json}->encode($response));
559  
560 2 $self->_in_background($self->{http}->do_request(request => $http_req));
561 2 return;
562 }
563  
564 # Private: a Future nobody waits for, held until it is done - see the
565 # background table in _init.
566 3 ▶sub _in_background {
Subroutine _in_background: called CC=1 SCAR=0.0
567 3 my ( $self, $future ) = @_;
568 3 my $key = "$future";
569 3 $self->{background}{$key} = $future;
570  
571 3 weaken( my $weak_self = $self );
572 3 ▶ $future->on_ready(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
573 3 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 3 0 3
574 3 delete $self->{background}{$key};
575 3 });
576 3 return;
577 }
578  
579 # The answer an event carrying one settles the request with, taken as it lands
580 # rather than held until the stream ends.
581 14 ▶sub _settle_response {
Subroutine _settle_response: called CC=5 SCAR=16.1
582 14 my ( $self, $outcome, $data ) = @_;
583  
584 14 ▶ if (defined(my $err = $data->{error})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $err = $data->{"error"})) 3 11 14
585 3 my @failure = $self->_jsonrpc_error_failure($data);
586 3 ▶ return $outcome->fail(@failure) if @failure;
Branch: 1 branch
BranchTrueFalseTotal
if @failure 2 1 3
587 1 return $outcome->fail($self->_foreign_error_message($err));
588 }
589  
590 # "error": null sits next to every result in JSON-RPC 1.0 and says nothing
591 # there. Without a result it answers nothing, and an undef handed out as the
592 # result would be a success the server never reported.
593 return $outcome->fail($self->_null_error_message)
594 11 ▶ if exists $data->{error} && !exists $data->{result};
Branch: 1 branch
BranchTrueFalseTotal
if exists $data->{"error"} and not exists $data->{"result"} 1 10 11
Condition100%3/3
exists $data->{"error"} and not exists $data->{"result"}
!ll&&!rl&&r
911
MC/DC100%2/2
exists $data->{"error"} and not exists $data->{"result"}
exists $data->{"error"} not exists $data->{"result"}
Truth table100%3/3
A and not(B)
A= exists $data->{"error"}B= not exists $data->{"result"}
ABresult
0X0
100
111
595  
596 10 return $outcome->done($data->{result});
597 }
598  
599 # The acknowledgement of a subscription, which is the answer to the request
600 # that opened it: its params are what the caller is handed - the subscription
601 # id and the notification types the server honoured - and the id is what the
602 # stream is filed under, since closing that stream is the only way to end the
603 # subscription again.
604 10 ▶sub _open_subscription {
Subroutine _open_subscription: called CC=6 SCAR=18.1
605 10 my ( $self, $outcome, $id, $acknowledgement ) = @_;
606  
607 10 ▶ my $params = ref $acknowledgement->{params} eq 'HASH' ? $acknowledgement->{params} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $acknowledgement->{'params'} eq 'HASH' ? : 10 0 10
608 10 ▶ my $meta = ref $params->{_meta} eq 'HASH' ? $params->{_meta} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $params->{'_meta'} eq 'HASH' ? : 9 1 10
609 10 my $subscription_id = $meta->{$SUBSCRIPTION_ID_META};
610  
611 # A subscription with no id is one nothing can address: it cannot be stopped
612 # and a close cannot reach it either, so handing it to a caller would be
613 # handing over a stream with no way of ending it. The stream goes with the
614 # refusal, which is what ends it on this side.
615 10 ▶ unless (defined $subscription_id && length $subscription_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $subscription_id and length $subscription_id) 1 9 10
Condition66%2/3
defined $subscription_id and length $subscription_id
!ll&&!rl&&r
109
MC/DC50%1/2
defined $subscription_id and length $subscription_id
defined $subscription_id length $subscription_id
Truth table66%2/3
A and B
A= defined $subscription_idB= length $subscription_id
ABresult
0X0
100
111
616 1 $outcome->fail("MCP HTTP subscription acknowledged without a subscription id");
617 1 $self->_close_stream($id);
618 1 return;
619 }
620  
621 9 $self->{subscriptions}{$subscription_id} = $id;
622 9 ▶ $self->{pending}{$id}{subscription} = $subscription_id if $self->{pending}{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pending"}{$id} 9 0 9
623  
624 9 return $outcome->done($params);
625 }
626  
627 # Closing the stream a request is running on, which is what both cancelling a
628 # request and unsubscribing come down to over this binding: Net::Async::HTTP
629 # closes the connection when its request Future is cancelled.
630 6 ▶sub _close_stream {
Subroutine _close_stream: called CC=5 SCAR=17.2
631 6 my ( $self, $id ) = @_;
632  
633 6 ▶ return 0 unless defined $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 6 6
634 6 ▶ my $exchange = ( $self->{pending}{$id} // {} )->{exchange} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $exchange = +($self->{"pending"}{$id} // {})->{"exchange"} or return 0 6 0 6
Condition50%1/2
$self->{"pending"}{$id} // {}
l!l
60
MC/DC0%0/1
$self->{"pending"}{$id} // {}
$self->{"pending"}{$id}
Truth table50%1/2
A
A= $self->{"pending"}{$id}
Aresult
11
00
635 6 ▶ return 0 if $exchange->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $exchange->is_ready 0 6 6
636  
637 6 $exchange->cancel;
638 6 return 1;
639 }
640  
641 # What a finished SSE stream leaves the exchange with. The answer it carried is
642 # already the caller's, so handing the same Future back keeps the exchange
643 # resolving with exactly what the request resolved with; only a stream that
644 # said nothing has anything of its own to report.
645 18 ▶sub _sse_result {
Subroutine _sse_result: called CC=3 SCAR=11.0
646 18 my ( $self, $outcome, $resolve_on ) = @_;
647  
648 18 ▶ return $outcome if $outcome->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $outcome->is_ready 15 3 18
649  
650 # A subscription is never answered with a response, so reporting a missing
651 # one would send a caller looking for something the server was never going
652 # to send.
653 3 ▶ return Future->fail("MCP HTTP stream ended before the subscription was acknowledged")
Branch: 1 branch
BranchTrueFalseTotal
if defined $resolve_on 1 2 3
654 if defined $resolve_on;
655  
656 2 return Future->fail("MCP HTTP no JSON-RPC response in SSE stream");
657 }
658  
659 # The metadata headers every POST carries. They are read back out of the body
660 # instead of out of transport state so that the two cannot drift apart: the
661 # server compares header against body and answers -32020 when they differ.
662 96 ▶sub _standard_headers {
Subroutine _standard_headers: called CC=11 SCAR=24.0
663 96 my ( $self, $method, $params, %options ) = @_;
664  
665 96 ▶ $params = {} unless ref $params eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params eq "HASH" 12 84 96
666  
667 96 my @headers = (
668 'Content-Type' => 'application/json',
669 'Accept' => 'application/json, text/event-stream',
670 );
671  
672 # A legacy session describes itself with its session id and the revision
673 # agreed on, and nothing about the request is mirrored - those headers are
674 # the modern revision's. The request opening the session has neither yet.
675 96 ▶ if ($self->{legacy}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"legacy"}) 41 55 96
676 41 ▶ push @headers, $self->_session_headers unless $options{start_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"start_session"} 29 12 41
677 41 return ( $self->_caller_headers(@headers), @headers );
678 }
679  
680 # Absent for a request built without _meta, and for a notification sent
681 # through send_notification with no params at all - this client sends none
682 # itself, but the method stays open to callers. Sending a made up version
683 # would be worse than sending none: the server only compares what it gets.
684 55 ▶ my $version = ($params->{_meta} // {})->{'io.modelcontextprotocol/protocolVersion'};
Condition100%2/2
$params->{"_meta"} // {}
l!l
2728
MC/DC100%1/1
$params->{"_meta"} // {}
$params->{"_meta"}
Truth table100%2/2
A
A= $params->{"_meta"}
Aresult
11
00
685 55 ▶ push @headers, 'MCP-Protocol-Version' => $version if defined $version;
Branch: 1 branch
BranchTrueFalseTotal
if defined $version 27 28 55
686  
687 55 push @headers, 'Mcp-Method' => $method;
688  
689 55 ▶ if (my $key = $NAME_PARAM{$method}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $key = $NAME_PARAM{$method}) 20 35 55
690 20 ▶ push @headers, 'Mcp-Name' => $self->_encode_header($params->{$key} // '');
Condition50%1/2
$params->{$key} // ""
l!l
200
MC/DC0%0/1
$params->{$key} // ""
$params->{$key}
Truth table50%1/2
A
A= $params->{$key}
Aresult
11
00
691 }
692  
693 # Tool arguments annotated with x-mcp-header, already resolved and formatted
694 # by the client: which arguments these are and what they look like is MCP
695 # semantics, only the wire form is this transport's business. They travel
696 # through the same sentinel encoding as Mcp-Name, which is what the server
697 # undoes before comparing.
698 55 ▶ for my $param (@{ $options{header_params} // [] }) {
Condition100%2/2
$options{"header_params"} // []
l!l
847
MC/DC100%1/1
$options{"header_params"} // []
$options{"header_params"}
Truth table100%2/2
A
A= $options{"header_params"}
Aresult
11
00
699 push @headers,
700 11 ▶ "Mcp-Param-$param->{name}" => $self->_encode_header($param->{value} // '');
Condition50%1/2
$param->{"value"} // ""
l!l
110
MC/DC0%0/1
$param->{"value"} // ""
$param->{"value"}
Truth table50%1/2
A
A= $param->{"value"}
Aresult
11
00
701 }
702  
703 # The caller's own headers go first and the derived ones after, so an
704 # Authorization can be added while an Mcp-Method cannot be taken over.
705 55 return ( $self->_caller_headers(@headers), @headers );
706 }
707  
708 # The headers that place a POST in a legacy session: its id, where the server
709 # assigned one, and the revision agreed on, once there is one.
710 31 ▶sub _session_headers {
Subroutine _session_headers: called CC=3 SCAR=11.1
711 31 my ( $self ) = @_;
712 return (
713 defined $self->{session_id}
714 ? ( 'Mcp-Session-Id' => $self->{session_id} ) : (),
715 defined $self->{legacy_protocol_version}
716 31 ▶ ? ( 'MCP-Protocol-Version' => $self->{legacy_protocol_version} ) : (),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'session_id'} ? : 29 2 31
defined $self->{'legacy_protocol_version'} ? : 31 0 31
717 );
718 }
719  
720 # The headers only this transport sets, whether or not a given request carries
721 # them: a caller's version of one would at best be ignored and at worst put a
722 # request into a session or a revision it is not in.
723 6 my %RESERVED_HEADERS = map { $_ => 1 }
724 qw( mcp-session-id mcp-protocol-version mcp-method mcp-name );
725  
726 # The headers configured on this transport, minus every field the request
727 # derives from its body and every one reserved above. Dropping them is not the
728 # same as ordering them: HTTP::Headers keeps a field given twice in one list as
729 # two values of one header rather than letting the later win, so a colliding
730 # caller header would travel alongside the derived one and diverge from the
731 # body just as visibly.
732 104 ▶sub _caller_headers {
Subroutine _caller_headers: called CC=4 SCAR=13.9
733 104 my ( $self, @derived ) = @_;
734  
735 104 my $headers = $self->{headers};
736 104 ▶ return () unless ref $headers eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $headers eq "HASH" 87 17 104
737  
738 17 my %derived = %RESERVED_HEADERS;
739 17 ▶ for (my $i = 0; $i < @derived; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @derived) 62 17 79
740 62 $derived{ lc $derived[$i] } = 1;
741 }
742  
743 18 return map { $_ => $headers->{$_} }
744 17 ▶ grep { !$derived{ lc $_ } && !/^mcp-param-/i }
Condition100%3/3
$derived{lc $_} || /^mcp-param-/i
l!l&&r!l&&!r
35318
MC/DC100%2/2
$derived{lc $_} || /^mcp-param-/i
$derived{lc $_} /^mcp-param-/i
Truth table100%3/3
A || B
A= $derived{lc $_}B= /^mcp-param-/i
ABresult
1X1
011
000
745 sort keys %$headers;
746 }
747  
748 # A header value that is not printable ASCII travels base64 encoded in a
749 # sentinel, as does one that already looks like the sentinel itself, which
750 # would otherwise be decoded by the server into something the body never said.
751 31 ▶sub _encode_header {
Subroutine _encode_header: called CC=3 SCAR=11.0
752 31 my ( $self, $value ) = @_;
753  
754 31 ▶ return $value
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /^[\x20-\x7e]*\z/ and not $value =~ /^=\?base64\?.*\?=$/ 26 5 31
Condition100%3/3
$value =~ /^[\x20-\x7e]*\z/ and not $value =~ /^=\?base64\?.*\?=$/
!ll&&!rl&&r
4126
MC/DC100%2/2
$value =~ /^[\x20-\x7e]*\z/ and not $value =~ /^=\?base64\?.*\?=$/
$value =~ /^[\x20-\x7e]*\z/ not $value =~ /^=\?base64\?.*\?=$/
Truth table100%3/3
A and not(B)
A= $value =~ /^[\x20-\x7e]*\z/B= not $value =~ /^=\?base64\?.*\?=$/
ABresult
0X0
100
111
755 if $value =~ /^[\x20-\x7e]*\z/ && $value !~ /^=\?base64\?.*\?=$/;
756  
757 5 return '=?base64?' . encode_base64(encode('UTF-8', $value), '') . '?=';
758 }
759  
760 66 ▶sub _handle_response {
Subroutine _handle_response: called CC=8 SCAR=21.9
761 66 my ( $self, $response, $sent_session ) = @_;
762  
763 66 my $status = $response->code;
764  
765 66 ▶ if (my @expired = $self->_session_expired($response, $sent_session)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@expired) = $self->_session_expired($response, $sent_session)) 6 60 66
766 6 return Future->fail(@expired);
767 }
768  
769 60 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 19 41 60
770 # An MCP server renders JSON-RPC errors with a non-2xx status taken from
771 # the request context (400 for a rejected _meta, 403 for insufficient
772 # scope, 404 for METHOD_NOT_FOUND), so the body carries the real error and
773 # must win over the HTTP status. Only a non-2xx without a JSON-RPC error
774 # body is an HTTP-level problem.
775 19 ▶ if (my @failure = $self->_jsonrpc_error_from_body($response)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@failure) = $self->_jsonrpc_error_from_body($response)) 11 8 19
776 11 return Future->fail(@failure);
777 }
778  
779 8 return Future->fail("MCP HTTP error: " . $response->status_line);
780 }
781  
782 41 ▶ my $content_type = $response->content_type // '';
Condition50%1/2
$response->content_type // ""
l!l
410
MC/DC0%0/1
$response->content_type // ""
$response->content_type
Truth table50%1/2
A
A= $response->content_type
Aresult
11
00
783  
784 # charset => 'none' undoes Content-Encoding but leaves the body as UTF-8
785 # bytes, which is what the JSON decoder below expects; letting
786 # decoded_content apply the charset too would decode text/event-stream twice.
787 41 ▶ if ($content_type =~ m{^application/json}i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($content_type =~ m[^application/json]i) { } 36 5 41
elsif ($content_type =~ m[^text/event-stream]i) { } 5 0 5
788 36 return $self->_handle_json_response($response->decoded_content(charset => 'none'));
789 }
790 elsif ($content_type =~ m{^text/event-stream}i) {
791 5 return $self->_handle_sse_response($response->decoded_content(charset => 'none'));
792 }
793  
794 # 202 Accepted with no body (for notifications/responses)
795 0 ▶ if ($status == 202) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 202) 0 0 0
796 0 return Future->done(undef);
797 }
798  
799 0 return Future->fail("MCP HTTP unexpected content-type: $content_type");
800 }
801  
802 # A notification is answered with a status and nothing this client reads, so
803 # the status is all there is to judge - 202 Accepted with an empty body is the
804 # normal case. Deliberately not routed through _handle_response, which would
805 # fail exactly that empty body as invalid JSON.
806 16 ▶sub _handle_notification_response {
Subroutine _handle_notification_response: called CC=4 SCAR=14.0
807 16 my ( $self, $response, $sent_session ) = @_;
808  
809 16 ▶ return Future->done if $response->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $response->is_success 13 3 16
810  
811 3 ▶ if (my @expired = $self->_session_expired($response, $sent_session)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@expired) = $self->_session_expired($response, $sent_session)) 0 3 3
812 0 return Future->fail(@expired);
813 }
814  
815 3 ▶ if (my @failure = $self->_jsonrpc_error_from_body($response)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@failure) = $self->_jsonrpc_error_from_body($response)) 2 1 3
816 2 return Future->fail(@failure);
817 }
818  
819 1 return Future->fail("MCP HTTP error: " . $response->status_line);
820 }
821  
822 # The failure of a POST the server answered with 404 although it carried a
823 # legacy session id, or nothing. The specification has a client read that
824 # status as the end of the session whatever the body says, so the session is
825 # forgotten - unless a newer one has replaced it meanwhile, which a 404 to the
826 # old one says nothing about - and the failure names it, for the client to
827 # start a new one.
828 69 ▶sub _session_expired {
Subroutine _session_expired: called CC=5 SCAR=16.1
829 69 my ( $self, $response, $sent_session ) = @_;
830 69 ▶ return unless defined $sent_session && $response->code == 404;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sent_session and $response->code == 404 63 6 69
Condition100%3/3
defined $sent_session and $response->code == 404
!ll&&!rl&&r
5766
MC/DC100%2/2
defined $sent_session and $response->code == 404
defined $sent_session $response->code == 404
Truth table100%3/3
A and B
A= defined $sent_sessionB= $response->code == 404
ABresult
0X0
100
111
831  
832 delete $self->{session_id}
833 6 ▶ if defined $self->{session_id} && $self->{session_id} eq $sent_session;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"session_id"} and $self->{"session_id"} eq $sent_session 4 2 6
Condition66%2/3
defined $self->{"session_id"} and $self->{"session_id"} eq $sent_session
!ll&&!rl&&r
204
MC/DC50%1/2
defined $self->{"session_id"} and $self->{"session_id"} eq $sent_session
defined $self->{"session_id"} $self->{"session_id"} eq $sent_session
Truth table66%2/3
A and B
A= defined $self->{"session_id"}B= $self->{"session_id"} eq $sent_session
ABresult
0X0
100
111
834  
835 6 return ("MCP HTTP session $sent_session not found (" . $response->status_line . ")",
836 mcp_session_expired => $sent_session);
837 }
838  
839 22 ▶sub _jsonrpc_error_from_body {
Subroutine _jsonrpc_error_from_body: called CC=3 SCAR=11.0
840 22 my ( $self, $response ) = @_;
841  
842 22 my $body = eval { $response->decoded_content(charset => 'none') };
843 22 ▶ return () unless defined $body && length $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body and length $body 4 18 22
Condition66%2/3
defined $body and length $body
!ll&&!rl&&r
0418
MC/DC50%1/2
defined $body and length $body
defined $body length $body
Truth table66%2/3
A and B
A= defined $bodyB= length $body
ABresult
0X0
100
111
844  
845 18 my $data = eval { $self->{json}->decode($body) };
846 18 return $self->_jsonrpc_error_failure($data);
847 }
848  
849 # Private: the class that reads the error of a response, named once.
850 28 ▶sub _jsonrpc_class { 'Net::Async::MCP::JSONRPC' }
Subroutine _jsonrpc_class: called CC=1 SCAR=0.0
851  
852 # The Future->fail arguments for a decoded body that carries a JSON-RPC error
853 # object, and the empty list for anything else - see
854 # Net::Async::MCP::JSONRPC, which the stdio transport reads its answers with
855 # too.
856 25 ▶sub _jsonrpc_error_failure {
Subroutine _jsonrpc_error_failure: called CC=1 SCAR=0.0
857 25 my ( $self, $data ) = @_;
858 25 return $self->_jsonrpc_class->error_failure($data);
859 }
860  
861 # A body that says "error" in a shape this client cannot read as JSON-RPC still
862 # says the request failed. Report it as a failure carrying whatever text it
863 # holds rather than reaching into it as if it were an object.
864 3 ▶sub _foreign_error_message {
Subroutine _foreign_error_message: called CC=1 SCAR=0.0
865 3 my ( $self, $err ) = @_;
866 3 return 'MCP HTTP error response: '.$self->_jsonrpc_class->error_text($err);
867 }
868  
869 # An "error": null with no result beside it, which answers nothing.
870 2 ▶sub _null_error_message { 'MCP HTTP invalid response: a null error and no result' }
Subroutine _null_error_message: called CC=1 SCAR=0.0
871  
872 36 ▶sub _handle_json_response {
Subroutine _handle_json_response: called CC=7 SCAR=19.5
873 36 my ( $self, $body ) = @_;
874  
875 36 my $data = eval { $self->{json}->decode($body) };
876 36 ▶ return Future->fail("MCP HTTP invalid JSON: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 36 36
877 36 ▶ return Future->fail("MCP HTTP invalid response") unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 36 36
878  
879 36 ▶ if (defined(my $err = $data->{error})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $err = $data->{"error"})) 4 32 36
880 4 my @failure = $self->_jsonrpc_error_failure($data);
881 4 ▶ return Future->fail(@failure) if @failure;
Branch: 1 branch
BranchTrueFalseTotal
if @failure 2 2 4
882 2 return Future->fail($self->_foreign_error_message($err));
883 }
884  
885 # The null error of _settle_response, read the same in a whole JSON body.
886 return Future->fail($self->_null_error_message)
887 32 ▶ if exists $data->{error} && !exists $data->{result};
Branch: 1 branch
BranchTrueFalseTotal
if exists $data->{"error"} and not exists $data->{"result"} 1 31 32
Condition100%3/3
exists $data->{"error"} and not exists $data->{"result"}
!ll&&!rl&&r
3011
MC/DC100%2/2
exists $data->{"error"} and not exists $data->{"result"}
exists $data->{"error"} not exists $data->{"result"}
Truth table100%3/3
A and not(B)
A= exists $data->{"error"}B= not exists $data->{"result"}
ABresult
0X0
100
111
888  
889 31 return Future->done($data->{result});
890 }
891  
892 # A whole SSE body in hand rather than a stream to read from, which is the
893 # same events through the same reader, all at once. Only a caller holding a
894 # complete response gets here: a streamed one is read by _sse_reader itself.
895 5 ▶sub _handle_sse_response {
Subroutine _handle_sse_response: called CC=1 SCAR=0.0
896 5 my ( $self, $body ) = @_;
897  
898 5 my $read = $self->_sse_reader;
899 5 $read->($body);
900 5 return $read->();
901 }
902  
903  
904 6 1;
905  
906 __END__
« blib/lib/Net/Async/MCP.pm ↑ Summary blib/lib/Net/Async/MCP/Transport/Stdio.pm »