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 42 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
278 42 ▶use parent "AnyEvent::MCP::Server";
Subroutine BEGIN: called CC=1 SCAR=0.0
279 42 ▶use AnyEvent::Log ();
Subroutine BEGIN: called CC=1 SCAR=0.0
280 42 ▶use AnyEvent::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
281 42 ▶use AnyEvent::Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
282 42 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
283 42 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
284 42 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
285 42 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
286  
287 118 ▶sub new {
Subroutine new: called CC=10 SCAR=23.0
Pod documented
288 118 my ($class, %kv) = @_;
289  
290 118 ▶ !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 118 118
291 or die "Legacy HTTP authentication options are unsupported; use tokens\n";
292  
293 118 ▶ $kv{auth} //= "tokens";
Condition100%2/2
$kv{"auth"} //= "tokens"
l!l
6058
MC/DC100%1/1
$kv{"auth"} //= "tokens"
$kv{"auth"}
Truth table100%2/2
A
A= $kv{"auth"}
Aresult
11
00
294 118 ▶ if ($kv{auth} eq "tokens") {
Branch: 2 branches
BranchTrueFalseTotal
if ($kv{'auth'} eq 'tokens') { } 58 60 118
elsif ($kv{'auth'} eq 'none') { } 59 1 60
295 58 ▶ 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" 56 2 58
Condition100%3/3
ref $kv{"tokens"} eq "ARRAY" and @{$kv{"tokens"};}
!ll&&!rl&&r
1156
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 56 ▶ for @{$kv{tokens}};
Branch: 1 branch
BranchTrueFalseTotal
/\A[A-Za-z0-9_.~-]+\z/u or die "Invalid HTTP server token\n" 68 1 69
299 } elsif ($kv{auth} eq "none") {
300 !exists $kv{tokens}
301 59 ▶ 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 58 59
302 } else {
303 1 die "Unsupported HTTP authentication type '$kv{auth}'\n";
304 }
305  
306 113 $class->SUPER::new (host => "127.0.0.1", port => 0, path => "/mcp/", origins => ["*"], %kv)
307 }
308  
309 51 ▶sub _tls_context {
Subroutine _tls_context: called CC=6 SCAR=31.3
310 51 my ($self) = @_;
311  
312 51 ▶ return unless defined $self->{tls_cert} || defined $self->{tls_key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"tls_cert"} or defined $self->{"tls_key"} 51 0 51
Condition33%1/3
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
l!l&&r!l&&!r
0051
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 51 ▶sub listen {
Subroutine listen: called CC=4 SCAR=14.1
Pod documented
324 51 my ($self, $host, $port, %handle) = @_;
325  
326 51 $self->_tls_context;
327 51 delete $self->{_closed};
328 51 ▶ $host = $self->{host} unless defined $host;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host 51 0 51
329 51 ▶ $port = $self->{port} unless defined $port;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $port 51 0 51
330  
331 51 $self->{listen_host} = $host;
332 51 ▶ $self->{listen_handle} = { %{$self->{handle} || {}}, %handle };
Condition50%1/2
$self->{'handle'} || {}
l!l
051
MC/DC0%0/1
$self->{'handle'} || {}
$self->{'handle'}
Truth table50%1/2
A
A= $self->{'handle'}
Aresult
11
00
333  
334 51 delete $self->{listener};
335 51 weaken $self;
336  
337 181 ▶ $self->{listener} = AnyEvent::Socket::tcp_server $host, $port, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
338 181 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 181 181
339 181 my ($socket, $host, $port) = @_;
340 181 my $handle = $self->accept ($socket, %handle);
341 181 $handle->{mcp_remote} = AnyEvent::Socket::format_hostport ($host, $port);
342 51 ▶ }, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
343 51 ▶ $self->{port} = $_[2] if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 51 0 51
344 ()
345 51 };
346 }
347  
348 176 ▶sub _token_path {
Subroutine _token_path: called CC=1 SCAR=0.0
349 176 my ($self, $token) = @_;
350  
351 176 "/$token$self->{path}"
352 }
353  
354 76 ▶sub url {
Subroutine url: called CC=17 SCAR=29.0
Pod documented
355 76 my ($self, $with_token) = @_;
356  
357 76 ▶ $with_token = 1 unless defined $with_token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $with_token 60 16 76
358  
359 my $host = $self->{url_host}
360 76 ▶ || (defined $self->{listen_host} ? $self->{listen_host} : $self->{host});
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'listen_host'} ? : 43 31 74
Condition66%2/3
$self->{'url_host'} || (defined $self->{'listen_host'} ? $self->{'listen_host'} : $self->{'host'})
l!l&&r!l&&!r
2740
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 76 ▶ $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 74 76
Condition66%4/6
not length $host or $host eq "0.0.0.0" or $host eq "::"
l!l&&r!l&&!r
2074
not length $host or $host eq "0.0.0.0"
l!l&&r!l&&!r
0274
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 76 $host =~ s/\A\[(.*)\]\z/$1/; # allow already bracketed IPv6 URL hosts
363  
364 76 ▶ 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" 73 3 76
365 my $scheme = $self->{url_scheme}
366 || (defined $self->{tls_cert} || defined $self->{tls_key}
367 73 ▶ || ($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 54 56
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
17560
defined $self->{"tls_cert"} or defined $self->{"tls_key"} or +($self->{"listen_handle"} || $self->{"handle"} || {})->{"tls"}
l!l&&r!l&&!r
0254
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
l!l&&r!l&&!r
0056
$self->{'listen_handle'} || $self->{'handle'} || {}
l!l
4511
$self->{"listen_handle"} or $self->{"handle"}
l!l&&r!l&&!r
43211
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 28 my $path = $with_token && $self->{tokens} && @{$self->{tokens}}
369 73 ▶ ? $self->_token_path ($self->{tokens}[0]) : $self->{path};
Branch: 1 branch
BranchTrueFalseTotal
$with_token && $self->{'tokens'} && @{$self->{'tokens'};} ? : 28 45 73
Condition83%5/6
$with_token and $self->{"tokens"} and @{$self->{"tokens"};}
!ll&&!rl&&r
45028
$with_token and $self->{"tokens"}
!ll&&!rl&&r
162928
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 73 "$scheme://" . AnyEvent::Socket::format_hostport ($host, $port) . $path
372 }
373  
374 249 ▶sub accept {
Subroutine accept: called CC=6 SCAR=22.1
Pod documented
375 249 my ($self, $socket, %handle) = @_;
376  
377 249 delete $self->{_closed};
378 249 weaken $self;
379  
380 my $handle = AnyEvent::Handle->new (
381 rbuf_max => $self->{max_size} || 8 * 1024 * 1024,
382 rtimeout => 15,
383 249 %{$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 249 ▶ );
Condition100%2/2
$self->{'max_size'} || 8388608
l!l
4245
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 249 $handle->{mcp_read_timeout} = $handle->{rtimeout};
395 249 $handle->{mcp_peer} = {};
396 249 $self->{connections}{$handle} = $handle;
397 $handle->push_read (tls_autostart => $self->_tls_context, "accept")
398 249 ▶ 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 249 249
Condition33%2/6
defined $self->{"tls_cert"} || defined $self->{"tls_key"} and not $handle->{"tls"}
!ll&&!rl&&r
24900
defined $self->{"tls_cert"} or defined $self->{"tls_key"}
l!l&&r!l&&!r
00249
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 249 ▶ if ($self->{on_extension}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'on_extension'}) { } 12 237 249
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 237 $self->_read ($handle);
421 }
422  
423 249 $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 256 ▶sub _parse_request_headers {
Subroutine _parse_request_headers: called CC=7 SCAR=19.5
429 256 local $_ = $_[0] . "\r\n";
430 256 ▶ /\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 254 2 256
431 ([^\x00-\x20]+) [ ]+ HTTP\/0*([0-9.]+)\r\n/gcix
432 or return;
433 254 my ($method, $uri, $version) = ($1, $2, $3);
434 254 ▶ return unless $version =~ /\A1\.[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $version =~ /\A1\.[0-9]+\z/u 1 253 254
435 253 my %hdr;
436  
437 253 ▶ $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" } 2133 253 2386
438 while /\G
439 ([!\#$%&'*+.^_\x60|~0-9A-Za-z-]+):
440 [\t ]*
441 ([^\x00-\x08\x0a-\x1f\x7f]*)
442 \r\n
443 /gcx;
444  
445 253 ▶ /\G\z/gc or return;
Branch: 1 branch
BranchTrueFalseTotal
/\G\z/cgu or return 249 4 253
446  
447 # discard the prefix used for comma-combining repeated field values.
448 249 substr $_, 0, 1, "" for values %hdr;
449 249 s/[\t ]+\z// for values %hdr;
450  
451 # request-line fields override any colliding HTTP header names.
452 249 +{ %hdr, method => $method, uri => $uri, http_version => $version }
453 }
454  
455 # Retain useful paths in rejection logs, without leaking URL credentials.
456 250 ▶sub _log_uri {
Subroutine _log_uri: called CC=7 SCAR=19.5
457 250 my ($self, $uri) = @_;
458  
459 250 ▶ return '"[non-path URI]"' unless $uri =~ m{\A/};
Branch: 1 branch
BranchTrueFalseTotal
unless $uri =~ m[\A/]u 2 248 250
460 248 $uri =~ s/[?#].*//s;
461  
462 248 ▶ if ($self->{tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tokens"}) 132 116 248
463 132 (my $endpoint = $self->{path}) =~ s{/\z}{};
464 132 ▶ $endpoint = "/" unless length $endpoint;
Branch: 1 branch
BranchTrueFalseTotal
unless length $endpoint 32 100 132
465 132 ▶ $uri =~ s{\A/[^/]+(?=\Q$endpoint\E(?:/|\z))}{/<token>}
Branch: 1 branch
BranchTrueFalseTotal
unless $endpoint eq "/" 100 32 132
466 unless $endpoint eq "/";
467 132 $uri =~ s/\Q$_\E/<token>/g for @{$self->{tokens}};
468 }
469  
470 248 ▶ $uri = substr ($uri, 0, 160) . "..." if length $uri > 160;
Branch: 1 branch
BranchTrueFalseTotal
if length $uri > 160 1 247 248
471 248 JSON::XS::encode_json $uri
472 }
473  
474 510 ▶sub _read {
Subroutine _read: called CC=2 SCAR=7.0
475 510 my ($self, $handle, $immediate) = @_;
476  
477 510 weaken $self;
478  
479 510 $handle->rtimeout_reset;
480 510 $handle->rtimeout ($handle->{mcp_read_timeout});
481 510 ▶ if ($immediate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($immediate) { } 250 260 510
482 248 ▶ $handle->push_read (line => "\r\n\r\n", sub {
Subroutine __ANON__: called CC=15 SCAR=27.9
483 248 my ($handle, $header) = @_;
484  
485 248 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 248 248
486  
487 248 my $hdr = _parse_request_headers ($header);
488 248 ▶ $handle->{mcp_method} = $hdr ? substr ($hdr->{method}, 0, 32) : "-";
Branch: 1 branch
BranchTrueFalseTotal
$hdr ? : 245 3 248
489 248 ▶ $handle->{mcp_uri} = $hdr ? $self->_log_uri ($hdr->{uri}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$hdr ? : 245 3 248
490 $handle->{mcp_close} = $self->{connection_close}
491 || !$hdr || $hdr->{http_version} =~ m{\A1\.0+\z}
492 248 ▶ || $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
817961
$self->{"connection_close"} or not $hdr or $hdr->{"http_version"} =~ /\A1\.0+\z/u
l!l&&r!l&&!r
80240
$self->{"connection_close"} or not $hdr
l!l&&r!l&&!r
53240
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 248 ▶ return $self->_respond ($handle, 400, "Bad Request", "") unless $hdr;
Branch: 1 branch
BranchTrueFalseTotal
unless $hdr 3 245 248
495  
496 245 ▶ $hdr->{"content-length"} = 0 unless defined $hdr->{"content-length"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hdr->{"content-length"} 7 238 245
497 return $self->_respond ($handle, 400, "Bad Request", "")
498 if exists $hdr->{"transfer-encoding"}
499 245 ▶ || $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 242 245
Condition100%3/3
exists $hdr->{"transfer-encoding"} or not $hdr->{"content-length"} =~ /\A[0-9]+\z/u
l!l&&r!l&&!r
12242
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 242 ▶ if $hdr->{"content-length"} > ($self->{max_size} || 8 * 1024 * 1024);
Branch: 1 branch
BranchTrueFalseTotal
if $hdr->{"content-length"} > ($self->{"max_size"} || 8388608) 0 242 242
Condition100%2/2
$self->{'max_size'} || 8388608
l!l
4238
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 242 ▶ if ($hdr->{expect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr->{"expect"}) 0 242 242
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 240 ▶ $handle->push_read (chunk => $hdr->{"content-length"}, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
512 240 my ($handle, $body) = @_;
513  
514 240 $handle->rtimeout (0);
515 240 ▶ $self->_request ($handle, $hdr, $body) if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 240 0 240
516 242 });
517 250 });
518 } else {
519 238 ▶ $handle->on_read (sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
520 238 my ($handle) = @_;
521 238 $handle->on_read (undef);
522 238 ▶ $self->_read ($handle, 1) if $self;
Branch: 1 branch
BranchTrueFalseTotal
if $self 238 0 238
523 260 });
524 }
525 }
526  
527 240 ▶sub _request {
Subroutine _request: called CC=46 SCAR=38.8
528 240 my ($self, $handle, $hdr, $body) = @_;
529  
530 240 delete $handle->{mcp_origin};
531  
532 240 ▶ if (my $hook = $self->{on_http_request}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hook = $self->{"on_http_request"}) 24 216 240
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 232 ▶ if $hdr->{method} eq "GET" && $hdr->{uri} eq "/";
Branch: 1 branch
BranchTrueFalseTotal
if $hdr->{"method"} eq "GET" and $hdr->{"uri"} eq "/" 4 228 232
Condition100%3/3
$hdr->{"method"} eq "GET" and $hdr->{"uri"} eq "/"
!ll&&!rl&&r
22084
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 228 my $uri = $hdr->{uri};
550 228 ▶ $uri .= "/" if $self->{path} =~ m{/$} && $uri !~ m{/$};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"path"} =~ m[/$]u and not $uri =~ m[/$]u 10 218 228
Condition100%3/3
$self->{"path"} =~ m[/$]u and not $uri =~ m[/$]u
!ll&&!rl&&r
121710
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 228 ▶ ? grep $uri eq $self->_token_path ($_), @{$self->{tokens}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tokens'} ? : 122 106 228
553 228 my $token_path = defined $path_token;
554  
555 return $self->_respond ($handle, 404, "Not Found", "")
556 228 ▶ unless $uri eq $self->{path} || $token_path;
Branch: 1 branch
BranchTrueFalseTotal
unless $uri eq $self->{"path"} or $token_path 12 216 228
Condition100%3/3
$uri eq $self->{"path"} or $token_path
l!l&&r!l&&!r
1942212
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 216 ▶ if (exists $hdr->{origin}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hdr->{"origin"}) 11 205 216
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 213 ▶ if ($hdr->{method} eq "OPTIONS" && @{$self->{origins}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr->{"method"} eq "OPTIONS" and @{$self->{"origins"};}) 4 209 213
Condition100%3/3
$hdr->{"method"} eq "OPTIONS" and @{$self->{"origins"};}
!ll&&!rl&&r
20814
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 209 ▶ unless $hdr->{method} eq "POST";
Branch: 1 branch
BranchTrueFalseTotal
unless $hdr->{"method"} eq "POST" 1 208 209
577  
578 208 my $authenticated = $path_token;
579 208 ▶ if ($self->{tokens}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tokens"}) 103 105 208
580 103 my $authorization = $hdr->{authorization};
581  
582 103 ▶ if ($authorization =~ /\ABearer ([^\s]+)\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($authorization =~ /\ABearer ([^\s]+)\z/iu) 78 25 103
583 78 my $token = $1;
584 78 ▶ if (grep $_ eq $token, @{$self->{tokens}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep(($_ eq $token), @{$$self{"tokens"};})) 73 5 78
585 73 ▶ return $self->_respond ($handle, 401, "Unauthorized", "")
Branch: 1 branch
BranchTrueFalseTotal
if defined $authenticated and $authenticated ne $token 1 72 73
Condition66%2/3
defined $authenticated and $authenticated ne $token
!ll&&!rl&&r
7201
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 72 $authenticated = $token;
588 }
589 }
590  
591 102 ▶ return $self->_respond ($handle, 401, "Unauthorized", "")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $authenticated 12 90 102
592 unless defined $authenticated;
593 }
594  
595 return $self->_respond ($handle, 415, "Unsupported Media Type", "")
596 195 ▶ 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 195 195
597  
598 195 my $message = eval { JSON::XS::decode_json $body };
599  
600 195 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 193 195
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 193 ▶ 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' ? : 181 12 193
Condition66%2/3
ref $message eq "HASH" and ref $message->{"params"} eq "HASH"
!ll&&!rl&&r
012181
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 193 ▶ my $meta = ref $params->{_meta} eq "HASH" ? $params->{_meta} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $params->{'_meta'} eq 'HASH' ? : 165 28 193
608 my $modern = exists $meta->{"io.modelcontextprotocol/protocolVersion"}
609 193 ▶ || $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
165127
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 193 ▶ if ($modern && ref $message eq "HASH" && exists $message->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($modern and ref $message eq "HASH" and exists $message->{"id"}) 165 28 193
Condition83%5/6
$modern and ref $message eq "HASH" and exists $message->{"id"}
!ll&&!rl&&r
271165
$modern and ref $message eq "HASH"
!ll&&!rl&&r
270166
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 165 );
616  
617 $expected{"mcp-name"} = exists $params->{name} ? $params->{name} : $params->{uri}
618 165 ▶ 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 78 165
exists $params->{'name'} ? : 87 0 87
619  
620 165 for my $name (keys %expected) {
621 417 my $value = $hdr->{$name};
622  
623 417 ▶ 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 416 417
Condition100%3/3
$name eq "mcp-name" and $value =~ m[\A=\?base64\?([A-Za-z0-9+/=]*)\?=\z]u
!ll&&!rl&&r
330861
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 417 ▶ 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 416 417
Condition50%3/6
defined $value and defined $expected{$name} and $value eq $expected{$name}
!ll&&!rl&&r
01416
defined $value and defined $expected{$name}
!ll&&!rl&&r
00417
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 192 weaken $self;
636  
637 192 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 192 };
659  
660 192 ▶ $self->rpc ($message, sub {
Subroutine __ANON__: called CC=11 SCAR=24.2
661 192 my ($response) = @_;
662  
663 192 ▶ return unless $self && !$handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self and not $handle->{"mcp_closed"} 0 192 192
Condition33%1/3
$self and not $handle->{"mcp_closed"}
!ll&&!rl&&r
00192
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 192 ▶ if ($streaming) {
Branch: 1 branch
BranchTrueFalseTotal
if ($streaming) 1 191 192
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 191 ▶ my ($status, $reason) = defined $response ? (200, "OK") : (202, "Accepted");
Branch: 1 branch
BranchTrueFalseTotal
defined $response ? : 185 6 191
673  
674 191 ▶ if ($modern && defined $response && $response->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($modern and defined $response and $response->{"error"}) 6 185 191
Condition100%6/6
$modern and defined $response and $response->{"error"}
!ll&&!rl&&r
281576
$modern and defined $response
!ll&&!rl&&r
271163
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 191 ▶ $self->_respond ($handle, $status, $reason, defined $response ? JSON::XS::encode_json $response : "");
Branch: 1 branch
BranchTrueFalseTotal
defined $response ? : 185 6 191
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 192 ▶ ? (on_notify => sub { $sse->($_[1]) }) : ()),
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 2 branches
BranchTrueFalseTotal
defined $authenticated ? : 88 104 192
($hdr->{'accept'} || '') =~ m[\btext/event-stream\b]iu ? : 170 22 192
Condition100%4/4
$hdr->{'mcp-protocol-version'} || '2025-03-26'
l!l
18012
$hdr->{'accept'} || ''
l!l
17022
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 245 ▶sub _respond {
Subroutine _respond: called CC=28 SCAR=35.0
690 245 my ($self, $handle, $status, $reason, $body, $headers) = @_;
691  
692 245 ▶ return if $handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $handle->{"mcp_closed"} 0 245 245
693  
694 245 ▶ $body = "" unless defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 0 245 245
695 245 my $content_type = "application/json";
696 245 my $extra = "";
697  
698 245 ▶ if ($headers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers) 8 237 245
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 245 ▶ if ($status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status >= 400) 48 197 245
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 245 ▶ my $close = $handle->{mcp_close} || $status != 200 && $status != 202;
Condition83%5/6
$handle->{'mcp_close'} || $status != 200 && $status != 202
l!l&&r!l&&!r
1863623
$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 232 245
$close ? : 222 23 245
Condition66%2/3
$status == 401 and $self->{"tokens"}
!ll&&!rl&&r
232013
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 245 ▶ . ($status == 401 && $self->{tokens} ? "WWW-Authenticate: Bearer\r\n" : "")
Branch: 5 branches
BranchTrueFalseTotal
defined $handle->{'mcp_origin'} ? : 8 237 245
$handle->{'mcp_origin'} ne '*' ? : 1 7 8
$status == 204 ? : 4 241 245
$status == 405 ? : 1 244 245
@{$self->{'origins'};} ? : 0 1 1
736 . ($close ? "Connection: close\r\n" : "")
737 . "\r\n$body"
738 );
739  
740 245 ▶ if ($close) {
Branch: 1 branch
BranchTrueFalseTotal
if ($close) { } 222 23 245
741 222 weaken $self;
742 222 ▶ $handle->on_drain (sub { $self->_close ($_[0]) if $self });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $self 222 0 222
743 } else {
744 23 $self->_read ($handle);
745 }
746 }
747  
748 249 ▶sub _close {
Subroutine _close: called CC=4 SCAR=13.9
749 249 my ($self, $handle) = @_;
750  
751 249 ▶ return if $handle->{mcp_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $handle->{"mcp_closed"} 0 249 249
752 249 $handle->{mcp_closed} = 1;
753  
754 249 ▶ my $requests = delete $handle->{mcp_peer}{requests} || {};
Condition100%2/2
delete $handle->{'mcp_peer'}{'requests'} || {}
l!l
18069
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 249 $_->cancel ("Connection closed") for grep defined, values %$requests;
756  
757 249 delete $self->{connections}{$handle};
758 249 $handle->destroy;
759 }
760  
761 225 ▶sub close {
Subroutine close: called CC=4 SCAR=13.9
Pod documented
762 225 my ($self) = @_;
763  
764 225 ▶ return if $self->{_closed}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_closed"}++ 100 125 225
765 125 delete $self->{listener};
766 125 ▶ $self->_close ($_) for values %{$self->{connections} || {}};
Condition100%2/2
$self->{'connections'} || {}
l!l
7946
MC/DC100%1/1
$self->{'connections'} || {}
$self->{'connections'}
Truth table100%2/2
A
A= $self->{'connections'}
Aresult
11
00
767 125 $self->event (close =>);
768 }
769  
770 107 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
771 107 $_[0]->close
772 }
773  
774 42 1
« lib/AnyEvent/MCP/IMAP/OAuth2.pm ↑ Summary bin/anyevent-mcp »