MCP/Server/Transport/HTTP.pm

filter: Statementstmt 100% 134 / 134 Branchbran 85.3% 70 / 82 Conditioncond 73.9% 17 / 23 MC/DCmcdc 61.5% 8 / 13 Subroutinesub 100% 30 / 30 Podpod 100% 4 / 4 totaltotal 91.9% 263 / 286 CC 55 SCAR 15.1
CC
55
Cov
92%
_handle_regular_request
8.0
handle_request
8.0
__ANON__
6.3
CRAP 4.5
« MCP/Tool.pm ↑ Summary MCP/Server/Context.pm »
1 package MCP::Server::Transport::HTTP;
2 4 ▶use Mojo::Base 'MCP::Server::Transport', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 4 ▶use Crypt::Misc qw(random_v4uuid);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use MCP::Server::Context;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use MCP::Server::Session;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Mojo::JSON qw(to_json true);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Mojo::Util qw(dumper);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 4 ▶use constant DEBUG => $ENV{MCP_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MCP_DEBUG'} || 0
l!l
04
MC/DC0%0/1
$ENV{'MCP_DEBUG'} || 0
$ENV{'MCP_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MCP_DEBUG'}
Aresult
11
00
13  
14 4 has 'auth';
15 4 has heartbeat => 30;
16 4 has 'metadata_url';
17 4 has session_timeout => 3600;
18 1 ▶has sessions => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
19 4 has streaming => 0;
20  
21 18 ▶sub notifications ($self) { $self->streaming ? 1 : 0 }
Subroutine notifications: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->streaming ? : 11 7 18
22  
23 ▶sub handle_request ($self, $c) {
Subroutine handle_request: called CC=8 SCAR=20.8
Pod documented
24 136 ▶ if (my $auth = $self->auth) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $auth = $self->auth) 28 108 136
25 28 ▶ return $self->_unauthorized($c) unless my $info = $auth->($c);
Branch: 1 branch
BranchTrueFalseTotal
unless my $info = &$auth($c) 2 26 28
26 26 $c->stash('mcp.auth' => $info);
27 }
28  
29 134 my $method = $c->req->method;
30 134 ▶ return $self->_handle_post($c) if $method eq 'POST';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "POST" 107 27 134
31 27 ▶ return $self->_handle_get($c) if $method eq 'GET' && $self->streaming;
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "GET" and $self->streaming 12 15 27
Condition100%3/3
$method eq "GET" and $self->streaming
!ll&&!rl&&r
14112
MC/DC100%2/2
$method eq "GET" and $self->streaming
$method eq "GET" $self->streaming
Truth table100%3/3
A and B
A= $method eq "GET"B= $self->streaming
ABresult
0X0
100
111
32 15 ▶ return $self->_handle_delete($c) if $method eq 'DELETE' && $self->streaming;
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DELETE" and $self->streaming 13 2 15
Condition100%3/3
$method eq "DELETE" and $self->streaming
!ll&&!rl&&r
1113
MC/DC100%2/2
$method eq "DELETE" and $self->streaming
$method eq "DELETE" $self->streaming
Truth table100%3/3
A and B
A= $method eq "DELETE"B= $self->streaming
ABresult
0X0
100
111
33 2 return $c->render(json => {error => 'Method not allowed'}, status => 405);
34 }
35  
36 4 ▶sub notify ($self, $session_id, $method, $params = {}) {
Subroutine notify: called CC=4 SCAR=13.9
Pod documented
37 4 ▶ return undef unless my $session = $self->sessions->{$session_id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $session = $self->sessions->{$session_id} 0 4 4
38 4 ▶ return undef unless my $stream = $session->stream;
Branch: 1 branch
BranchTrueFalseTotal
unless my $stream = $session->stream 1 3 4
39 3 $stream->write_sse({text => to_json({jsonrpc => '2.0', method => $method, params => $params})});
40 3 return 1;
41 }
42  
43 3 ▶sub notify_all ($self, $method, $params = {}) {
Subroutine notify_all: called CC=5 SCAR=16.1
Pod documented
44 3 ▶ return undef unless $self->streaming;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->streaming 1 2 3
45 2 my $payload = {text => to_json({jsonrpc => '2.0', method => $method, params => $params})};
46 2 for my $session (values %{$self->sessions}) {
47 1 ▶ next unless my $stream = $session->stream;
Branch: 1 branch
BranchTrueFalseTotal
unless my $stream = $session->stream 0 1 1
48 1 $stream->write_sse($payload);
49 }
50 2 return 1;
51 }
52  
53 ▶sub _challenge_header ($self, %extra) {
Subroutine _challenge_header: called CC=5 SCAR=16.2
54 6 my @parts;
55 6 ▶ push @parts, qq{resource_metadata="@{[$self->metadata_url]}"} if $self->metadata_url;
Branch: 1 branch
BranchTrueFalseTotal
if $self->metadata_url 6 0 6
56 6 ▶ push @parts, qq{error="$extra{error}"} if $extra{error};
Branch: 1 branch
BranchTrueFalseTotal
if $extra{"error"} 4 2 6
57 6 ▶ push @parts, qq{scope="$extra{scope}"} if defined $extra{scope};
Branch: 1 branch
BranchTrueFalseTotal
if defined $extra{"scope"} 4 2 6
58 6 ▶ return 'Bearer' . (@parts ? ' ' . join(', ', @parts) : '');
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 6 0 6
59 }
60  
61 132 ▶sub _extract_session_id ($self, $c) { return $c->req->headers->header('Mcp-Session-Id') }
Subroutine _extract_session_id: called CC=1 SCAR=0.0
62  
63 ▶sub _scopes ($self, $c) {
Subroutine _scopes: called CC=4 SCAR=14.5
64 105 ▶ return undef unless $self->auth;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->auth 79 26 105
65 26 ▶ return ($c->stash('mcp.auth') // {})->{scopes} // [];
Condition50%2/4
+($c->stash("mcp.auth") // {})->{"scopes"} // []
l!l
260
$c->stash("mcp.auth") // {}
l!l
260
MC/DC0%0/1
+($c->stash("mcp.auth") // {})->{"scopes"} // []
$c->stash("mcp.auth")
Truth table50%1/2
A
A= $c->stash("mcp.auth")
Aresult
11
00
66 }
67  
68 ▶sub _unauthorized ($self, $c) {
Subroutine _unauthorized: called CC=1 SCAR=0.0
69 2 $c->res->headers->header('WWW-Authenticate' => $self->_challenge_header);
70 2 return $c->render(json => {error => 'Unauthorized'}, status => 401);
71 }
72  
73 ▶sub _handle ($self, $data, $context) {
Subroutine _handle: called CC=1 SCAR=0.0
74 105 warn "-- MCP Request\n@{[dumper($data)]}\n" if DEBUG;
75 105 my $result = $self->server->handle($data, $context);
76 105 warn "-- MCP Response\n@{[dumper($result)]}\n" if DEBUG && $result;
77 105 return $result;
78 }
79  
80 ▶sub _handle_delete ($self, $c) {
Subroutine _handle_delete: called CC=4 SCAR=13.9
81 13 ▶ return $c->render(json => {error => 'Missing session ID'}, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless my $session_id = $self->_extract_session_id($c) 1 12 13
82 unless my $session_id = $self->_extract_session_id($c);
83 return $c->render(json => {error => 'Session not found'}, status => 404)
84 12 ▶ unless my $session = delete $self->sessions->{$session_id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $session = delete $self->sessions->{$session_id} 2 10 12
85  
86 10 ▶ if (my $stream = $session->stream) { $stream->finish }
Branch: 1 branch
BranchTrueFalseTotal
if (my $stream = $session->stream) 6 4 10
87 10 $c->render(data => '', status => 204);
88 }
89  
90 ▶sub _handle_get ($self, $c) {
Subroutine _handle_get: called CC=5 SCAR=16.1
91 12 ▶ return $c->render(json => {error => 'Missing session ID'}, status => 400)
Branch: 1 branch
BranchTrueFalseTotal
unless my $session_id = $self->_extract_session_id($c) 1 11 12
92 unless my $session_id = $self->_extract_session_id($c);
93 return $c->render(json => {error => 'Session not found'}, status => 404)
94 11 ▶ unless my $session = $self->sessions->{$session_id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $session = $self->sessions->{$session_id} 3 8 11
95 8 ▶ return $c->render(json => {error => 'Stream already open'}, status => 409) if $session->stream;
Branch: 1 branch
BranchTrueFalseTotal
if $session->stream 1 7 8
96  
97 7 $c->inactivity_timeout(0);
98 7 $c->res->headers->header('Mcp-Session-Id' => $session_id);
99 7 $session->stream($c)->touch;
100 7 $c->write_sse;
101  
102 7 my $heartbeat_id;
103 7 ▶ if (my $interval = $self->heartbeat) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $interval = $self->heartbeat) 1 6 7
104 1 ▶ $heartbeat_id = Mojo::IOLoop->recurring($interval => sub { $c->write_sse({comment => 'keepalive'}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
105 }
106  
107 7 weaken(my $self_weak = $self);
108 $c->on(
109 finish => sub {
110 7 ▶ Mojo::IOLoop->remove($heartbeat_id) if $heartbeat_id;
Subroutine __ANON__: called CC=6 SCAR=18.4
Branch: 1 branch
BranchTrueFalseTotal
if $heartbeat_id 1 6 7
111 7 ▶ return unless $self_weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $self_weak 0 7 7
112 7 ▶ return unless my $session = $self_weak->sessions->{$session_id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $session = $self_weak->sessions->{$session_id} 6 1 7
113 1 ▶ return unless ($session->stream // 0) == $c;
Branch: 1 branch
BranchTrueFalseTotal
unless ($session->stream // 0) == $c 0 1 1
Condition50%1/2
$session->stream // 0
l!l
10
MC/DC0%0/1
$session->stream // 0
$session->stream
Truth table50%1/2
A
A= $session->stream
Aresult
11
00
114 1 $session->stream(undef)->touch;
115 }
116 7 );
117 }
118  
119 ▶sub _handle_initialization ($self, $c, $data) {
Subroutine _handle_initialization: called CC=2 SCAR=6.9
120 18 my $session_id = random_v4uuid;
121 18 my $result = $self->_handle($data, MCP::Server::Context->new(scopes => $self->_scopes($c)));
122 18 ▶ if ($self->streaming) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->streaming) 11 7 18
123 11 $self->sessions->{$session_id} = MCP::Server::Session->new(id => $session_id);
124 11 $self->_start_sweep;
125 }
126 18 $c->res->headers->header('Mcp-Session-Id' => $session_id);
127 18 $c->render(json => $result, status => 200);
128 }
129  
130 ▶sub _handle_post ($self, $c) {
Subroutine _handle_post: called CC=5 SCAR=16.5
131 107 my $session_id = $self->_extract_session_id($c);
132  
133 107 ▶ return $c->render(json => {error => 'Invalid JSON'}, status => 400) unless my $data = $c->req->json;
Branch: 1 branch
BranchTrueFalseTotal
unless my $data = $c->req->json 0 107 107
134 107 ▶ return $c->render(json => {error => 'Invalid JSON', status => 400}) unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 107 107
135  
136 107 ▶ if ($data->{method} && $data->{method} eq 'initialize') { $self->_handle_initialization($c, $data) }
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{'method'} and $data->{'method'} eq 'initialize') { } 18 89 107
Condition66%2/3
$data->{"method"} and $data->{"method"} eq "initialize"
!ll&&!rl&&r
08918
MC/DC50%1/2
$data->{"method"} and $data->{"method"} eq "initialize"
$data->{"method"} $data->{"method"} eq "initialize"
Truth table66%2/3
A and B
A= $data->{"method"}B= $data->{"method"} eq "initialize"
ABresult
0X0
100
111
137 89 else { $self->_handle_regular_request($c, $data, $session_id) }
138 }
139  
140 ▶sub _handle_regular_request ($self, $c, $data, $session_id) {
Subroutine _handle_regular_request: called CC=8 SCAR=20.8
141 89 ▶ return $c->render(json => {error => 'Missing session ID'}, status => 400) unless $session_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $session_id 0 89 89
142 89 ▶ if ($self->streaming) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->streaming) 18 71 89
143 return $c->render(json => {error => 'Session not found'}, status => 404)
144 18 ▶ unless my $session = $self->sessions->{$session_id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $session = $self->sessions->{$session_id} 2 16 18
145 16 $session->touch;
146 }
147  
148 87 $c->res->headers->header('Mcp-Session-Id' => $session_id);
149 87 my $context = MCP::Server::Context->new(
150 transport => $self,
151 session_id => $session_id,
152 controller => $c,
153 scopes => $self->_scopes($c)
154 );
155 87 ▶ return $c->render(data => '', status => 202) unless defined(my $result = $self->_handle($data, $context));
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $result = $self->_handle($data, $context)) 17 70 87
156  
157 # Insufficient scope
158 70 ▶ if (my $needed = $context->insufficient_scope) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $needed = $context->insufficient_scope) 4 66 70
159 4 $c->res->headers->header(
160 'WWW-Authenticate' => $self->_challenge_header(error => 'insufficient_scope', scope => join(' ', @$needed)));
161 4 return $c->render(json => $result, status => 403);
162 }
163  
164 # Sync
165 66 ▶ return $c->render(json => $result, status => 200) if !blessed($result) || !$result->isa('Mojo::Promise');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($result) and $result->isa("Mojo::Promise") 60 6 66
Condition66%2/3
builtin::blessed($result) and $result->isa("Mojo::Promise")
!ll&&!rl&&r
6006
MC/DC50%1/2
builtin::blessed($result) and $result->isa("Mojo::Promise")
builtin::blessed($result) $result->isa("Mojo::Promise")
Truth table66%2/3
A and B
A= builtin::blessed($result)B= $result->isa("Mojo::Promise")
ABresult
0X0
100
111
166  
167 # Async
168 6 $c->inactivity_timeout(0);
169 6 $c->write_sse;
170 6 ▶ $result->then(sub { $c->write_sse({text => to_json($_[0])})->finish });
Subroutine __ANON__: called CC=1 SCAR=0.0
171 }
172  
173 ▶sub _start_sweep ($self) {
Subroutine _start_sweep: called CC=3 SCAR=11.2
174 11 ▶ return if $self->{_sweep_id};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_sweep_id"} 10 1 11
175 1 ▶ return unless my $interval = $self->session_timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless my $interval = $self->session_timeout 0 1 1
176 1 weaken(my $self_weak = $self);
177 1 ▶ $self->{_sweep_id} = Mojo::IOLoop->recurring($interval => sub { $self_weak->_sweep if $self_weak });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $self_weak 7 0 7
178 }
179  
180 ▶sub _sweep ($self) {
Subroutine _sweep: called CC=5 SCAR=16.1
181 7 ▶ return unless my $timeout = $self->session_timeout;
Branch: 1 branch
BranchTrueFalseTotal
unless my $timeout = $self->session_timeout 0 7 7
182 7 my $cutoff = time - $timeout;
183 7 my $sessions = $self->sessions;
184 7 for my $id (keys %$sessions) {
185 9 my $session = $sessions->{$id};
186 9 ▶ delete $sessions->{$id} if !$session->stream && $session->last_used < $cutoff;
Branch: 1 branch
BranchTrueFalseTotal
if not $session->stream and $session->last_used < $cutoff 1 8 9
Condition100%3/3
not $session->stream and $session->last_used < $cutoff
!ll&&!rl&&r
621
MC/DC100%2/2
not $session->stream and $session->last_used < $cutoff
not $session->stream $session->last_used < $cutoff
Truth table100%3/3
not(A) and B
A= not $session->streamB= $session->last_used < $cutoff
ABresult
0X0
100
111
187 }
188 }
189  
190 4 1;
191  
192 =encoding utf8
193  
194 =head1 NAME
195  
196 MCP::Server::Transport::HTTP - HTTP transport for MCP servers
197  
198 =head1 SYNOPSIS
199  
200 use MCP::Server::Transport::HTTP;
201  
202 my $http = MCP::Server::Transport::HTTP->new;
203  
204 =head1 DESCRIPTION
205  
206 L<MCP::Server::Transport::HTTP> is a transport for MCP (Model Context Protocol) server that uses HTTP as the
207 underlying transport mechanism.
208  
209 By default only C<POST> requests are handled. When L</"streaming"> is enabled, the transport additionally supports
210 the server-to-client SSE stream (C<GET>) and explicit session termination (C<DELETE>) defined by the Streamable
211 HTTP transport. Note that this requires per-process state and is therefore not compatible with pre-forking web
212 servers.
213  
214 =head1 ATTRIBUTES
215  
216 L<MCP::Server::Transport::HTTP> inherits all attributes from L<MCP::Server::Transport> and implements the following
217 new ones.
218  
219 =head2 auth
220  
221 my $cb = $http->auth;
222 $http = $http->auth(sub ($c) {...});
223  
224 Optional callback to authenticate each request before it is dispatched. It receives the L<Mojolicious::Controller>
225 and returns a hash reference of authentication info on success, or a false value to reject the request with a
226 C<401> C<WWW-Authenticate> challenge. The C<scopes> key of the returned hash reference is made available to handlers
227 as L<MCP::Server::Context/"scopes">. Token validation is left to the application, so this is where you verify an
228 OAuth 2.0 access token; when not set, requests are not authenticated.
229  
230 =head2 heartbeat
231  
232 my $seconds = $http->heartbeat;
233 $http = $http->heartbeat(30);
234  
235 Interval in seconds at which a keep-alive comment is sent on each open server-to-client stream. Defaults to C<30>;
236 set to C<0> to disable. Useful when running behind reverse proxies that close idle connections. Only used when
237 L</"streaming"> is enabled.
238  
239 =head2 metadata_url
240  
241 my $url = $http->metadata_url;
242 $http = $http->metadata_url('https://example.com/.well-known/oauth-protected-resource');
243  
244 URL of the OAuth 2.0 Protected Resource Metadata document. When set, it is included as the C<resource_metadata>
245 parameter of the C<WWW-Authenticate> challenge sent with C<401> and C<403> responses, so clients can discover the
246 authorization server. See L<MCP::Server/"oauth_metadata">.
247  
248 =head2 session_timeout
249  
250 my $seconds = $http->session_timeout;
251 $http = $http->session_timeout(3600);
252  
253 Idle timeout in seconds for sessions without an open server-to-client stream. Defaults to C<3600>; set to C<0> to
254 disable. A periodic sweep removes sessions whose last activity is older than this value, so the effective lifetime
255 of an idle session is up to twice the configured timeout. Only used when L</"streaming"> is enabled.
256  
257 =head2 sessions
258  
259 my $sessions = $http->sessions;
260 $http = $http->sessions({});
261  
262 Per-process registry of active L<MCP::Server::Session> objects, keyed by session ID. Only used when L</"streaming">
263 is enabled.
264  
265 =head2 streaming
266  
267 my $bool = $http->streaming;
268 $http = $http->streaming(1);
269  
270 Enable server-to-client streaming and session lifecycle management. Defaults to false. When enabled, the transport
271 tracks all sessions in L</"sessions">, accepts C<GET> requests to open a long-lived SSE stream the server can push
272 notifications to, and accepts C<DELETE> requests to terminate a session. Requests for unknown sessions are rejected
273 with status C<404>.
274  
275 =head1 METHODS
276  
277 L<MCP::Server::Transport::HTTP> inherits all methods from L<MCP::Server::Transport> and implements the following new
278 ones.
279  
280 =head2 handle_request
281  
282 $http->handle_request(Mojolicious::Controller->new);
283  
284 Handles an incoming HTTP request.
285  
286 =head2 notifications
287  
288 my $bool = $http->notifications;
289  
290 True when L</"streaming"> is enabled, false otherwise.
291  
292 =head2 notify
293  
294 my $bool = $http->notify($session_id, $method);
295 my $bool = $http->notify($session_id, $method, {foo => 'bar'});
296  
297 Send a JSON-RPC notification to the open SSE stream of a session. Returns true on success, or C<undef> if the
298 session does not exist or has no open stream. Only available when L</"streaming"> is enabled.
299  
300 =head2 notify_all
301  
302 my $bool = $http->notify_all($method);
303 my $bool = $http->notify_all($method, {foo => 'bar'});
304  
305 Send a JSON-RPC notification to the open SSE stream of every active session. Returns true on success, or C<undef>
306 when L</"streaming"> is disabled.
307  
308 =head1 SEE ALSO
309  
310 L<MCP>, L<https://mojolicious.org>, L<https://modelcontextprotocol.io>.
311  
312 =cut
« MCP/Tool.pm ↑ Summary MCP/Server/Context.pm »