MCP/Server/Transport/HTTP.pm

filter: Statementstmt 100% 172 / 172 Branchbran 91.1% 93 / 102 Conditioncond 69.7% 30 / 43 MC/DCmcdc 47.8% 11 / 23 Subroutinesub 100% 41 / 41 Podpod 100% 3 / 3 totaltotal 91.1% 350 / 384 CC 75 SCAR 18.4
CC
75
Cov
93%
_check_headers
15.2
_handle_request
12.0
_check_params
9.1
CRAP 6.3
« MCP/Server/Legacy.pm ↑ Summary MCP/Client.pm »
1 package MCP::Server::Transport::HTTP;
2 10 ▶use Mojo::Base 'MCP::Server::Transport', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 10 ▶use Crypt::Misc qw(random_v4uuid);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use MCP::Constants qw(HEADER_MISMATCH META_PROTOCOL_VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use MCP::Server::Context;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use MCP::Server::Legacy qw(legacy_request);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use MCP::Server::Subscription;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Mojo::JSON qw(to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use Mojo::Util qw(b64_decode decode dumper);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use Scalar::Util qw(blessed looks_like_number weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 10 ▶use constant DEBUG => $ENV{MCP_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MCP_DEBUG'} || 0
l!l
010
MC/DC0%0/1
$ENV{'MCP_DEBUG'} || 0
$ENV{'MCP_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MCP_DEBUG'}
Aresult
11
00
16  
17 10 ▶use constant NAMES => {'prompts/get' => 'name', 'resources/read' => 'uri', 'tools/call' => 'name'};
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 10 has 'auth';
20 10 has heartbeat => 30;
21 10 has 'metadata_url';
22 10 has 'origins';
23 10 has streaming => 0;
24 1 ▶has subscriptions => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
25  
26 156 ▶sub handle_request ($self, $c) {
Subroutine handle_request: called CC=6 SCAR=17.9
Pod documented
27 156 my $server = $self->server;
28 156 ▶ $server->log($c->app->log) unless $server->{log};
Branch: 1 branch
BranchTrueFalseTotal
unless $server->{"log"} 12 144 156
29  
30 156 ▶ return $c->render(json => {error => 'Origin not allowed'}, status => 403) unless $self->_check_origin($c);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_origin($c) 1 155 156
31  
32 155 ▶ if (my $auth = $self->auth) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $auth = $self->auth) 31 124 155
33 31 ▶ return $self->_unauthorized($c) unless my $info = $auth->($c);
Branch: 1 branch
BranchTrueFalseTotal
unless my $info = &$auth($c) 2 29 31
34 29 $c->stash('mcp.auth' => $info);
35 }
36  
37 153 ▶ return $self->_handle_post($c) if $c->req->method eq 'POST';
Branch: 1 branch
BranchTrueFalseTotal
if $c->req->method eq "POST" 149 4 153
38 4 return $c->render(json => {error => 'Method not allowed'}, status => 405);
39 }
40  
41 6 ▶sub notifications ($self) { $self->streaming ? 1 : 0 }
Subroutine notifications: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->streaming ? : 3 3 6
42  
43 5 ▶sub notify_all ($self, $method, $params = {}) {
Subroutine notify_all: called CC=5 SCAR=16.1
Pod documented
44 5 ▶ return undef unless $self->streaming;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->streaming 2 3 5
45 3 for my $subscription (values %{$self->subscriptions}) {
46 2 ▶ next unless $subscription->wants($method);
Branch: 1 branch
BranchTrueFalseTotal
unless $subscription->wants($method) 1 1 2
47 1 _write($subscription->stream, $subscription->notification($method, $params));
48 }
49 3 return 1;
50 }
51  
52 38 ▶sub _arg_value ($args, $path) {
Subroutine _arg_value: called CC=3 SCAR=11.0
53 38 my $value = $args;
54 38 for my $key (@$path) {
55 48 ▶ return undef unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 6 42 48
56 42 $value = $value->{$key};
57 }
58 32 return $value;
59 }
60  
61 6 ▶sub _challenge_header ($self, %extra) {
Subroutine _challenge_header: called CC=5 SCAR=16.2
62 6 my @parts;
63 6 ▶ push @parts, qq{resource_metadata="@{[$self->metadata_url]}"} if $self->metadata_url;
Branch: 1 branch
BranchTrueFalseTotal
if $self->metadata_url 6 0 6
64 6 ▶ push @parts, qq{error="$extra{error}"} if $extra{error};
Branch: 1 branch
BranchTrueFalseTotal
if $extra{"error"} 4 2 6
65 6 ▶ push @parts, qq{scope="$extra{scope}"} if defined $extra{scope};
Branch: 1 branch
BranchTrueFalseTotal
if defined $extra{"scope"} 4 2 6
66 6 ▶ return 'Bearer' . (@parts ? ' ' . join(', ', @parts) : '');
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 6 0 6
67 }
68  
69 130 ▶sub _check_headers ($self, $c, $data) {
Subroutine _check_headers: called CC=15 SCAR=27.2
70 130 my $headers = $c->req->headers;
71 130 ▶ my $params = $data->{params} // {};
Condition50%1/2
$data->{"params"} // {}
l!l
1300
MC/DC0%0/1
$data->{"params"} // {}
$data->{"params"}
Truth table50%1/2
A
A= $data->{"params"}
Aresult
11
00
72  
73 130 my $version = $headers->header('MCP-Protocol-Version');
74 130 ▶ return 'Missing MCP-Protocol-Version header' unless defined $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version 1 129 130
75 129 ▶ my $expected = ($params->{_meta} // {})->{+META_PROTOCOL_VERSION};
Condition50%1/2
$params->{"_meta"} // {}
l!l
1290
MC/DC0%0/1
$params->{"_meta"} // {}
$params->{"_meta"}
Truth table50%1/2
A
A= $params->{"_meta"}
Aresult
11
00
76 129 ▶ return 'MCP-Protocol-Version header does not match the request body' if defined $expected && $expected ne $version;
Branch: 1 branch
BranchTrueFalseTotal
if defined $expected and $expected ne $version 2 127 129
Condition100%3/3
defined $expected and $expected ne $version
!ll&&!rl&&r
11262
MC/DC100%2/2
defined $expected and $expected ne $version
defined $expected $expected ne $version
Truth table100%3/3
A and B
A= defined $expectedB= $expected ne $version
ABresult
0X0
100
111
77  
78 127 ▶ my $method = $data->{method} // '';
Condition50%1/2
$data->{"method"} // ""
l!l
1270
MC/DC0%0/1
$data->{"method"} // ""
$data->{"method"}
Truth table50%1/2
A
A= $data->{"method"}
Aresult
11
00
79 127 my $sent = $headers->header('Mcp-Method');
80 127 ▶ return 'Missing Mcp-Method header' unless defined $sent;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sent 2 125 127
81 125 ▶ return 'Mcp-Method header does not match the request body' unless $sent eq $method;
Branch: 1 branch
BranchTrueFalseTotal
unless $sent eq $method 2 123 125
82  
83 123 ▶ if (my $key = NAMES->{$method}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $key = {"prompts/get" => "name","resources/read" => "uri","tools/call" => "name"}->{$method}) 93 30 123
84 93 my $name = $headers->header('Mcp-Name');
85 93 ▶ return 'Missing Mcp-Name header' unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 1 92 93
86 92 ▶ return 'Invalid Mcp-Name header' unless defined($name = _decode_header($name));
Branch: 1 branch
BranchTrueFalseTotal
unless defined($name = _decode_header($name)) 1 91 92
87 91 ▶ return 'Mcp-Name header does not match the request body' unless $name eq ($params->{$key} // '');
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq ($params->{$key} // "") 2 89 91
Condition50%1/2
$params->{$key} // ""
l!l
910
MC/DC0%0/1
$params->{$key} // ""
$params->{$key}
Truth table50%1/2
A
A= $params->{$key}
Aresult
11
00
88 }
89  
90 119 ▶ return $method eq 'tools/call' ? $self->_check_params($c, $params) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'tools/call' ? : 58 61 119
91 }
92  
93 156 ▶sub _check_origin ($self, $c) {
Subroutine _check_origin: called CC=5 SCAR=17.5
94 156 ▶ return 1 unless defined(my $origin = $c->req->headers->origin);
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $origin = $c->req->headers->origin) 154 2 156
95 2 ▶ return 1 unless my $origins = $self->origins;
Branch: 1 branch
BranchTrueFalseTotal
unless my $origins = $self->origins 0 2 2
96 2 ▶ return $origins->($c, $origin) ? 1 : 0 if ref $origins eq 'CODE';
Branch: 2 branches
BranchTrueFalseTotal
if ref $origins eq "CODE" 0 2 2
&$origins($c, $origin) ? : 0 0 0
97 2 ▶ return first { $_ eq $origin } @$origins;
Subroutine __ANON__: called CC=1 SCAR=0.0
98 }
99  
100 58 ▶sub _check_params ($self, $c, $params) {
Subroutine _check_params: called CC=9 SCAR=22.0
101 58 ▶ return undef unless my $tool = first { $_->name eq ($params->{name} // '') } @{$self->server->tools};
Subroutine __ANON__: called CC=2 SCAR=7.0
Branch: 1 branch
BranchTrueFalseTotal
unless my $tool = &first(sub { $_->name eq ($params->{"name"} // ""); } , @{$self->server->tools;}) 2 56 58
Condition50%1/2
$params->{"name"} // ""
l!l
1310
MC/DC0%0/1
$params->{"name"} // ""
$params->{"name"}
Truth table50%1/2
A
A= $params->{"name"}
Aresult
11
00
102 56 ▶ my $args = $params->{arguments} // {};
Condition50%1/2
$params->{"arguments"} // {}
l!l
560
MC/DC0%0/1
$params->{"arguments"} // {}
$params->{"arguments"}
Truth table50%1/2
A
A= $params->{"arguments"}
Aresult
11
00
103 56 my $headers = $c->req->headers;
104  
105 56 for my $param (@{$tool->header_params}) {
106 38 my $name = "Mcp-Param-$param->{name}";
107 38 my $value = _arg_value($args, $param->{path});
108 38 my $header = $headers->header($name);
109  
110 38 ▶ if (!defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 26 12 38
111 26 ▶ return "Unexpected $name header" if defined $header;
Branch: 1 branch
BranchTrueFalseTotal
if defined $header 2 24 26
112 24 next;
113 }
114 12 ▶ return "Missing $name header" unless defined $header;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header 1 11 12
115 11 ▶ return "Invalid $name header" unless defined($header = _decode_header($header));
Branch: 1 branch
BranchTrueFalseTotal
unless defined($header = _decode_header($header)) 0 11 11
116 11 ▶ return "$name header does not match the request body" unless _match_value($param->{type}, $header, $value);
Branch: 1 branch
BranchTrueFalseTotal
unless _match_value($param->{"type"}, $header, $value) 1 10 11
117 }
118  
119 52 return undef;
120 }
121  
122 103 ▶sub _decode_header ($value) {
Subroutine _decode_header: called CC=3 SCAR=11.0
123 103 ▶ return decode('UTF-8', b64_decode($1)) if $value =~ /^=\?base64\?(.*)\?=$/s;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /^=\?base64\?(.*)\?=$/su 3 100 103
124 100 ▶ return $value =~ /^[\t\x20-\x7e]*\z/ ? $value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /^[\t\x20-\x7e]*\z/u ? : 99 1 100
125 }
126  
127 11 ▶sub _finish ($c, $context, $response) {
Subroutine _finish: called CC=2 SCAR=6.9
128 11 ▶ return undef if $context->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $context->is_cancelled 1 10 11
129 10 $context->stream(undef);
130 10 return _write($c, $response)->finish;
131 }
132  
133 133 ▶sub _handle ($self, $data, $context) {
Subroutine _handle: called CC=1 SCAR=0.0
134 133 warn "-- MCP Request\n@{[dumper($data)]}\n" if DEBUG;
135 133 my $result = $self->server->handle($data, $context);
136 133 warn "-- MCP Response\n@{[dumper($result)]}\n" if DEBUG && $result;
137 133 return $result;
138 }
139  
140 149 ▶sub _handle_post ($self, $c) {
Subroutine _handle_post: called CC=5 SCAR=16.1
141 149 my $data = $c->req->json;
142 149 ▶ return $c->render(json => {error => 'Invalid JSON'}, status => 400) unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 1 148 149
143  
144 # Legacy
145 148 my $legacy = legacy_request($c->req->headers->header('MCP-Protocol-Version'), $data);
146  
147 148 ▶ if (!$legacy && defined(my $id = $data->{id})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $legacy and defined(my $id = $data->{"id"})) 130 18 148
Condition66%2/3
not $legacy and defined(my $id = $data->{"id"})
!ll&&!rl&&r
180130
MC/DC50%1/2
not $legacy and defined(my $id = $data->{"id"})
not $legacy defined(my $id = $data->{"id"})
Truth table66%2/3
not(A) and B
A= not $legacyB= defined(my $id = $data->{"id"})
ABresult
0X0
100
111
148 130 ▶ if (my $message = $self->_check_headers($c, $data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $message = $self->_check_headers($c, $data)) 15 115 130
149 15 my $error = {code => HEADER_MISMATCH, message => $message};
150 15 return $c->render(json => {jsonrpc => '2.0', id => $id, error => $error}, status => 400);
151 }
152 }
153  
154 133 return $self->_handle_request($c, $data, $legacy);
155 }
156  
157 133 ▶sub _handle_request ($self, $c, $data, $legacy = undef) {
Subroutine _handle_request: called CC=12 SCAR=24.9
158 133 ▶ my $info = $c->stash('mcp.auth') // {};
Condition100%2/2
$c->stash("mcp.auth") // {}
l!l
29104
MC/DC100%1/1
$c->stash("mcp.auth") // {}
$c->stash("mcp.auth")
Truth table100%2/2
A
A= $c->stash("mcp.auth")
Aresult
11
00
159 my $context = MCP::Server::Context->new(
160 controller => $c,
161 legacy => $legacy,
162 principal => $info->{principal},
163 133 scopes => $self->_scopes($c),
164 transport => $self
165 );
166 133 ▶ 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)) 2 131 133
167  
168 # Subscription
169 131 ▶ return $self->_handle_subscription($c, $result) if blessed($result) && $result->isa('MCP::Server::Subscription');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($result) and $result->isa("MCP::Server::Subscription") 2 129 131
Condition100%3/3
builtin::blessed($result) and $result->isa("MCP::Server::Subscription")
!ll&&!rl&&r
12092
MC/DC100%2/2
builtin::blessed($result) and $result->isa("MCP::Server::Subscription")
builtin::blessed($result) $result->isa("MCP::Server::Subscription")
Truth table100%3/3
A and B
A= builtin::blessed($result)B= $result->isa("MCP::Server::Subscription")
ABresult
0X0
100
111
170  
171 # Async
172 129 ▶ if (blessed($result) && $result->isa('Mojo::Promise')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->isa("Mojo::Promise")) 9 120 129
Condition66%2/3
builtin::blessed($result) and $result->isa("Mojo::Promise")
!ll&&!rl&&r
12009
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
173 9 _stream($c, $context);
174 9 ▶ return $result->then(sub { _finish($c, $context, $_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
175 }
176  
177 # Insufficient scope
178 120 ▶ if (my $needed = $context->insufficient_scope) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $needed = $context->insufficient_scope) 4 116 120
179 4 $c->res->headers->header(
180 'WWW-Authenticate' => $self->_challenge_header(error => 'insufficient_scope', scope => join(' ', @$needed)));
181 }
182  
183 # Sync
184 120 ▶ my $status = $context->status // 200;
Condition100%2/2
$context->status // 200
l!l
18102
MC/DC100%1/1
$context->status // 200
$context->status
Truth table100%2/2
A
A= $context->status
Aresult
11
00
185 120 ▶ return $c->render(json => $result, status => $status) if $status != 200 || !@{$context->buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $status != 200 or not @{$context->buffer;} 118 2 120
Condition100%3/3
$status != 200 or not @{$context->buffer;}
l!l&&r!l&&!r
181002
MC/DC100%2/2
$status != 200 or not @{$context->buffer;}
$status != 200 not @{$context->buffer;}
Truth table100%3/3
A or not(B)
A= $status != 200B= not @{$context->buffer;}
ABresult
1X1
011
000
186 2 _stream($c, $context);
187 2 return _finish($c, $context, $result);
188 }
189  
190 2 ▶sub _handle_subscription ($self, $c, $subscription) {
Subroutine _handle_subscription: called CC=2 SCAR=6.9
191 2 my $id = random_v4uuid;
192 2 $self->subscriptions->{$id} = $subscription->stream($c);
193 2 _write(_open_stream($c), $subscription->acknowledgement);
194  
195 2 my $heartbeat_id;
196 2 ▶ if (my $interval = $self->heartbeat) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $interval = $self->heartbeat) 1 1 2
197 1 ▶ $heartbeat_id = Mojo::IOLoop->recurring($interval => sub { $c->write_sse({comment => 'keepalive'}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
198 }
199  
200 2 weaken(my $self_weak = $self);
201 return $c->on(
202 2 ▶ finish => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
203 2 ▶ Mojo::IOLoop->remove($heartbeat_id) if $heartbeat_id;
Branch: 1 branch
BranchTrueFalseTotal
if $heartbeat_id 1 1 2
204 2 ▶ delete $self_weak->subscriptions->{$id} if $self_weak;
Branch: 1 branch
BranchTrueFalseTotal
if $self_weak 2 0 2
205 }
206 2 );
207 }
208  
209 11 ▶sub _match_value ($type, $header, $value) {
Subroutine _match_value: called CC=6 SCAR=19.0
210 11 ▶ return looks_like_number($header) && looks_like_number($value) && $header == $value if $type eq 'integer';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "integer" 3 8 11
Condition50%3/6
&looks_like_number($header) && &looks_like_number($value) && $header == $value
!ll&&!rl&&r
012
&looks_like_number($header) and &looks_like_number($value)
!ll&&!rl&&r
003
MC/DC33%1/3
&looks_like_number($header) && &looks_like_number($value) && $header == $value
&looks_like_number($header) &looks_like_number($value) $header == $value
Truth table50%2/4
A and B && C
A= &looks_like_number($header)B= &looks_like_number($value)C= $header == $value
ABCresult
0XX0
10X0
1100
1111
211 8 ▶ return $header eq ($value ? 'true' : 'false') if $type eq 'boolean';
Branch: 2 branches
BranchTrueFalseTotal
if $type eq "boolean" 2 6 8
$value ? : 2 0 2
212 6 return $header eq "$value";
213 }
214  
215 13 ▶sub _open_stream ($c) {
Subroutine _open_stream: called CC=1 SCAR=0.0
216 13 $c->inactivity_timeout(0);
217 13 $c->res->headers->header('X-Accel-Buffering' => 'no');
218 13 return $c->write_sse;
219 }
220  
221 133 ▶sub _scopes ($self, $c) {
Subroutine _scopes: called CC=4 SCAR=13.9
222 133 ▶ return undef unless $self->auth;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->auth 104 29 133
223 29 ▶ return ($c->stash('mcp.auth') // {})->{scopes} // [];
Condition75%3/4
+($c->stash("mcp.auth") // {})->{"scopes"} // []
l!l
1910
$c->stash("mcp.auth") // {}
l!l
290
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
224 }
225  
226 11 ▶sub _stream ($c, $context) {
Subroutine _stream: called CC=1 SCAR=0.0
227 11 _open_stream($c);
228 11 ▶ $c->on(finish => sub { $context->stream(undef)->cancel if $context->stream });
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $context->stream 1 10 11
229 4 ▶ return $context->stream(sub ($notification) {
Subroutine __ANON__: called CC=1 SCAR=0.0
230 4 _write($c, $notification);
231 11 })->flush;
232 }
233  
234 2 ▶sub _unauthorized ($self, $c) {
Subroutine _unauthorized: called CC=1 SCAR=0.0
235 2 $c->res->headers->header('WWW-Authenticate' => $self->_challenge_header);
236 2 return $c->render(json => {error => 'Unauthorized'}, status => 401);
237 }
238  
239 17 ▶sub _write ($c, $message) { return $c->write_sse({text => to_json($message)}) }
Subroutine _write: called CC=1 SCAR=0.0
240  
241 10 1;
242  
243 =encoding utf8
244  
245 =head1 NAME
246  
247 MCP::Server::Transport::HTTP - HTTP transport for MCP servers
248  
249 =head1 SYNOPSIS
250  
251 use MCP::Server::Transport::HTTP;
252  
253 my $http = MCP::Server::Transport::HTTP->new;
254  
255 =head1 DESCRIPTION
256  
257 L<MCP::Server::Transport::HTTP> is a transport for MCP (Model Context Protocol) server that uses HTTP as the
258 underlying transport mechanism.
259  
260 Only C<POST> requests are handled; C<GET> and C<DELETE> are answered with status C<405>. The protocol is stateless,
261 so nothing is remembered between requests and the transport can be deployed behind a load balancer and a pre-forking
262 web server. Notifications that belong to a request, such as progress reports, are delivered on the response stream
263 of that very request, which is upgraded from C<application/json> to C<text/event-stream> whenever there is something
264 to deliver.
265  
266 The one exception is L</"streaming">, which opts in to C<subscriptions/listen>. Long-lived notification streams
267 require per-process state and are therefore not compatible with pre-forking web servers.
268  
269 Routing headers are validated against the JSON-RPC body before a request is dispatched, so a gateway that routes on
270 C<Mcp-Method>, C<Mcp-Name>, or C<Mcp-Param-*> alone can never disagree with the server about what was called.
271  
272 =head1 ATTRIBUTES
273  
274 L<MCP::Server::Transport::HTTP> inherits all attributes from L<MCP::Server::Transport> and implements the following
275 new ones.
276  
277 =head2 auth
278  
279 my $cb = $http->auth;
280 $http = $http->auth(sub ($c) {...});
281  
282 Optional callback to authenticate each request before it is dispatched. It receives the L<Mojolicious::Controller>
283 and returns a hash reference of authentication info on success, or a false value to reject the request with a
284 C<401> C<WWW-Authenticate> challenge. The C<scopes> and C<principal> keys of the returned hash reference are made
285 available to handlers as L<MCP::Server::Context/"scopes"> and L<MCP::Server::Context/"principal">. Token validation
286 is left to the application, so this is where you verify an OAuth 2.0 access token; when not set, requests are not
287 authenticated.
288  
289 =head2 heartbeat
290  
291 my $seconds = $http->heartbeat;
292 $http = $http->heartbeat(30);
293  
294 Interval in seconds at which a keep-alive comment is sent on each open subscription stream. Defaults to C<30>; set
295 to C<0> to disable. Useful when running behind reverse proxies that close idle connections. Only used when
296 L</"streaming"> is enabled.
297  
298 =head2 metadata_url
299  
300 my $url = $http->metadata_url;
301 $http = $http->metadata_url('https://example.com/.well-known/oauth-protected-resource');
302  
303 URL of the OAuth 2.0 Protected Resource Metadata document. When set, it is included as the C<resource_metadata>
304 parameter of the C<WWW-Authenticate> challenge sent with C<401> and C<403> responses, so clients can discover the
305 authorization server. Use an absolute URL so remote clients can fetch it. See L<MCP::Server/"oauth_metadata">.
306  
307 =head2 origins
308  
309 my $origins = $http->origins;
310 $http = $http->origins(['https://example.com']);
311 $http = $http->origins(sub ($c, $origin) {...});
312  
313 Origins allowed to make browser requests, as an array reference of exact matches or a callback returning true for
314 an acceptable origin. Requests carrying an C<Origin> header that is not allowed are rejected with status C<403>,
315 which protects against DNS rebinding attacks on servers bound to localhost. Defaults to C<undef>, which accepts
316 every origin.
317  
318 =head2 streaming
319  
320 my $bool = $http->streaming;
321 $http = $http->streaming(1);
322  
323 Enable C<subscriptions/listen>, so clients can open a long-lived stream for the C<list_changed> notifications they
324 ask for. Defaults to false. When enabled, the transport tracks every open stream in L</"subscriptions"> and
325 advertises the C<listChanged> capabilities in C<server/discover>. Progress and log notifications do not depend on
326 this, since they are delivered on the response stream of the request they belong to.
327  
328 =head2 subscriptions
329  
330 my $subscriptions = $http->subscriptions;
331 $http = $http->subscriptions({});
332  
333 Per-process registry of active L<MCP::Server::Subscription> objects. Only used when L</"streaming"> is enabled.
334  
335 =head1 METHODS
336  
337 L<MCP::Server::Transport::HTTP> inherits all methods from L<MCP::Server::Transport> and implements the following new
338 ones.
339  
340 =head2 handle_request
341  
342 $http->handle_request(Mojolicious::Controller->new);
343  
344 Handles an incoming HTTP request.
345  
346 =head2 notifications
347  
348 my $bool = $http->notifications;
349  
350 True when L</"streaming"> is enabled, false otherwise.
351  
352 =head2 notify_all
353  
354 my $bool = $http->notify_all($method);
355 my $bool = $http->notify_all($method, {foo => 'bar'});
356  
357 Send a JSON-RPC notification to every subscription that asked for it. Returns true on success, or C<undef> when
358 L</"streaming"> is disabled.
359  
360 =head1 SEE ALSO
361  
362 L<MCP>, L<https://mojolicious.org>, L<https://modelcontextprotocol.io>.
363  
364 =cut
« MCP/Server/Legacy.pm ↑ Summary MCP/Client.pm »