blib/lib/AnyEvent/MCP/Server/HTTP.pm

filter: Statementstmt 95.5% 257 / 269 Branchbran 80.8% 181 / 224 Conditioncond 68.7% 110 / 160 MC/DCmcdc 53.4% 46 / 86 Subroutinesub 95.1% 39 / 41 Podpod 100% 5 / 5 totaltotal 81.2% 638 / 785 CC 177 SCAR 30.3
CC
177
Cov
84%
_request
48.5
_respond
33.0
_tls_context
22.9
CRAP 20.7
« lib/AnyEvent/MCP/IMAP/OAuth2.pm ↑ Summary bin/anyevent-mcp »
1 =head1 NAME
2  
3 AnyEvent::MCP::Server::HTTP - an optional MCP HTTP listener and socket handler
4  
5 =head1 DESCRIPTION
6  
7 A subclass of L<AnyEvent::MCP::Server> that handles HTTP POST requests.
8 It can open its own listener, or you can give it sockets accepted elsewhere.
9 If your application already parses HTTP, you can pass decoded requests to
10 L<AnyEvent::MCP::Server> instead of running another HTTP implementation.
11  
12 Requests sharing one connection are dispatched in sequence, preserving their
13 HTTP response order; requests on other connections are independent.
14 Ordinary requests return JSON. When a client accepts C<text/event-stream>,
15 notifications from an outstanding request switch that POST response to
16 chunked SSE, carrying the notifications followed by the JSON-RPC result.
17 Without notifications the response remains JSON. SSE streams close after
18 their final response. This implements request-scoped Streamable HTTP, not
19 the old separate SSE endpoint. GET streams and subscriptions are unsupported.
20  
21 Request bodies need C<Content-Length>: chunked transfer encoding is not
22 supported. The server does not assign protocol sessions. Legacy clients
23 use the 2025 request/response subset.
24  
25 C<Mcp-Param-*> headers from C<x-mcp-header> tool schema annotations are not
26 currently validated against the body. The built-in protocol headers
27 C<Mcp-Protocol-Version>, C<Mcp-Method> and, where applicable, C<Mcp-Name>
28 must agree with modern request metadata and parameters; a mismatch is
29 rejected. Custom schema-derived headers do not receive this check.
30  
31 =head1 FIRST USE
32  
33 For an application that already registers tools in
34 L<AnyEvent::MCP::Server::Toolset>, start an HTTP listener:
35  
36 use AnyEvent;
37 use AnyEvent::MCP::Server::HTTP;
38  
39 my $server = AnyEvent::MCP::Server::HTTP->new (
40 toolsets => [$tools], tokens => [$secret],
41 host => "127.0.0.1", port => 31740,
42 );
43 $server->listen;
44 print $server->url, "\n";
45 AE::cv->recv;
46  
47 C<$tools> is a Toolset and C<$secret> is a previously generated private
48 URL-safe token. Do not use a sample or hardcoded token in a real service.
49 This object handles sockets and HTTP; L<AnyEvent::MCP::Server> dispatches
50 requests, while the Toolset runs tool callbacks. For a standalone program
51 with automatic configuration and startup, prefer
52 L<AnyEvent::MCP::Server::Simple>.
53  
54 =head1 AUTHENTICATION
55  
56 Unlike L<AnyEvent::MCP::Server::Simple/mcp_start>, this low-level object
57 does not load global configuration or derive credentials. Supply C<tokens>
58 explicitly, for example:
59  
60 my $server = AnyEvent::MCP::Server::HTTP->new (
61 host => "127.0.0.1",
62 port => 31740,
63 path => "/mcp/",
64 tokens => ["a-long-random-secret", "another-long-random-secret"],
65 );
66 $server->listen;
67  
68 Each token authorizes the same requests. For either token, a client may
69 POST to C</TOKEN/mcp/> without an Authorization header, or POST to
70 C</mcp/> with C<Authorization: Bearer TOKEN>. URL credentials are path
71 components, B<not> HTTP cookies. C<url> advertises the first token;
72 C<url (0)> returns the clean endpoint. A trailing slash may be omitted
73 from either request path when the configured endpoint path ends in one;
74 this accommodates clients that strip it from a configured URL.
75  
76 The accepted tokens are static, URL-safe strings. HTTP Basic and OAuth
77 access-token validation are not implemented here. There is no automatic
78 fallback to the master-secret-derived token: that belongs to C<mcp_start>
79 or L<AnyEvent::MCP::Config/http_settings>.
80  
81 Authentication defaults to C<tokens>, and construction B<fails> unless a
82 nonempty array of valid tokens is provided. To deliberately delegate
83 authentication to a trusted embedding layer (for example, a reverse proxy
84 that rejects unauthorized requests before they reach MCP), specify
85 C<auth =E<gt> "none"> instead, B<without> C<tokens>. This is an explicit
86 opt-out, not a permissive default. The embedding layer then owns the
87 entire authentication boundary.
88 The C<origins> setting filters browser origins; it is not authentication.
89 URLs can leak through logs and histories, and HTTP alone does not encrypt
90 tokens. Use TLS when credentials cross an untrusted network. A local address
91 is a sensible default, but not a credential.
92  
93 =head1 METHODS
94  
95 =over
96  
97 =item $server = AnyEvent::MCP::Server::HTTP->new (%config)
98  
99 Construction does not start a listener. In addition to Server options,
100 the following configuration options are supported:
101  
102 =over
103  
104 =item host => $host
105  
106 The listening address, defaulting to C<127.0.0.1>.
107  
108 =item port => $port
109  
110 The listening port, defaulting to zero for an automatically assigned port.
111  
112 =item path => $path
113  
114 The MCP endpoint path, defaulting to C</mcp/>. Bearer authentication uses
115 C<$path> directly; URL tokens prefix it with C</TOKEN>. If this path ends
116 in C</>, requests without that final slash are also accepted. Other
117 path differences are not normalized.
118  
119 =item connection_close => $boolean
120  
121 When true, disables persistent connections, sends C<Connection: close> and
122 closes the socket after draining each response. Defaults to false.
123 This is useful when an existing listener routes sockets by their first
124 request and cannot route subsequent requests independently.
125  
126 =item max_size => $bytes
127  
128 Limits incoming headers and request bodies, defaulting to 8 MiB.
129  
130 =item origins => [$origin...]
131  
132 Allowed Origin header values. Defaults to C<["*"]>, permitting browser requests
133 from any origin. An empty array rejects requests with an Origin header, while
134 requests without one are accepted. Allowed origins receive CORS response headers,
135 and nonempty origin lists enable OPTIONS preflight for POST. Preflight does not
136 require authentication; the subsequent POST still does.
137  
138 =item handle => { %handle }
139  
140 AnyEvent::Handle constructor options, such as C<tls>, C<tls_ctx>, C<timeout>
141 or C<on_starttls>. The socket and the read/error/EOF handlers belong to this
142 class.
143 HTTP connections default to a 15-second read inactivity timeout, including
144 idle keep-alive connections. It is suspended while the server processes a
145 complete request and restored for the next request. Set C<rtimeout> in the
146 handle options to override or disable it.
147  
148 =item tls_cert => $file
149  
150 Serve HTTP and HTTPS opportunistically on the same port. FILE contains
151 a PEM certificate chain and optionally its private key. The TLS context
152 is loaded once when listening starts. TLS needs L<Net::SSLeay>.
153  
154 =item tls_key => $file
155  
156 PEM private key for C<tls_cert>. If only one TLS option is supplied, its
157 file must contain both certificate and private key. On accepted connections,
158 C<< $handle->{tls} >> identifies encrypted traffic. Plain HTTP remains
159 available; TLS is not required of clients.
160  
161 =item tokens => [$token, ...]
162  
163 Ordered tokens accepted either as C</TOKEN> before the configured
164 C<path> or in an C<Authorization: Bearer TOKEN> header. The first token
165 is used in advertised URLs. Token strings must be URL-safe and nonempty.
166  
167 =item auth => "tokens" | "none"
168  
169 Select authentication mode. C<tokens> is the default and requires at least
170 one token; C<none> explicitly disables HTTP authentication and cannot be
171 combined with tokens. Other values are rejected. Browser origins are
172 not a replacement for authentication.
173  
174 =item name => $name
175  
176 Identifies the service. Use L<AnyEvent::MCP::Config/http_settings>
177 to resolve named listener configuration before constructing this transport.
178  
179 =item url_host => $hostname
180  
181 Overrides the advertised hostname, for example when listening on a wildcard
182 address. Otherwise a wildcard uses the nodename from C<uname>.
183  
184 =item url_scheme => $scheme
185  
186 Overrides the advertised scheme; otherwise TLS credentials or handle options
187 select C<https>, and plain handles select C<http>.
188  
189 =back
190  
191 Every configured token authenticates in either the URL or the Authorization
192 header. Without tokens, the constructor requires C<auth =E<gt> "none">.
193  
194 =item $url = $server->url ($with_token)
195  
196 Returns the advertised URL with the actual listening port. C<$with_token>
197 defaults to true, including the first configured token. Pass false for
198 the clean URL to use with an Authorization bearer token.
199  
200 The port must be known. Wildcard hostname resolution and reverse-proxy
201 routing remain the caller's responsibility.
202  
203 =item $server->listen ($host, $port, %handle)
204  
205 Starts a listener, replacing any previous listener. Omitted arguments use
206 the configured host and port. The actual bound port is stored in
207 C<< $server->{port} >>, including when requesting an ephemeral port.
208  
209 C<%handle> overrides the configured C<handle> options for connections
210 accepted by this listener.
211  
212 =item $handle = $server->accept ($socket, %handle)
213  
214 Starts handling an already accepted socket. The server takes ownership of
215 C<$socket>. No listener is needed.
216  
217 C<%handle> overrides the configured C<handle> options for this connection.
218  
219 =item $server->close
220  
221 Stops listening, closes accepted sockets and cancels outstanding requests.
222 The same object can subsequently listen or accept again.
223  
224 =back
225  
226 =head1 EVENTS
227  
228 =over
229  
230 =item on_extension => $callback->($server, $handle, $hello)
231  
232 Accept raw extension connections on the HTTP listener. A first byte of C<[>
233 selects a bounded, newline-terminated JSON hello whose first two fields are
234 the protocol name and an accepted listener token. Authenticate before invoking
235 this callback, which validates the protocol-specific fields and takes ownership
236 of the handle, preserving buffered input. Throw an exception to reject it.
237 HTTP connections continue through the normal parser. This dispatch examines
238 decrypted bytes when TLS is configured, but the built-in reverse connector
239 currently supports only plain C<http://> endpoints.
240  
241 =item on_http_request => $callback->($server, $request, $reply)
242  
243 Called for every complete, syntactically valid HTTP request before MCP routing
244 or authentication. C<$request> is a hash containing the parsed HTTP fields
245 (including C<method>, C<uri>, and C<http_version>) and a C<body> field holding
246 the raw request body. Return false to use the normal MCP handling, or true to
247 handle the request yourself.
248  
249 C<$reply-E<gt>($status, $reason, \%headers, $body)> sends a response, either
250 immediately or asynchronously after the callback returns. C<%headers> is
251 optional; C<Content-Type> defaults to C<application/json>, and the server
252 generates C<Content-Length> and manages persistent connections. The body is
253 an octet string. Reply at most once, and return true when taking ownership
254 of the request, even if the response will be sent later. The next request on
255 the same connection is not read until that response is sent.
256  
257 The hook runs B<before> MCP authentication and CORS checks. Application
258 endpoints must perform their own authentication and browser request checks.
259 It does not replace or bypass the normal authentication of unhandled MCP
260 requests. Malformed or oversized requests are rejected before the hook.
261  
262 =item on_connection_error => $callback->($server, $handle, $message)
263  
264 Called for socket errors before closing the connection.
265  
266 =item on_close => $callback->($server)
267  
268 Called once after C<close> stops the listener and closes all connections.
269 Calling C<listen> or C<accept> again starts a new lifetime.
270  
271 =back
272  
273 =cut
274  
275 package AnyEvent::MCP::Server::HTTP;
276  
277 43 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
278 43 ▶use parent "AnyEvent::MCP::Server";
Subroutine BEGIN: called CC=1 SCAR=0.0
279 43 ▶use AnyEvent::Log ();
Subroutine BEGIN: called CC=1 SCAR=0.0
280 43 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
281 43 ▶use AnyEvent::Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
282 43 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
283 43 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
284 43 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
285 43 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
286  
287 120 ▶sub new {
Subroutine new: called CC=10 SCAR=23.0
Pod documented
288 120 my ($class, %kv) = @_;
289  
290 120 ▶ !grep (exists $kv{$_}, qw(cookie bearer users))
Branch: 1 branch
BranchTrueFalseTotal
grep exists $kv{$_}, ("cookie", "bearer", "users") and die "Legacy HTTP authentication options are unsupported; use tokens\n" 0 120 120
291 or die "Legacy HTTP authentication options are unsupported; use tokens\n";
292  
293 120 ▶ $kv{auth} //= "tokens";
Condition100%2/2
$kv{"auth"} //= "tokens"
l!l
6159
MC/DC100%1/1
$kv{"auth"} //= "tokens"
$kv{"auth"}
Truth table100%2/2
A
A= $kv{"auth"}
Aresult
11
00
294 120 ▶ if ($kv{auth} eq "tokens") {
Branch: 2 branches
BranchTrueFalseTotal
if ($kv{'auth'} eq 'tokens') { } 59 61 120
elsif ($kv{'auth'} eq 'none') { } 60 1 61
295 59 ▶ ref $kv{tokens} eq "ARRAY" && @{$kv{tokens}}
Branch: 1 branch
BranchTrueFalseTotal
ref $kv{"tokens"} eq "ARRAY" and @{$kv{"tokens"};} or die "HTTP server requires nonempty tokens\n" 57 2 59
Condition100%3/3
ref $kv{"tokens"} eq "ARRAY" and @{$kv{"tokens"};}
!ll&&!rl&&r
1157
MC/DC100%2/2
ref $kv{"tokens"} eq "ARRAY" and @{$kv{"tokens"};}
ref $kv{"tokens"} eq "ARRAY" @{$kv{"tokens"};}
Truth table100%3/3
A and B
A= ref $kv{"tokens"} eq "ARRAY"B= @{$kv{"tokens"};}
ABresult
0X0
100
111
296 or die "HTTP server requires nonempty tokens\n";
297 /\A[A-Za-z0-9_.~-]+\z/ or die "Invalid HTTP server token\n"
298 57 ▶ for @{$kv{tokens}};
Branch: 1 branch
BranchTrueFalseTotal
/\A[A-Za-z0-9_.~-]+\z/u or die "Invalid HTTP server token\n" 69 1 70
299 } elsif ($kv{auth} eq "none") {
300 !exists $kv{tokens}
301 60 ▶ or die "Unauthenticated HTTP server must not configure tokens\n";
Branch: 1 branch
BranchTrueFalseTotal
exists $kv{"tokens"} and die "Unauthenticated HTTP server must not configure tokens\n" 1 59 60
302 } else {
303 1 die "Unsupported HTTP authentication type '$kv{auth}'\n";
304 }
305  
306 115 $class->SUPER::new (host => "127.0.0.1", port => 0, path => "/mcp/", origins => ["*"], %kv)
307 }
308  
309 52 ▶sub _tls_context {
Subroutine _tls_context: called CC=6 SCAR=31.3
310 52 my ($self) = @_;
311  
312 52 ▶ return unless defined $self->{tls_cert} || defined $self->{tls_key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"tls_cert"} or defined $self->{"tls_key"} 52 0 52
Condition33%1/3
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
l!l&&r!l&&!r
0052
MC/DC0%0/2
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
defined $self->{"tls_cert"} defined $self->{"tls_key"}
Truth table33%1/3
A or B
A= defined $self->{"tls_cert"}B= defined $self->{"tls_key"}
ABresult
1X1
011
000
313  
314 0 ▶ $self->{_tls_context} ||= do {
Condition0%0/3
$self->{"_tls_context"} ||= do { require AnyEvent::TLS; "AnyEvent::TLS"->new("cert_file", $self->{"tls_cert"} // $self->{"tls_key"}, defined $self->{"tls_key"} ? ("key_file", $self->{"tls_key"}) : ()) }
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_tls_context"} ||= do { require AnyEvent::TLS; "AnyEvent::TLS"->new("cert_file", $self->{"tls_cert"} // $self->{"tls_key"}, defined $self->{"tls_key"} ? ("key_file", $self->{"tls_key"}) : ()) }
$self->{"_tls_context"} do { require AnyEvent::TLS; "AnyEvent::TLS"->new("cert_file", $self->{"tls_cert"} // $self->{"tls_key"}, defined $self->{"tls_key"} ? ("key_file", $self->{"tls_key"}) : ()) }
Truth table0%0/3
A ||= B
A= $self->{"_tls_context"}B= do { require AnyEvent::TLS; "AnyEvent::TLS"->new("cert_file", $self->{"tls_cert"} // $self->{"tls_key"}, defined $self->{"tls_key"} ? ("key_file", $self->{"tls_key"}) : ()) }
ABresult
1X1
011
000
315 0 require AnyEvent::TLS;
316 AnyEvent::TLS->new (
317 cert_file => $self->{tls_cert} // $self->{tls_key},
318 0 ▶ (defined $self->{tls_key} ? (key_file => $self->{tls_key}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'tls_key'} ? : 0 0 0
Condition0%0/3
$self->{"tls_cert"} // $self->{"tls_key"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"tls_cert"} // $self->{"tls_key"}
$self->{"tls_cert"} $self->{"tls_key"}
Truth table0%0/3
A // B
A= $self->{"tls_cert"}B= $self->{"tls_key"}
ABresult
1X1
011
000
319 )
320 }
321 }
322  
323 52 ▶sub listen {
Subroutine listen: called CC=4 SCAR=14.1
Pod documented
324 52 my ($self, $host, $port, %handle) = @_;
325  
326 52 $self->_tls_context;
327 52 delete $self->{_closed};
328 52 ▶ $host = $self->{host} unless defined $host;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host 52 0 52
329 52 ▶ $port = $self->{port} unless defined $port;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $port 52 0 52
330  
331 52 $self->{listen_host} = $host;
332 52 ▶ $self->{listen_handle} = { %{$self->{handle} || {}}, %handle };
Condition50%1/2
$self->{'handle'} || {}
l!l
052
MC/DC0%0/1
$self->{'handle'} || {}
$self->{'handle'}
Truth table50%1/2
A
A= $self->{'handle'}
Aresult
11
00
333  
334 52 delete $self->{listener};
335 52 weaken $self;
336  
337 192 ▶ $self->{listener} = AnyEvent::Socket::tcp_server $host, $port, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
338 192 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 192 192
339 192 my ($socket, $host, $port) = @_;
340 192 my $handle = $self->accept ($socket, %handle);
341 192 $handle->{mcp_remote} = AnyEvent::Socket::format_hostport ($host, $port);
342 52 ▶ }, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
343 52 ▶ $self->{port} = $_[2] if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 52 0 52
344 ()
345 52 };
346 }
347  
348 182 ▶sub _token_path {
Subroutine _token_path: called CC=1 SCAR=0.0
349 182 my ($self, $token) = @_;
350  
351 182 "/$token$self->{path}"
352 }
353  
354 78 ▶sub url {
Subroutine url: called CC=17 SCAR=29.0
Pod documented
355 78 my ($self, $with_token) = @_;
356  
357 78 ▶ $with_token = 1 unless defined $with_token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $with_token 61 17 78
358  
359 my $host = $self->{url_host}
360 78 ▶ || (defined $self->{listen_host} ? $self->{listen_host} : $self->{host});
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'listen_host'} ? : 44 32 76
Condition66%2/3
$self->{'url_host'} || (defined $self->{'listen_host'} ? $self->{'listen_host'} : $self->{'host'})
l!l&&r!l&&!r
2760
MC/DC0%0/2
$self->{'url_host'} || (defined $self->{'listen_host'} ? $self->{'listen_host'} : $self->{'host'})
$self->{'url_host'} (defined $self->{'listen_host'} ? $self->{'listen_host'} : $self->{'host'})
Truth table66%2/3
A || B
A= $self->{'url_host'}B= (defined $self->{'listen_host'} ? $self->{'listen_host'} : $self->{'host'})
ABresult
1X1
011
000
361 78 ▶ $host = (POSIX::uname)[1] if !length $host || $host eq "0.0.0.0" || $host eq "::";
Branch: 1 branch
BranchTrueFalseTotal
if not length $host or $host eq "0.0.0.0" or $host eq "::" 2 76 78
Condition66%4/6
not length $host or $host eq "0.0.0.0" or $host eq "::"
l!l&&r!l&&!r
2076
not length $host or $host eq "0.0.0.0"
l!l&&r!l&&!r
0276
MC/DC33%1/3
not length $host or $host eq "0.0.0.0" or $host eq "::"
not length $host $host eq "0.0.0.0" $host eq "::"
Truth table50%2/4
not(A) or B or C
A= not length $hostB= $host eq "0.0.0.0"C= $host eq "::"
ABCresult
1XX1
01X1
0011
0000
362 78 $host =~ s/\A\[(.*)\]\z/$1/; # allow already bracketed IPv6 URL hosts
363  
364 78 ▶ my $port = $self->{port} or die "HTTP port is not known\n";
Branch: 1 branch
BranchTrueFalseTotal
my $port = $self->{"port"} or die "HTTP port is not known\n" 75 3 78
365 my $scheme = $self->{url_scheme}
366 || (defined $self->{tls_cert} || defined $self->{tls_key}
367 75 ▶ || ($self->{listen_handle} || $self->{handle} || {})->{tls} ? "https" : "http");
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'tls_cert'} || defined $self->{'tls_key'} || +($self->{'listen_handle'} || $self->{'handle'} || {})->{'tls'} ? : 2 55 57
Condition71%10/14
$self->{'url_scheme'} || (defined $self->{'tls_cert'} || defined $self->{'tls_key'} || +($self->{'listen_handle'} || $self->{'handle'} || {})->{'tls'} ? 'https' : 'http')
l!l&&r!l&&!r
18570
defined $self->{"tls_cert"} or defined $self->{"tls_key"} or +($self->{"listen_handle"} || $self->{"handle"} || {})->{"tls"}
l!l&&r!l&&!r
0255
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
l!l&&r!l&&!r
0057
$self->{'listen_handle'} || $self->{'handle'} || {}
l!l
4611
$self->{"listen_handle"} or $self->{"handle"}
l!l&&r!l&&!r
44211
MC/DC60%3/5
$self->{'url_scheme'} || (defined $self->{'tls_cert'} || defined $self->{'tls_key'} || +($self->{'listen_handle'} || $self->{'handle'} || {})->{'tls'} ? 'https' : 'http')
$self->{'url_scheme'} defined $self->{"tls_cert"} defined $self->{"tls_key"} $self->{"listen_handle"} $self->{"handle"}
Truth table66%4/6
A || B or C or D or E
A= $self->{'url_scheme'}B= defined $self->{"tls_cert"}C= defined $self->{"tls_key"}D= $self->{"listen_handle"}E= $self->{"handle"}
ABCDEresult
1XXXX1
01XXX1
001XX1
0001X1
000011
000000
368 29 my $path = $with_token && $self->{tokens} && @{$self->{tokens}}
369 75 ▶ ? $self->_token_path ($self->{tokens}[0]) : $self->{path};
Branch: 1 branch
BranchTrueFalseTotal
$with_token && $self->{'tokens'} && @{$self->{'tokens'};} ? : 29 46 75
Condition83%5/6
$with_token and $self->{"tokens"} and @{$self->{"tokens"};}
!ll&&!rl&&r
46029
$with_token and $self->{"tokens"}
!ll&&!rl&&r
172929
MC/DC66%2/3
$with_token and $self->{"tokens"} and @{$self->{"tokens"};}
$with_token $self->{"tokens"} @{$self->{"tokens"};}
Truth table75%3/4
A and B and C
A= $with_tokenB= $self->{"tokens"}C= @{$self->{"tokens"};}
ABCresult
0XX0
10X0
1100
1111
370  
371 75 "$scheme://" . AnyEvent::Socket::format_hostport ($host, $port) . $path
372 }
373  
374 260 ▶sub accept {
Subroutine accept: called CC=6 SCAR=22.1
Pod documented
375 260 my ($self, $socket, %handle) = @_;
376  
377 260 delete $self->{_closed};
378 260 weaken $self;
379  
380 my $handle = AnyEvent::Handle->new (
381 rbuf_max => $self->{max_size} || 8 * 1024 * 1024,
382 rtimeout => 15,
383 260 %{$self->{handle}},
384 %handle,
385 fh => $socket,
386 on_read => undef,
387 6 ▶ on_error => sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
388 6 ▶ $self->event (connection_error => $_[0], $_[2]) if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 6 0 6
389 6 ▶ $self->_close ($_[0]) if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 6 0 6
390 },
391 4 ▶ on_eof => sub { $self->_close ($_[0]) if $self },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $self 4 0 4
392 260 ▶ );
Condition100%2/2
$self->{'max_size'} || 8388608
l!l
4256
MC/DC100%1/1
$self->{'max_size'} || 8388608
$self->{'max_size'}
Truth table100%2/2
A
A= $self->{'max_size'}
Aresult
11
00
393  
394 260 $handle->{mcp_read_timeout} = $handle->{rtimeout};
395 260 $handle->{mcp_peer} = {};
396 260 $self->{connections}{$handle} = $handle;
397 $handle->push_read (tls_autostart => $self->_tls_context, "accept")
398 260 ▶ if (defined $self->{tls_cert} || defined $self->{tls_key}) && !$handle->{tls};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"tls_cert"} || defined $self->{"tls_key"} and not $handle->{"tls"} 0 260 260
Condition33%2/6
defined $self->{"tls_cert"} || defined $self->{"tls_key"} and not $handle->{"tls"}
!ll&&!rl&&r
26000
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
l!l&&r!l&&!r
00260
MC/DC0%0/3
defined $self->{"tls_cert"} || defined $self->{"tls_key"} and not $handle->{"tls"}
defined $self->{"tls_cert"} defined $self->{"tls_key"} not $handle->{"tls"}
Truth table20%1/5
A or B and not(C)
A= defined $self->{"tls_cert"}B= defined $self->{"tls_key"}C= not $handle->{"tls"}
ABCresult
00X0
1X00
0100
1X11
0111
399  
400 260 ▶ if ($self->{on_extension}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'on_extension'}) { } 12 248 260
401 12 ▶ $handle->on_read (sub {
Subroutine __ANON__: called CC=5 SCAR=26.6
402 12 my ($handle) = @_;
403  
404 12 $handle->on_read (undef);
405 12 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 12 12
406  
407 12 ▶ if (substr ($handle->{rbuf}, 0, 1) eq "[") {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($handle->{'rbuf'}, 0, 1) eq '[') { } 0 12 12
408 0 require AnyEvent::MCP::Extension;
409 0 ▶ AnyEvent::MCP::Extension::accept ($handle, $self->{connect_tokens} || $self->{tokens} || [], sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
410 0 my ($handle, $hello) = @_;
411 0 ▶ return $handle->destroy unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 0 0
412 0 delete $self->{connections}{$handle};
413 0 $self->{on_extension}->($self, $handle, $hello);
414 0 ▶ }, sub { $self->_close ($_[0]) if $self });
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $self 0 0 0
Condition0%0/5
$self->{'connect_tokens'} || $self->{'tokens'} || []
l!l
00
$self->{"connect_tokens"} or $self->{"tokens"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{'connect_tokens'} || $self->{'tokens'} || []
$self->{"connect_tokens"} $self->{"tokens"}
Truth table0%0/3
A or B
A= $self->{"connect_tokens"}B= $self->{"tokens"}
ABresult
1X1
011
000
415 } else {
416 12 $self->_read ($handle, 1);
417 }
418 12 });
419 } else {
420 248 $self->_read ($handle);
421 }
422  
423 260 $handle
424 }
425  
426 # parse a request line and HTTP fields, using the same comma-combining
427 # approach as AnyEvent::HTTP::_parse_hdr. The caller already bounds headers.
428 267 ▶sub _parse_request_headers {
Subroutine _parse_request_headers: called CC=7 SCAR=19.5
429 267 local $_ = $_[0] . "\r\n";
430 267 ▶ /\A([!#$%&'*+.^_\x60|~0-9A-Za-z-]+) [ ]+
Branch: 1 branch
BranchTrueFalseTotal
m[\A([!#$%&'*+.^_\x60|~0-9A-Za-z-]+) [ ]+ ([^\x00-\x20]+) [ ]+ HTTP/0*([0-9.]+)\r\n]cgiux or return 265 2 267
431 ([^\x00-\x20]+) [ ]+ HTTP\/0*([0-9.]+)\r\n/gcix
432 or return;
433 265 my ($method, $uri, $version) = ($1, $2, $3);
434 265 ▶ return unless $version =~ /\A1\.[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $version =~ /\A1\.[0-9]+\z/u 1 264 265
435 264 my %hdr;
436  
437 264 ▶ $hdr{lc $1} .= ",$2"
Branch: 1 branch
BranchTrueFalseTotal
/\G ([!\#$%&'*+.^_\x60|~0-9A-Za-z-]+): [\t ]* ([^\x00-\x08\x0a-\x1f\x7f]*) \r\n /cgux and do { $hdr{lc $1} .= ",$2" } 2248 264 2512
438 while /\G
439 ([!\#$%&'*+.^_\x60|~0-9A-Za-z-]+):
440 [\t ]*
441 ([^\x00-\x08\x0a-\x1f\x7f]*)
442 \r\n
443 /gcx;
444  
445 264 ▶ /\G\z/gc or return;
Branch: 1 branch
BranchTrueFalseTotal
/\G\z/cgu or return 260 4 264
446  
447 # discard the prefix used for comma-combining repeated field values.
448 260 substr $_, 0, 1, "" for values %hdr;
449 260 s/[\t ]+\z// for values %hdr;
450  
451 # request-line fields override any colliding HTTP header names.
452 260 +{ %hdr, method => $method, uri => $uri, http_version => $version }
453 }
454  
455 # Retain useful paths in rejection logs, without leaking URL credentials.
456 261 ▶sub _log_uri {
Subroutine _log_uri: called CC=7 SCAR=19.5
457 261 my ($self, $uri) = @_;
458  
459 261 ▶ return '"[non-path URI]"' unless $uri =~ m{\A/};
Branch: 1 branch
BranchTrueFalseTotal
unless $uri =~ m[\A/]u 2 259 261
460 259 $uri =~ s/[?#].*//s;
461  
462 259 ▶ if ($self->{tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tokens"}) 137 122 259
463 137 (my $endpoint = $self->{path}) =~ s{/\z}{};
464 137 ▶ $endpoint = "/" unless length $endpoint;
Branch: 1 branch
BranchTrueFalseTotal
unless length $endpoint 32 105 137
465 137 ▶ $uri =~ s{\A/[^/]+(?=\Q$endpoint\E(?:/|\z))}{/<token>}
Branch: 1 branch
BranchTrueFalseTotal
unless $endpoint eq "/" 105 32 137
466 unless $endpoint eq "/";
467 137 $uri =~ s/\Q$_\E/<token>/g for @{$self->{tokens}};
468 }
469  
470 259 ▶ $uri = substr ($uri, 0, 160) . "..." if length $uri > 160;
Branch: 1 branch
BranchTrueFalseTotal
if length $uri > 160 1 258 259
471 259 JSON::XS::encode_json $uri
472 }
473  
474 532 ▶sub _read {
Subroutine _read: called CC=2 SCAR=7.0
475 532 my ($self, $handle, $immediate) = @_;
476  
477 532 weaken $self;
478  
479 532 $handle->rtimeout_reset;
480 532 $handle->rtimeout ($handle->{mcp_read_timeout});
481 532 ▶ if ($immediate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($immediate) { } 261 271 532
482 259 ▶ $handle->push_read (line => "\r\n\r\n", sub {
Subroutine __ANON__: called CC=15 SCAR=27.9
483 259 my ($handle, $header) = @_;
484  
485 259 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 259 259
486  
487 259 my $hdr = _parse_request_headers ($header);
488 259 ▶ $handle->{mcp_method} = $hdr ? substr ($hdr->{method}, 0, 32) : "-";
Branch: 1 branch
BranchTrueFalseTotal
$hdr ? : 256 3 259
489 259 ▶ $handle->{mcp_uri} = $hdr ? $self->_log_uri ($hdr->{uri}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$hdr ? : 256 3 259
490 $handle->{mcp_close} = $self->{connection_close}
491 || !$hdr || $hdr->{http_version} =~ m{\A1\.0+\z}
492 259 ▶ || $hdr->{connection} =~ /\bclose\b/i;
Condition88%8/9
$self->{'connection_close'} || !$hdr || $hdr->{'http_version'} =~ /\A1\.0+\z/u || $hdr->{'connection'} =~ /\bclose\b/iu
l!l&&r!l&&!r
819061
$self->{"connection_close"} or not $hdr or $hdr->{"http_version"} =~ /\A1\.0+\z/u
l!l&&r!l&&!r
80251
$self->{"connection_close"} or not $hdr
l!l&&r!l&&!r
53251
MC/DC75%3/4
$self->{'connection_close'} || !$hdr || $hdr->{'http_version'} =~ /\A1\.0+\z/u || $hdr->{'connection'} =~ /\bclose\b/iu
$self->{"connection_close"} not $hdr $hdr->{"http_version"} =~ /\A1\.0+\z/u $hdr->{'connection'} =~ /\bclose\b/iu
Truth table80%4/5
A or not(B) or C || D
A= $self->{"connection_close"}B= not $hdrC= $hdr->{"http_version"} =~ /\A1\.0+\z/uD= $hdr->{'connection'} =~ /\bclose\b/iu
ABCDresult
1XXX1
01XX1
001X1
00011
00000
493  
494 259 ▶ return $self->_respond ($handle, 400, "Bad Request", "") unless $hdr;
Branch: 1 branch
BranchTrueFalseTotal
unless $hdr 3 256 259
495  
496 256 ▶ $hdr->{"content-length"} = 0 unless defined $hdr->{"content-length"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hdr->{"content-length"} 7 249 256
497 return $self->_respond ($handle, 400, "Bad Request", "")
498 if exists $hdr->{"transfer-encoding"}
499 256 ▶ || $hdr->{"content-length"} !~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if exists $hdr->{"transfer-encoding"} or not $hdr->{"content-length"} =~ /\A[0-9]+\z/u 3 253 256
Condition100%3/3
exists $hdr->{"transfer-encoding"} or not $hdr->{"content-length"} =~ /\A[0-9]+\z/u
l!l&&r!l&&!r
12253
MC/DC100%2/2
exists $hdr->{"transfer-encoding"} or not $hdr->{"content-length"} =~ /\A[0-9]+\z/u
exists $hdr->{"transfer-encoding"} not $hdr->{"content-length"} =~ /\A[0-9]+\z/u
Truth table100%3/3
A or not(B)
A= exists $hdr->{"transfer-encoding"}B= not $hdr->{"content-length"} =~ /\A[0-9]+\z/u
ABresult
1X1
011
000
500  
501 return $self->_respond ($handle, 413, "Content Too Large", "")
502 253 ▶ if $hdr->{"content-length"} > ($self->{max_size} || 8 * 1024 * 1024);
Branch: 1 branch
BranchTrueFalseTotal
if $hdr->{"content-length"} > ($self->{"max_size"} || 8388608) 0 253 253
Condition100%2/2
$self->{'max_size'} || 8388608
l!l
4249
MC/DC100%1/1
$self->{'max_size'} || 8388608
$self->{'max_size'}
Truth table100%2/2
A
A= $self->{'max_size'}
Aresult
11
00
503  
504 253 ▶ if ($hdr->{expect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr->{"expect"}) 0 253 253
505 return $self->_respond ($handle, 417, "Expectation Failed", "")
506 0 ▶ unless lc $hdr->{expect} eq "100-continue";
Branch: 1 branch
BranchTrueFalseTotal
unless lc $hdr->{"expect"} eq "100-continue" 0 0 0
507  
508 0 $handle->push_write ("HTTP/1.1 100 Continue\r\n\r\n");
509 }
510  
511 251 ▶ $handle->push_read (chunk => $hdr->{"content-length"}, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
512 251 my ($handle, $body) = @_;
513  
514 251 $handle->rtimeout (0);
515 251 ▶ $self->_request ($handle, $hdr, $body) if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 251 0 251
516 253 });
517 261 });
518 } else {
519 249 ▶ $handle->on_read (sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
520 249 my ($handle) = @_;
521 249 $handle->on_read (undef);
522 249 ▶ $self->_read ($handle, 1) if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 249 0 249
523 271 });
524 }
525 }
526  
527 251 ▶sub _request {
Subroutine _request: called CC=46 SCAR=38.8
528 251 my ($self, $handle, $hdr, $body) = @_;
529  
530 251 delete $handle->{mcp_origin};
531  
532 251 ▶ if (my $hook = $self->{on_http_request}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hook = $self->{"on_http_request"}) 24 227 251
533 24 weaken $self;
534 24 my $replied;
535 9 ▶ my $reply = sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
536 9 ▶ return if $replied++ || !$self || $handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $replied++ or not $self or $handle->{"mcp_closed"} 1 8 9
Condition66%4/6
$replied++ or not $self or $handle->{"mcp_closed"}
l!l&&r!l&&!r
108
$replied++ or not $self
l!l&&r!l&&!r
108
MC/DC33%1/3
$replied++ or not $self or $handle->{"mcp_closed"}
$replied++ not $self $handle->{"mcp_closed"}
Truth table50%2/4
A or not(B) or C
A= $replied++B= not $selfC= $handle->{"mcp_closed"}
ABCresult
1XX1
01X1
0011
0000
537 8 my ($status, $reason, $headers, $content) = @_;
538 8 $self->_respond ($handle, $status, $reason, $content, $headers);
539 24 };
540  
541 24 ▶ return if $hook->($self, { %$hdr, body => $body }, $reply);
Branch: 1 branch
BranchTrueFalseTotal
if &$hook($self, {%$hdr, "body", $body}, $reply) 8 16 24
542 }
543  
544 # ordinary root probes are not MCP requests, even when / is the endpoint
545 return $self->_respond ($handle, 404, "Not Found", "")
546 243 ▶ if $hdr->{method} eq "GET" && $hdr->{uri} eq "/";
Branch: 1 branch
BranchTrueFalseTotal
if $hdr->{"method"} eq "GET" and $hdr->{"uri"} eq "/" 4 239 243
Condition100%3/3
$hdr->{"method"} eq "GET" and $hdr->{"uri"} eq "/"
!ll&&!rl&&r
23184
MC/DC100%2/2
$hdr->{"method"} eq "GET" and $hdr->{"uri"} eq "/"
$hdr->{"method"} eq "GET" $hdr->{"uri"} eq "/"
Truth table100%3/3
A and B
A= $hdr->{"method"} eq "GET"B= $hdr->{"uri"} eq "/"
ABresult
0X0
100
111
547  
548 # some MCP clients strip a trailing slash from the configured URL.
549 239 my $uri = $hdr->{uri};
550 239 ▶ $uri .= "/" if $self->{path} =~ m{/$} && $uri !~ m{/$};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"path"} =~ m[/$]u and not $uri =~ m[/$]u 10 229 239
Condition100%3/3
$self->{"path"} =~ m[/$]u and not $uri =~ m[/$]u
!ll&&!rl&&r
122810
MC/DC100%2/2
$self->{"path"} =~ m[/$]u and not $uri =~ m[/$]u
$self->{"path"} =~ m[/$]u not $uri =~ m[/$]u
Truth table100%3/3
A and not(B)
A= $self->{"path"} =~ m[/$]uB= not $uri =~ m[/$]u
ABresult
0X0
100
111
551 my ($path_token) = $self->{tokens}
552 239 ▶ ? grep $uri eq $self->_token_path ($_), @{$self->{tokens}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tokens'} ? : 127 112 239
553 239 my $token_path = defined $path_token;
554  
555 return $self->_respond ($handle, 404, "Not Found", "")
556 239 ▶ unless $uri eq $self->{path} || $token_path;
Branch: 1 branch
BranchTrueFalseTotal
unless $uri eq $self->{"path"} or $token_path 12 227 239
Condition100%3/3
$uri eq $self->{"path"} or $token_path
l!l&&r!l&&!r
2052212
MC/DC100%2/2
$uri eq $self->{"path"} or $token_path
$uri eq $self->{"path"} $token_path
Truth table100%3/3
A or B
A= $uri eq $self->{"path"}B= $token_path
ABresult
1X1
011
000
557  
558 227 ▶ if (exists $hdr->{origin}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hdr->{"origin"}) 11 216 227
559 11 my $wildcard = grep $_ eq "*", @{$self->{origins}};
560  
561 return $self->_respond ($handle, 403, "Forbidden", "")
562 11 ▶ unless $wildcard || grep $_ eq $hdr->{origin}, @{$self->{origins}};
Branch: 1 branch
BranchTrueFalseTotal
unless $wildcard or grep(($_ eq $hdr->{"origin"}), @{$$self{"origins"};}) 3 8 11
Condition100%3/3
$wildcard or grep(($_ eq $hdr->{"origin"}), @{$$self{"origins"};})
l!l&&r!l&&!r
713
MC/DC100%2/2
$wildcard or grep(($_ eq $hdr->{"origin"}), @{$$self{"origins"};})
$wildcard grep(($_ eq $hdr->{"origin"}), @{$$self{"origins"};})
Truth table100%3/3
A or B
A= $wildcardB= grep(($_ eq $hdr->{"origin"}), @{$$self{"origins"};})
ABresult
1X1
011
000
563  
564 8 ▶ $handle->{mcp_origin} = $wildcard ? "*" : $hdr->{origin};
Branch: 1 branch
BranchTrueFalseTotal
$wildcard ? : 7 1 8
565 }
566  
567 224 ▶ if ($hdr->{method} eq "OPTIONS" && @{$self->{origins}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr->{"method"} eq "OPTIONS" and @{$self->{"origins"};}) 4 220 224
Condition100%3/3
$hdr->{"method"} eq "OPTIONS" and @{$self->{"origins"};}
!ll&&!rl&&r
21914
MC/DC100%2/2
$hdr->{"method"} eq "OPTIONS" and @{$self->{"origins"};}
$hdr->{"method"} eq "OPTIONS" @{$self->{"origins"};}
Truth table100%3/3
A and B
A= $hdr->{"method"} eq "OPTIONS"B= @{$self->{"origins"};}
ABresult
0X0
100
111
568 return $self->_respond ($handle, 405, "Method Not Allowed", "")
569 if exists $hdr->{"access-control-request-method"}
570 4 ▶ && $hdr->{"access-control-request-method"} ne "POST";
Branch: 1 branch
BranchTrueFalseTotal
if exists $hdr->{"access-control-request-method"} and $hdr->{"access-control-request-method"} ne "POST" 0 4 4
Condition33%1/3
exists $hdr->{"access-control-request-method"} and $hdr->{"access-control-request-method"} ne "POST"
!ll&&!rl&&r
040
MC/DC0%0/2
exists $hdr->{"access-control-request-method"} and $hdr->{"access-control-request-method"} ne "POST"
exists $hdr->{"access-control-request-method"} $hdr->{"access-control-request-method"} ne "POST"
Truth table33%1/3
A and B
A= exists $hdr->{"access-control-request-method"}B= $hdr->{"access-control-request-method"} ne "POST"
ABresult
0X0
100
111
571  
572 4 return $self->_respond ($handle, 204, "No Content", "");
573 }
574  
575 return $self->_respond ($handle, 405, "Method Not Allowed", "")
576 220 ▶ unless $hdr->{method} eq "POST";
Branch: 1 branch
BranchTrueFalseTotal
unless $hdr->{"method"} eq "POST" 1 219 220
577  
578 219 my $authenticated = $path_token;
579 219 ▶ if ($self->{tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tokens"}) 108 111 219
580 108 my $authorization = $hdr->{authorization};
581  
582 108 ▶ if ($authorization =~ /\ABearer ([^\s]+)\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($authorization =~ /\ABearer ([^\s]+)\z/iu) 83 25 108
583 83 my $token = $1;
584 83 ▶ if (grep $_ eq $token, @{$self->{tokens}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep(($_ eq $token), @{$$self{"tokens"};})) 78 5 83
585 78 ▶ return $self->_respond ($handle, 401, "Unauthorized", "")
Branch: 1 branch
BranchTrueFalseTotal
if defined $authenticated and $authenticated ne $token 1 77 78
Condition66%2/3
defined $authenticated and $authenticated ne $token
!ll&&!rl&&r
7701
MC/DC50%1/2
defined $authenticated and $authenticated ne $token
defined $authenticated $authenticated ne $token
Truth table66%2/3
A and B
A= defined $authenticatedB= $authenticated ne $token
ABresult
0X0
100
111
586 if defined $authenticated && $authenticated ne $token;
587 77 $authenticated = $token;
588 }
589 }
590  
591 107 ▶ return $self->_respond ($handle, 401, "Unauthorized", "")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $authenticated 12 95 107
592 unless defined $authenticated;
593 }
594  
595 return $self->_respond ($handle, 415, "Unsupported Media Type", "")
596 206 ▶ unless $hdr->{"content-type"} =~ m{\Aapplication/json(?:\s*;|\z)}i;
Branch: 1 branch
BranchTrueFalseTotal
unless $hdr->{"content-type"} =~ m[\Aapplication/json(?:\s*;|\z)]iu 0 206 206
597  
598 206 my $message = eval { JSON::XS::decode_json $body };
599  
600 206 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 204 206
601 2 ▶ return $self->_rpc_error (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
602 2 $self->_respond ($handle, 400, "Bad Request", JSON::XS::encode_json $_[0]);
603 2 }, undef, -32700, "Parse error");
604 }
605  
606 204 ▶ my $params = ref $message eq "HASH" && ref $message->{params} eq "HASH" ? $message->{params} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $message eq 'HASH' && ref $message->{'params'} eq 'HASH' ? : 192 12 204
Condition66%2/3
ref $message eq "HASH" and ref $message->{"params"} eq "HASH"
!ll&&!rl&&r
012192
MC/DC50%1/2
ref $message eq "HASH" and ref $message->{"params"} eq "HASH"
ref $message eq "HASH" ref $message->{"params"} eq "HASH"
Truth table66%2/3
A and B
A= ref $message eq "HASH"B= ref $message->{"params"} eq "HASH"
ABresult
0X0
100
111
607 204 ▶ my $meta = ref $params->{_meta} eq "HASH" ? $params->{_meta} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $params->{'_meta'} eq 'HASH' ? : 176 28 204
608 my $modern = exists $meta->{"io.modelcontextprotocol/protocolVersion"}
609 204 ▶ || $hdr->{"mcp-protocol-version"} ge "2026";
Condition100%3/3
exists $meta->{'io.modelcontextprotocol/protocolVersion'} || $hdr->{'mcp-protocol-version'} ge '2026'
l!l&&r!l&&!r
176127
MC/DC100%2/2
exists $meta->{'io.modelcontextprotocol/protocolVersion'} || $hdr->{'mcp-protocol-version'} ge '2026'
exists $meta->{'io.modelcontextprotocol/protocolVersion'} $hdr->{'mcp-protocol-version'} ge '2026'
Truth table100%3/3
A || B
A= exists $meta->{'io.modelcontextprotocol/protocolVersion'}B= $hdr->{'mcp-protocol-version'} ge '2026'
ABresult
1X1
011
000
610  
611 204 ▶ if ($modern && ref $message eq "HASH" && exists $message->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($modern and ref $message eq "HASH" and exists $message->{"id"}) 176 28 204
Condition83%5/6
$modern and ref $message eq "HASH" and exists $message->{"id"}
!ll&&!rl&&r
271176
$modern and ref $message eq "HASH"
!ll&&!rl&&r
270177
MC/DC66%2/3
$modern and ref $message eq "HASH" and exists $message->{"id"}
$modern ref $message eq "HASH" exists $message->{"id"}
Truth table75%3/4
A and B and C
A= $modernB= ref $message eq "HASH"C= exists $message->{"id"}
ABCresult
0XX0
10X0
1100
1111
612 my %expected = (
613 "mcp-protocol-version" => $meta->{"io.modelcontextprotocol/protocolVersion"},
614 "mcp-method" => $message->{method},
615 176 );
616  
617 $expected{"mcp-name"} = exists $params->{name} ? $params->{name} : $params->{uri}
618 176 ▶ if $message->{method} =~ /\A(?:tools\/call|prompts\/get|resources\/read)\z/;
Branch: 2 branches
BranchTrueFalseTotal
if $message->{"method"} =~ m[\A(?:tools/call|prompts/get|resources/read)\z]u 87 89 176
exists $params->{'name'} ? : 87 0 87
619  
620 176 for my $name (keys %expected) {
621 439 my $value = $hdr->{$name};
622  
623 439 ▶ if ($name eq "mcp-name" && $value =~ /\A=\?base64\?([A-Za-z0-9+\/=]*)\?=\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "mcp-name" and $value =~ m[\A=\?base64\?([A-Za-z0-9+/=]*)\?=\z]u) 1 438 439
Condition100%3/3
$name eq "mcp-name" and $value =~ m[\A=\?base64\?([A-Za-z0-9+/=]*)\?=\z]u
!ll&&!rl&&r
352861
MC/DC100%2/2
$name eq "mcp-name" and $value =~ m[\A=\?base64\?([A-Za-z0-9+/=]*)\?=\z]u
$name eq "mcp-name" $value =~ m[\A=\?base64\?([A-Za-z0-9+/=]*)\?=\z]u
Truth table100%3/3
A and B
A= $name eq "mcp-name"B= $value =~ m[\A=\?base64\?([A-Za-z0-9+/=]*)\?=\z]u
ABresult
0X0
100
111
624 1 $value = eval { AnyEvent::MCP::utf8dec (MIME::Base64::decode_base64 ($1)) };
625 }
626  
627 439 ▶ unless (defined $value && defined $expected{$name} && $value eq $expected{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value and defined $expected{$name} and $value eq $expected{$name}) 1 438 439
Condition50%3/6
defined $value and defined $expected{$name} and $value eq $expected{$name}
!ll&&!rl&&r
01438
defined $value and defined $expected{$name}
!ll&&!rl&&r
00439
MC/DC33%1/3
defined $value and defined $expected{$name} and $value eq $expected{$name}
defined $value defined $expected{$name} $value eq $expected{$name}
Truth table50%2/4
A and B and C
A= defined $valueB= defined $expected{$name}C= $value eq $expected{$name}
ABCresult
0XX0
10X0
1100
1111
628 1 ▶ return $self->_rpc_error (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
629 1 $self->_respond ($handle, 400, "Bad Request", JSON::XS::encode_json $_[0]);
630 1 }, $message->{id}, -32020, "Header mismatch: $name");
631 }
632 }
633 }
634  
635 203 weaken $self;
636  
637 203 my $streaming;
638 2 ▶ my $sse = sub {
Subroutine __ANON__: called CC=6 SCAR=19.9
639 2 my ($message) = @_;
640  
641 2 ▶ return unless $self && !$handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self and not $handle->{"mcp_closed"} 0 2 2
Condition33%1/3
$self and not $handle->{"mcp_closed"}
!ll&&!rl&&r
002
MC/DC0%0/2
$self and not $handle->{"mcp_closed"}
$self not $handle->{"mcp_closed"}
Truth table33%1/3
A and not(B)
A= $selfB= not $handle->{"mcp_closed"}
ABresult
0X0
100
111
642 2 ▶ unless ($streaming) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($streaming) 1 1 2
643 1 $streaming = 1;
644 $handle->push_write (
645 "HTTP/1.1 200 OK\r\n"
646 . "Content-Type: text/event-stream\r\n"
647 . "Cache-Control: no-cache\r\n"
648 . "X-Accel-Buffering: no\r\n"
649 . "Transfer-Encoding: chunked\r\n"
650 . "Connection: close\r\n"
651 . (defined $handle->{mcp_origin} ? "Access-Control-Allow-Origin: $handle->{mcp_origin}\r\n"
652 1 ▶ . ($handle->{mcp_origin} ne "*" ? "Vary: Origin\r\n" : "") : "")
Branch: 2 branches
BranchTrueFalseTotal
defined $handle->{'mcp_origin'} ? : 0 1 1
$handle->{'mcp_origin'} ne '*' ? : 0 0 0
653 . "\r\n"
654 );
655 }
656 2 my $data = "data: " . JSON::XS::encode_json ($message) . "\r\n\r\n";
657 2 $handle->push_write (sprintf "%x\r\n%s\r\n", length $data, $data);
658 203 };
659  
660 203 ▶ $self->rpc ($message, sub {
Subroutine __ANON__: called CC=11 SCAR=24.2
661 203 my ($response) = @_;
662  
663 203 ▶ return unless $self && !$handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self and not $handle->{"mcp_closed"} 0 203 203
Condition33%1/3
$self and not $handle->{"mcp_closed"}
!ll&&!rl&&r
00203
MC/DC0%0/2
$self and not $handle->{"mcp_closed"}
$self not $handle->{"mcp_closed"}
Truth table33%1/3
A and not(B)
A= $selfB= not $handle->{"mcp_closed"}
ABresult
0X0
100
111
664  
665 203 ▶ if ($streaming) {
Branch: 1 branch
BranchTrueFalseTotal
if ($streaming) 1 202 203
666 1 ▶ $sse->($response) if defined $response;
Branch: 1 branch
BranchTrueFalseTotal
if defined $response 1 0 1
667 1 $handle->push_write ("0\r\n\r\n");
668 1 ▶ $handle->on_drain (sub { $self->_close ($_[0]) if $self });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $self 1 0 1
669 1 return;
670 }
671  
672 202 ▶ my ($status, $reason) = defined $response ? (200, "OK") : (202, "Accepted");
Branch: 1 branch
BranchTrueFalseTotal
defined $response ? : 196 6 202
673  
674 202 ▶ if ($modern && defined $response && $response->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($modern and defined $response and $response->{"error"}) 6 196 202
Condition100%6/6
$modern and defined $response and $response->{"error"}
!ll&&!rl&&r
281686
$modern and defined $response
!ll&&!rl&&r
271174
MC/DC100%3/3
$modern and defined $response and $response->{"error"}
$modern defined $response $response->{"error"}
Truth table100%4/4
A and B and C
A= $modernB= defined $responseC= $response->{"error"}
ABCresult
0XX0
10X0
1100
1111
675 6 ▶ ($status, $reason) = $response->{error}{code} == -32601
Branch: 1 branch
BranchTrueFalseTotal
$response->{'error'}{'code'} == -32601 ? : 1 5 6
676 ? (404, "Not Found") : (400, "Bad Request");
677 }
678  
679 202 ▶ $self->_respond ($handle, $status, $reason, defined $response ? JSON::XS::encode_json $response : "");
Branch: 1 branch
BranchTrueFalseTotal
defined $response ? : 196 6 202
680 },
681 peer => $handle->{mcp_peer},
682 user => defined $authenticated ? $self->{token_users}{$authenticated} : undef,
683 protocol_version => $hdr->{"mcp-protocol-version"} || "2025-03-26",
684 (($hdr->{accept} || "") =~ m{\btext/event-stream\b}i
685 203 ▶ ? (on_notify => sub { $sse->($_[1]) }) : ()),
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 2 branches
BranchTrueFalseTotal
defined $authenticated ? : 93 110 203
($hdr->{'accept'} || '') =~ m[\btext/event-stream\b]iu ? : 181 22 203
Condition100%4/4
$hdr->{'mcp-protocol-version'} || '2025-03-26'
l!l
19112
$hdr->{'accept'} || ''
l!l
18122
MC/DC100%1/1
$hdr->{'mcp-protocol-version'} || '2025-03-26'
$hdr->{'mcp-protocol-version'}
MC/DC100%1/1
$hdr->{'accept'} || ''
$hdr->{'accept'}
Truth table100%2/2
A
A= $hdr->{'mcp-protocol-version'}
Aresult
11
00
Truth table100%2/2
A
A= $hdr->{'accept'}
Aresult
11
00
686 );
687 }
688  
689 256 ▶sub _respond {
Subroutine _respond: called CC=28 SCAR=35.0
690 256 my ($self, $handle, $status, $reason, $body, $headers) = @_;
691  
692 256 ▶ return if $handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $handle->{"mcp_closed"} 0 256 256
693  
694 256 ▶ $body = "" unless defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 0 256 256
695 256 my $content_type = "application/json";
696 256 my $extra = "";
697  
698 256 ▶ if ($headers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers) 8 248 256
699 8 ▶ ref $headers eq "HASH" or die "HTTP response headers must be a hash\n";
Branch: 1 branch
BranchTrueFalseTotal
ref $headers eq "HASH" or die "HTTP response headers must be a hash\n" 8 0 8
700 8 ▶ while (my ($name, $value) = each %$headers) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$headers) 4 8 12
701 4 ▶ $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/u and defined $value and not ref $value and not $value =~ /[\r\n\0]/u or die "Invalid HTTP response header\n" 4 0 4
Condition33%3/9
$name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/u and defined $value and not ref $value and not $value =~ /[\r\n\0]/u
!ll&&!rl&&r
004
$name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/u and defined $value and not ref $value
!ll&&!rl&&r
004
$name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/u and defined $value
!ll&&!rl&&r
004
MC/DC0%0/4
$name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/u and defined $value and not ref $value and not $value =~ /[\r\n\0]/u
$name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/u defined $value not ref $value not $value =~ /[\r\n\0]/u
Truth table20%1/5
A and B and not(C) and not(D)
A= $name =~ /\A[!#\$%&'*+.^_`|~0-9A-Za-z-]+\z/uB= defined $valueC= not ref $valueD= not $value =~ /[\r\n\0]/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
702 && defined $value && !ref $value && $value !~ /[\r\n\0]/
703 or die "Invalid HTTP response header\n";
704 4 ▶ $name !~ /\A(?:content-length|connection|transfer-encoding)\z/i
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /\A(?:content-length|connection|transfer-encoding)\z/iu and die "HTTP response framing headers are managed by the server\n" 0 4 4
705 or die "HTTP response framing headers are managed by the server\n";
706 4 ▶ if (lc $name eq "content-type") {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $name eq 'content-type') { } 2 2 4
707 2 $content_type = $value;
708 } else {
709 2 $extra .= "$name: $value\r\n";
710 }
711 }
712 }
713  
714 256 ▶ if ($status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status >= 400) 48 208 256
715 48 ▶ my $level = $status == 404 ? "trace" : "warn";
Branch: 1 branch
BranchTrueFalseTotal
$status == 404 ? : 17 31 48
716 AE::log $level => "MCP HTTP"
717 . (defined $handle->{mcp_remote} ? " remote=$handle->{mcp_remote}" : "")
718 . ": " . ($handle->{mcp_method} // "-") . " $status"
719 48 ▶ . (defined $handle->{mcp_uri} ? " uri=$handle->{mcp_uri}" : "");
Branch: 2 branches
BranchTrueFalseTotal
defined $handle->{'mcp_remote'} ? : 29 19 48
defined $handle->{'mcp_uri'} ? : 45 3 48
Condition50%1/2
$handle->{"mcp_method"} // "-"
l!l
480
MC/DC0%0/1
$handle->{"mcp_method"} // "-"
$handle->{"mcp_method"}
Truth table50%1/2
A
A= $handle->{"mcp_method"}
Aresult
11
00
720 }
721  
722 256 ▶ my $close = $handle->{mcp_close} || $status != 200 && $status != 202;
Condition83%5/6
$handle->{'mcp_close'} || $status != 200 && $status != 202
l!l&&r!l&&!r
1973623
$status != 200 and $status != 202
!ll&&!rl&&r
23036
MC/DC66%2/3
$handle->{'mcp_close'} || $status != 200 && $status != 202
$handle->{'mcp_close'} $status != 200 $status != 202
Truth table75%3/4
A || B and C
A= $handle->{'mcp_close'}B= $status != 200C= $status != 202
ABCresult
1XX1
0111
00X0
0100
723  
724 $handle->push_write (
725 "HTTP/1.1 $status $reason\r\n"
726 . "Content-Type: $content_type\r\n"
727 . "Content-Length: " . (length $body) . "\r\n"
728 . $extra
729 . (defined $handle->{mcp_origin} ? "Access-Control-Allow-Origin: $handle->{mcp_origin}\r\n"
730 . ($handle->{mcp_origin} ne "*" ? "Vary: Origin\r\n" : "") : "")
731 . ($status == 204 ? "Access-Control-Allow-Methods: POST, OPTIONS\r\n"
732 . "Access-Control-Allow-Headers: content-type,authorization,mcp-protocol-version,mcp-method,mcp-name\r\n"
733 . "Access-Control-Max-Age: 86400\r\n" : "")
734 1 ▶ . ($status == 405 ? "Allow: POST" . (@{$self->{origins}} ? ", OPTIONS" : "") . "\r\n" : "")
Branch: 2 branches
BranchTrueFalseTotal
$status == 401 && $self->{'tokens'} ? : 13 243 256
$close ? : 233 23 256
Condition66%2/3
$status == 401 and $self->{"tokens"}
!ll&&!rl&&r
243013
MC/DC50%1/2
$status == 401 and $self->{"tokens"}
$status == 401 $self->{"tokens"}
Truth table66%2/3
A and B
A= $status == 401B= $self->{"tokens"}
ABresult
0X0
100
111
735 256 ▶ . ($status == 401 && $self->{tokens} ? "WWW-Authenticate: Bearer\r\n" : "")
Branch: 5 branches
BranchTrueFalseTotal
defined $handle->{'mcp_origin'} ? : 8 248 256
$handle->{'mcp_origin'} ne '*' ? : 1 7 8
$status == 204 ? : 4 252 256
$status == 405 ? : 1 255 256
@{$self->{'origins'};} ? : 0 1 1
736 . ($close ? "Connection: close\r\n" : "")
737 . "\r\n$body"
738 );
739  
740 256 ▶ if ($close) {
Branch: 1 branch
BranchTrueFalseTotal
if ($close) { } 233 23 256
741 233 weaken $self;
742 233 ▶ $handle->on_drain (sub { $self->_close ($_[0]) if $self });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $self 233 0 233
743 } else {
744 23 $self->_read ($handle);
745 }
746 }
747  
748 260 ▶sub _close {
Subroutine _close: called CC=4 SCAR=13.9
749 260 my ($self, $handle) = @_;
750  
751 260 ▶ return if $handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $handle->{"mcp_closed"} 0 260 260
752 260 $handle->{mcp_closed} = 1;
753  
754 260 ▶ my $requests = delete $handle->{mcp_peer}{requests} || {};
Condition100%2/2
delete $handle->{'mcp_peer'}{'requests'} || {}
l!l
19169
MC/DC100%1/1
delete $handle->{'mcp_peer'}{'requests'} || {}
delete $handle->{'mcp_peer'}{'requests'}
Truth table100%2/2
A
A= delete $handle->{'mcp_peer'}{'requests'}
Aresult
11
00
755 260 $_->cancel ("Connection closed") for grep defined, values %$requests;
756  
757 260 delete $self->{connections}{$handle};
758 260 $handle->destroy;
759 }
760  
761 228 ▶sub close {
Subroutine close: called CC=4 SCAR=13.9
Pod documented
762 228 my ($self) = @_;
763  
764 228 ▶ return if $self->{_closed}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_closed"}++ 101 127 228
765 127 delete $self->{listener};
766 127 ▶ $self->_close ($_) for values %{$self->{connections} || {}};
Condition100%2/2
$self->{'connections'} || {}
l!l
8047
MC/DC100%1/1
$self->{'connections'} || {}
$self->{'connections'}
Truth table100%2/2
A
A= $self->{'connections'}
Aresult
11
00
767 127 $self->event (close =>);
768 }
769  
770 109 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
771 109 $_[0]->close
772 }
773  
774 43 1
« lib/AnyEvent/MCP/IMAP/OAuth2.pm ↑ Summary bin/anyevent-mcp »