MCP/Server/Context.pm

filter: Statementstmt 100% 75 / 75 Branchbran 82.5% 33 / 40 Conditioncond 57.8% 11 / 19 MC/DCmcdc 20.0% 2 / 10 Subroutinesub 100% 18 / 18 Podpod 100% 9 / 9 totaltotal 86.5% 148 / 171 CC 35 SCAR 18.9
CC
35
Cov
89%
_unseal
15.4
notify_progress
6.1
notify_log
5.2
CRAP 6.6
« MCP/Server/Transport/Stdio.pm ↑ Summary MCP/Server/Legacy.pm »
1 package MCP::Server::Context;
2 12 ▶use Mojo::Base 'Mojo::EventEmitter', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 12 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 12 ▶use Crypt::Mac::HMAC qw(hmac);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 12 ▶use Crypt::Misc qw(slow_eq);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 12 ▶use Mojo::JSON qw(decode_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 12 ▶use Mojo::Util qw(b64_decode b64_encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 12 ▶use constant LEVELS =>
Subroutine BEGIN: called CC=1 SCAR=0.0
11 12 {debug => 0, info => 1, notice => 2, warning => 3, error => 4, critical => 5, alert => 6, emergency => 7};
12  
13 111 ▶has buffer => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
14 12 has [qw(client_capabilities client_info controller input_responses insufficient_scope legacy log_level principal)];
15 12 has [qw(progress_token protocol_version raw_request_state scopes state_binding state_secret)];
16 12 has state_timeout => 300;
17 12 has [qw(status stream transport)];
18  
19 1 ▶sub cancel ($self) {
Subroutine cancel: called CC=2 SCAR=7.2
Pod documented
20 1 ▶ return $self if $self->{cancelled}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cancelled"}++ 0 1 1
21 1 return $self->emit('cancelled');
22 }
23  
24 11 ▶sub flush ($self) {
Subroutine flush: called CC=3 SCAR=11.1
Pod documented
25 11 ▶ return 0 unless my $stream = $self->stream;
Branch: 1 branch
BranchTrueFalseTotal
unless my $stream = $self->stream 0 11 11
26 11 my @buffered = splice @{$self->buffer};
27 11 $stream->($_) for @buffered;
28 11 return scalar @buffered;
29 }
30  
31 130 ▶sub has_scope ($self, @needed) {
Subroutine has_scope: called CC=4 SCAR=13.9
Pod documented
32 130 ▶ return 1 unless defined(my $scopes = $self->scopes);
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $scopes = $self->scopes) 94 36 130
33 36 my %granted = map { $_ => 1 } @$scopes;
34 36 ▶ for my $scope (@needed) { return 0 unless $granted{$scope} }
Branch: 1 branch
BranchTrueFalseTotal
unless $granted{$scope} 7 19 26
35 29 return 1;
36 }
37  
38 18 ▶sub is_cancelled ($self) { $self->{cancelled} ? 1 : 0 }
Subroutine is_cancelled: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->{'cancelled'} ? : 3 15 18
39  
40 5 ▶sub notify ($self, $method, $params = {}) {
Subroutine notify: called CC=4 SCAR=13.9
Pod documented
41 5 ▶ return undef if $self->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_cancelled 1 4 5
42 4 my $notification = {jsonrpc => '2.0', method => $method, params => $params};
43 4 ▶ if (my $stream = $self->stream) { $stream->($notification) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $stream = $self->stream) { } 1 3 4
44 3 else { push @{$self->buffer}, $notification }
45 4 return 1;
46 }
47  
48 4 ▶sub notify_log ($self, $level, $data) {
Subroutine notify_log: called CC=5 SCAR=16.4
Pod documented
49 4 ▶ return undef unless defined(my $minimum = $self->log_level);
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $minimum = $self->log_level) 2 2 4
50 2 ▶ return undef unless (LEVELS->{$level} // 0) >= (LEVELS->{$minimum} // 0);
Branch: 1 branch
BranchTrueFalseTotal
unless ({"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$level} // 0) >= ({"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$minimum} // 0) 1 1 2
Condition50%2/4
{"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$level} // 0
l!l
20
{"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$minimum} // 0
l!l
20
MC/DC0%0/1
{"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$level} // 0
{"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$level}
MC/DC0%0/1
{"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$minimum} // 0
{"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$minimum}
Truth table50%1/2
A
A= {"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$level}
Aresult
11
00
Truth table50%1/2
A
A= {"alert" => 6,"critical" => 5,"debug" => 0,"emergency" => 7,"error" => 4,"info" => 1,"notice" => 2,"warning" => 3}->{$minimum}
Aresult
11
00
51 1 return $self->notify('notifications/message', {level => $level, data => $data});
52 }
53  
54 4 ▶sub notify_progress ($self, $progress, $total = undef, $message = undef) {
Subroutine notify_progress: called CC=6 SCAR=18.1
Pod documented
55 4 ▶ return undef unless defined(my $token = $self->progress_token);
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $token = $self->progress_token) 1 3 4
56 3 my $params = {progressToken => $token, progress => $progress};
57 3 ▶ $params->{total} = $total if defined $total;
Branch: 1 branch
BranchTrueFalseTotal
if defined $total 3 0 3
58 3 ▶ $params->{message} = $message if defined $message;
Branch: 1 branch
BranchTrueFalseTotal
if defined $message 3 0 3
59 3 return $self->notify('notifications/progress', $params);
60 }
61  
62 10 ▶sub request_state ($self) { return $self->{request_state} //= $self->_unseal }
Subroutine request_state: called CC=2 SCAR=7.2
Pod documented
Condition66%2/3
$self->{"request_state"} //= $self->_unseal
l!l&&r!l&&!r
037
MC/DC50%1/2
$self->{"request_state"} //= $self->_unseal
$self->{"request_state"} $self->_unseal
Truth table66%2/3
A //= B
A= $self->{"request_state"}B= $self->_unseal
ABresult
1X1
011
000
63  
64 7 ▶sub seal_state ($self, $state) {
Subroutine seal_state: called CC=2 SCAR=7.0
Pod documented
65 7 ▶ croak 'No state secret' unless my $secret = $self->state_secret;
Branch: 1 branch
BranchTrueFalseTotal
unless my $secret = $self->state_secret 0 7 7
66 7 my $data = {
67 binding => $self->state_binding,
68 expires => time + $self->state_timeout,
69 payload => $state,
70 principal => $self->principal
71 };
72 7 my $payload = b64_encode(encode_json($data), '');
73 7 return "$payload." . b64_encode(hmac('SHA256', $secret, $payload), '');
74 }
75  
76 10 ▶sub _unseal ($self) {
Subroutine _unseal: called CC=14 SCAR=27.4
77 10 ▶ return undef unless my $secret = $self->state_secret;
Branch: 1 branch
BranchTrueFalseTotal
unless my $secret = $self->state_secret 0 10 10
78 10 ▶ return undef unless ($self->raw_request_state // '') =~ /^([^.]+)\.([^.]+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->raw_request_state // "") =~ /^([^.]+)\.([^.]+)$/u 3 7 10
Condition100%2/2
$self->raw_request_state // ""
l!l
73
MC/DC100%1/1
$self->raw_request_state // ""
$self->raw_request_state
Truth table100%2/2
A
A= $self->raw_request_state
Aresult
11
00
79 7 my ($payload, $mac) = ($1, $2);
80 7 ▶ return undef unless slow_eq(b64_decode($mac), hmac('SHA256', $secret, $payload));
Branch: 1 branch
BranchTrueFalseTotal
unless slow_eq(&b64_decode($mac), hmac("SHA256", $secret, $payload)) 1 6 7
81 6 ▶ return undef unless my $data = eval { decode_json(b64_decode($payload)) };
Branch: 1 branch
BranchTrueFalseTotal
unless my $data = eval { do { decode_json(&b64_decode($payload)) } } 0 6 6
82 6 ▶ return undef unless ($data->{expires} // 0) > time;
Branch: 1 branch
BranchTrueFalseTotal
unless ($data->{"expires"} // 0) > time 1 5 6
Condition50%1/2
$data->{"expires"} // 0
l!l
60
MC/DC0%0/1
$data->{"expires"} // 0
$data->{"expires"}
Truth table50%1/2
A
A= $data->{"expires"}
Aresult
11
00
83 5 ▶ return undef unless ($data->{binding} // '') eq ($self->state_binding // '');
Branch: 1 branch
BranchTrueFalseTotal
unless ($data->{"binding"} // "") eq ($self->state_binding // "") 1 4 5
Condition50%2/4
$data->{"binding"} // ""
l!l
50
$self->state_binding // ""
l!l
50
MC/DC0%0/1
$data->{"binding"} // ""
$data->{"binding"}
MC/DC0%0/1
$self->state_binding // ""
$self->state_binding
Truth table50%1/2
A
A= $data->{"binding"}
Aresult
11
00
Truth table50%1/2
A
A= $self->state_binding
Aresult
11
00
84 4 ▶ return undef unless ($data->{principal} // '') eq ($self->principal // '');
Branch: 1 branch
BranchTrueFalseTotal
unless ($data->{"principal"} // "") eq ($self->principal // "") 1 3 4
Condition50%2/4
$data->{"principal"} // ""
l!l
40
$self->principal // ""
l!l
40
MC/DC0%0/1
$data->{"principal"} // ""
$data->{"principal"}
MC/DC0%0/1
$self->principal // ""
$self->principal
Truth table50%1/2
A
A= $data->{"principal"}
Aresult
11
00
Truth table50%1/2
A
A= $self->principal
Aresult
11
00
85 3 return $data->{payload};
86 }
87  
88 12 1;
89  
90 =encoding utf8
91  
92 =head1 NAME
93  
94 MCP::Server::Context - Request context container
95  
96 =head1 SYNOPSIS
97  
98 use MCP::Server::Context;
99  
100 my $context = MCP::Server::Context->new;
101 $context->notify_progress(1, 2, 'halfway');
102  
103 =head1 DESCRIPTION
104  
105 L<MCP::Server::Context> is a container for per-invocation request context.
106  
107 =head1 EVENTS
108  
109 L<MCP::Server::Context> inherits all events from L<Mojo::EventEmitter> and emits the following new ones.
110  
111 =head2 cancelled
112  
113 $context->on(cancelled => sub ($context) { ... });
114  
115 Emitted once when the client abandons the current request, either by closing its response stream or by sending a
116 C<notifications/cancelled> notification. Long running operations should stop as soon as practical.
117  
118 my $id = Mojo::IOLoop->recurring(1 => sub { ... });
119 $context->on(cancelled => sub ($context) { Mojo::IOLoop->remove($id) });
120  
121 =head1 ATTRIBUTES
122  
123 L<MCP::Server::Context> implements the following attributes.
124  
125 =head2 buffer
126  
127 my $buffer = $context->buffer;
128 $context = $context->buffer([]);
129  
130 Notifications that have been queued up because no response L</"stream"> was available yet, to be delivered by
131 L</"flush">.
132  
133 =head2 client_capabilities
134  
135 my $capabilities = $context->client_capabilities;
136 $context = $context->client_capabilities({elicitation => {}});
137  
138 Capabilities declared by the client for the current request, from
139 C<_meta.io.modelcontextprotocol/clientCapabilities>. Every request has to declare them, so this is only C<undef>
140 outside of request handling.
141  
142 =head2 client_info
143  
144 my $info = $context->client_info;
145 $context = $context->client_info({name => 'MyClient', version => '1.0.0'});
146  
147 Name and version of the client making the current request, from C<_meta.io.modelcontextprotocol/clientInfo>, or
148 C<undef> if the client did not identify itself.
149  
150 =head2 controller
151  
152 my $c = $context->controller;
153 $context = $context->controller(Mojolicious::Controller->new);
154  
155 The L<Mojolicious::Controller> serving the current request, when the HTTP transport is in use.
156  
157 =head2 input_responses
158  
159 my $responses = $context->input_responses;
160 $context = $context->input_responses({confirm => {action => 'accept', content => {ok => \1}}});
161  
162 Responses to the input requests of an earlier C<input_required> result, keyed by the same names, or C<undef> if the
163 current request is not a retry. See L<MCP::Primitive/"input_required">.
164  
165 =head2 insufficient_scope
166  
167 my $needed = $context->insufficient_scope;
168 $context = $context->insufficient_scope(['mcp:write']);
169  
170 Array reference of scopes a denied request was missing, set by the server so the HTTP transport can emit an
171 C<insufficient_scope> challenge. C<undef> when no scope check failed.
172  
173 =head2 legacy
174  
175 my $version = $context->legacy;
176 $context = $context->legacy('2025-11-25');
177  
178 The protocol revision a legacy request was made with, or C<undef> for a current request, see
179 L<MCP::Server::Legacy>.
180  
181 =head2 log_level
182  
183 my $level = $context->log_level;
184 $context = $context->log_level('info');
185  
186 The minimum severity of log messages the client wants for the current request, from
187 C<_meta.io.modelcontextprotocol/logLevel>, or C<undef> if the client asked for none.
188  
189 =head2 principal
190  
191 my $principal = $context->principal;
192 $context = $context->principal('user@example.com');
193  
194 The authenticated caller the current request belongs to, populated from the C<principal> key returned by the C<auth>
195 hook of the HTTP transport. Request state is bound to it, so state minted for one caller is never accepted from
196 another. C<undef> for unauthenticated requests.
197  
198 =head2 progress_token
199  
200 my $token = $context->progress_token;
201 $context = $context->progress_token('tok-1');
202  
203 The progress token provided by the client in C<_meta.progressToken>, or C<undef> if none was sent.
204  
205 =head2 protocol_version
206  
207 my $version = $context->protocol_version;
208 $context = $context->protocol_version('2026-07-28');
209  
210 The protocol version the current request was made with, from C<_meta.io.modelcontextprotocol/protocolVersion>.
211  
212 =head2 raw_request_state
213  
214 my $state = $context->raw_request_state;
215 $context = $context->raw_request_state('eyJ...');
216  
217 The C<requestState> string the client sent back, exactly as received and not verified in any way. Use
218 L</"request_state"> instead, unless you want to protect the state yourself.
219  
220 =head2 scopes
221  
222 my $scopes = $context->scopes;
223 $context = $context->scopes(['mcp:read', 'mcp:write']);
224  
225 OAuth scopes granted to the current request, as an array reference, populated from the C<auth> hook of the HTTP
226 transport. C<undef> (the default) imposes no scope restriction, so scopes are only enforced for authenticated
227 requests that provide them.
228  
229 =head2 state_binding
230  
231 my $binding = $context->state_binding;
232 $context = $context->state_binding("tools/call\0deploy");
233  
234 Identifies the request that request state may be used with, set by the server to the method name and the name or
235 URI of the primitive being called. State sealed for one primitive is never accepted by another.
236  
237 =head2 state_secret
238  
239 my $secret = $context->state_secret;
240 $context = $context->state_secret($bytes);
241  
242 Key used to authenticate request state, copied from L<MCP::Server/"state_secret">.
243  
244 =head2 state_timeout
245  
246 my $seconds = $context->state_timeout;
247 $context = $context->state_timeout(300);
248  
249 How long request state sealed during this request stays valid, in seconds, copied from
250 L<MCP::Server/"state_timeout">.
251  
252 =head2 status
253  
254 my $status = $context->status;
255 $context = $context->status(404);
256  
257 HTTP status the current request has to be answered with, set by the server for the protocol errors the specification
258 maps to a specific status, such as C<404> for an unknown method. C<undef> (the default) means C<200>, and transports
259 other than L<MCP::Server::Transport::HTTP> ignore it.
260  
261 =head2 stream
262  
263 my $cb = $context->stream;
264 $context = $context->stream(sub ($notification) { ... });
265  
266 Callback the transport installs once the response stream for the current request is open, to be called with every
267 notification that belongs to it. Notifications sent before that are queued up in L</"buffer">.
268  
269 =head2 transport
270  
271 my $transport = $context->transport;
272 $context = $context->transport(MCP::Server::Transport::HTTP->new);
273  
274 The transport handling the current request.
275  
276 =head1 METHODS
277  
278 L<MCP::Server::Context> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
279  
280 =head2 cancel
281  
282 $context = $context->cancel;
283  
284 Mark the current request as cancelled and emit the L</"cancelled"> event, at most once.
285  
286 =head2 flush
287  
288 my $num = $context->flush;
289  
290 Deliver all notifications queued up in L</"buffer"> to L</"stream">, and return the number of notifications
291 delivered.
292  
293 =head2 has_scope
294  
295 my $bool = $context->has_scope('mcp:write');
296 my $bool = $context->has_scope('mcp:read', 'mcp:write');
297  
298 Returns true if every given scope is present in L</"scopes">, or if L</"scopes"> is C<undef> (no restriction).
299  
300 =head2 is_cancelled
301  
302 my $bool = $context->is_cancelled;
303  
304 Returns true if the current request has been cancelled, for operations that cannot subscribe to the
305 L</"cancelled"> event and have to poll instead.
306  
307 =head2 notify
308  
309 my $bool = $context->notify($method);
310 my $bool = $context->notify($method, {foo => 'bar'});
311  
312 Send a JSON-RPC notification on the response stream of the current request. Returns true on success, or C<undef> if
313 the request has been cancelled.
314  
315 =head2 notify_log
316  
317 my $bool = $context->notify_log('info', 'Something happened');
318 my $bool = $context->notify_log('error', {code => 23});
319  
320 Send a C<notifications/message> JSON-RPC notification with the given severity and payload. Returns C<undef> unless
321 the client requested logging with C<_meta.io.modelcontextprotocol/logLevel> and the given severity is at or above
322 the level it asked for.
323  
324 =head2 notify_progress
325  
326 my $bool = $context->notify_progress($progress);
327 my $bool = $context->notify_progress($progress, $total);
328 my $bool = $context->notify_progress($progress, $total, $message);
329  
330 Send a C<notifications/progress> JSON-RPC notification for the progress token associated with the current request.
331 Returns true on success, or C<undef> if no progress token was provided by the client.
332  
333 =head2 request_state
334  
335 my $state = $context->request_state;
336  
337 Verify and decode the request state the client sent back, returning the data structure that was passed to
338 L<MCP::Primitive/"input_required">. Returns C<undef> if there was no state, or if it was tampered with, has expired,
339 was sealed for a different primitive, or belongs to a different L</"principal">, so a primitive that cannot tell
340 those cases apart simply asks for input again.
341  
342 Replay within L</"state_timeout"> is not prevented; servers that need one-shot semantics have to enforce that
343 themselves, for example by embedding a nonce and remembering it.
344  
345 =head2 seal_state
346  
347 my $sealed = $context->seal_state({step => 2});
348  
349 Serialize a data structure into an opaque string, authenticated with L</"state_secret"> and bound to
350 L</"state_binding">, L</"principal">, and L</"state_timeout">. Usually called through
351 L<MCP::Primitive/"input_required"> rather than directly.
352  
353 =head1 SEE ALSO
354  
355 L<MCP>, L<https://mojolicious.org>, L<https://modelcontextprotocol.io>.
356  
357 =cut
« MCP/Server/Transport/Stdio.pm ↑ Summary MCP/Server/Legacy.pm »