MCP.pm untested

filter: Statementstmt 0.0% 0 / 4 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 1 Podpod n/a totaltotal 0.0% 0 / 5 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
CRAP 2.0
1 package MCP;
2 use Mojo::Base -base, -signatures;
3  
4 our $VERSION = '0.15';
5  
6 1;
7  
8 =encoding utf8
9  
10 =head1 NAME
11  
12 MCP - Model Context Protocol Perl SDK
13  
14 =head1 SYNOPSIS
15  
16 use Mojolicious::Lite -signatures;
17  
18 use MCP::Server;
19  
20 my $server = MCP::Server->new;
21 $server->tool(
22 name => 'time',
23 description => 'Get the current local time',
24 code => sub ($tool, $args) {
25 return localtime(time);
26 }
27 );
28  
29 any '/mcp' => $server->to_action;
30  
31 app->start;
32  
33 =head1 DESCRIPTION
34  
35 Connect Perl with AI using the Model Context Protocol (MCP). An MCP server hands a model three kinds of things:
36 L<tools|MCP::Tool> it can call, L<prompts|MCP::Prompt> it can start from, and L<resources|MCP::Resource> it can read.
37 At its core MCP is all about text processing, which makes it a great fit for Perl.
38  
39 The protocol revision implemented is C<2026-07-28>, and it is stateless. There is no handshake and no session, every
40 request stands on its own, so an MCP endpoint is just another route in your L<Mojolicious> application and scales
41 the same way.
42  
43 Read on for a tour, or go straight to L<MCP::Server> for the reference documentation.
44  
45 =head1 TUTORIAL
46  
47 A walk through building MCP applications with Perl, from a single tool to a deployed web service.
48  
49 =head2 Concepts
50  
51 A server exposes three kinds of primitives, and you can mix them freely.
52  
53 # Called by the model, whenever it decides to
54 $server->tool(name => 'deploy', code => sub ($tool, $args) {...});
55  
56 # Picked by the user, usually from a menu
57 $server->prompt(name => 'review', code => sub ($prompt, $args) {...});
58  
59 # Read by the client, to put into context
60 $server->resource(uri => 'file:///readme', code => sub ($resource) {...});
61  
62 L<Tools|MCP::Tool> are functions the model calls on its own, and are what most servers are made of.
63 L<Prompts|MCP::Prompt> are templates a user invokes deliberately. L<Resources|MCP::Resource> are documents a client
64 attaches to a conversation. Everything else in this tutorial builds on those three.
65  
66 =head2 Your first server
67  
68 This is a complete MCP server that gives a model access to your local Perl documentation.
69  
70 use Mojo::Base -strict, -signatures;
71  
72 use MCP::Server;
73  
74 my $server = MCP::Server->new(name => 'PerldocServer');
75  
76 $server->tool(
77 name => 'perldoc',
78 description => 'Look up the documentation of a Perl module',
79 input_schema => {
80 type => 'object',
81 properties => {module => {type => 'string', description => 'Module name, such as Mojo::UserAgent'}},
82 required => ['module']
83 },
84 code => sub ($tool, $args) {
85 my $module = $args->{module};
86 return $tool->text_result("Not a module name: $module", 1) unless $module =~ /^\w+(?:::\w+)*\z/;
87 open my $doc, '-|', 'perldoc', '-o', 'text', '-T', $module or return $tool->text_result('Found no perldoc', 1);
88 my $text = do { local $/; <$doc> };
89 return length($text // '') ? $text : $tool->text_result("Found no documentation for $module", 1);
90 }
91 );
92  
93 $server->to_stdio;
94  
95 The name and description are how a model decides to call the tool, so write them for the model rather than for a
96 human reader. The L<input schema|MCP::Tool/"input_schema"> is enforced before your code runs, so C<$args> is always
97 valid by the time you see it. Returning a plain string is shorthand for a text result.
98  
99 =head2 Talking to your server
100  
101 L<MCP::Server/"to_stdio"> speaks JSON-RPC on standard input and output, so you can drive the server by hand. Every
102 request declares the protocol version it was made with and the capabilities of the client making it.
103  
104 $ perl perldoc_stdio.pl
105 {"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
106 {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"perldoc","arguments":{"module":"Mojo::JSON"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
107  
108 One JSON object per line, in and out. That is the whole protocol, and it is worth doing once before reaching for a
109 client.
110  
111 =head2 Connecting a client
112  
113 Most MCP hosts launch stdio servers themselves and are configured with a JSON file, C<claude_desktop_config.json>
114 for Claude Desktop and C<mcp.json> for many others.
115  
116 {
117 "mcpServers": {
118 "perldoc": {
119 "command": "perl",
120 "args": ["/absolute/path/to/perldoc_stdio.pl"]
121 }
122 }
123 }
124  
125 Use absolute paths, since the host does not run the command from your working directory, and restart the host to
126 pick up changes. When a server does not show up, its C<STDERR> is where to look, see L</"Logging">.
127  
128 =head2 Web applications
129  
130 The same server becomes an HTTP endpoint with L<MCP::Server/"to_action">, which returns a plain L<Mojolicious>
131 action.
132  
133 use Mojolicious::Lite -signatures;
134  
135 use MCP::Server;
136  
137 my $server = MCP::Server->new(name => 'PerldocServer');
138 $server->tool(...);
139  
140 any '/mcp' => $server->to_action;
141  
142 app->start;
143  
144 There is nothing special about that route. It can sit under an C<under>, carry placeholders, or share authentication
145 with the rest of your application. In a full L<Mojolicious> application it goes into C<startup> like any other.
146  
147 sub startup ($self) {
148 my $server = MCP::Server->new(name => 'PerldocServer');
149 $server->tool(...);
150 $self->routes->any('/mcp' => $server->to_action);
151 }
152  
153 Clients reach it with the Streamable HTTP transport, so the same JSON travels in a C<POST> body.
154  
155 {
156 "mcpServers": {
157 "perldoc": {
158 "url": "http://127.0.0.1:3000/mcp"
159 }
160 }
161 }
162  
163 =head2 Testing
164  
165 L<MCP::Client> is conformant on the wire, so pointing it at a L<Test::Mojo> application tests a server the way a real
166 client sees it.
167  
168 use Mojo::Base -strict, -signatures;
169  
170 use Test::More;
171 use Test::Mojo;
172 use MCP::Client;
173  
174 my $t = Test::Mojo->new('MyApp');
175 my $client = MCP::Client->new(ua => $t->ua, url => $t->ua->server->url->path('/mcp'));
176  
177 my $result = $client->call_tool('perldoc', {module => 'Mojo::JSON'});
178 like $result->{content}[0]{text}, qr/Minimalistic JSON/, 'documentation found';
179  
180 done_testing;
181  
182 Sharing the user agent with L<Test::Mojo> keeps requests inside the process, so no port is ever bound.
183  
184 =head2 Validating arguments
185  
186 Input schemas are JSON Schema 2020-12 unless they name another dialect with C<$schema>, and are checked before your
187 code is reached, so a call with bad arguments never becomes your problem.
188  
189 use Mojo::JSON qw(false);
190  
191 input_schema => {
192 type => 'object',
193 properties => {
194 module => {type => 'string', description => 'Module name, such as Mojo::UserAgent'},
195 lines => {type => 'integer', description => 'Maximum number of lines', minimum => 1, maximum => 500}
196 },
197 required => ['module'],
198 additionalProperties => false
199 }
200  
201 Descriptions are part of the interface, since the model reads them to decide what to pass, and so are the
202 constraints. A schema that says up front what is acceptable produces fewer failed calls than a tool that says so
203 afterwards.
204  
205 =head2 Tool results
206  
207 Returning a string is shorthand for L<MCP::Tool/"text_result">, and there are constructors for the other content
208 types.
209  
210 # Text
211 return $tool->text_result('Hello!');
212  
213 # Error the model can see and react to
214 return $tool->text_result("Found no documentation for $module", 1);
215  
216 # Image or audio bytes, base64 encoded for you
217 return $tool->image_result($png, {mime_type => 'image/png'});
218 return $tool->audio_result($wav);
219  
220 # Pointer to a resource, instead of its content
221 return $tool->resource_link_result('file:///perl/config', {name => 'perl_config'});
222  
223 Anything the model could react to belongs in the result with the error flag set, such as a name that does not exist
224 or an argument that makes no sense together with another. A tool that dies is answered with an C<InternalError>
225 instead, and the exception goes to L<MCP::Server/"log"> rather than to the caller, since it can easily contain file
226 system paths or connection strings. That is a safe fallback and a poor error message, so prefer returning an error
227 result for anything you can predict.
228  
229 =head2 Structured results
230  
231 A tool with an L<output schema|MCP::Tool/"output_schema"> returns data instead of prose, and the client gets a
232 guarantee about its shape.
233  
234 $server->tool(
235 name => 'perl_version',
236 description => 'Version of the Perl interpreter running this server',
237 output_schema => {
238 type => 'object',
239 properties => {version => {type => 'string'}, release => {type => 'number'}},
240 required => ['version', 'release']
241 },
242 code => sub ($tool, $args) {
243 return $tool->structured_result({version => "$^V", release => $] + 0});
244 }
245 );
246  
247 Structured content is validated against the output schema before it is sent, and data that does not match becomes an
248 error result, so a tool cannot quietly break its own contract.
249  
250 =head2 Prompts
251  
252 Prompts are templates a user picks deliberately, usually from a menu in the client.
253  
254 $server->prompt(
255 name => 'explain',
256 description => 'Explain what a Perl module is for',
257 arguments => [{name => 'module', description => 'Module name', required => 1}],
258 code => sub ($prompt, $args) {
259 return "Read the documentation of $args->{module} with the perldoc tool, then explain in three sentences "
260 . 'what problem it solves and when to reach for it.';
261 }
262 );
263  
264 A plain string becomes a user message, and L<MCP::Prompt/"text_prompt"> gives you control over the role.
265  
266 return $prompt->text_prompt('You are a Perl mentor.', 'assistant');
267  
268 =head2 Resources
269  
270 Resources are documents a client can read and attach to a conversation, identified by URI.
271  
272 use Config;
273  
274 $server->resource(
275 uri => 'file:///perl/config',
276 name => 'perl_config',
277 description => 'Configuration of the Perl interpreter running this server',
278 mime_type => 'text/plain',
279 code => sub ($resource) {
280 return join "\n", map {"$_=$Config{$_}"} qw(archname osname perlpath version);
281 }
282 );
283  
284 Resources take no arguments, only the URI they were registered with. For binary content use
285 L<MCP::Resource/"binary_resource">, which base64 encodes it for you.
286  
287 =head2 Non-blocking tools
288  
289 A tool that returns a L<Mojo::Promise> leaves the server free to handle other requests while it waits, which starts
290 to matter as soon as it talks to the network.
291  
292 use Mojo::URL;
293 use Mojo::UserAgent;
294  
295 my $ua = Mojo::UserAgent->new;
296  
297 $server->tool(
298 name => 'metacpan',
299 description => 'Look up the latest release of a distribution on MetaCPAN',
300 input_schema => {type => 'object', properties => {dist => {type => 'string'}}, required => ['dist']},
301 code => sub ($tool, $args) {
302 my $url = Mojo::URL->new('https://fastapi.metacpan.org/v1/release');
303 push @{$url->path->parts}, $args->{dist};
304  
305 return $ua->get_p($url)->then(sub ($tx) {
306 my $release = $tx->result->json;
307 return "$release->{name} was released on $release->{date} by $release->{author}";
308 })->catch(sub ($err) {
309 return $tool->text_result("MetaCPAN is unavailable: $err", 1);
310 });
311 }
312 );
313  
314 The promise resolves to whatever a synchronous tool would have returned. Both transports serve other requests while
315 it is pending.
316  
317 Two details are worth copying. The argument becomes a path part instead of being interpolated into the URL, so a
318 value containing a slash or a question mark cannot change which endpoint is called. And the chain ends in a
319 C<catch>, which turns a failure into an error result; a promise that is rejected instead never produces a response
320 at all.
321  
322 =head2 Progress reports
323  
324 Long running tools report progress through the L<context|MCP::Server::Context>, the per-request object your code
325 shares with the transport.
326  
327 code => sub ($tool, $args) {
328 my $context = $tool->context;
329  
330 my $total = @{$args->{modules}};
331 my $done = 0;
332 for my $module (@{$args->{modules}}) {
333 $context->notify_progress(++$done, $total, "Indexed $module");
334 ...
335 }
336  
337 return "Indexed $total modules";
338 }
339  
340 Notifications travel on the response stream of the request they belong to, which is upgraded from JSON to SSE the
341 moment there is something to send. That needs no configuration and works behind a pre-forking web server.
342  
343 Capture the context in a variable before an async boundary, since L<MCP::Primitive/"context"> is only valid for the
344 duration of the call itself.
345  
346 code => sub ($tool, $args) {
347 my $context = $tool->context;
348 my $promise = Mojo::Promise->new;
349 Mojo::IOLoop->timer(1 => sub {
350 $context->notify_progress(1, 1, 'Finished');
351 $promise->resolve('Done');
352 });
353 return $promise;
354 }
355  
356 Progress is only sent when the client asked for it with a progress token, so C<notify_progress> is always safe to
357 call.
358  
359 =head2 Logging
360  
361 L<MCP::Server::Context/"notify_log"> sends log messages to the client, gated by the level it asked for.
362  
363 $context->notify_log(info => "Looking up $module");
364 $context->notify_log(warning => {module => $module, truncated => 1});
365  
366 Nothing is sent unless the client requested logging for the current request, and messages below the level it asked
367 for are dropped, so this too is always safe to call.
368  
369 Your own logs belong on C<STDERR>, which is where L<Mojo::Log> writes and where an MCP host collects them. Never
370 write to C<STDOUT> from a stdio server, because that is the JSON-RPC channel and a stray C<print> corrupts it.
371  
372 # Bad, breaks the stdio transport
373 print "Looking up $module\n";
374  
375 # Good
376 my $log = Mojo::Log->new;
377 $log->info("Looking up $module");
378  
379 =head2 Cancellation
380  
381 When a client goes away the context emits L<MCP::Server::Context/"cancelled">, so work can stop instead of running
382 to completion for nobody.
383  
384 code => sub ($tool, $args) {
385 my $context = $tool->context;
386 my $promise = Mojo::Promise->new;
387 my $id = Mojo::IOLoop->recurring(1 => sub {...});
388 $context->on(cancelled => sub ($context) { Mojo::IOLoop->remove($id) });
389 return $promise;
390 }
391  
392 Code that cannot subscribe to an event polls L<MCP::Server::Context/"is_cancelled"> instead. Both transports feed the
393 same signal, a closed response stream over HTTP and a C<notifications/cancelled> notification over stdio, so a tool
394 only has to handle it once.
395  
396 =head2 Asking the client for input
397  
398 A tool that needs a decision from the user returns an C<input_required> result instead of a final one, and the client
399 calls it again with the answer.
400  
401 $server->tool(
402 name => 'delete_release',
403 input_schema => {type => 'object', properties => {name => {type => 'string'}}, required => ['name']},
404 code => sub ($tool, $args) {
405 my $context = $tool->context;
406 my $state = $context->request_state;
407 my $confirm = ($context->input_responses // {})->{confirm} // {};
408 return $tool->text_result("Deleted $state->{name}") if $state && ($confirm->{action} // '') eq 'accept';
409  
410 return $tool->input_required({
411 confirm => {
412 method => 'elicitation/create',
413 params => {
414 message => "Really delete $args->{name}?",
415 requestedSchema => {type => 'object', properties => {ok => {type => 'boolean'}}}
416 }
417 }
418 }, {name => $args->{name}});
419 }
420 );
421  
422 The second argument is state carried across the round trip, and the server remembers nothing. It is sealed with
423 HMAC-SHA256, bound to the caller and to this very tool, and given a short lifetime, so a client cannot edit it on the
424 way back. L<MCP::Server::Context/"request_state"> returns C<undef> for state that fails any of those checks, which
425 your code should treat exactly like a first call and simply ask again.
426  
427 Note that the retry acts on C<< $state->{name} >> and not on C<< $args->{name} >>. Only the state is sealed; the
428 arguments of the second call are as fresh and as untrusted as those of the first, so a client could ask about one
429 release and then present that confirmation with another one named. Whatever the user actually agreed to has to come
430 back out of the state.
431  
432 Only ask for capabilities the client declared in L<MCP::Server::Context/"client_capabilities">, and set
433 L<MCP::Server/"state_secret"> if the server runs in more than one process, see L</"Deployment">.
434  
435 =head2 Authentication and scopes
436  
437 An MCP endpoint is authenticated like any other route, and for OAuth 2.0 bearer tokens the HTTP transport has an
438 L<auth hook|MCP::Server::Transport::HTTP/"auth"> that runs before dispatch.
439  
440 any '/mcp' => $server->to_action({
441 auth => sub ($c) {
442 return undef unless ($c->req->headers->authorization // '') =~ /^Bearer\s+(\S+)$/;
443 return undef unless my $token = validate_token($1);
444 $c->stash(role => $token->{role});
445 return {principal => $token->{sub}, scopes => $token->{scopes}};
446 },
447 metadata_url => 'https://example.com/.well-known/oauth-protected-resource'
448 });
449  
450 Returning a false value rejects the request with a C<401> and a C<WWW-Authenticate> challenge pointing at the
451 metadata document. Validating the token is yours to do, since only your application knows the authorization server.
452  
453 Primitives can then require scopes, which are checked on every call and hide the primitive from callers who are not
454 entitled to see it.
455  
456 $server->tool(name => 'delete_release', scopes => ['mcp:write'], code => sub ($tool, $args) {...});
457  
458 Scopes are enforced against what the hook granted, so they only protect anything on a server that has one. Without
459 it no request carries scopes, and a scoped primitive is as reachable as an unscoped one; over stdio, where the
460 caller is whoever started the process, that is the intended behaviour.
461  
462 Serve the metadata document with L<MCP::Server/"oauth_metadata">, which fills in the scopes your server actually
463 uses.
464  
465 get '/.well-known/oauth-protected-resource' => sub ($c) {
466 $c->render(json => $server->oauth_metadata(
467 resource => 'https://example.com/mcp',
468 authorization_servers => ['https://auth.example.com']
469 ));
470 };
471  
472 =head2 Per-caller primitives
473  
474 The lists of tools, prompts and resources are assembled per request, and L<MCP::Server> emits an event for each one,
475 so a single server can show different things to different callers.
476  
477 $server->on(tools => sub ($server, $tools, $context) {
478 my $c = $context->controller;
479 return if $c && ($c->stash('role') // '') eq 'admin';
480 @$tools = grep { $_->name ne 'delete_release' } @$tools;
481 });
482  
483 The array reference is yours to modify in place, and removing a primitive also makes it uncallable, not merely
484 invisible. Everything known about the caller is on the L<context|MCP::Server::Context>, including the
485 L<Mojolicious::Controller> for HTTP requests, which is only there for the HTTP transport. Decide what to hide from
486 what the context actually says, never from what it fails to say, so an unauthenticated request ends up with the
487 smallest list rather than the largest.
488  
489 =head2 Caching
490  
491 Results that are expensive to produce and rarely change may be cached by clients and gateways, for as long as the
492 primitive says.
493  
494 $server->resource(uri => 'file:///perl/config', cache_ttl => 3_600_000, code => sub ($resource) {...});
495  
496 Times are in milliseconds, and the default of C<0> means every result has to be revalidated. Lists derive their
497 hints from the primitives in them, and are marked C<private> as soon as they could differ per caller, which is the
498 case for every server using scopes or the events above, so caching never leaks one caller's view to another.
499  
500 =head2 Notification streams
501  
502 Notifications that belong to no request, such as a tool list that changed while a client was connected, need a
503 stream of their own. Clients open one with C<subscriptions/listen>, which has to be enabled explicitly.
504  
505 any '/mcp' => $server->to_action({streaming => 1});
506  
507 # Somewhere else in the application
508 $server->notify_list_changed('tools');
509  
510 Every subscription only receives the notification types it asked for. This is the one part of the protocol that
511 keeps per-process state, so it is off by default and not compatible with pre-forking web servers. Progress and log
512 notifications do not depend on it.
513  
514 =head2 Deployment
515  
516 An MCP endpoint deploys exactly like the rest of your L<Mojolicious> application, see
517 L<Mojolicious::Guides::Cookbook/"DEPLOYMENT">. The protocol is stateless, so a pre-forking web server and a load
518 balancer need no special handling.
519  
520 $ ./myapp.pl prefork
521  
522 Serve a remote endpoint over HTTPS, which the protocol requires and which is usually the reverse proxy's job. Two
523 settings are worth having as well. L<MCP::Server/"state_secret"> has to be shared by every process that could serve
524 a retry, or state minted by one worker is rejected by the next, and L<MCP::Server::Transport::HTTP/"origins">
525 protects a server bound to localhost from being driven by a web page.
526  
527 my $server = MCP::Server->new(state_secret => $ENV{MCP_STATE_SECRET});
528  
529 any '/mcp' => $server->to_action({origins => ['https://example.com']});
530  
531 Everything except L</"Notification streams"> works under C<prefork>.
532  
533 =head1 COPYRIGHT AND LICENSE
534  
535 Copyright (C) 2025-2026, Sebastian Riedel.
536  
537 This program is free software, you can redistribute it and/or modify it under the terms of the MIT license.
538  
539 =head1 SEE ALSO
540  
541 L<MCP::Server>, L<MCP::Client>, L<Mojolicious>, L<https://mojolicious.org>, L<https://modelcontextprotocol.io>.
542  
543 =cut