MCP.pm

filter: Statementstmt 98.9% 276 / 279 Branchbran 88.2% 90 / 102 Conditioncond 65.9% 58 / 88 MC/DCmcdc 35.4% 17 / 48 Subroutinesub 97.7% 44 / 45 Podpod 100% 19 / 19 totaltotal 86.7% 504 / 581 CC 98 SCAR 18.7
CC
98
Cov
90%
_renegotiated_version
14.6
_input_responses
13.9
_request
9.0
CRAP 6.5
« MCP/Transport/HTTP.pm ↑ Summary MCP/Transport/Stdio.pm »
1 package Net::Async::MCP;
2 # ABSTRACT: Async MCP (Model Context Protocol) client for IO::Async
3  
4 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 7 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Scalar::Util qw( blessed looks_like_number weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 7 our $VERSION = '0.006';
13  
14  
15 # The protocol revisions this client speaks, newest first: the first of them is
16 # what a client that was not told otherwise sends, and they are the only ones a
17 # refused request may be renegotiated into.
18 #
19 # What belongs in here is decided by the code below and by nothing else: an
20 # entry means that what this file builds is what that revision defines - today
21 # a server/discover handshake with no initialize/initialized pair, the
22 # io.modelcontextprotocol/* keys in _meta, and input_required results answered
23 # with inputResponses. So adding one means first teaching this client to build
24 # that revision's request shapes. A revision some dependency happens to know
25 # about is not one this client can speak, and switching to it on that strength
26 # would put a new version string on requests that revision never had - trading
27 # a clear "unsupported protocol version" for a confusing "method not found".
28 #
29 # Deliberately not MCP::Constants::SUPPORTED_VERSIONS: that list says what the
30 # installed server library accepts, which is a different question whose answer
31 # only happens to be the same one today.
32 7 my @SPOKEN_PROTOCOL_VERSIONS = ('2026-07-28');
33  
34 # What this client sends when the caller named no protocol_version: the newest
35 # revision it speaks. Deliberately not MCP::Constants::PROTOCOL_VERSION - that
36 # is the revision the installed server library implements, and following it
37 # onto a newer one would put that version string on requests this file still
38 # builds in the old one, for the reason spelled out above.
39 7 my $DEFAULT_PROTOCOL_VERSION = $SPOKEN_PROTOCOL_VERSIONS[0];
40  
41 # The code a server answers a request made in a revision it does not speak
42 # with. The number the specification gives it, written out rather than read
43 # from L<MCP::Constants>: it is compared against what a remote server sent, so
44 # a locally installed library has no say in it, and a client on stdio or HTTP
45 # has no reason to have L<MCP> installed at all.
46 7 my $UNSUPPORTED_PROTOCOL_VERSION = -32022;
47  
48 # The settings this client keeps to itself, whichever transport it ends up
49 # with.
50 7 my @CLIENT_KEYS = qw( server command url protocol_version client_capabilities
51 on_input_request );
52  
53 # The settings handed on to the transport instead, each with the class a
54 # transport has to be for it to reach it. Kept apart from @CLIENT_KEYS because
55 # they are passed on only when the caller actually gave them: the transport's
56 # own default for stall_timeout has to survive a client that was never asked
57 # about it.
58 #
59 # Which transport takes what is one decision per key rather than one for the
60 # lot. headers, timeout and stall_timeout describe an HTTP request, and handing
61 # one to the Stdio transport is not a setting it ignores but an "Unrecognised
62 # configuration keys" croak; on_notification is an event both wire transports
63 # have. on_subscription_end has only the HTTP transport to go to, a stream
64 # being the one thing a subscription can end on. The InProcess transport is no
65 # L<IO::Async::Notifier>, has no C<configure> and no events at all, so it
66 # matches nothing here and is handed nothing.
67 7 my %TRANSPORT_KEYS = (
68 headers => 'Net::Async::MCP::Transport::HTTP',
69 timeout => 'Net::Async::MCP::Transport::HTTP',
70 stall_timeout => 'Net::Async::MCP::Transport::HTTP',
71 on_notification => 'IO::Async::Notifier',
72 on_subscription_end => 'Net::Async::MCP::Transport::HTTP',
73 );
74  
75 # The keys of %TRANSPORT_KEYS that are events of this client rather than
76 # settings. They travel to the transport wrapped - see _event_handler - and
77 # are asked for by event rather than by key, because a subclass method of that
78 # name is a handler just as much as a configured code ref is.
79 7 my %EVENT_KEYS = map { $_ => 1 } qw( on_notification on_subscription_end );
80  
81 38 ▶sub _init {
Subroutine _init: called CC=5 SCAR=16.1
82 38 my ( $self, $params ) = @_;
83 38 for my $key (@CLIENT_KEYS, keys %TRANSPORT_KEYS) {
84 418 ▶ $self->{$key} = delete $params->{$key} if exists $params->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params->{$key} 61 357 418
85 }
86 38 ▶ $self->{protocol_version} //= $DEFAULT_PROTOCOL_VERSION;
Condition66%2/3
$self->{"protocol_version"} //= $DEFAULT_PROTOCOL_VERSION
l!l&&r!l&&!r
4340
MC/DC0%0/2
$self->{"protocol_version"} //= $DEFAULT_PROTOCOL_VERSION
$self->{"protocol_version"} $DEFAULT_PROTOCOL_VERSION
Truth table66%2/3
A //= B
A= $self->{"protocol_version"}B= $DEFAULT_PROTOCOL_VERSION
ABresult
1X1
011
000
87 38 ▶ $self->{client_capabilities} //= {};
Condition100%2/2
$self->{"client_capabilities"} //= {}
l!l
731
MC/DC100%1/1
$self->{"client_capabilities"} //= {}
$self->{"client_capabilities"}
Truth table100%2/2
A
A= $self->{"client_capabilities"}
Aresult
11
00
88 38 $self->SUPER::_init($params);
89 }
90  
91 47 ▶sub configure {
Subroutine configure: called CC=7 SCAR=19.5
Pod documented
92 47 my ( $self, %params ) = @_;
93 47 my @changed = grep { exists $params{$_} } sort keys %TRANSPORT_KEYS;
94 47 for my $key (@CLIENT_KEYS, keys %TRANSPORT_KEYS) {
95 517 ▶ $self->{$key} = delete $params{$key} if exists $params{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$key} 9 508 517
96 }
97 47 ▶ $self->{protocol_version} //= $DEFAULT_PROTOCOL_VERSION;
Condition66%2/3
$self->{"protocol_version"} //= $DEFAULT_PROTOCOL_VERSION
l!l&&r!l&&!r
4610
MC/DC0%0/2
$self->{"protocol_version"} //= $DEFAULT_PROTOCOL_VERSION
$self->{"protocol_version"} $DEFAULT_PROTOCOL_VERSION
Truth table66%2/3
A //= B
A= $self->{"protocol_version"}B= $DEFAULT_PROTOCOL_VERSION
ABresult
1X1
011
000
98 47 ▶ $self->{client_capabilities} //= {};
Condition100%2/2
$self->{"client_capabilities"} //= {}
l!l
461
MC/DC100%1/1
$self->{"client_capabilities"} //= {}
$self->{"client_capabilities"}
Truth table100%2/2
A
A= $self->{"client_capabilities"}
Aresult
11
00
99  
100 # A transport that already exists takes the change too: the transport is
101 # built when this client joins a loop, and a bearer token that has to be
102 # rotated, or a handler for the notifications of a call about to be made,
103 # arrives long after that. Only the keys that transport takes, though - see
104 # %TRANSPORT_KEYS for why that is asked per key and not once for the lot.
105 47 ▶ if ( my $transport = $self->{transport} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $transport = $self->{"transport"}) 9 38 47
106 9 my @keys = grep { $transport->isa($TRANSPORT_KEYS{$_}) } @changed;
107 9 ▶ $transport->configure($self->_transport_params(@keys)) if @keys;
Branch: 1 branch
BranchTrueFalseTotal
if @keys 5 4 9
108 }
109  
110 47 $self->SUPER::configure(%params);
111 }
112  
113 # Private: the named settings as the transport takes them. All of them travel
114 # as they stand except the events among them, which the transport would
115 # otherwise invoke with itself - see _event_handler.
116 11 ▶sub _transport_params {
Subroutine _transport_params: called CC=2 SCAR=6.9
117 11 my ( $self, @keys ) = @_;
118 11 my %params = map { $_ => $self->{$_} } @keys;
119 11 for my $event (grep { $EVENT_KEYS{$_} } keys %params) {
120 8 $params{$event} = $self->_event_handler($event);
121 }
122 11 return %params;
123 }
124  
125 # Private: the handler handed to the transport for an event of this client's
126 # own. It is the transport that receives the underlying thing - a notification,
127 # an ended subscription - and invokes the event, so a handler passed on as it
128 # stands would be called with the transport, while every other event of this
129 # client is called with the client. This wrapper puts the client back in front,
130 # and leaves the choice of handler to the client's own event dispatch, so a
131 # subclass method serves as well as a configured code ref.
132 #
133 # The client holds the transport, so what the transport holds must not hold the
134 # client: a strong reference in here would close the cycle. It is never undef
135 # where it matters - a transport that can still deliver anything is in a loop,
136 # and the loop holds the client that holds it.
137 8 ▶sub _event_handler {
Subroutine _event_handler: called CC=2 SCAR=7.1
138 8 my ( $self, $event ) = @_;
139 8 ▶ return undef unless $self->can_event($event);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can_event($event) 0 8 8
140  
141 8 weaken( my $weak_self = $self );
142 5 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
143 5 my ( undef, @args ) = @_;
144 5 ▶ my $client = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $client = $weak_self or return 5 0 5
145 5 return $client->maybe_invoke_event($event => @args);
146 8 };
147 }
148  
149 29 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=1 SCAR=0.0
150 29 my ( $self, $loop ) = @_;
151 29 $self->SUPER::_add_to_loop($loop);
152 29 $self->_ensure_transport;
153 }
154  
155 40 ▶sub _ensure_transport {
Subroutine _ensure_transport: called CC=7 SCAR=19.8
156 40 my ( $self ) = @_;
157 40 ▶ return if $self->{transport};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"transport"} 11 29 40
158  
159 29 ▶ if ($self->{server}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->{'server'}) { } 23 6 29
elsif ($self->{'command'}) { } 3 3 6
elsif ($self->{'url'}) { } 3 0 3
160 23 require Net::Async::MCP::Transport::InProcess;
161 $self->{transport} = Net::Async::MCP::Transport::InProcess->new(
162 server => $self->{server},
163 23 );
164 }
165 elsif ($self->{command}) {
166 3 ▶ croak "Stdio transport requires being added to an IO::Async::Loop"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->loop 0 3 3
167 unless $self->loop;
168 3 require Net::Async::MCP::Transport::Stdio;
169 $self->_build_transport('Net::Async::MCP::Transport::Stdio',
170 3 command => $self->{command});
171 }
172 elsif ($self->{url}) {
173 3 ▶ croak "HTTP transport requires being added to an IO::Async::Loop"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->loop 0 3 3
174 unless $self->loop;
175 3 require Net::Async::MCP::Transport::HTTP;
176 $self->_build_transport('Net::Async::MCP::Transport::HTTP',
177 3 url => $self->{url});
178 }
179 else {
180 0 croak "Must provide server, command, or url";
181 }
182 }
183  
184 # Private: a transport of $class, built with the setting that selected it and
185 # whichever of %TRANSPORT_KEYS that class takes, and made a child of this
186 # client so that it joins and leaves the loop along with it.
187 6 ▶sub _build_transport {
Subroutine _build_transport: called CC=2 SCAR=6.9
188 6 my ( $self, $class, %params ) = @_;
189  
190 # Only the keys the caller actually gave: handing over a stall_timeout of
191 # undef for one that was never set would switch off the transport's default
192 # instead of leaving it alone. Events are asked for by name rather than by
193 # key, because a subclass method of that name is a handler just as much as a
194 # configured code ref is.
195 6 my @keys = grep { $class->isa($TRANSPORT_KEYS{$_}) }
196 6 ▶ grep { $EVENT_KEYS{$_} ? $self->can_event($_) : exists $self->{$_} }
Branch: 1 branch
BranchTrueFalseTotal
$EVENT_KEYS{$_} ? : 12 18 30
197 sort keys %TRANSPORT_KEYS;
198  
199 6 my $transport = $class->new(%params, $self->_transport_params(@keys));
200 6 $self->{transport} = $transport;
201 6 $self->add_child($transport);
202 6 return $transport;
203 }
204  
205 5 ▶sub protocol_version { $_[0]->{protocol_version} }
Subroutine protocol_version: called CC=1 SCAR=0.0
Pod documented
206  
207  
208 3 ▶sub client_capabilities { $_[0]->{client_capabilities} }
Subroutine client_capabilities: called CC=1 SCAR=0.0
Pod documented
209  
210  
211 2 ▶sub headers { $_[0]->{headers} }
Subroutine headers: called CC=1 SCAR=0.0
Pod documented
212  
213  
214 1 ▶sub timeout { $_[0]->{timeout} }
Subroutine timeout: called CC=1 SCAR=0.0
Pod documented
215  
216  
217 1 ▶sub stall_timeout { $_[0]->{stall_timeout} }
Subroutine stall_timeout: called CC=1 SCAR=0.0
Pod documented
218  
219  
220  
221  
222  
223 # Private: the C<_meta> fields carried on every JSON-RPC request, as required
224 # by the current MCP revision.
225 78 ▶sub _meta {
Subroutine _meta: called CC=1 SCAR=0.0
226 78 my ( $self ) = @_;
227 return {
228 'io.modelcontextprotocol/protocolVersion' => $self->{protocol_version},
229 'io.modelcontextprotocol/clientCapabilities' => $self->{client_capabilities},
230 78 'io.modelcontextprotocol/clientInfo' => {
231 name => 'Net::Async::MCP',
232 version => $VERSION,
233 },
234 };
235 }
236  
237 # Private: merge a caller's C<_meta> (if any) into the standard one, returning
238 # params that carry C<_meta> on every request.
239 78 ▶sub _with_meta {
Subroutine _with_meta: called CC=3 SCAR=11.2
240 78 my ( $self, $params ) = @_;
241 78 ▶ my %params = %{ $params // {} };
Condition50%1/2
$params // {}
l!l
780
MC/DC0%0/1
$params // {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
242 78 ▶ my %meta = (%{ $self->_meta }, %{ $params{_meta} // {} });
Condition50%1/2
$params{"_meta"} // {}
l!l
078
MC/DC0%0/1
$params{"_meta"} // {}
$params{"_meta"}
Truth table50%1/2
A
A= $params{"_meta"}
Aresult
11
00
243 78 return { %params, _meta => \%meta };
244 }
245  
246 # Private: how many input_required results one request may collect before the
247 # client gives up on it. A server is allowed to ask again after being answered
248 # - a confirmation can lead to a second question - but one that never arrives
249 # at a final result would keep this going for as long as it feels like.
250 7 my $MAX_INPUT_ROUNDS = 8;
251  
252 # Private: the protocol revision to send a refused request again with, or undef
253 # if there is none. A server that does not speak the revision a request was
254 # made with answers UNSUPPORTED_PROTOCOL_VERSION and lists the ones it does
255 # speak in error.data.supported, newest first; the first of those this client
256 # speaks too is the one to switch to.
257 8 ▶sub _renegotiated_version {
Subroutine _renegotiated_version: called CC=13 SCAR=26.8
258 8 my ( $self, $failed ) = @_;
259  
260 8 my ( undef, $category, $error ) = $failed->failure;
261 8 ▶ return undef unless ( $category // '' ) eq 'mcp' && ref $error eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ($category // "") eq "mcp" and ref $error eq "HASH" 2 6 8
Condition80%4/5
($category // "") eq "mcp" and ref $error eq "HASH"
!ll&&!rl&&r
206
$category // ""
l!l
62
MC/DC50%1/2
($category // "") eq "mcp" and ref $error eq "HASH"
$category ref $error eq "HASH"
Truth table66%2/3
A and B
A= $categoryB= ref $error eq "HASH"
ABresult
0X0
100
111
262 6 ▶ return undef unless ( $error->{code} // 0 ) == $UNSUPPORTED_PROTOCOL_VERSION;
Branch: 1 branch
BranchTrueFalseTotal
unless ($error->{"code"} // 0) == $UNSUPPORTED_PROTOCOL_VERSION 2 4 6
Condition50%1/2
$error->{"code"} // 0
l!l
60
MC/DC0%0/1
$error->{"code"} // 0
$error->{"code"}
Truth table50%1/2
A
A= $error->{"code"}
Aresult
11
00
263  
264 4 ▶ my $supported = ref $error->{data} eq 'HASH' ? $error->{data}{supported} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $error->{'data'} eq 'HASH' ? : 4 0 4
265 4 ▶ return undef unless ref $supported eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $supported eq "ARRAY" 0 4 4
266  
267 4 my %usable = map { $_ => 1 } @SPOKEN_PROTOCOL_VERSIONS;
268 4 for my $version (@$supported) {
269 4 ▶ next unless defined $version && !ref $version && $usable{$version};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and not ref $version and $usable{$version} 1 3 4
Condition50%3/6
defined $version and not ref $version and $usable{$version}
!ll&&!rl&&r
013
defined $version and not ref $version
!ll&&!rl&&r
004
MC/DC33%1/3
defined $version and not ref $version and $usable{$version}
defined $version not ref $version $usable{$version}
Truth table50%2/4
A and not(B) and C
A= defined $versionB= not ref $versionC= $usable{$version}
ABCresult
0XX0
10X0
1100
1111
270  
271 # The one offer that is no answer: the request that was just refused
272 # carried this very version, so sending it again would be sending the same
273 # request twice and getting the same refusal back.
274 3 ▶ return undef if $version eq $self->{protocol_version};
Branch: 1 branch
BranchTrueFalseTotal
if $version eq $self->{"protocol_version"} 0 3 3
275 3 return $version;
276 }
277  
278 1 return undef;
279 }
280  
281 # Private: one MCP request, from a method's own params to the final result.
282 # Every method goes through here, because this is the one place that holds what
283 # is true of all of them: the _meta every request carries, the input_required
284 # round trips a result may take before it is one, and the one retry a refused
285 # protocol version is worth.
286 63 ▶async sub _request {
Subroutine _request: called CC=9 SCAR=22.0
287 63 my ( $self, $method, $params, %options ) = @_;
288  
289 63 my ( %retry, $rounds, $renegotiated );
290 63 while ( 1 ) {
291 # Awaited as a completed Future rather than for its value: a failure has
292 # more to it than its message, and the server's error object - which is
293 # where a refused version names the ones it would accept instead - travels
294 # as the failure's details.
295 my $answered = await $self->{transport}->send_request($method,
296 78 ▶ $self->_with_meta({ %{ $params // {} }, %retry }), %options)
Condition100%2/2
$params // {}
l!l
5820
MC/DC100%1/1
$params // {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
297 78 ▶ ->followed_by(sub { Future->done( $_[0] ) });
Subroutine __ANON__: called CC=1 SCAR=0.0
298  
299 77 ▶ if ( $answered->is_failed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($answered->is_failed) 9 68 77
300 9 ▶ my $version = $renegotiated ? undef : $self->_renegotiated_version($answered);
Branch: 1 branch
BranchTrueFalseTotal
$renegotiated ? : 1 8 9
301  
302 # Nothing to switch to, or one switch already made - which makes a second
303 # refusal the server's problem and not one more version away from being
304 # solved. Either way the server's own error is what the caller gets, code
305 # and data and all, rather than a summary of it written here.
306 9 ▶ return await $answered unless defined $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version 6 3 9
307  
308 # Kept on the client, not just used for the retry: every following
309 # request would otherwise pay for the same refusal again. The _meta at
310 # the top of this loop is built afresh, so the retry carries the version
311 # agreed on here and the answers of any input_required round already
312 # walked.
313 3 $renegotiated = 1;
314 3 $self->{protocol_version} = $version;
315 3 next;
316 }
317  
318 68 my $result = $answered->get;
319  
320 return $result
321 unless ref $result eq 'HASH'
322 68 ▶ && ( $result->{resultType} // '' ) eq 'input_required';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $result eq "HASH" and ($result->{"resultType"} // "") eq "input_required" 51 17 68
Condition80%4/5
ref $result eq "HASH" and ($result->{"resultType"} // "") eq "input_required"
!ll&&!rl&&r
05117
$result->{"resultType"} // ""
l!l
3533
MC/DC50%1/2
ref $result eq "HASH" and ($result->{"resultType"} // "") eq "input_required"
ref $result eq "HASH" $result->{"resultType"}
Truth table66%2/3
A and B
A= ref $result eq "HASH"B= $result->{"resultType"}
ABresult
0X0
100
111
323  
324 17 ▶ croak "MCP $method: server answered with input_required more than "
Branch: 1 branch
BranchTrueFalseTotal
if ++$rounds > $MAX_INPUT_ROUNDS 1 16 17
325 . "$MAX_INPUT_ROUNDS times without returning a result"
326 if ++$rounds > $MAX_INPUT_ROUNDS;
327  
328 16 %retry = await $self->_input_required($method, $result);
329 }
330 7 }
331  
332 # Private: the top-level params that turn a request into the retry an
333 # input_required result asks for. Both of them are optional and each is sent
334 # only when the result actually carried it.
335 16 ▶async sub _input_required {
Subroutine _input_required: called CC=5 SCAR=16.1
336 16 my ( $self, $method, $result ) = @_;
337  
338 16 my %retry;
339  
340 # Mirrored back exactly as it arrived. The server sealed it against its own
341 # secret and bound it to this caller and this primitive, so there is nothing
342 # here to read and everything to break by touching it.
343 16 ▶ $retry{requestState} = $result->{requestState} if defined $result->{requestState};
Branch: 1 branch
BranchTrueFalseTotal
if defined $result->{"requestState"} 11 5 16
344  
345 16 my $requests = $result->{inputRequests};
346 16 ▶ if ( ref $requests eq 'HASH' && keys %$requests ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $requests eq 'HASH' and keys %$requests) { } 6 10 16
elsif (not %retry) { } 1 9 10
Condition66%2/3
ref $requests eq "HASH" and keys %$requests
!ll&&!rl&&r
1006
MC/DC50%1/2
ref $requests eq "HASH" and keys %$requests
ref $requests eq "HASH" keys %$requests
Truth table66%2/3
A and B
A= ref $requests eq "HASH"B= keys %$requests
ABresult
0X0
100
111
347 6 $retry{inputResponses} = await $self->_input_responses($method, $requests);
348 }
349 elsif ( !%retry ) {
350 # Neither half: no question to answer, and nothing to hand back that would
351 # make the second attempt any different from the first.
352 1 croak "MCP $method: server sent an input_required result with neither "
353 . "inputRequests nor requestState";
354 }
355  
356 12 return %retry;
357 7 }
358  
359 # Private: the answers to a server's input requests, under the keys it asked
360 # them by - the same keys it reads its own responses back from.
361 6 ▶async sub _input_responses {
Subroutine _input_responses: called CC=13 SCAR=26.3
362 6 my ( $self, $method, $requests ) = @_;
363  
364 # Checked over the whole ask before a single answer is gathered: a server
365 # that asks for an undeclared capability has broken its side of the
366 # capability promise, and no part of that ask should be acted on.
367 6 ▶ my $capabilities = $self->{client_capabilities} // {};
Condition50%1/2
$self->{"client_capabilities"} // {}
l!l
60
MC/DC0%0/1
$self->{"client_capabilities"} // {}
$self->{"client_capabilities"}
Truth table50%1/2
A
A= $self->{"client_capabilities"}
Aresult
11
00
368 6 for my $key (sort keys %$requests) {
369 7 my $request = $requests->{$key};
370 7 ▶ my $wanted = ref $request eq 'HASH' ? $request->{method} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $request eq 'HASH' ? : 7 0 7
371  
372 7 ▶ croak "MCP $method: server sent an input request '$key' without a method"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wanted and length $wanted 0 7 7
Condition33%1/3
defined $wanted and length $wanted
!ll&&!rl&&r
007
MC/DC0%0/2
defined $wanted and length $wanted
defined $wanted length $wanted
Truth table33%1/3
A and B
A= defined $wantedB= length $wanted
ABresult
0X0
100
111
373 unless defined $wanted && length $wanted;
374  
375 # The capability is the namespace of the method asked for:
376 # elicitation/create needs elicitation, sampling/createMessage needs
377 # sampling, roots/list needs roots.
378 7 my $capability = ( split m{/}, $wanted, 2 )[0];
379 croak "MCP $method: server sent input request '$key' for '$wanted', "
380 . "a capability this client did not declare in client_capabilities"
381 7 ▶ unless exists $capabilities->{$capability};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $capabilities->{$capability} 1 6 7
382 }
383  
384 5 ▶ croak "MCP $method: server sent input requests ("
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can_event("on_input_request") 1 4 5
385 . join(', ', sort keys %$requests)
386 . ") but no on_input_request handler is set to answer them"
387 unless $self->can_event('on_input_request');
388  
389 4 my %responses;
390 4 for my $key (sort keys %$requests) {
391 5 my $request = $requests->{$key};
392 my $response = $self->invoke_event(on_input_request =>
393 5 ▶ $request->{method}, $request->{params} // {});
Condition50%1/2
$request->{"params"} // {}
l!l
50
MC/DC0%0/1
$request->{"params"} // {}
$request->{"params"}
Truth table50%1/2
A
A= $request->{"params"}
Aresult
11
00
394  
395 # A handler that has to ask a human answers with a Future instead of an
396 # answer, and the retry waits for it.
397 5 ▶ $response = await $response if blessed($response) && $response->isa('Future');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($response) and $response->isa("Future") 1 4 5
Condition66%2/3
builtin::blessed($response) and $response->isa("Future")
!ll&&!rl&&r
401
MC/DC50%1/2
builtin::blessed($response) and $response->isa("Future")
builtin::blessed($response) $response->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($response)B= $response->isa("Future")
ABresult
0X0
100
111
398  
399 5 ▶ croak "MCP $method: on_input_request answered input request '$key' with "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $response eq "HASH" 1 4 5
400 . "something that is not a HashRef"
401 unless ref $response eq 'HASH';
402  
403 4 $responses{$key} = $response;
404 }
405  
406 3 return \%responses;
407 7 }
408  
409 3 ▶sub server_info { $_[0]->{server_info} }
Subroutine server_info: called CC=1 SCAR=0.0
Pod documented
410  
411  
412 0 ▶sub server_capabilities { $_[0]->{server_capabilities} }
Subroutine server_capabilities: not called CC=1 SCAR=6.9
Pod documented
413  
414  
415 3 ▶async sub initialize {
Subroutine initialize: called CC=4 SCAR=13.9
Pod documented
416 3 my ( $self ) = @_;
417 3 $self->_ensure_transport;
418  
419 3 my $result = await $self->_request('server/discover');
420  
421 # Read without autovivifying an _meta key into the result we hand back.
422 3 ▶ my $meta = $result->{_meta} // {};
Condition100%2/2
$result->{"_meta"} // {}
l!l
21
MC/DC100%1/1
$result->{"_meta"} // {}
$result->{"_meta"}
Truth table100%2/2
A
A= $result->{"_meta"}
Aresult
11
00
423 3 ▶ $self->{server_info} = $meta->{'io.modelcontextprotocol/serverInfo'} // {};
Condition100%2/2
$meta->{"io.modelcontextprotocol/serverInfo"} // {}
l!l
21
MC/DC100%1/1
$meta->{"io.modelcontextprotocol/serverInfo"} // {}
$meta->{"io.modelcontextprotocol/serverInfo"}
Truth table100%2/2
A
A= $meta->{"io.modelcontextprotocol/serverInfo"}
Aresult
11
00
424 3 ▶ $self->{server_capabilities} = $result->{capabilities} // {};
Condition50%1/2
$result->{"capabilities"} // {}
l!l
30
MC/DC0%0/1
$result->{"capabilities"} // {}
$result->{"capabilities"}
Truth table50%1/2
A
A= $result->{"capabilities"}
Aresult
11
00
425  
426 3 return $result;
427 7 }
428  
429  
430 # Private: how many pages a list method walks before giving up. Only a cursor
431 # that comes round again proves a server is looping; one that keeps changing
432 # while never running out cannot be told apart from a genuinely long list, so
433 # there has to be an end to it somewhere.
434 7 my $MAX_LIST_PAGES = 100;
435  
436 # Private: every entry of a paginated list method, following nextCursor until
437 # the server stops handing one out. $key is the result key holding the entries,
438 # and each page is appended in the order the server sent it.
439 #
440 # Anything short of the full list is failed rather than returned. Handing back
441 # the pages collected so far would be indistinguishable from a server that
442 # really has that many entries, which is exactly the bug this walk exists to
443 # fix - it would just move from the first page to the hundredth.
444 17 ▶async sub _list_all {
Subroutine _list_all: called CC=6 SCAR=18.0
445 17 my ( $self, $method, $key ) = @_;
446  
447 17 my ( @entries, %seen, $cursor );
448  
449 17 for my $page ( 1 .. $MAX_LIST_PAGES ) {
450 21 ▶ my $result = await $self->_request($method,
Branch: 1 branch
BranchTrueFalseTotal
defined $cursor ? : 4 17 21
451 defined $cursor ? { cursor => $cursor } : undef);
452  
453 20 ▶ push @entries, @{ $result->{$key} // [] };
Condition50%1/2
$result->{$key} // []
l!l
200
MC/DC0%0/1
$result->{$key} // []
$result->{$key}
Truth table50%1/2
A
A= $result->{$key}
Aresult
11
00
454  
455 20 $cursor = $result->{nextCursor};
456 20 ▶ return \@entries unless defined $cursor;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cursor 15 5 20
457  
458 # A cursor is a position in the list, so being handed one back that was
459 # already followed means the server is not moving. Left alone that spins
460 # for as long as the server keeps answering.
461 croak "MCP $method pagination: server repeated cursor '$cursor'"
462 5 ▶ if $seen{$cursor}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$cursor}++ 1 4 5
463 }
464  
465 0 croak "MCP $method pagination: server offered more than $MAX_LIST_PAGES pages";
466 7 }
467  
468 13 ▶async sub list_tools {
Subroutine list_tools: called CC=2 SCAR=7.1
Pod documented
469 13 my ( $self ) = @_;
470 13 my $tools = await $self->_list_all('tools/list', 'tools');
471  
472 # A fresh listing is the whole truth about the server's tools, so it replaces
473 # the cache rather than adding to it - and the whole truth is every page,
474 # which is why this runs on the merged list once the walk is through. A walk
475 # that failed part way leaves the cache as it was instead of replacing it with
476 # what happens to have arrived.
477 $self->{tool_header_params} = {
478 14 map { $_->{name} => _header_params($_->{inputSchema}) }
479 11 ▶ grep { ref $_ eq 'HASH' && defined $_->{name} } @$tools
Condition33%1/3
ref $_ eq 'HASH' && defined $_->{'name'}
!ll&&!rl&&r
0014
MC/DC0%0/2
ref $_ eq 'HASH' && defined $_->{'name'}
ref $_ eq 'HASH' defined $_->{'name'}
Truth table33%1/3
A && B
A= ref $_ eq 'HASH'B= defined $_->{'name'}
ABresult
0X0
100
111
480 };
481  
482 11 return $tools;
483 7 }
484  
485  
486 # Private: the arguments a server expects mirrored into Mcp-Param-{Name}
487 # headers - every property annotated with x-mcp-header, reachable from the
488 # schema root through a chain of "properties" keys and nothing else. Same walk
489 # as MCP::Tool::_header_params, whose result the server checks the headers
490 # against, down to sorting by key so both sides agree on order.
491 63 ▶sub _header_params {
Subroutine _header_params: called CC=8 SCAR=20.8
492 63 my ( $schema, $path ) = @_;
493 63 ▶ $path //= [];
Condition100%2/2
$path //= []
l!l
4518
MC/DC100%1/1
$path //= []
$path
Truth table100%2/2
A
A= $path
Aresult
11
00
494  
495 63 ▶ return [] unless ref $schema eq 'HASH' && ref $schema->{properties} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $schema eq "HASH" and ref $schema->{"properties"} eq "HASH" 42 21 63
Condition100%3/3
ref $schema eq "HASH" and ref $schema->{"properties"} eq "HASH"
!ll&&!rl&&r
14121
MC/DC100%2/2
ref $schema eq "HASH" and ref $schema->{"properties"} eq "HASH"
ref $schema eq "HASH" ref $schema->{"properties"} eq "HASH"
Truth table100%3/3
A and B
A= ref $schema eq "HASH"B= ref $schema->{"properties"} eq "HASH"
ABresult
0X0
100
111
496  
497 21 my $properties = $schema->{properties};
498 21 my @params;
499 21 for my $key (sort keys %$properties) {
500 45 my $property = $properties->{$key};
501 45 ▶ next unless ref $property eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $property eq "HASH" 0 45 45
502  
503 45 my @next = ( @$path, $key );
504 push @params, {
505 name => $property->{'x-mcp-header'},
506 path => \@next,
507 type => $property->{type} // '',
508 45 ▶ } if defined $property->{'x-mcp-header'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $property->{"x-mcp-header"} 22 23 45
Condition50%1/2
$property->{"type"} // ""
l!l
220
MC/DC0%0/1
$property->{"type"} // ""
$property->{"type"}
Truth table50%1/2
A
A= $property->{"type"}
Aresult
11
00
509 45 push @params, @{ _header_params($property, \@next) };
510 }
511  
512 21 return \@params;
513 }
514  
515 # Private: the argument a header parameter points at, or undef if the caller
516 # passed none. Same walk as MCP::Server::Transport::HTTP::_arg_value, which is
517 # what the server compares the header against.
518 20 ▶sub _arg_value {
Subroutine _arg_value: called CC=3 SCAR=11.0
519 20 my ( $arguments, $path ) = @_;
520  
521 20 my $value = $arguments;
522 20 for my $key (@$path) {
523 25 ▶ return undef unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 4 21 25
524 21 $value = $value->{$key};
525 }
526 16 return $value;
527 }
528  
529 # Private: an argument value in the form the server's _match_value compares it
530 # in. Getting this wrong is not a degradation but a rejection: the server
531 # answers -32020 (HEADER_MISMATCH) for a header that disagrees with the body.
532 8 ▶sub _header_value {
Subroutine _header_value: called CC=8 SCAR=21.0
533 8 my ( $type, $value ) = @_;
534  
535 8 ▶ if ($type eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "boolean") 3 5 8
536 # A JSON false reaches us either as \0, which JSON::MaybeXS encodes as
537 # false, or as a JSON::PP::Boolean. The latter knows it is false, but \0 is
538 # a reference and so a *true* Perl value: asking it directly would put
539 # "true" in the header while the body says false. Unwrap plain scalar
540 # references first, and let an object's own boolean overload speak.
541 3 ▶ $value = $$value while ref $value eq 'SCALAR' || ref $value eq 'REF';
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq "SCALAR" || ref $value eq "REF" and do { $value = $$value } 2 3 5
Condition66%2/3
ref $value eq "SCALAR" or ref $value eq "REF"
l!l&&r!l&&!r
203
MC/DC50%1/2
ref $value eq "SCALAR" or ref $value eq "REF"
ref $value eq "SCALAR" ref $value eq "REF"
Truth table66%2/3
A or B
A= ref $value eq "SCALAR"B= ref $value eq "REF"
ABresult
1X1
011
000
542 3 ▶ return $value ? 'true' : 'false';
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 1 2 3
543 }
544  
545 # Compared numerically by the server, so the number decides, not its
546 # spelling. Anything that is not a number at all is passed through as text
547 # for the server to reject.
548 5 ▶ return 0 + $value if $type eq 'integer' && !ref $value && looks_like_number($value);
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "integer" and not ref $value and &looks_like_number($value) 1 4 5
Condition66%4/6
$type eq "integer" and not ref $value and &looks_like_number($value)
!ll&&!rl&&r
401
$type eq "integer" and not ref $value
!ll&&!rl&&r
401
MC/DC33%1/3
$type eq "integer" and not ref $value and &looks_like_number($value)
$type eq "integer" not ref $value &looks_like_number($value)
Truth table50%2/4
A and not(B) and C
A= $type eq "integer"B= not ref $valueC= &looks_like_number($value)
ABCresult
0XX0
10X0
1100
1111
549  
550 4 return "$value";
551 }
552  
553 # Private: the Mcp-Param-{Name} bindings for a tools/call, as a list of
554 # name/value pairs with each value already formatted the way the server
555 # compares it.
556 31 ▶async sub _tool_header_params {
Subroutine _tool_header_params: called CC=7 SCAR=19.5
557 31 my ( $self, $name, $arguments ) = @_;
558  
559 31 my $transport = $self->{transport};
560 31 ▶ return () unless $transport->can('mirrors_header_params')
Branch: 1 branch
BranchTrueFalseTotal
unless $transport->can("mirrors_header_params") and $transport->mirrors_header_params 25 6 31
Condition66%2/3
$transport->can("mirrors_header_params") and $transport->mirrors_header_params
!ll&&!rl&&r
0256
MC/DC50%1/2
$transport->can("mirrors_header_params") and $transport->mirrors_header_params
$transport->can("mirrors_header_params") $transport->mirrors_header_params
Truth table66%2/3
A and B
A= $transport->can("mirrors_header_params")B= $transport->mirrors_header_params
ABresult
0X0
100
111
561 && $transport->mirrors_header_params;
562  
563 6 ▶ unless (exists $self->{tool_header_params}{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"tool_header_params"}{$name}) 5 1 6
564 # Calling a tool whose schema this client has never seen is not safe over a
565 # binding that mirrors arguments into headers: an annotated argument
566 # without its header is rejected outright, so the schema has to be fetched
567 # before the call goes out. A failure is deliberately swallowed - the tool
568 # may well have no annotated argument at all, and must not become
569 # uncallable because an unrelated tools/list failed. The request then goes
570 # out bare and the server decides.
571 5 ▶ await $self->list_tools->else(sub { Future->done });
Subroutine __ANON__: called CC=1 SCAR=0.0
572 }
573  
574 6 my @params;
575 6 ▶ for my $param (@{ $self->{tool_header_params}{$name} // [] }) {
Condition100%2/2
$self->{"tool_header_params"}{$name} // []
l!l
51
MC/DC100%1/1
$self->{"tool_header_params"}{$name} // []
$self->{"tool_header_params"}{$name}
Truth table100%2/2
A
A= $self->{"tool_header_params"}{$name}
Aresult
11
00
576 20 my $value = _arg_value($arguments, $param->{path});
577  
578 # A header the server does not expect is rejected exactly like a missing
579 # one, so an argument the caller left out gets no header.
580 20 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 12 8 20
581  
582 push @params, {
583 name => $param->{name},
584 8 value => _header_value($param->{type}, $value),
585 };
586 }
587  
588 6 return @params;
589 7 }
590  
591 31 ▶async sub call_tool {
Subroutine call_tool: called CC=3 SCAR=11.0
Pod documented
592 31 my ( $self, $name, $arguments ) = @_;
593 31 ▶ $arguments //= {};
Condition50%1/2
$arguments //= {}
l!l
310
MC/DC0%0/1
$arguments //= {}
$arguments
Truth table50%1/2
A
A= $arguments
Aresult
11
00
594  
595 31 my @header_params = await $self->_tool_header_params($name, $arguments);
596  
597 31 ▶ my $result = await $self->_request('tools/call',
Branch: 1 branch
BranchTrueFalseTotal
@header_params ? : 5 26 31
598 {
599 name => $name,
600 arguments => $arguments,
601 },
602 @header_params ? ( header_params => \@header_params ) : (),
603 );
604 23 return $result;
605 7 }
606  
607  
608 2 ▶async sub list_prompts {
Subroutine list_prompts: called CC=1 SCAR=0.0
Pod documented
609 2 my ( $self ) = @_;
610 2 return await $self->_list_all('prompts/list', 'prompts');
611 7 }
612  
613  
614 1 ▶async sub get_prompt {
Subroutine get_prompt: called CC=2 SCAR=7.0
Pod documented
615 1 my ( $self, $name, $arguments ) = @_;
616 1 ▶ my $result = await $self->_request('prompts/get', {
Condition50%1/2
$arguments // {}
l!l
10
MC/DC0%0/1
$arguments // {}
$arguments
Truth table50%1/2
A
A= $arguments
Aresult
11
00
617 name => $name,
618 arguments => $arguments // {},
619 });
620 1 return $result;
621 7 }
622  
623  
624 2 ▶async sub list_resources {
Subroutine list_resources: called CC=1 SCAR=0.0
Pod documented
625 2 my ( $self ) = @_;
626 2 return await $self->_list_all('resources/list', 'resources');
627 7 }
628  
629  
630 2 ▶async sub read_resource {
Subroutine read_resource: called CC=1 SCAR=0.0
Pod documented
631 2 my ( $self, $uri ) = @_;
632 2 my $result = await $self->_request('resources/read', {
633 uri => $uri,
634 });
635 1 return $result;
636 7 }
637  
638  
639 # Private: the notification a server answers a subscriptions/listen with in
640 # place of a response. Named to the transport rather than recognised by it -
641 # see subscriptions_listen.
642 7 my $SUBSCRIPTION_ACKNOWLEDGED = 'notifications/subscriptions/acknowledged';
643  
644 5 ▶async sub subscriptions_listen {
Subroutine subscriptions_listen: called CC=2 SCAR=7.0
Pod documented
645 5 my ( $self, $notifications ) = @_;
646 5 ▶ my $result = await $self->_request('subscriptions/listen',
Condition50%1/2
$notifications // {}
l!l
50
MC/DC0%0/1
$notifications // {}
$notifications
Truth table50%1/2
A
A= $notifications
Aresult
11
00
647 { notifications => $notifications // {} },
648 resolve_on_notification => $SUBSCRIPTION_ACKNOWLEDGED);
649 3 return $result;
650 7 }
651  
652  
653 5 ▶async sub subscriptions_stop {
Subroutine subscriptions_stop: called CC=2 SCAR=6.9
Pod documented
654 5 my ( $self, $subscription_id ) = @_;
655 5 $self->_ensure_transport;
656  
657 5 my $transport = $self->{transport};
658 5 ▶ return 0 unless $transport->can('stop_subscription');
Branch: 1 branch
BranchTrueFalseTotal
unless $transport->can("stop_subscription") 1 4 5
659 4 return $transport->stop_subscription($subscription_id);
660 7 }
661  
662  
663 3 ▶async sub ping {
Subroutine ping: called CC=2 SCAR=6.9
Pod documented
664 3 my ( $self ) = @_;
665 # The current MCP revision moved liveness to the transport level and has no
666 # client-addressable JSON-RPC "ping" request. Sending one would fail against
667 # MCP::Server >= 0.15 (InProcess errors with -32601); stdio only "succeeded"
668 # via an accidental legacy latch. Ask the transport whether it is still
669 # usable instead of reporting success unconditionally.
670 3 $self->_ensure_transport;
671 3 ▶ croak "MCP transport is not alive" unless $self->{transport}->is_alive;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"transport"}->is_alive 1 2 3
672 2 return 1;
673 7 }
674  
675  
676 3 ▶async sub shutdown {
Subroutine shutdown: called CC=3 SCAR=11.8
Pod documented
677 3 my ( $self ) = @_;
678 3 ▶ if ($self->{transport} && $self->{transport}->can('close')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"transport"} and $self->{"transport"}->can("close")) 3 0 3
Condition33%1/3
$self->{"transport"} and $self->{"transport"}->can("close")
!ll&&!rl&&r
003
MC/DC0%0/2
$self->{"transport"} and $self->{"transport"}->can("close")
$self->{"transport"} $self->{"transport"}->can("close")
Truth table33%1/3
A and B
A= $self->{"transport"}B= $self->{"transport"}->can("close")
ABresult
0X0
100
111
679 3 await $self->{transport}->close;
680 }
681 3 return 1;
682 7 }
683  
684  
685  
686 7 1;
687  
688 __END__
« MCP/Transport/HTTP.pm ↑ Summary MCP/Transport/Stdio.pm »